From cff62167a569d46db1c17bfcfeb4144f6dec63df Mon Sep 17 00:00:00 2001 From: Mukhamediyar <86684638+myxamediyar@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:14:44 -0800 Subject: [PATCH 1/3] feat(mothership): sign the private memory scope for the memory sidecar read_scope returns an attestation while memory is enabled and MOTHERSHIP_MEMORY_SIGNING_KEY is set: a one-minute EdDSA JWT over the user, organization, workspace, space and chat it just authorized, which the mothership memory sidecar verifies with Sim's public key instead of trusting the worker that forwards it. Co-Authored-By: Claude Opus 5.5 --- apps/sim/lib/core/config/env.ts | 1 + .../lib/mothership/generated/memory-scope.ts | 6 +++ .../memory/application/read-scope.test.ts | 51 ++++++++++++++++++- .../memory/application/read-scope.ts | 17 ++++++- apps/sim/lib/mothership/memory/attestation.ts | 39 ++++++++++++++ 5 files changed, 111 insertions(+), 3 deletions(-) create mode 100644 apps/sim/lib/mothership/memory/attestation.ts diff --git a/apps/sim/lib/core/config/env.ts b/apps/sim/lib/core/config/env.ts index da8c2d61915..b488d73f461 100644 --- a/apps/sim/lib/core/config/env.ts +++ b/apps/sim/lib/core/config/env.ts @@ -156,6 +156,7 @@ export const env = createEnv({ /** Enables the organization benchmark UI and its authenticated endpoints. */ MOTHERSHIP_BENCHMARK_ENABLED: z.boolean().optional(), MOTHERSHIP_BENCHMARK_URL: z.string().url().optional(), + MOTHERSHIP_MEMORY_SIGNING_KEY: z.string().min(1).optional(), // Ed25519 private key (PKCS#8 PEM) signing each private-memory scope; the memory sidecar verifies it with the public key. Unset, scopes go unsigned SIM_AGENT_API_URL: z.string().url().optional(), // URL for internal sim agent API MSHIP_SYSPROMPT_OVERRIDE: z.string().min(1).optional(), // Enterprise-only highest-priority Mothership system prompt override forwarded by Sim COPILOT_SOURCE_ENV: z.enum(['dev', 'staging', 'prod']).optional(), // Source Sim environment sent to mothership for callbacks diff --git a/apps/sim/lib/mothership/generated/memory-scope.ts b/apps/sim/lib/mothership/generated/memory-scope.ts index 9f7d46038c1..9e3595a1ccd 100644 --- a/apps/sim/lib/mothership/generated/memory-scope.ts +++ b/apps/sim/lib/mothership/generated/memory-scope.ts @@ -11,4 +11,10 @@ export const MemoryScopeResponse = z.object({ organizationId: z.string().min(1).nullable(), workspaceId: z.uuid().nullable(), spaceId: z.uuid().nullable().optional(), + /** + * Sim's signature over this scope (an EdDSA JWT: `sub` the user, `org`, `ws`, `space`, `chat`; + * one minute), sent while memory is enabled on a Sim with a signing key. The memory sidecar + * verifies it, so who a memory request acts for never rests on the worker alone. + */ + attestation: z.string().min(1).max(4096).optional(), }); diff --git a/apps/sim/lib/mothership/memory/application/read-scope.test.ts b/apps/sim/lib/mothership/memory/application/read-scope.test.ts index b2e5194e54e..43a1e120442 100644 --- a/apps/sim/lib/mothership/memory/application/read-scope.test.ts +++ b/apps/sim/lib/mothership/memory/application/read-scope.test.ts @@ -2,12 +2,14 @@ import { copilotChats, member, settings, user, workspace } from '@sim/db/schema' import { queueTableRows, resetDbChainMock, setEnvFlags } from '@sim/testing' import { authBanMock, authBanMockFns } from '@sim/testing/mocks/auth-ban.mock' +import { resetEnvMock, setEnv } from '@sim/testing/mocks/env.mock' import { permissionGroupsResolveMock, permissionGroupsResolveMockFns, } from '@sim/testing/mocks/permission-groups-resolve.mock' import { workspaceAuthzMock, workspaceAuthzMockFns } from '@sim/testing/mocks/workspace-authz.mock' -import { beforeEach, describe, expect, it, vi } from 'vitest' +import { exportPKCS8, generateKeyPair, jwtVerify } from 'jose' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createTrustedCopilotPrincipal, createTrustedOrganizationCopilotPrincipal, @@ -98,6 +100,53 @@ describe('private memory scope', () => { await expect(readMemoryScope.execute({ principal: caller, input })).rejects.toThrow() } ) + describe('attestation', () => { + afterEach(resetEnvMock) + async function signingKeys() { + const keys = await generateKeyPair('EdDSA', { extractable: true }) + setEnv({ MOTHERSHIP_MEMORY_SIGNING_KEY: await exportPKCS8(keys.privateKey) }) + return keys + } + it('signs the scope it returns, for the memory sidecar only, for one minute', async () => { + const { publicKey } = await signingKeys() + queueChat() + const scope = await readMemoryScope.execute({ principal: principal(), input }) + if (!('attestation' in scope) || typeof scope.attestation !== 'string') + throw new Error('Expected an attestation') + const { payload } = await jwtVerify(scope.attestation, publicKey, { + issuer: 'sim', + audience: 'mothership-memory', + algorithms: ['EdDSA'], + }) + expect(payload).toMatchObject({ + sub: 'actor', + chat: 'chat-1', + org: 'org-1', + ws: null, + space: null, + }) + expect((payload.exp ?? 0) - (payload.iat ?? 0)).toBe(60) + const other = await generateKeyPair('EdDSA') + await expect(jwtVerify(scope.attestation, other.publicKey)).rejects.toThrow() + }) + it('signs nothing while memory is off or no key is set', async () => { + await signingKeys() + setEnvFlags({ isMothershipBenchmarkEnabled: false }) + queueChat() + expect(await readMemoryScope.execute({ principal: principal(), input })).not.toHaveProperty( + 'attestation' + ) + setEnvFlags({ isMothershipBenchmarkEnabled: true }) + setEnv({ MOTHERSHIP_MEMORY_SIGNING_KEY: undefined }) + resetDbChainMock() + queueTableRows(user, [{ role: 'admin' }]) + queueTableRows(settings, [{ superUserModeEnabled: true }]) + queueChat() + expect(await readMemoryScope.execute({ principal: principal(), input })).not.toHaveProperty( + 'attestation' + ) + }) + }) it('rejects revoked membership, Search chats, and suspended users', async () => { queueChat('plan', false) await expect(readMemoryScope.execute({ principal: principal(), input })).rejects.toThrow() diff --git a/apps/sim/lib/mothership/memory/application/read-scope.ts b/apps/sim/lib/mothership/memory/application/read-scope.ts index 57cd3791f82..a9c6eb20855 100644 --- a/apps/sim/lib/mothership/memory/application/read-scope.ts +++ b/apps/sim/lib/mothership/memory/application/read-scope.ts @@ -6,6 +6,7 @@ import { defineAuthorizedChatUseCase } from '@/lib/mothership/chat/application/a import { resolveOwnedChatContext } from '@/lib/mothership/chat/application/context' import { isMemorySpacesEnabled } from '@/lib/mothership/feature-flags' import type { MemoryScopeRequest } from '@/lib/mothership/generated/memory-scope' +import { signMemoryScope } from '@/lib/mothership/memory/attestation' import { requireOwnedMemorySpace } from '@/lib/mothership/memory/spaces' export const MEMORY_SCOPE_AUDIENCE = 'sim:copilot-memory' @@ -60,12 +61,24 @@ export const readMemoryScope = defineAuthorizedChatUseCase({ context.memorySpaceId ) } + const workspaceId = context.workspaceId ?? null + // Signed only when memory is on: the attestation is what the sidecar trusts, not the worker. + const attestation = enabled + ? await signMemoryScope({ + userId: context.userId, + chatId: context.chatId, + organizationId, + workspaceId, + spaceId: context.memorySpaceId ?? null, + }) + : null return { enabled, ...(context.memorySpaceId ? { spaceId: context.memorySpaceId } : {}), userId: context.userId, - organizationId: context.organizationId ?? context.workspaceOrganizationId ?? null, - workspaceId: context.workspaceId ?? null, + organizationId, + workspaceId, + ...(attestation ? { attestation } : {}), } }, }) diff --git a/apps/sim/lib/mothership/memory/attestation.ts b/apps/sim/lib/mothership/memory/attestation.ts new file mode 100644 index 00000000000..4aa45d94dd0 --- /dev/null +++ b/apps/sim/lib/mothership/memory/attestation.ts @@ -0,0 +1,39 @@ +import { importPKCS8, SignJWT } from 'jose' +import { env } from '@/lib/core/config/env' + +/** Who the memory sidecar accepts an attestation from, and for. */ +const ISSUER = 'sim' +const AUDIENCE = 'mothership-memory' +/** Long enough for one memory call (the worker allows 30 seconds) and one retry. */ +const TTL_SECONDS = 60 + +export interface MemoryScopeClaims { + userId: string + chatId: string + organizationId: string | null + workspaceId: string | null + spaceId: string | null +} + +/** + * Signs the scope Sim just authorized, so the memory sidecar can verify who a request acts for + * without trusting the worker that forwards it: an EdDSA JWT over the canonical ids, valid for + * one minute. `null` when this deployment has no signing key. + */ +export async function signMemoryScope(claims: MemoryScopeClaims): Promise { + const pem = env.MOTHERSHIP_MEMORY_SIGNING_KEY + if (!pem) return null + return new SignJWT({ + chat: claims.chatId, + org: claims.organizationId, + ws: claims.workspaceId, + space: claims.spaceId, + }) + .setProtectedHeader({ alg: 'EdDSA' }) + .setIssuer(ISSUER) + .setAudience(AUDIENCE) + .setSubject(claims.userId) + .setIssuedAt() + .setExpirationTime(`${TTL_SECONDS}s`) + .sign(await importPKCS8(pem.replace(/\\n/g, '\n'), 'EdDSA')) +} From 053df2411ed3763d18509e5507a9dc5f2b78729e Mon Sep 17 00:00:00 2001 From: Mukhamediyar <86684638+myxamediyar@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:57:08 -0800 Subject: [PATCH 2/3] docs(mothership): document the memory signing key in the env example MOTHERSHIP_MEMORY_SIGNING_KEY is set only for a Mothership whose memory service lists its public key; a Sim on the hosted endpoint leaves it unset. Co-Authored-By: Claude Opus 5.5 --- apps/sim/.env.example | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/sim/.env.example b/apps/sim/.env.example index 1bacb5f98a9..d5c55d1d11e 100644 --- a/apps/sim/.env.example +++ b/apps/sim/.env.example @@ -31,6 +31,7 @@ NEXT_PUBLIC_APP_URL=http://localhost:3000 # NEXT_PUBLIC_CHAT_DISABLED=true # Hides the Chat module: the workspace lands on your first workflow, and the chats list, scheduled tasks, and editor Chat panel are absent. Chat is shown when unset; `bun run setup` sets this for you if you skip the chat key # MOTHERSHIP_BENCHMARK_ENABLED=true # Shows the organization Benchmark tab and enables its authenticated APIs # COPILOT_DEV_URL=http://localhost:8080 # Benchmark worker endpoint; requires the worker benchmark profile and the normal COPILOT_API_KEY +# MOTHERSHIP_MEMORY_SIGNING_KEY= # Ed25519 private key (PKCS#8 PEM, newlines as \n) signing who each private-memory request acts for; only with a Mothership whose memory service lists its public key. Leave unset on the hosted endpoint # Remote Function sandboxes (Optional) # Build a dedicated Function base before enabling JavaScript imports, Python, or Shell. From 3b701b4b0f9dce02f0ab8b9a47df9361352339a5 Mon Sep 17 00:00:00 2001 From: Mukhamediyar <86684638+myxamediyar@users.noreply.github.com> Date: Wed, 18 Nov 2026 16:04:57 -0800 Subject: [PATCH 3/3] improvement(mothership): describe the memory scope signature as an ids check The signature lets the memory service check that a request carries exactly the ids Sim returned for the call. It does not on its own stop a worker that names another chat when it asks for a scope; run grants on the worker routes cover that separately. --- apps/sim/lib/mothership/generated/memory-scope.ts | 2 +- apps/sim/lib/mothership/memory/application/read-scope.ts | 2 +- apps/sim/lib/mothership/memory/attestation.ts | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/sim/lib/mothership/generated/memory-scope.ts b/apps/sim/lib/mothership/generated/memory-scope.ts index 9e3595a1ccd..bcd414b3b91 100644 --- a/apps/sim/lib/mothership/generated/memory-scope.ts +++ b/apps/sim/lib/mothership/generated/memory-scope.ts @@ -14,7 +14,7 @@ export const MemoryScopeResponse = z.object({ /** * Sim's signature over this scope (an EdDSA JWT: `sub` the user, `org`, `ws`, `space`, `chat`; * one minute), sent while memory is enabled on a Sim with a signing key. The memory sidecar - * verifies it, so who a memory request acts for never rests on the worker alone. + * verifies it and checks a request's ids against it. */ attestation: z.string().min(1).max(4096).optional(), }); diff --git a/apps/sim/lib/mothership/memory/application/read-scope.ts b/apps/sim/lib/mothership/memory/application/read-scope.ts index a9c6eb20855..2838485ee90 100644 --- a/apps/sim/lib/mothership/memory/application/read-scope.ts +++ b/apps/sim/lib/mothership/memory/application/read-scope.ts @@ -62,7 +62,7 @@ export const readMemoryScope = defineAuthorizedChatUseCase({ ) } const workspaceId = context.workspaceId ?? null - // Signed only when memory is on: the attestation is what the sidecar trusts, not the worker. + // Signed only while memory is on. const attestation = enabled ? await signMemoryScope({ userId: context.userId, diff --git a/apps/sim/lib/mothership/memory/attestation.ts b/apps/sim/lib/mothership/memory/attestation.ts index 4aa45d94dd0..9cb7805b9a0 100644 --- a/apps/sim/lib/mothership/memory/attestation.ts +++ b/apps/sim/lib/mothership/memory/attestation.ts @@ -16,9 +16,9 @@ export interface MemoryScopeClaims { } /** - * Signs the scope Sim just authorized, so the memory sidecar can verify who a request acts for - * without trusting the worker that forwards it: an EdDSA JWT over the canonical ids, valid for - * one minute. `null` when this deployment has no signing key. + * Signs the scope Sim just returned, so the memory sidecar can check that a request carries + * exactly these ids: an EdDSA JWT over the canonical ids, valid for one minute. `null` when this + * deployment has no signing key. */ export async function signMemoryScope(claims: MemoryScopeClaims): Promise { const pem = env.MOTHERSHIP_MEMORY_SIGNING_KEY