Skip to content
Closed
1 change: 1 addition & 0 deletions apps/sim/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions apps/sim/lib/core/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions apps/sim/lib/mothership/generated/memory-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
});
51 changes: 50 additions & 1 deletion apps/sim/lib/mothership/memory/application/read-scope.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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()
Expand Down
17 changes: 15 additions & 2 deletions apps/sim/lib/mothership/memory/application/read-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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,
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
chatId: context.chatId,
organizationId,
workspaceId,
spaceId: context.memorySpaceId ?? null,
})
Comment thread
myxamediyar marked this conversation as resolved.
Resolved
: 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 } : {}),
}
},
})
39 changes: 39 additions & 0 deletions apps/sim/lib/mothership/memory/attestation.ts
Original file line number Diff line number Diff line change
@@ -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<string | null> {
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'))
}
Loading