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. diff --git a/apps/sim/lib/core/config/env.ts b/apps/sim/lib/core/config/env.ts index 5a757490398..0a9f6848b30 100644 --- a/apps/sim/lib/core/config/env.ts +++ b/apps/sim/lib/core/config/env.ts @@ -162,6 +162,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..bcd414b3b91 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 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.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..2838485ee90 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 while memory is on. + 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..9cb7805b9a0 --- /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 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 + 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')) +}