π€― 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): inject into the topic's sandbox, refuse on device runs (#22639)
Rdmclin25b7cc2ffb236
diff --git a/apps/server/src/routers/lambda/market/creds.test.ts b/apps/server/src/routers/lambda/market/creds.test.tsindex 13facf51e7a..3f0b2047022 100644--- a/apps/server/src/routers/lambda/market/creds.test.ts+++ b/apps/server/src/routers/lambda/market/creds.test.ts@@ -9,12 +9,16 @@ interface MockOrgCredRow {}const {+ mockCredsInject,+ mockResolveSandboxSessionConfig,mockOrgCredsList,mockPersonalCredsList,mockPersonalCredsShare,mockPersonalCredsPublish,mockPersonalCredsUnshare,} = vi.hoisted(() => ({+ mockCredsInject: vi.fn(async () => ({ credentials: { env: {} }, success: true })),+ mockResolveSandboxSessionConfig: vi.fn(),mockOrgCredsList: vi.fn(async (): Promise<{ data: MockOrgCredRow[] }> => ({data: [{ id: 1, key: 'ORG_SECRET' }],})),@@ -69,6 +73,7 @@ vi.mock('@/server/services/market', () => ({return {market: {creds: {+ inject: mockCredsInject,list: mockPersonalCredsList,publish: mockPersonalCredsPublish,share: mockPersonalCredsShare,@@ -84,6 +89,10 @@ vi.mock('@/server/services/market', () => ({}),}));+vi.mock('@/server/services/sandbox', () => ({+ resolveSandboxSessionConfig: mockResolveSandboxSessionConfig,+}));+describe('credsRouter is always personal-scoped', () => {beforeEach(() => {vi.clearAllMocks();@@ -296,3 +305,60 @@ describe('credsRouter share/publish/unshare', () => {});});});++describe('credsRouter inject routes to the topic sandbox', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ // Regression: this route forwarded only keys/sandbox/topicId/userId and+ // signed no storage claim, so the client-executor path always injected into+ // a throwaway sandbox, never the topic's persistent environment or drive.+ it('resolves mode, instance and claim server-side and signs the claim', async () => {+ const { MarketService } = await import('@/server/services/market');+ mockResolveSandboxSessionConfig.mockResolvedValue({+ claim: { key: 'u-user-1' },+ drive: 'personal',+ environment: 'inst-1',+ mode: 'persistent',+ });+ const { credsRouter } = await import('./creds');++ const caller = credsRouter.createCaller({ userId: 'user-1' } as any);+ await caller.inject({ keys: ['FOO'], topicId: 'topic-1', userId: 'someone-else' });++ expect(mockResolveSandboxSessionConfig).toHaveBeenCalledWith(+ expect.objectContaining({ topicId: 'topic-1', userId: 'user-1' }),+ );+ expect(MarketService).toHaveBeenLastCalledWith(+ expect.objectContaining({+ userInfo: expect.objectContaining({+ sandboxStorage: { key: 'u-user-1' },+ userId: 'user-1',+ }),+ }),+ );+ expect(mockCredsInject).toHaveBeenCalledWith(+ expect.objectContaining({+ keys: ['FOO'],+ sandbox: true,+ sandboxInstanceId: 'inst-1',+ sandboxMode: 'persistent',+ topicId: 'topic-1',+ userId: 'user-1',+ }),+ );+ });++ it('skips sandbox resolution when not injecting into a sandbox', async () => {+ const { credsRouter } = await import('./creds');++ const caller = credsRouter.createCaller({ userId: 'user-1' } as any);+ await caller.inject({ keys: ['FOO'], sandbox: false, topicId: 'topic-1' });++ expect(mockResolveSandboxSessionConfig).not.toHaveBeenCalled();+ expect(mockCredsInject).toHaveBeenCalledWith(+ expect.objectContaining({ sandbox: false, sandboxMode: undefined }),+ );+ });+});diff --git a/apps/server/src/routers/lambda/market/creds.ts b/apps/server/src/routers/lambda/market/creds.tsindex 6ae8d110040..b0bfdc14065 100644--- a/apps/server/src/routers/lambda/market/creds.ts+++ b/apps/server/src/routers/lambda/market/creds.ts@@ -9,6 +9,7 @@ import { cloudWorkspaceAuth } from '@/business/server/trpc-middlewares/workspaceimport { publicProcedure, router } from '@/libs/trpc/lambda';import { marketUserInfo, requireMarketAuth, serverDatabase } from '@/libs/trpc/lambda/middleware';import { MarketService } from '@/server/services/market';+import { resolveSandboxSessionConfig } from '@/server/services/sandbox';const log = debug('lambda-router:market:creds');@@ -365,7 +366,9 @@ export const credsRouter = router({log('inject input: %O', input);try {- const userId = input.userId || ctx.userId;+ // The authenticated caller wins: the session is keyed by this id, and+ // the placement and claim below are resolved for it.+ const userId = ctx.userId || input.userId;if (!userId) {throw new TRPCError({code: 'BAD_REQUEST',@@ -373,9 +376,45 @@ export const credsRouter = router({});}- const result = await ctx.marketService.market.creds.inject({+ // Injection often creates the topic's sandbox, so it has to land where+ // the topic's tool calls run. Resolved here, as `execInSandbox` does,+ // rather than taken from the client: the browser cannot see the+ // topic's placement, and without the storage claim on the signed+ // identity Market ignores the mode and uses the throwaway runtime.+ // Read as the authenticated caller only, so a request cannot resolve+ // someone else's topic placement.+ const sandbox =+ input.sandbox && ctx.userId+ ? await resolveSandboxSessionConfig({+ // Direct client call, so the caller is always acting as themselves.+ isShareVisitorRun: false,+ serverDB: ctx.serverDB,+ topicId: input.topicId,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ })+ : undefined;++ // The claim has to ride on the signed identity: Market reads the+ // entitlement off the trusted-client token, and `ctx.marketService`+ // was built before it was known.+ const marketService =+ sandbox?.claim && ctx.userId+ ? new MarketService({+ accessToken: ctx.marketAccessToken,+ userInfo: {+ ...ctx.marketUserInfo,+ sandboxStorage: sandbox.claim,+ userId: ctx.userId,+ },+ })+ : ctx.marketService;++ const result = await marketService.market.creds.inject({keys: input.keys,sandbox: input.sandbox,+ sandboxInstanceId: sandbox?.environment,+ sandboxMode: sandbox?.mode,topicId: input.topicId,userId,});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.tsindex 3d8c19f753f..d7c1d6c8553 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts@@ -5,8 +5,13 @@ import { MarketService } from '@/server/services/market';import { type ToolExecutionContext } from '../../types';import { credsRuntime, ServerCredsService } from '../creds';-const { getMember } = vi.hoisted(() => ({+const { getMember, resolveSandboxSessionConfig } = vi.hoisted(() => ({getMember: vi.fn(),+ resolveSandboxSessionConfig: vi.fn(),+}));++vi.mock('@/server/services/sandbox', () => ({+ resolveSandboxSessionConfig,}));vi.mock('@/database/models/workspaceMember', () => ({@@ -25,6 +30,11 @@ describe('credsRuntime', () => {beforeEach(() => {vi.clearAllMocks();getMember.mockResolvedValue({ role: 'member' });+ resolveSandboxSessionConfig.mockResolvedValue({+ claim: null,+ drive: 'personal',+ mode: 'ephemeral',+ });});it('signs verified workspace context into the Market trusted-client identity', async () => {@@ -119,6 +129,89 @@ describe('credsRuntime', () => {expect(result.success).toBe(false);expect(result.error?.message).toContain('unavailable in shared conversations');});++ describe('injectCredsToSandbox', () => {+ const mockInject = () => {+ const inject = vi.fn().mockResolvedValue({ credentials: { env: {} }, success: true });+ vi.mocked(MarketService).mockImplementation(function () {+ return { market: { creds: { inject } } } as any;+ });+ return inject;+ };++ // Regression: inject only sent keys/sandbox/topicId/userId, so a topic on a+ // persistent environment or a drive had its credentials written into a+ // throwaway sandbox, which the next persistent tool call then replaced.+ it.each([+ ['persistent', 'inst-1'],+ ['drive', undefined],+ ] as const)('routes injection to the topic %s sandbox', async (mode, environment) => {+ resolveSandboxSessionConfig.mockResolvedValue({+ claim: { key: 'u-user-1' },+ drive: 'personal',+ environment,+ mode,+ });+ const inject = mockInject();++ const runtime = await credsRuntime.factory({+ serverDB,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ });+ const result = await (runtime as any).injectCredsToSandbox({ keys: ['FOO'] });++ expect(result.success).toBe(true);+ expect(inject).toHaveBeenCalledWith(+ expect.objectContaining({+ keys: ['FOO'],+ sandboxInstanceId: environment,+ sandboxMode: mode,+ topicId: 'topic-1',+ }),+ );+ });++ // A device-routed run executes commands on the device, so an injection+ // would report success while no command could ever read the values.+ it('refuses when the run is routed to a device', async () => {+ const inject = mockInject();++ const runtime = await credsRuntime.factory({+ activeDeviceId: 'device-1',+ executionPlan: { deviceId: 'device-1', kind: 'device', target: 'device' },+ serverDB,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ });+ const result = await (runtime as any).injectCredsToSandbox({ keys: ['FOO'] });++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('SandboxUnreachable');+ expect(inject).not.toHaveBeenCalled();+ });++ // In auto mode the Cloud Sandbox tool still reaches the sandbox even with a+ // device routed, so refusing on "target is not sandbox" would block it.+ it('allows injection in auto mode with a device routed', async () => {+ const inject = mockInject();++ const runtime = await credsRuntime.factory({+ activeDeviceId: 'device-1',+ executionPlan: { deviceId: 'device-1', kind: 'device', target: 'auto' },+ serverDB,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ });+ const result = await (runtime as any).injectCredsToSandbox({ keys: ['FOO'] });++ expect(result.success).toBe(true);+ expect(inject).toHaveBeenCalledTimes(1);+ });+ });});describe('ServerCredsService.injectCreds', () => {@@ -143,7 +236,9 @@ describe('ServerCredsService.injectCreds', () => {success: true,};const inject = vi.fn().mockResolvedValue(injectResult);- const service = new ServerCredsService(buildMarketService(inject), 'workspace-1');+ const service = new ServerCredsService(buildMarketService(inject), {+ workspaceId: 'workspace-1',+ });const result = await service.injectCreds({keys: ['dc-cli-token'],diff --git a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts b/apps/server/src/services/toolExecution/serverRuntimes/creds.tsindex bcebcd5eae4..e1a78f736b2 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/creds.ts@@ -1,3 +1,4 @@+import type { SandboxMode } from '@lobechat/builtin-tool-cloud-sandbox';import { CredsIdentifier, type ICredsService } from '@lobechat/builtin-tool-creds';import { CredsExecutionRuntime } from '@lobechat/builtin-tool-creds/executionRuntime';import debug from 'debug';@@ -7,12 +8,23 @@ import { WorkspaceMemberModel } from '@/database/models/workspaceMember';import type { MarketService } from '@/server/services/market';import { resolveSandboxSessionConfig } from '@/server/services/sandbox';+import { type ToolExecutionContext } from '../types';import { resolveContentWorkspaceId } from './resolveWorkspaceScope';import { createSandboxMarketService } from './sandboxMarket';import { type ServerRuntimeRegistration } from './types';const log = debug('lobe-server:creds-runtime');+/**+ * The sandbox the topic's tool calls run in, resolved the same way the+ * cloud-sandbox runtime resolves it. `instanceId` is the environment instance+ * (`SandboxSessionConfig.environment`).+ */+export interface CredsSandboxTarget {+ instanceId?: string;+ mode?: SandboxMode;+}+/*** Server-side Creds Service implementation* Wraps MarketService.market.creds to provide ICredsService interface@@ -23,23 +35,30 @@ export class ServerCredsService implements ICredsService {private isShareVisitor: boolean;+ private sandboxTarget: CredsSandboxTarget;+constructor(marketService: MarketService,- workspaceId?: string,- /**- * Belt-and-braces guard: true for an Agent Share visitor's run- * (`context.agentShareVisitor` set). `lobe-creds` is already absent from- * `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS`, so this runtime should never- * be constructed for a visitor in the first place β but `injectCreds`- * refuses again here too, so the guarantee that the creator's decrypted- * credentials never land in a sandbox a visitor controls doesn't rest on- * the allowlist alone.- */- isShareVisitor = false,+ options: {+ /**+ * Belt-and-braces guard: true for an Agent Share visitor's run+ * (`context.agentShareVisitor` set). `lobe-creds` is already absent from+ * `AGENT_SHARE_ALLOWED_BUILTIN_IDENTIFIERS`, so this runtime should never+ * be constructed for a visitor in the first place β but `injectCreds`+ * refuses again here too, so the guarantee that the creator's decrypted+ * credentials never land in a sandbox a visitor controls doesn't rest on+ * the allowlist alone.+ */+ isShareVisitor?: boolean;+ /** Where the topic's tool calls run; injection must land in the same sandbox. */+ sandboxTarget?: CredsSandboxTarget;+ workspaceId?: string;+ } = {},) {this.marketService = marketService;- this.workspaceId = workspaceId;- this.isShareVisitor = isShareVisitor;+ this.workspaceId = options.workspaceId;+ this.isShareVisitor = options.isShareVisitor ?? false;+ this.sandboxTarget = options.sandboxTarget ?? {};}/**@@ -149,9 +168,17 @@ export class ServerCredsService implements ICredsService {// 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.+ //+ // Injection is often a topic's first sandbox call, so it creates the+ // session: without the mode and instance it lands on the throwaway+ // runtime, and the topic's first persistent tool call then replaces that+ // sandbox β discarding the credentials written here. Named one by one,+ // like `callTool`'s context, so a dropped SDK field fails the build.const result = await this.marketService.market.creds.inject({keys: params.keys,sandbox: params.sandbox,+ sandboxInstanceId: this.sandboxTarget.instanceId,+ sandboxMode: this.sandboxTarget.mode,topicId: params.topicId,userId: params.userId,});@@ -174,6 +201,17 @@ export class ServerCredsService implements ICredsService {}}+/**+ * Whether this run's commands can reach the cloud sandbox the credentials are+ * written into β the same formula as the `creds_sandbox_reachable` prompt+ * variable. A routed device runs `runCommand` / `execScript` on the device,+ * except in `auto`, where the dedicated Cloud Sandbox tool still reaches the+ * sandbox even though Skills' own `runCommand` goes to the device.+ */+const isCredsSandboxReachable = (+ context: Pick<ToolExecutionContext, 'activeDeviceId' | 'executionPlan'>,+): boolean => !context.activeDeviceId || context.executionPlan?.target === 'auto';+/*** Creds Server Runtime* Per-request runtime (needs userId, topicId)@@ -242,13 +280,14 @@ export const credsRuntime: ServerRuntimeRegistration = {sandbox.claim,);- const credsService = new ServerCredsService(- marketService,+ const credsService = new ServerCredsService(marketService, {+ isShareVisitor: Boolean(context.agentShareVisitor),+ sandboxTarget: { instanceId: sandbox.environment, mode: sandbox.mode },workspaceId,- Boolean(context.agentShareVisitor),- );+ });return new CredsExecutionRuntime(credsService, {+ sandboxReachable: isCredsSandboxReachable(context),topicId: context.topicId,userId: context.userId,});diff --git a/packages/builtin-tool-activator/src/systemRole.ts b/packages/builtin-tool-activator/src/systemRole.tsindex 8d790663cea..32ef1a063b5 100644--- a/packages/builtin-tool-activator/src/systemRole.ts+++ b/packages/builtin-tool-activator/src/systemRole.ts@@ -110,7 +110,7 @@ When \`{{creds_sandbox_reachable}}\` is \`true\`:- Use \`injectCredsToSandbox\` before running code that needs credentials. Injected credentials become automatically available as environment variables in every \`runCommand\`/\`execScript\` call β you do NOT need to \`source\` any file yourself. See the \`lobe-creds\` system prompt's \`<sandbox_integration>\` section for the full contract.When \`{{creds_sandbox_reachable}}\` is \`false\` (this run is routed to a device):-- Do NOT call \`injectCredsToSandbox\` β it would still report success, but it writes into a cloud sandbox nothing in this run actually executes in.+- Do NOT call \`injectCredsToSandbox\` β it only writes into the cloud sandbox, and nothing in this run executes there.- There is currently no tool exposed to read a saved credential's plaintext value for inline use on a device-routed run. Tell the user this credential can't be used in this run rather than inventing a workaround.</credential_usage_by_runtime></credentials_management>`;diff --git a/packages/builtin-tool-creds/src/ExecutionRuntime/index.ts b/packages/builtin-tool-creds/src/ExecutionRuntime/index.tsindex 2900e52224c..9ccc0372e30 100644--- a/packages/builtin-tool-creds/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-creds/src/ExecutionRuntime/index.ts@@ -62,6 +62,19 @@ export interface ICredsService {}>;}+export interface CredsExecutionRuntimeContext {+ /**+ * Whether this run's commands can reach the cloud sandbox the credentials+ * are injected into (the `creds_sandbox_reachable` prompt variable). `false`+ * when the run is routed to a device outside `auto` mode: injection would+ * still succeed, but nothing this run executes could read the values.+ * Undefined is treated as reachable.+ */+ sandboxReachable?: boolean;+ topicId?: string;+ userId?: string;+}+/*** Creds Execution Runtime (Server-side)*@@ -75,9 +88,9 @@ export interface ICredsService {*/export class CredsExecutionRuntime {private credsService: ICredsService;- private context: { topicId?: string; userId?: string };+ private context: CredsExecutionRuntimeContext;- constructor(credsService: ICredsService, context: { topicId?: string; userId?: string } = {}) {+ constructor(credsService: ICredsService, context: CredsExecutionRuntimeContext = {}) {this.credsService = credsService;this.context = context;}@@ -192,6 +205,18 @@ export class CredsExecutionRuntime {async injectCredsToSandbox(args: InjectCredsToSandboxParams,): Promise<BuiltinServerRuntimeOutput> {+ if (this.context.sandboxReachable === false) {+ return {+ content:+ 'Cannot inject credentials: this run executes commands on a device, not in the cloud sandbox, so injected credentials would not be visible to any command. Credential injection only works when commands run in the cloud sandbox.',+ error: {+ message: 'The cloud sandbox is not reachable in this run',+ type: 'SandboxUnreachable',+ },+ success: false,+ };+ }+try {const topicId = this.context.topicId;if (!topicId) {diff --git a/packages/builtin-tool-creds/src/systemRole.ts b/packages/builtin-tool-creds/src/systemRole.tsindex 01873466608..2a2773c8f93 100644--- a/packages/builtin-tool-creds/src/systemRole.ts+++ b/packages/builtin-tool-creds/src/systemRole.ts@@ -76,7 +76,7 @@ When \`{{creds_sandbox_reachable}}\` is \`true\` and you need to run code that r3. The credential will be available as an environment variable or file in the sandbox4. Never pass credential values directly in code - always use environment variables or file paths-When \`{{creds_sandbox_reachable}}\` is \`false\`, this run is routed to a device β \`injectCredsToSandbox\` will still report success, but it writes into a cloud sandbox nothing in this run actually executes in, so the credential is unreachable. Don't call it. There is currently no way to load a saved credential's value onto a device-routed run β tell the user this credential can't be used here and ask them to run the command in a cloud-sandbox context instead, or supply the value themselves for this run.+When \`{{creds_sandbox_reachable}}\` is \`false\`, this run is routed to a device β \`injectCredsToSandbox\` only writes into the cloud sandbox, and nothing in this run executes there. Don't call it. There is currently no way to load a saved credential's value onto a device-routed run β tell the user this credential can't be used here and ask them to run the command in a cloud-sandbox context instead, or supply the value themselves for this run.**Important Notes:**- \`executeCode\` runs in an isolated process that may NOT have access to injected environment variables. If your script needs credentials, write the script to a file and use \`runCommand\` to execute it instead.