From 79781e805c7dbac412ff4e8a67dd0d6fd263fcbd Mon Sep 17 00:00:00 2001 From: Neil Date: Mon, 16 Nov 2026 00:50:25 -0800 Subject: [PATCH] feat(cloud): TEAM-SHARING hold: TEAM_SHARING (default off) refuses sharing with the team and makes stored team workspaces act private --- cloud/apps/sandbox-control/src/env.ts | 2 + cloud/apps/sandbox-control/src/index.ts | 3 + cloud/apps/sandbox-control/src/lifecycle.ts | 6 +- .../sandbox-control/src/read-snapshots.ts | 7 +- .../apps/sandbox-control/src/team-sharing.ts | 21 ++++++ .../sandbox-control/src/workspace-follows.ts | 3 +- cloud/apps/sandbox-control/src/workspaces.ts | 12 ++- cloud/apps/sandbox-control/test/harness.ts | 2 + .../test/team-sharing-hold.test.ts | 73 +++++++++++++++++++ 9 files changed, 121 insertions(+), 8 deletions(-) create mode 100644 cloud/apps/sandbox-control/src/team-sharing.ts create mode 100644 cloud/apps/sandbox-control/test/team-sharing-hold.test.ts diff --git a/cloud/apps/sandbox-control/src/env.ts b/cloud/apps/sandbox-control/src/env.ts index 9f346eed413..36aecdc7638 100644 --- a/cloud/apps/sandbox-control/src/env.ts +++ b/cloud/apps/sandbox-control/src/env.ts @@ -41,6 +41,8 @@ export type Env = { /** GH-AS-MEMBER: how long a shared workspace's latest sender keeps acting after their last send (default 60; `0`: no cap). */ MEMBER_GIT_SHARED_MAX_MINUTES?: string /** GH-AS-MEMBER: `on` lets gh in workspaces act as the attested sender (off by default). */ + /** TEAM-SHARING hold (team-sharing.ts): `on` lets workspaces be shared with the team; anything else holds it. */ + TEAM_SHARING?: string GH_AS_MEMBER?: string /** * Who sees a member's daily activity heatmap on their profile. `opt_in` (default): only members diff --git a/cloud/apps/sandbox-control/src/index.ts b/cloud/apps/sandbox-control/src/index.ts index 9640ce772b2..42790d76d40 100644 --- a/cloud/apps/sandbox-control/src/index.ts +++ b/cloud/apps/sandbox-control/src/index.ts @@ -39,6 +39,7 @@ // Operator (OPERATOR_TOKEN): /v1/internal/* (see operator.ts) // Public share links (src/share-gateway.ts): /s//*, plus the root-path cookie fallback // Vercel network-policy forwardURL target (Vercel sandbox OIDC): /v1/egress/proxy +import { configureTeamSharing, teamSharingEnabled } from './team-sharing' import { purgeTeamSecrets, teamDeleteRoute, teamWorkspaceCount } from './team-delete' import { ReadSnapshotRouteError, getReadSnapshot, handleReaderKeysRoute, pruneReadSnapshotToOwner, revokeDeviceSessionReaderKeys } from './read-snapshots' import { refreshEnvironment, refreshStaleEnvironments, type GoldenRefreshOptions } from './environment-golden-refresh' @@ -1355,6 +1356,7 @@ async function shareGateway(request: Request, url: URL, env: Env, deps: Deps): P } export async function handleRequest(request: Request, env: Env, deps: Deps = {}): Promise { + configureTeamSharing(env) try { return await routeRequest(request, env, deps) } catch (error) { @@ -2804,6 +2806,7 @@ export default { return handleRequest(request, env, { waitUntil: (work) => ctx.waitUntil(work.catch(() => undefined)) }) }, async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise { + configureTeamSharing(env) // Every minute: routines (schedule slots, run polling). Every fifth minute: everything else. ctx.waitUntil( lifecycleDeps(env, {}).then(async (life) => { diff --git a/cloud/apps/sandbox-control/src/lifecycle.ts b/cloud/apps/sandbox-control/src/lifecycle.ts index aaa6aa6b0c3..eeebbd6fde0 100644 --- a/cloud/apps/sandbox-control/src/lifecycle.ts +++ b/cloud/apps/sandbox-control/src/lifecycle.ts @@ -1,5 +1,6 @@ // Sandbox lifecycle: one persistent provider sandbox per Orca workspace, with an Orca-owned lease, // a forced stop before the provider's 24h cap, usage metering and write-ahead rows. +import { teamSharingEnabled } from './team-sharing' import { accountProvider } from './account-providers' import { readUsableAgentCredential } from './agent-credentials' import { CODEX_FIREWALL_ALL_PATHS, CODEX_FIREWALL_PATHS } from './codex-paths' @@ -1438,8 +1439,9 @@ export async function createSandbox( source_snapshot_id: bootSnapshotId, repo_branch: request.repo?.ref ?? null, name: request.title ?? null, - // A personal account has no team: its workspaces are always private. - visibility: request.visibility === 'team' && caller.accountId.includes('org:') ? 'team' : 'private', + // A personal account has no team: its workspaces are always private. So is every one while team sharing + // is held (team-sharing.ts). + visibility: request.visibility === 'team' && caller.accountId.includes('org:') && teamSharingEnabled() ? 'team' : 'private', section: request.section ?? null, ownership_transferred_at: request.ownershipTransferredAt ?? null }, diff --git a/cloud/apps/sandbox-control/src/read-snapshots.ts b/cloud/apps/sandbox-control/src/read-snapshots.ts index f422767f59a..3b2cedae064 100644 --- a/cloud/apps/sandbox-control/src/read-snapshots.ts +++ b/cloud/apps/sandbox-control/src/read-snapshots.ts @@ -9,6 +9,7 @@ // the control plane at runtime chooses the recipient keys and drives the VM, so it is trusted not to // add its own key (same as relaying grant keys). Access mirrors canOpen at read time, and pruning // (removal, private, revoke) deletes wrapped keys at once, without the VM. +import { effectiveVisibility } from './team-sharing' import { z } from 'zod' import type { SandboxCaller } from './auth' import { ensureEntryPoints } from './golden-images' @@ -202,7 +203,7 @@ export async function readerKeysFor(db: D1Database, row: SandboxRow, now: number if (row.archived_at !== null) { return [] } - const team = row.visibility === 'team' + const team = effectiveVisibility(row) === 'team' const { results } = await db .prepare( `SELECT k.id, k.public_key FROM reader_keys k @@ -340,7 +341,7 @@ export async function captureReadSnapshot(deps: LifecycleDeps, row: SandboxRow, await deps.db.batch(statements) // The workspace may have been made private while sealing: re-apply the current rule. const current = await deps.db.prepare('SELECT * FROM sandboxes WHERE id = ?').bind(row.id).first() - if (current && current.visibility !== 'team') { + if (current && effectiveVisibility(current) !== 'team') { await pruneReadSnapshotToOwner(deps.db, current) } return done({ @@ -387,7 +388,7 @@ export async function readSnapshotTimes(db: D1Database, ids: readonly string[]): export async function getReadSnapshot(db: D1Database, caller: SandboxCaller, row: SandboxRow, keyId: string | null, now: number) { // Belt and braces over canOpen: a private workspace's snapshot opens only for its owner. - if (!canOpen(caller, row) || (row.visibility !== 'team' && !isOwner(caller, row))) { + if (!canOpen(caller, row) || (effectiveVisibility(row) !== 'team' && !isOwner(caller, row))) { throw new WorkspaceError('not_found') } if (!keyId || !KEY_ID.test(keyId)) { diff --git a/cloud/apps/sandbox-control/src/team-sharing.ts b/cloud/apps/sandbox-control/src/team-sharing.ts new file mode 100644 index 00000000000..6b83a46c540 --- /dev/null +++ b/cloud/apps/sandbox-control/src/team-sharing.ts @@ -0,0 +1,21 @@ +// TEAM-SHARING hold: team workspace sharing ships in a later release. TEAM_SHARING=on turns it on; anything else +// (the default) holds it. While held, a workspace stored as `team` acts private everywhere access is decided +// (owner only, plus org admins' metadata as before): the column and its data stay, so turning it on restores +// each workspace's own setting. Set from the Worker's env at the start of every request and scheduled run (the +// same value for the whole isolate: no per-request state). +import type { SandboxRow } from './store' + +let enabled = false + +export function configureTeamSharing(env: { TEAM_SHARING?: string }): void { + enabled = env.TEAM_SHARING === 'on' +} + +export function teamSharingEnabled(): boolean { + return enabled +} + +/** The visibility access rules use: the stored one with sharing on, else always private. */ +export function effectiveVisibility(row: Pick): 'private' | 'team' { + return enabled && row.visibility === 'team' ? 'team' : 'private' +} diff --git a/cloud/apps/sandbox-control/src/workspace-follows.ts b/cloud/apps/sandbox-control/src/workspace-follows.ts index 77c494d0716..aec5435a764 100644 --- a/cloud/apps/sandbox-control/src/workspace-follows.ts +++ b/cloud/apps/sandbox-control/src/workspace-follows.ts @@ -6,6 +6,7 @@ // visible to the whole team). A private workspace's only viewer is its owner, so a teammate's old // follow of a workspace that turned private is never shown and never counts. Archived workspaces // may still be followed: they stay browsable. +import { effectiveVisibility } from './team-sharing' import type { SandboxCaller } from './auth' import type { SandboxRow } from './store' @@ -42,7 +43,7 @@ export function visibleFollowers( if (!seen) { return [] } - return row.visibility === 'team' ? [...followers] : followers.filter((id) => id === row.user_id) + return effectiveVisibility(row) === 'team' ? [...followers] : followers.filter((id) => id === row.user_id) } /** The caller must be able to see the row (the route checks canSee first). */ diff --git a/cloud/apps/sandbox-control/src/workspaces.ts b/cloud/apps/sandbox-control/src/workspaces.ts index 11e593c4ea1..84a92810ccc 100644 --- a/cloud/apps/sandbox-control/src/workspaces.ts +++ b/cloud/apps/sandbox-control/src/workspaces.ts @@ -9,6 +9,7 @@ // Access rule: a workspace is visible to its owner, and to every member of the owning org when // visibility is `team`. Org owners/admins additionally see private rows' metadata (scope=all) so a // departed member's workspaces can be reassigned or archived — metadata only, never access. +import { effectiveVisibility, teamSharingEnabled } from './team-sharing' import { githubActingViews, type GithubActingOptions, type GithubActingView } from './git-actor' import type { TeamMembershipCheck } from './team-membership' import { z } from 'zod' @@ -63,7 +64,7 @@ export function canSee(caller: SandboxCaller, row: SandboxRow): boolean { if (row.account_id !== caller.accountId || row.status === 'destroyed') { return false } - return row.user_id === caller.userId || (row.visibility === 'team' && caller.orgId !== undefined) + return row.user_id === caller.userId || (effectiveVisibility(row) === 'team' && caller.orgId !== undefined) } /** Can the caller pair a device with it (grant) or keep it awake (lease)? */ @@ -231,7 +232,8 @@ export async function workspaceViews( // The link to copy: org slug + number when both exist, else the sandbox id form. link: workspaceLink(row, slug), repo: repoView(row), - visibility: row.visibility, + // TEAM-SHARING hold: what access actually follows (stored `team` reads private while held). + visibility: effectiveVisibility(row), section: row.section, archivedAt: row.archived_at, createdBy: row.created_by ?? row.user_id, @@ -315,6 +317,8 @@ export async function listWorkspaces(db: D1Database, caller: SandboxCaller, url: ]) return { workspaces: views.map((view, i) => ({ ...view, routineName: routineNames.get(rows[i]!.id) ?? null })), + // TEAM-SHARING hold: whether workspaces can be shared with the team on this control plane (older ones omit it). + teamSharing: teamSharingEnabled(), // Home: offer the Routine runs switch only when the team has routines, and say what it hides // (its count and hours still belong in the team's totals). routineRuns: { @@ -393,6 +397,10 @@ export async function patchWorkspace( if (patch.archived === true) { throw new WorkspaceError('invalid_request', 'archive_via_lifecycle') } + if (patch.visibility === 'team' && !teamSharingEnabled()) { + // TEAM-SHARING hold (team-sharing.ts): sharing with the team isn't available yet. + throw new WorkspaceError('invalid_request', 'team_sharing_unavailable') + } if (patch.visibility === 'team' && !row.account_id.includes('org:')) { // A personal account has no team to share with. throw new WorkspaceError('invalid_request', 'personal_account') diff --git a/cloud/apps/sandbox-control/test/harness.ts b/cloud/apps/sandbox-control/test/harness.ts index 82f28179479..cf1a90fad23 100644 --- a/cloud/apps/sandbox-control/test/harness.ts +++ b/cloud/apps/sandbox-control/test/harness.ts @@ -61,6 +61,8 @@ export async function createHarness(overrides: Partial = {}, extraDeps: Par VERCEL_PROJECT_ID: 'prj_orca', // Off unless a test turns it on (auto-environments.test.ts): it starts builds behind creates. AUTO_ENVIRONMENTS: 'off', + // Team sharing is on for the suite (its behavior is what most team tests cover); test/team-sharing-hold.test.ts holds it. + TEAM_SHARING: 'on', ...overrides } // No live github.com from tests: repos count as public unless a test says otherwise. diff --git a/cloud/apps/sandbox-control/test/team-sharing-hold.test.ts b/cloud/apps/sandbox-control/test/team-sharing-hold.test.ts new file mode 100644 index 00000000000..d23c7c2294f --- /dev/null +++ b/cloud/apps/sandbox-control/test/team-sharing-hold.test.ts @@ -0,0 +1,73 @@ +// TEAM-SHARING hold (team-sharing.ts): with TEAM_SHARING off, nothing can be shared with the team, and a +// 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 { createHarness } from './harness' + +async function held(teamSharing: 'off' | undefined = 'off') { + const h = await createHarness({ PUBLIC_API_URL: 'https://api.test', ...(teamSharing ? { TEAM_SHARING: teamSharing } : { TEAM_SHARING: undefined }) }) + const token = (sub: string, role: 'member' | 'admin' = 'member') => h.token(sub, 'acme', 'sandbox', { org_role: role }) + const created = await h.call('POST', '/v1/sandboxes', { + bearer: await token('alice'), + body: { workspaceId: 'ws-1', machineSize: 'standard', title: 'Fix login', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' } + }) + expect(created.status).toBe(200) + return { h, token, id: created.body.sandbox.id as string } +} + +describe('TEAM_SHARING held (the default)', () => { + it('a create asking for team is private, a PATCH to team is refused, and the list says sharing is off', async () => { + for (const setting of ['off', undefined] as const) { + const t = await held(setting) + expect(t.h.raw.prepare('SELECT visibility FROM sandboxes WHERE id = ?').get(t.id)).toEqual({ visibility: 'private' }) + const patch = await t.h.call('PATCH', `/v1/team/workspaces/${t.id}`, { bearer: await t.token('alice'), body: { visibility: 'team' } }) + expect(patch.status).toBe(400) + expect(patch.body).toEqual({ error: 'invalid_request', reason: 'team_sharing_unavailable' }) + const list = await t.h.call('GET', '/v1/team/workspaces', { bearer: await t.token('alice') }) + expect(list.body.teamSharing).toBe(false) + // Other edits still work, and making it private is always allowed. + expect((await t.h.call('PATCH', `/v1/team/workspaces/${t.id}`, { bearer: await t.token('alice'), body: { visibility: 'private', section: 'Auth' } })).status).toBe(200) + } + }) + + it('a workspace already stored as team acts private: owner only, admins see metadata, teammates nothing', async () => { + const t = await held() + t.h.raw.prepare("UPDATE sandboxes SET visibility = 'team' WHERE id = ?").run(t.id) + const bob = await t.token('bob') + // Team registry: not listed, not addressable, no grant, no follow. + expect((await t.h.call('GET', '/v1/team/workspaces?scope=team', { bearer: bob })).body.workspaces).toEqual([]) + expect((await t.h.call('GET', `/v1/team/workspaces/${t.id}`, { bearer: bob })).status).toBe(404) + const grant = await t.h.call('POST', `/v1/team/workspaces/${t.id}/grants`, { + bearer: bob, + body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: 'b', deviceKind: 'desktop' } + }) + expect(grant.status).toBe(404) + expect((await t.h.call('PUT', `/v1/team/workspaces/${t.id}/follow`, { bearer: bob })).status).toBe(404) + // Public API and MCP's rule (api/access.ts): nothing for a teammate. + expect((await t.h.call('GET', '/v1/workspaces', { bearer: bob })).body.workspaces).toEqual([]) + expect((await t.h.call('GET', `/v1/workspaces/${t.id}`, { bearer: bob })).status).toBe(404) + expect((await t.h.call('POST', `/v1/workspaces/${t.id}/messages`, { bearer: bob, body: { text: 'hi' } })).status).toBe(404) + // The owner sees it as private (what access follows); the stored value is kept for when sharing ships. + const own = await t.h.call('GET', `/v1/team/workspaces/${t.id}`, { bearer: await t.token('alice') }) + expect(own.body.workspace).toMatchObject({ visibility: 'private', access: 'owner' }) + expect(t.h.raw.prepare('SELECT visibility FROM sandboxes WHERE id = ?').get(t.id)).toEqual({ visibility: 'team' }) + // An admin keeps today's management view (scope=all metadata), not the teammate view. + const admin = await t.token('carol', 'admin') + const all = await t.h.call('GET', '/v1/team/workspaces?scope=all', { bearer: admin }) + expect(all.body.workspaces.map((w: { id: string; visibility: string; access: string }) => [w.id, w.visibility, w.access])).toEqual([[t.id, 'private', 'none']]) + expect((await t.h.call('GET', '/v1/team/workspaces?scope=team', { bearer: admin })).body.workspaces).toEqual([]) + }) + + it('TEAM_SHARING=on restores each workspace’s own setting', async () => { + const h = await createHarness() + 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 bob = await h.token('bob', 'acme', 'sandbox', { org_role: 'member' }) + const list = await h.call('GET', '/v1/team/workspaces?scope=team', { bearer: bob }) + 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']]) + }) +})