Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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_REQUIRE_RUN_GRANT=true # Refuse Mothership worker calls that carry no run grant for their user and chat; set once your Mothership forwards run grants

# 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_REQUIRE_RUN_GRANT: z.boolean().optional(), // Worker calls must carry a run grant naming their user and chat; unset, a call without one is still served
Comment thread
myxamediyar marked this conversation as resolved.
Resolved
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
38 changes: 37 additions & 1 deletion apps/sim/lib/mothership/auth/internal.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { createMockRequest } from '@sim/testing'
import { copilotHttpMock, copilotHttpMockFns } from '@sim/testing/mocks/copilot-http.mock'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { resetEnvMock, setEnv } from '@sim/testing/mocks/env.mock'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { internalCopilotAuth } from '@/lib/mothership/auth/internal'
import { issueRunGrant } from '@/lib/mothership/auth/run-grant'
import { RUN_GRANT_HEADER } from '@/lib/mothership/generated/sim-transport'

vi.mock('@/lib/mothership/request/http', () => copilotHttpMock)

Expand Down Expand Up @@ -44,4 +47,37 @@ describe('worker control identity', () => {
apiKey.mockReturnValue({ success: false })
await expect(auth.authenticate(request(headers))).rejects.toThrow('Unauthorized')
})
describe('run grants', () => {
afterEach(resetEnvMock)
const auth = internalCopilotAuth('control', { organization: true })
const grant = () =>
issueRunGrant({
userId: 'actor',
chatId: 'chat-1',
workspaceId: null,
organizationId: 'org-1',
})
it('admits identity headers the run grant names, and refuses forged or mismatched grants', async () => {
await expect(
auth.authenticate(request({ ...headers, [RUN_GRANT_HEADER]: await grant() }))
).resolves.toMatchObject({ subjectUserId: 'actor', resourceScope: { chatId: 'chat-1' } })
await expect(
auth.authenticate(
request({
...headers,
'x-mothership-chat-id': 'chat-2',
[RUN_GRANT_HEADER]: await grant(),
})
)
).rejects.toThrow('Unauthorized')
await expect(
auth.authenticate(request({ ...headers, [RUN_GRANT_HEADER]: 'not-a-grant' }))
).rejects.toThrow('Unauthorized')
})
it('refuses a call without a grant once grants are required', async () => {
await expect(auth.authenticate(request(headers))).resolves.toBeDefined()
setEnv({ MOTHERSHIP_REQUIRE_RUN_GRANT: true })
await expect(auth.authenticate(request(headers))).rejects.toThrow('Unauthorized')
})
})
})
49 changes: 32 additions & 17 deletions apps/sim/lib/mothership/auth/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,14 @@ import {
createTrustedCopilotPrincipal,
createTrustedOrganizationCopilotPrincipal,
} from '@/lib/mothership/auth/application-delegation'
import { acceptsRunGrant, checkRunGrant, rememberRunGrant } from '@/lib/mothership/auth/run-grant'
import { RUN_GRANT_HEADER } from '@/lib/mothership/generated/sim-transport'
import { checkInternalApiKey } from '@/lib/mothership/request/http'

