π€― 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): stop double-writing masked credentials into the sandbox (#19032)
LiJian4719b958adcb
diff --git a/apps/server/src/services/sandbox/providers/market.ts b/apps/server/src/services/sandbox/providers/market.tsindex b98f3a2b284..2a35f1fce0d 100644--- a/apps/server/src/services/sandbox/providers/market.ts+++ b/apps/server/src/services/sandbox/providers/market.ts@@ -16,9 +16,9 @@ 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+ * Any command that writes into `~/.creds/env` (the path documented to the+ * model as where `injectCredsToSandbox` places credentials) 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 targetsdiff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.tsindex b06251694a5..7a2d2bb7b54 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts@@ -1,10 +1,9 @@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, writeEnvCredsToSandbox } from '../creds';+import { credsRuntime, ServerCredsService } from '../creds';const { getMember } = vi.hoisted(() => ({getMember: vi.fn(),@@ -87,135 +86,44 @@ 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',+describe('ServerCredsService.injectCreds', () => {+ const buildMarketService = (inject = vi.fn()) =>+ ({ market: { creds: { inject } } }) as unknown as MarketService;++ // Regression test: an earlier version of this method took the+ // `credentials.env` map back from market's `/inject-creds` response and+ // wrote it into the sandbox a second time. But that response is already+ // masked for safe display (market itself writes the *real* values into+ // ~/.creds/env server-side when `sandbox` is true) β so the second write+ // appended a masked `export` line after market's real one, and since+ // re-sourcing the file applies `export`s in file order, the masked line+ // silently shadowed the real credential for every later command. The fix+ // is to only forward market's response, never re-write it β this test+ // locks that in by asserting `market.creds.inject` is the only call made+ // and its result is returned untouched.+ it("forwards market.creds.inject's result without writing it into the sandbox again", async () => {+ const injectResult = {+ credentials: { env: { DC_CLI_TOKEN: '8f******vZ' } },+ notFound: [],+ success: true,+ };+ const inject = vi.fn().mockResolvedValue(injectResult);+ const service = new ServerCredsService(buildMarketService(inject), 'workspace-1');++ const result = await service.injectCreds({+ keys: ['dc-cli-token'],+ sandbox: true,+ topicId: 'topic-1',+ userId: 'user-1',});- 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,+ expect(inject).toHaveBeenCalledTimes(1);+ expect(inject).toHaveBeenCalledWith({+ keys: ['dc-cli-token'],+ sandbox: true,+ topicId: 'topic-1',+ userId: 'user-1',});-- 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');+ expect(result).toBe(injectResult);});});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts b/apps/server/src/services/toolExecution/serverRuntimes/creds.tsindex 41ac08308f7..a07fa060950 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/creds.ts@@ -5,98 +5,22 @@ 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*/-class ServerCredsService implements ICredsService {+export class ServerCredsService implements ICredsService {private marketService: MarketService;private workspaceId?: string;- private getSandboxService?: () => SandboxService;- constructor(- marketService: MarketService,- workspaceId?: string,- getSandboxService?: () => SandboxService,- ) {+ constructor(marketService: MarketService, workspaceId?: string) {this.marketService = marketService;this.workspaceId = workspaceId;- this.getSandboxService = getSandboxService;}/**@@ -187,7 +111,15 @@ class ServerCredsService implements ICredsService {log('injectCreds: keys=%O, topicId=%s', params.keys, params.topicId);// Market's generic inject endpoint resolves organization credentials from- // the workspaceId signed into this service's trusted-client token.+ // the workspaceId signed into this service's trusted-client token, and β+ // when `sandbox` is true (the default) β already writes the *real*+ // (unmasked) values into the sandbox's ~/.creds/env server-side before+ // responding. The `credentials.env` map in that response is masked for+ // safe display to the model, so it must never be written into the+ // sandbox again here: an earlier version of this method did exactly+ // that, appending a masked `export` line after market's real one. Since+ // re-sourcing ~/.creds/env applies `export`s in file order, the masked+ // line silently shadowed the real credential for every later command.const result = await this.marketService.market.creds.inject({keys: params.keys,sandbox: params.sandbox,@@ -197,39 +129,6 @@ 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;}@@ -310,35 +209,7 @@ export const credsRuntime: ServerRuntimeRegistration = {userInfo: { userId: context.userId, workspaceId: 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,- );+ const credsService = new ServerCredsService(marketService, context.workspaceId);return new CredsExecutionRuntime(credsService, {topicId: context.topicId,