π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
fix(creds): actually write injected credentials into the sandbox (#18994)
LiJiand5e54b769b79
diff --git a/apps/server/src/services/sandbox/providers/market.test.ts b/apps/server/src/services/sandbox/providers/market.test.tsindex a8caebfa644..924f6353f98 100644--- a/apps/server/src/services/sandbox/providers/market.test.ts+++ b/apps/server/src/services/sandbox/providers/market.test.ts@@ -177,6 +177,17 @@ describe('MarketSandboxProvider', () => {});});+ it('fully redacts a command that writes into ~/.creds/env, regardless of the credential names it carries', () => {+ const params = {+ command:+ "mkdir -p ~/.creds && \\\n(printf '%s\\n' 'export DC_CLI_TOKEN='\\''sk-super-secret'\\''') >> ~/.creds/env",+ };++ expect(redactSandboxParams(params)).toEqual({+ command: '[redacted]',+ });+ });+it('redacts sandbox resource URLs from params', () => {expect(redactSandboxParams({diff --git a/apps/server/src/services/sandbox/providers/market.ts b/apps/server/src/services/sandbox/providers/market.tsindex 78a43953994..b98f3a2b284 100644--- a/apps/server/src/services/sandbox/providers/market.ts+++ b/apps/server/src/services/sandbox/providers/market.ts@@ -15,6 +15,17 @@ import type {const log = debug('lobe-server:sandbox:market');const REDACTED_SANDBOX_PARAM = '[redacted]';const SANDBOX_AUTH_ENV_PATTERN = /\b(LOBEHUB_JWT|GITHUB_TOKEN)=("[^"]*"|'[^']*'|\S+)/g;+/**+ * Any command that writes into `~/.creds/env` (the injectCredsToSandbox+ * write path β see `serverRuntimes/creds.ts`'s `writeEnvCredsToSandbox`)+ * carries arbitrary, caller-named plaintext secrets whose variable names+ * `SANDBOX_AUTH_ENV_PATTERN` can't predict. Rather than extend that+ * name-specific pattern (which would need updating every time a new+ * credential key shape shows up), blank the whole command when it targets+ * that path β the credential name/value details aren't worth preserving in+ * a debug log anyway.+ */+const CREDS_ENV_WRITE_PATTERN = />>\s*~\/\.creds\/env\b/;export class MarketSandboxProvider implements SandboxProvider {readonly capabilities = {@@ -153,10 +164,12 @@ export const redactSandboxParams = (params: Record<string, unknown>) => {if (params.zipUrl) redacted.zipUrl = REDACTED_SANDBOX_PARAM;if (params.skillZipUrls) redacted.skillZipUrls = REDACTED_SANDBOX_PARAM;if (typeof params.command === 'string') {- redacted.command = params.command.replaceAll(- SANDBOX_AUTH_ENV_PATTERN,- (_, name: string) => `${name}=${REDACTED_SANDBOX_PARAM}`,- );+ redacted.command = CREDS_ENV_WRITE_PATTERN.test(params.command)+ ? REDACTED_SANDBOX_PARAM+ : params.command.replaceAll(+ SANDBOX_AUTH_ENV_PATTERN,+ (_, name: string) => `${name}=${REDACTED_SANDBOX_PARAM}`,+ );}return redacted;diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.tsindex 5a917f1cac0..b06251694a5 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts@@ -1,9 +1,10 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { MarketService } from '@/server/services/market';+import { type SandboxService } from '@/server/services/sandbox';import { type ToolExecutionContext } from '../../types';-import { credsRuntime } from '../creds';+import { credsRuntime, writeEnvCredsToSandbox } from '../creds';const { getMember } = vi.hoisted(() => ({getMember: vi.fn(),@@ -85,3 +86,136 @@ describe('credsRuntime', () => {);});});++describe('writeEnvCredsToSandbox', () => {+ const buildSandboxService = (callTool = vi.fn()): SandboxService =>+ ({ callTool }) as unknown as SandboxService;++ /**+ * Reverses `shellQuote`'s escaping (`'a'\''b'` -> `a'b`) so tests can+ * round-trip a value through the two nested quoting layers instead of+ * hand-deriving the exact escaped string β hand-derivation is exactly+ * the kind of thing that's easy to get subtly wrong for values containing+ * their own quotes, which is the case that actually matters here.+ */+ const posixUnquote = (quoted: string): string => {+ if (!quoted.startsWith("'") || !quoted.endsWith("'")) {+ throw new Error(`Not a single-quoted shell literal: ${quoted}`);+ }+ return quoted.slice(1, -1).replaceAll("'\\''", "'");+ };++ /** Extracts the single printf argument from a one-entry writeEnvCredsToSandbox command. */+ const extractWrittenLine = (command: string): string => {+ const match = command.match(/printf '%s\\n' (.+)\) >> ~\/\.creds\/env$/);+ if (!match) throw new Error(`Could not find printf argument in command: ${command}`);+ return posixUnquote(match[1]);+ };++ /** Extracts and unquotes the value from an `export KEY=<quoted value>` line. */+ const extractExportedValue = (exportLine: string, key: string): string => {+ const prefix = `export ${key}=`;+ if (!exportLine.startsWith(prefix)) {+ throw new Error(`Expected an "${prefix}" line, got: ${exportLine}`);+ }+ return posixUnquote(exportLine.slice(prefix.length));+ };++ it('is a no-op and never calls the sandbox when there is nothing to write', async () => {+ const callTool = vi.fn();+ const result = await writeEnvCredsToSandbox(buildSandboxService(callTool), {});++ expect(callTool).not.toHaveBeenCalled();+ expect(result).toEqual({});+ });++ it('writes each entry into ~/.creds/env as an `export` assignment via a single runCommand call', async () => {+ const callTool = vi.fn().mockResolvedValue({ result: null, success: true });++ const result = await writeEnvCredsToSandbox(buildSandboxService(callTool), {+ DC_CLI_TOKEN: 'secret-token',+ DC_BASE_URL: 'https://dc.lobe.li',+ });++ expect(result).toEqual({ skippedInvalidNames: [] });+ expect(callTool).toHaveBeenCalledTimes(1);+ const [toolName, params] = callTool.mock.calls[0];+ expect(toolName).toBe('runCommand');+ expect(params.command).toContain('mkdir -p ~/.creds');+ expect(params.command).toContain('>> ~/.creds/env');+ // `export`, not a bare assignment β a bare NAME=value is a shell+ // variable invisible to any child process the sourcing shell spawns.+ expect(params.command).toContain("printf '%s\\n' 'export DC_CLI_TOKEN='\\''secret-token'\\'''");+ expect(params.command).toContain(+ "printf '%s\\n' 'export DC_BASE_URL='\\''https://dc.lobe.li'\\'''",+ );+ });++ it('round-trips a value containing shell metacharacters back to the exact original, proving `source` would load it as an inert literal', async () => {+ const callTool = vi.fn().mockResolvedValue({ result: null, success: true });+ const dangerousValue = '$(rm -rf ~); echo pwned `whoami` && exit 1 # trailing';++ await writeEnvCredsToSandbox(buildSandboxService(callTool), { TOKEN: dangerousValue });++ const command = callTool.mock.calls[0][1].command as string;+ const exportLine = extractWrittenLine(command);+ expect(exportLine.startsWith('export TOKEN=')).toBe(true);+ expect(extractExportedValue(exportLine, 'TOKEN')).toBe(dangerousValue);+ });++ it('round-trips a value that itself contains a single quote, through both nested quoting layers', async () => {+ const callTool = vi.fn().mockResolvedValue({ result: null, success: true });+ const trickyValue = "it's a 'quoted' secret";++ await writeEnvCredsToSandbox(buildSandboxService(callTool), { TOKEN: trickyValue });++ const command = callTool.mock.calls[0][1].command as string;+ const exportLine = extractWrittenLine(command);+ expect(extractExportedValue(exportLine, 'TOKEN')).toBe(trickyValue);+ });++ it('skips a credential key that is not a valid shell identifier and reports it, without touching the sandbox for it', async () => {+ const callTool = vi.fn().mockResolvedValue({ result: null, success: true });++ const result = await writeEnvCredsToSandbox(buildSandboxService(callTool), {+ 'TEST-WORKSPACE-CREDS-KV': 'value-a',+ 'VALID_KEY': 'value-b',+ });++ expect(result.skippedInvalidNames).toEqual(['TEST-WORKSPACE-CREDS-KV']);+ const command = callTool.mock.calls[0][1].command as string;+ expect(command).toContain('export VALID_KEY=');+ expect(command).not.toContain('TEST-WORKSPACE-CREDS-KV');+ });++ it('never calls the sandbox when every key is an invalid shell identifier', async () => {+ const callTool = vi.fn();++ const result = await writeEnvCredsToSandbox(buildSandboxService(callTool), {+ 'bad key': 'value',+ });++ expect(callTool).not.toHaveBeenCalled();+ expect(result).toEqual({ skippedInvalidNames: ['bad key'] });+ });++ it('surfaces a descriptive error when the sandbox write fails', async () => {+ const callTool = vi.fn().mockResolvedValue({+ error: { message: 'sandbox unreachable' },+ result: null,+ success: false,+ });++ const result = await writeEnvCredsToSandbox(buildSandboxService(callTool), { KEY: 'value' });++ expect(result).toEqual({ error: 'sandbox unreachable', skippedInvalidNames: [] });+ });++ it('falls back to a generic error message when the sandbox failure carries none', async () => {+ const callTool = vi.fn().mockResolvedValue({ result: null, success: false });++ const result = await writeEnvCredsToSandbox(buildSandboxService(callTool), { KEY: 'value' });++ expect(result.error).toBe('Failed to write credentials into the sandbox');+ });+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts b/apps/server/src/services/toolExecution/serverRuntimes/creds.tsindex 60b4a7faafb..41ac08308f7 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/creds.ts@@ -5,11 +5,81 @@ import debug from 'debug';import { UserModel } from '@/database/models/user';import { WorkspaceMemberModel } from '@/database/models/workspaceMember';import { MarketService } from '@/server/services/market';+import { createSandboxService, type SandboxService } from '@/server/services/sandbox';import { type ServerRuntimeRegistration } from './types';const log = debug('lobe-server:creds-runtime');+const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;++/** POSIX shell identifier β the only names `export NAME=...` can safely take. */+const VALID_ENV_NAME_PATTERN = /^[A-Z_]\w*$/i;++/**+ * Write injected env-style credentials into the sandbox at `~/.creds/env`,+ * matching the exact contract `packages/builtin-tool-creds/src/systemRole.ts`+ * documents to the model ("Environment-based credentials... Written to+ * `~/.creds/env` file"). Without this, `injectCreds` only fetched and+ * decrypted the values and returned them in the tool result β nothing ever+ * placed them in the sandbox, so the tool reported "injected successfully"+ * while `~/.creds/env` never existed and subsequent `runCommand` calls that+ * `source`d it found nothing.+ *+ * Appends rather than overwrites, since a topic can call `injectCredsToSandbox`+ * more than once across a session and earlier values should survive.+ *+ * Two layers of shell-safety, not one:+ * 1. Each written line is `export NAME=<single-quoted value>` β the quoting+ * happens INSIDE the file content, so when the documented consumer later+ * runs `source ~/.creds/env`, a value containing `$(...)`, backticks,+ * `;`, or a newline is loaded as an inert literal, not executed. `export`+ * (not a bare assignment) is required too β a bare `NAME=value` is a+ * shell variable, invisible to any child process the sourcing shell+ * spawns (a Python/Node subprocess, another binary, etc.), which is a+ * silent-failure shape indistinguishable from "injection didn't happen".+ * 2. Each fully-built line is itself passed through `shellQuote` as a single+ * `printf '%s\n' <line>` argument, so the runCommand call that WRITES the+ * file can't be broken out of either β the value is opaque to the outer+ * shell that's doing the writing.+ * Credential keys that aren't valid shell identifiers (seen in practice:+ * hyphenated keys like `TEST-WORKSPACE-CREDS-KV`) can't be made into a safe+ * `export NAME=...` at all β writing them raw could inject shell syntax+ * through the name position, which quoting the value alone can't stop. Skip+ * and report them rather than attempt it.+ */+export async function writeEnvCredsToSandbox(+ sandboxService: SandboxService,+ env: Record<string, string>,+): Promise<{ error?: string; skippedInvalidNames?: string[] }> {+ const entries = Object.entries(env);+ if (entries.length === 0) return {};++ const valid = entries.filter(([key]) => VALID_ENV_NAME_PATTERN.test(key));+ const skippedInvalidNames = entries+ .filter(([key]) => !VALID_ENV_NAME_PATTERN.test(key))+ .map(([key]) => key);++ if (valid.length === 0) return { skippedInvalidNames };++ const printfCalls = valid+ .map(([key, value]) => {+ const exportLine = `export ${key}=${shellQuote(value)}`;+ return `printf '%s\\n' ${shellQuote(exportLine)}`;+ })+ .join(' && \\\n');+ const command = `mkdir -p ~/.creds && \\\n(${printfCalls}) >> ~/.creds/env`;++ const result = await sandboxService.callTool('runCommand', { command });+ if (!result.success) {+ return {+ error: result.error?.message || 'Failed to write credentials into the sandbox',+ skippedInvalidNames,+ };+ }+ return { skippedInvalidNames };+}+/*** Server-side Creds Service implementation* Wraps MarketService.market.creds to provide ICredsService interface@@ -17,10 +87,16 @@ const log = debug('lobe-server:creds-runtime');class ServerCredsService implements ICredsService {private marketService: MarketService;private workspaceId?: string;+ private getSandboxService?: () => SandboxService;- constructor(marketService: MarketService, workspaceId?: string) {+ constructor(+ marketService: MarketService,+ workspaceId?: string,+ getSandboxService?: () => SandboxService,+ ) {this.marketService = marketService;this.workspaceId = workspaceId;+ this.getSandboxService = getSandboxService;}/**@@ -121,6 +197,39 @@ class ServerCredsService implements ICredsService {log('injectCreds success: notFound=%d', result.notFound?.length || 0);+ // Fetching+decrypting the values is not the same as *injecting* them β+ // `sandbox` defaults true (matches ICredsService.injectCreds' contract of+ // "inject credentials into sandbox"), so unless the caller explicitly+ // opted out, actually write them into the sandbox at the path the+ // creds tool's own system prompt documents (~/.creds/env). Without this+ // the call reports success while leaving the sandbox with nothing to+ // read β the exact bug this fixes.+ const envToWrite = (result as any)?.credentials?.env as Record<string, string> | undefined;+ if (params.sandbox !== false && envToWrite && Object.keys(envToWrite).length > 0) {+ if (!this.getSandboxService) {+ log('injectCreds: sandbox write skipped, no sandbox service available for this context');+ } else {+ const { error, skippedInvalidNames } = await writeEnvCredsToSandbox(+ this.getSandboxService(),+ envToWrite,+ );+ if (skippedInvalidNames?.length) {+ log(+ 'injectCreds: skipped %d credential(s) whose key is not a valid shell env var name: %O',+ skippedInvalidNames.length,+ skippedInvalidNames,+ );+ }+ if (error) {+ log('injectCreds: failed to write credentials into sandbox: %s', error);+ throw new Error(+ `Credentials were fetched but could not be written into the sandbox: ${error}`,+ );+ }+ log('injectCreds: wrote %d env var(s) into ~/.creds/env', Object.keys(envToWrite).length);+ }+ }+return result as any;}@@ -200,7 +309,36 @@ export const credsRuntime: ServerRuntimeRegistration = {accessToken,userInfo: { userId: context.userId, workspaceId: context.workspaceId },});- const credsService = new ServerCredsService(marketService, context.workspaceId);++ // Lazy + memoized: only actually constructed if injectCreds needs to+ // write env vars into the sandbox. serverDB/topicId are the same+ // preconditions cloudSandboxRuntime requires for its own sandbox+ // service β when either is missing (e.g. a context without an active+ // sandbox-capable topic) sandbox writing is simply skipped, matching+ // the pre-existing "fetch only" behavior for that case.+ let sandboxService: SandboxService | undefined;+ const getSandboxService = (): SandboxService => {+ if (!sandboxService) {+ if (!context.serverDB || !context.topicId || !context.userId) {+ throw new Error(+ 'serverDB, topicId, and userId are required to write creds into the sandbox',+ );+ }+ sandboxService = createSandboxService({+ marketService,+ serverDB: context.serverDB,+ topicId: context.topicId,+ userId: context.userId,+ });+ }+ return sandboxService;+ };++ const credsService = new ServerCredsService(+ marketService,+ context.workspaceId,+ context.serverDB && context.topicId ? getSandboxService : undefined,+ );return new CredsExecutionRuntime(credsService, {topicId: context.topicId,