/** Identity headers are assertions from the authenticated worker, never browser credentials. */
/**
* Identity headers are assertions from the authenticated worker, never browser credentials; the
* run grant Sim issued with the turn proves them (`run-grant.ts`).
*/
export function internalCopilotAuth(audience: string, options: { organization?: boolean } = {}) {
return {
async authenticate(
Expand All @@ -21,22 +26,32 @@ export function internalCopilotAuth(audience: string, options: { organization?:
const chatId = request.headers.get('x-mothership-chat-id')
if (!userId || Boolean(workspaceId) === Boolean(organizationId))
throw new InternalUnauthenticatedError()
if (organizationId) {
if (!options.organization || !chatId) throw new InternalUnauthenticatedError()
return createTrustedOrganizationCopilotPrincipal(
{ userId, organizationId, chatId, delegationId: `worker:${generateId()}` },
{ audience, ttlMs: 60_000 }
)
}
return createTrustedCopilotPrincipal(
{
userId,
workspaceId: workspaceId!,
...(chatId ? { chatId } : {}),
delegationId: `worker:${generateId()}`,
},
{ audience, ttlMs: 60_000 }
)
if (organizationId && (!options.organization || !chatId))
throw new InternalUnauthenticatedError()
const grant = await checkRunGrant(request.headers.get(RUN_GRANT_HEADER), {
userId,
...(chatId ? { chatId } : {}),
...(workspaceId ? { workspaceId } : {}),
...(organizationId ? { organizationId } : {}),
})
if (!acceptsRunGrant(grant)) throw new InternalUnauthenticatedError()
const principal =
organizationId && chatId
? createTrustedOrganizationCopilotPrincipal(
{ userId, organizationId, chatId, delegationId: `worker:${generateId()}` },
{ audience, ttlMs: 60_000 }
)
: createTrustedCopilotPrincipal(
{
userId,
workspaceId: workspaceId!,
...(chatId ? { chatId } : {}),
delegationId: `worker:${generateId()}`,
},
{ audience, ttlMs: 60_000 }
)
rememberRunGrant(principal, grant)
return principal
},
}
}
103 changes: 103 additions & 0 deletions apps/sim/lib/mothership/auth/run-grant.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { resetEnvMock, setEnv } from '@sim/testing/mocks/env.mock'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { generateInternalToken } from '@/lib/auth/internal'
import {
acceptsRunGrant,
checkRunGrant,
issueRunGrant,
rememberRunGrant,
renewedRunGrant,
runGrantHeaders,
} from '@/lib/mothership/auth/run-grant'

const HOUR_MS = 60 * 60 * 1000
const turn = { userId: 'actor', chatId: 'chat-1', workspaceId: 'ws-1', organizationId: null }
const claimed = { userId: 'actor', chatId: 'chat-1', workspaceId: 'ws-1' }

describe('run grants', () => {
afterEach(() => {
resetEnvMock()
vi.useRealTimers()
})

it('admits a call naming exactly the identity its grant names, and no other', async () => {
const grant = issueRunGrant(turn)
expect(await checkRunGrant(grant, claimed)).toMatchObject({ ok: true, identity: turn })
for (const other of [
{ ...claimed, userId: 'someone-else' },
{ ...claimed, chatId: 'chat-2' },
{ ...claimed, workspaceId: 'ws-2' },
{ userId: 'actor', chatId: 'chat-1', organizationId: 'org-1' },
]) {
expect(await checkRunGrant(grant, other)).toEqual({ ok: false, reason: 'mismatch' })
}
})

it('admits a grant for a turn with no chat only on calls that name no chat', async () => {
const chatless = issueRunGrant({ ...turn, chatId: undefined })
expect(await checkRunGrant(chatless, claimed)).toEqual({ ok: false, reason: 'mismatch' })
const { chatId: _chatId, ...noChat } = claimed
expect(await checkRunGrant(chatless, noChat)).toMatchObject({ ok: true })
})

it('issues no grants and serves grant-less calls where Sim runs without an auth secret', async () => {
const grant = issueRunGrant(turn)
setEnv({ BETTER_AUTH_SECRET: undefined })
expect(runGrantHeaders({ userId: 'actor', chatId: 'chat-1', workspaceId: 'ws-1' })).toEqual({})
const check = await checkRunGrant(grant, claimed)
expect(check).toEqual({ ok: false, reason: 'missing' })
expect(acceptsRunGrant(check)).toBe(true)
})

it('reads the enforcement switch as the string the environment holds', async () => {
const missing = await checkRunGrant(undefined, claimed)
for (const [value, accepted] of [
['false', true],
['0', true],
['true', false],
['1', false],
] as const) {
setEnv({ MOTHERSHIP_REQUIRE_RUN_GRANT: value })
expect([value, acceptsRunGrant(missing)]).toEqual([value, accepted])
}
})

it('refuses a token the worker could mint itself with the secret it holds', async () => {
const forged = await generateInternalToken('actor')
const check = await checkRunGrant(forged, claimed)
expect(check).toEqual({ ok: false, reason: 'invalid' })
expect(acceptsRunGrant(check)).toBe(false)
})

it('serves a call with a missing or expired grant only until grants are required', async () => {
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(Date.now())
const grant = issueRunGrant(turn)
vi.setSystemTime(Date.now() + 25 * HOUR_MS)
const expired = await checkRunGrant(grant, claimed)
const missing = await checkRunGrant(undefined, claimed)
expect([expired, missing]).toEqual([
{ ok: false, reason: 'expired' },
{ ok: false, reason: 'missing' },
])
expect([acceptsRunGrant(expired), acceptsRunGrant(missing)]).toEqual([true, true])
setEnv({ MOTHERSHIP_REQUIRE_RUN_GRANT: true })
expect([acceptsRunGrant(expired), acceptsRunGrant(missing)]).toEqual([false, false])
})

it('renews a verified grant once past half its life, for the same identity only', async () => {
vi.useFakeTimers({ toFake: ['Date'] })
const issuedAt = Date.now()
vi.setSystemTime(issuedAt)
const verified = {}
rememberRunGrant(verified, await checkRunGrant(issueRunGrant(turn), claimed))
vi.setSystemTime(issuedAt + 11 * HOUR_MS)
expect(renewedRunGrant(verified)).toBeUndefined()
vi.setSystemTime(issuedAt + 13 * HOUR_MS)
const renewed = renewedRunGrant(verified)
expect(await checkRunGrant(renewed, claimed)).toMatchObject({ ok: true, identity: turn })
const unverified = {}
rememberRunGrant(unverified, await checkRunGrant(undefined, claimed))
expect(renewedRunGrant(unverified)).toBeUndefined()
})
})
Loading
Loading