From 05fe1508f21175967fed810ca1143002c7c2bdde Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 16 Nov 2026 00:58:26 -0800 Subject: [PATCH] feat(cloud): TEAM-SHARING hold sweep revokes non-owner grants (team_sharing_held); credential mode follows effective visibility once no teammate grants remain --- .../apps/sandbox-control/src/agent-sources.ts | 8 ++-- cloud/apps/sandbox-control/src/grants.ts | 35 +++++++++++++++ cloud/apps/sandbox-control/src/index.ts | 22 ++++++++-- cloud/apps/sandbox-control/src/lifecycle.ts | 5 ++- cloud/apps/sandbox-control/src/secrets.ts | 11 +++-- .../sandbox-control/src/shared-workspace.ts | 26 +++++++++++ .../test/team-sharing-hold.test.ts | 43 +++++++++++++++++++ 7 files changed, 138 insertions(+), 12 deletions(-) diff --git a/cloud/apps/sandbox-control/src/agent-sources.ts b/cloud/apps/sandbox-control/src/agent-sources.ts index ed5764361e8..df29b5aaa56 100644 --- a/cloud/apps/sandbox-control/src/agent-sources.ts +++ b/cloud/apps/sandbox-control/src/agent-sources.ts @@ -15,7 +15,8 @@ import { memberNamesFor } from './member-names' import { effectiveSecrets } from './secrets' import { getSandbox, type SandboxRow } from './store' import { agentCredentialState, isUsable } from './agent-credentials' -import { accountProvider, isSharedWorkspace } from './account-providers' +import { accountProvider } from './account-providers' +import { sharedWorkspaceMode } from './shared-workspace' export type AgentSource = 'sign-in' | 'key' type OfferAnswer = 'unanswered' | 'accepted' | 'declined' @@ -157,7 +158,7 @@ export async function agentSourcesView( owner = { userId: row.user_id, displayName: names.get(row.user_id) ?? null, isCaller: row.user_id === caller.userId } } // D13: personal accounts never apply in a workspace shared with teammates. - const sharedWorkspace = row ? isSharedWorkspace(row) : false + const sharedWorkspace = row ? await sharedWorkspaceMode(db, row) : false return { defaults, inWorkspace, workspace, effective: resolved, coveredByKey: covered, signInOffer, owner, sharedWorkspace } } @@ -236,6 +237,7 @@ export async function agentModesFor( const inWorkspace = inWorkspaceAgents(rows) const covered = coveredByKey(new Set(Object.keys(env))) const modes = {} as Record + const shared = await sharedWorkspaceMode(db, row) for (const agent of CREDENTIAL_AGENTS) { if (!workspace[agent] && inWorkspace[agent]) { // Nothing of Orca's for this agent: no placeholder, no key, no egress route, so the login the person @@ -255,7 +257,7 @@ export async function agentModesFor( } else if (!enabled) { // Kill switch (or no provider yet): the agent signs in inside the sandbox; keys stay out (Rule 3). modes[agent] = 'omit' - } else if (usable && options.accountsUsable && !isSharedWorkspace(row)) { + } else if (usable && options.accountsUsable && !shared) { modes[agent] = 'account' } else { // Expired/revoked, placeholders off, or a shared workspace (D13): the winning key, if any. diff --git a/cloud/apps/sandbox-control/src/grants.ts b/cloud/apps/sandbox-control/src/grants.ts index 34ad6b27db7..b4e87c6a426 100644 --- a/cloud/apps/sandbox-control/src/grants.ts +++ b/cloud/apps/sandbox-control/src/grants.ts @@ -7,6 +7,7 @@ // DELETE /v1/team/workspaces/:id/grants/:grantId grantee, workspace owner or org admin // Revocation removes the device from orcad's registry (orca-sandbox-revoke); while the sandbox is // not running it is queued and applied at the next boot before orcad starts. +import { teamSharingEnabled } from './team-sharing' import { z } from 'zod' import type { SandboxCaller } from './auth' import { isDeviceSessionLive } from './device-sessions' @@ -260,6 +261,40 @@ export async function revokeForAccessChange( return revokeGrants(deps, row, results, { by, reason: mode === 'non_owner' ? 'workspace_private' : 'owner_changed' }) } +/** + * TEAM-SHARING hold (team-sharing.ts): while sharing is held, a workspace stored as `team` acts private, so + * every device grant but its owner's goes, the way making it private revokes them (reason team_sharing_held). + * Transferred workspaces keep their own rules. Bounded per run; the next run takes the rest. + */ +export async function sweepHeldTeamGrants(deps: LifecycleDeps): Promise<{ workspaces: number; revoked: number; queued: number }> { + const out = { workspaces: 0, revoked: 0, queued: 0 } + if (teamSharingEnabled()) { + return out + } + const { results } = await deps.db + .prepare( + `SELECT g.* FROM workspace_grants g JOIN sandboxes s ON s.id = g.sandbox_id + WHERE g.status IN ('issuing', 'active') AND g.user_id <> s.user_id AND s.ownership_transferred_at IS NULL AND s.status <> 'destroyed' + ORDER BY g.sandbox_id LIMIT 500` + ) + .all() + const bySandbox = new Map() + for (const grant of results) { + bySandbox.set(grant.sandbox_id, [...(bySandbox.get(grant.sandbox_id) ?? []), grant]) + } + for (const [sandboxId, grants] of bySandbox) { + const row = await getSandbox(deps.db, sandboxId) + if (!row) { + continue + } + const result = await revokeGrants(deps, row, grants, { by: 'system', reason: 'team_sharing_held' }).catch(() => ({ revoked: 0, queued: 0 })) + out.workspaces++ + out.revoked += result.revoked + out.queued += result.queued + } + return out +} + /** A member left the org (auth push) or a phone session ended (W8): revoke everywhere. */ async function revokeWhere(deps: LifecycleDeps, where: string, binds: (string | number)[], audit: { by: string; reason: string }) { const { results } = await deps.db diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 42790d76d40..625f12a436a 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -138,7 +138,8 @@ import { pushCredentialToSandbox, refreshAfterSecretChange, refreshSandboxEnv } import { credentialPushTargets, markCredentialChanged, pushCredentialChange, pushPendingCredentialChanges, type CredentialChange, type PushDeps } from './credential-outbox' import { markExpiredAccountCredentials, refreshGitHubUserTokens } from './credential-refresh' import type { CredentialAgent } from './agent-credential-names' -import { ACCOUNT_PROVIDERS, accountProvider, claudeAccount, isSharedWorkspace } from './account-providers' +import { ACCOUNT_PROVIDERS, accountProvider, claudeAccount } from './account-providers' +import { sharedWorkspaceMode } from './shared-workspace' import { handleAccountRequestSucceeded, handleAccountUnauthorized, runScheduledAccountChecks, verifyAccountCredential } from './agent-credential-checks' import { codexBrokerTick, handleCodexBrokerRoute, type BrokerDeps } from './codex-broker' import { codexAccount, parseStoredCodex, refreshCodexLeases, storeCodexLogin } from './codex-credentials' @@ -208,7 +209,8 @@ import { recordOwnerDeviceForCreate, revokeForAccessChange, revokeGrantsForDeviceSession, - revokeOne + revokeOne, + sweepHeldTeamGrants } from './grants' import { getOrgPrompts, putOrgPrompts } from './org-prompts' import { @@ -476,7 +478,7 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) => scheduleEnvRefresh(env, deps, row) return signedOut('account_owner_changed') } - if (isSharedWorkspace(row)) { + if (await sharedWorkspaceMode(env.SANDBOX_DB, row)) { scheduleEnvRefresh(env, deps, row) return signedOut('account_not_shared') } @@ -2801,6 +2803,9 @@ function errorResponse(error: unknown): Response { return fail('internal_error', 500) } +/** TEAM-SHARING hold: whether this isolate has run the held-grants sweep yet (a value, never a promise). */ +let heldSweepRan = false + export default { fetch(request: Request, env: Env, ctx: ExecutionContext): Promise { return handleRequest(request, env, { waitUntil: (work) => ctx.waitUntil(work.catch(() => undefined)) }) @@ -2837,6 +2842,17 @@ export default { ) const fifthMinute = new Date(controller.scheduledTime).getUTCMinutes() % 5 === 0 ctx.waitUntil(credentialTick(env, fifthMinute)) + // TEAM-SHARING hold: every fifth minute, and on an isolate's first run (so right after a deploy). + if (!teamSharingEnabled() && (fifthMinute || !heldSweepRan)) { + heldSweepRan = true + ctx.waitUntil( + lifecycleDeps(env, {}).then(async (life) => { + const swept = life ? await sweepHeldTeamGrants(life).catch(() => null) : null + // Counts only. + console.log(JSON.stringify({ event: 'team_sharing_held_sweep', ...(swept ?? { failed: true }) })) + }) + ) + } if (env.AGENT_ACCOUNTS_CODEX === 'on') { ctx.waitUntil(codexTick(env, fifthMinute)) } diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index eeebbd6fde0..fae7f5108f7 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -8,7 +8,7 @@ import { codexPlaceholder } from './codex-credentials' /** Where Codex refreshes its ChatGPT login. */ export const CODEX_AUTH_HOST = 'auth.openai.com' import { parseStoredCodex } from './codex-credentials' -import { isSharedWorkspace } from './shared-workspace' +import { sharedWorkspaceMode } from './shared-workspace' import { deleteAgentSourcesForSandbox } from './agent-sources' import { signOutAgentsBeforeDelete } from './agent-signout' import type { EntitlementClient, MachineSize } from './entitlements' @@ -429,11 +429,12 @@ export async function firewallInputsFor(deps: LifecycleDeps, row: SandboxRow): P } const keyring = deps.secrets.keyring const accounts: FirewallAccount[] = [] + const shared = await sharedWorkspaceMode(deps.db, row) for (const route of egressAccountRoutes(row)) { if (!classes.has(route.agent)) { continue } - const applies = route.owner === row.user_id && !isSharedWorkspace(row) && Boolean(deps.secrets.accountProviders?.[route.agent]) + const applies = route.owner === row.user_id && !shared && Boolean(deps.secrets.accountProviders?.[route.agent]) const stored = applies ? await readUsableAgentCredential(deps.db, keyring, row.user_id, route.agent, deps.now()).catch(() => null) : null if (route.agent === 'codex') { const tokens = stored ? parseStoredCodex(stored) : null diff --git a/cloud/apps/sandbox-control/src/secrets.ts b/cloud/apps/sandbox-control/src/secrets.ts index 2d15240032f..b3c3f575638 100644 --- a/cloud/apps/sandbox-control/src/secrets.ts +++ b/cloud/apps/sandbox-control/src/secrets.ts @@ -13,7 +13,7 @@ import { createKeyring, type Keyring, type SealFormat, type SecretBinding } from import { createKekUnwrapper, SecretsKmsError } from './secrets-kms' import { AUTH_IAT_BACKDATE_MS } from './member-changes' import { BASE_URL_NAMES, baseUrlHost } from './provider-env' -import { isSharedWorkspace } from './shared-workspace' +import { isSharedWorkspace, sharedWorkspaceMode } from './shared-workspace' import type { SandboxRow } from './store' import { secretLog } from './secret-log' import { @@ -196,12 +196,15 @@ function repoOwner(accountId: string, repo: string): string { * never its owner's personal ones, the same rule as personal accounts (D13). Fails closed: only a row * known to be private counts as unshared. */ -export function ownersForSandbox(row: Pick) { +export function ownersForSandbox( + row: Pick, + shared: boolean = isSharedWorkspace(row) +) { const repo = normalizeRepo(row.repo_url) return { org: ORG_ACCOUNT.test(row.account_id) ? row.account_id : null, // The one definition of "shared" (visibility, or ever transferred to another owner). - personal: isSharedWorkspace(row) ? null : personalOwner(row.user_id, row.account_id.startsWith('dev:')), + personal: shared ? null : personalOwner(row.user_id, row.account_id.startsWith('dev:')), repo: repo ? repoOwner(row.account_id, repo) : null } } @@ -362,7 +365,7 @@ export async function resolveSandboxSecrets( keyring: Keyring, row: Pick ): Promise { - const owners = ownersForSandbox(row) + const owners = ownersForSandbox(row, await sharedWorkspaceMode(db, row)) const pairs: [SecretScope, string][] = [] if (owners.personal) { pairs.push(['personal', owners.personal]) diff --git a/cloud/apps/sandbox-control/src/shared-workspace.ts b/cloud/apps/sandbox-control/src/shared-workspace.ts index 8fc679ec56d..e9ecb4aefd6 100644 --- a/cloud/apps/sandbox-control/src/shared-workspace.ts +++ b/cloud/apps/sandbox-control/src/shared-workspace.ts @@ -1,6 +1,7 @@ // What counts as a shared workspace when deciding whose credentials a session may carry. One // definition, used by secrets, agent accounts, the egress proxy and the member git rules. import type { SandboxRow } from './store' +import { teamSharingEnabled } from './team-sharing' /** * D13: a workspace shared with teammates never uses a personal account. Fails closed: only a row @@ -12,3 +13,28 @@ import type { SandboxRow } from './store' export function isSharedWorkspace(row: Pick): boolean { return row.visibility !== 'private' || row.ownership_transferred_at != null } + +/** + * The rule above, precisely, for callers that can read the database (all of them today). TEAM-SHARING hold: a + * workspace stored as `team` acts private while sharing is held, but keeps shared mode until no one but its + * owner holds a device grant on it (the hold's sweep revokes them, grants.ts sweepHeldTeamGrants): personal + * credentials never reach a VM a teammate may still be paired to. Fails closed on a failed read. + */ +export async function sharedWorkspaceMode( + db: D1Database, + row: Pick +): Promise { + if (row.ownership_transferred_at != null || row.visibility === 'private') { + return row.ownership_transferred_at != null + } + if (teamSharingEnabled() || row.visibility !== 'team') { + return true + } + const others = await db + .prepare(`SELECT COUNT(*) AS n FROM workspace_grants WHERE sandbox_id = ? AND user_id <> ? AND status IN ('issuing', 'active', 'revoking')`) + .bind(row.id, row.user_id) + .first<{ n: number }>() + .catch(() => null) + return !others || others.n > 0 +} + diff --git a/cloud/apps/sandbox-control/test/team-sharing-hold.test.ts b/cloud/apps/sandbox-control/test/team-sharing-hold.test.ts index d23c7c2294f..2411b5867bf 100644 --- a/cloud/apps/sandbox-control/test/team-sharing-hold.test.ts +++ b/cloud/apps/sandbox-control/test/team-sharing-hold.test.ts @@ -2,6 +2,12 @@ // workspace already stored as `team` acts private everywhere (owner only, plus org admins' metadata). import { describe, expect, it } from 'vitest' import { generateGrantRecipientKey } from '../../../../src/main/cloud-workspaces/sealed-grant-node' +import { sweepHeldTeamGrants } from '../src/grants' +import { lifecycleDeps } from '../src/index' +import { resolveSandboxSecrets } from '../src/secrets' +import { sharedWorkspaceMode } from '../src/shared-workspace' +import { getSandbox } from '../src/store' +import { configureTeamSharing } from '../src/team-sharing' import { createHarness } from './harness' async function held(teamSharing: 'off' | undefined = 'off') { @@ -70,4 +76,41 @@ describe('TEAM_SHARING held (the default)', () => { expect(list.body.teamSharing).toBe(true) expect(list.body.workspaces.map((w: { id: string; visibility: string }) => [w.id, w.visibility])).toEqual([[created.body.sandbox.id, 'team']]) }) + + it('the sweep revokes teammates’ grants on a held team workspace; credentials stay shared until it has', async () => { + // Shared while sharing was on: Bob holds a device grant. + const h = await createHarness({ SECRETS_KEK: Buffer.alloc(32, 7).toString('base64') }) + const alice = await h.token('alice', 'acme', 'sandbox', { org_role: 'member' }) + const created = await h.call('POST', '/v1/sandboxes', { + bearer: alice, + body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' } + }) + const id = created.body.sandbox.id as string + const grant = await h.call('POST', `/v1/team/workspaces/${id}/grants`, { + bearer: await h.token('bob', 'acme', 'sandbox', { org_role: 'member' }), + body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: 'b', deviceKind: 'desktop' } + }) + expect(grant.status).toBe(200) + // Now held. + h.env.TEAM_SHARING = undefined + configureTeamSharing(h.env) + const db = h.env.SANDBOX_DB + const row = (await getSandbox(db, id))! + // Bob's grant is still active: shared mode (no personal credentials), though it acts private. + expect(await sharedWorkspaceMode(db, row)).toBe(true) + expect((await h.call('PUT', '/v1/secrets/personal/MY_TOKEN', { bearer: alice, body: { value: 'personal-value' } })).status).toBe(200) + const life = (await lifecycleDeps(h.env, h.deps))! + const keyring = await life.secrets!.keyring + expect((await resolveSandboxSecrets(db, keyring, row)).env.MY_TOKEN).toBeUndefined() + expect(await sweepHeldTeamGrants(life)).toEqual({ workspaces: 1, revoked: 1, queued: 0 }) + expect(h.raw.prepare('SELECT status, revoke_reason FROM workspace_grants WHERE user_id = ?').get('bob')).toEqual({ status: 'revoked', revoke_reason: 'team_sharing_held' }) + // Cleared: it is the owner's alone, so it acts private for credentials too. + expect(await sharedWorkspaceMode(db, row)).toBe(false) + expect((await resolveSandboxSecrets(db, keyring, row)).env.MY_TOKEN).toBe('personal-value') + // Nothing left to sweep; and with sharing on again, nothing is swept at all. + expect(await sweepHeldTeamGrants(life)).toEqual({ workspaces: 0, revoked: 0, queued: 0 }) + configureTeamSharing({ TEAM_SHARING: 'on' }) + expect(await sharedWorkspaceMode(db, row)).toBe(true) + }) }) +