Merge pull request #822 from nwparker/cloud/gh-solo-member

fix(cloud): solo workspace gh/git act as the member without an attested sender (orca-plugins#89 bot-authored PR)
This commit is contained in:
Neil
2026-11-16 01:28:51 -08:00
committed by GitHub
9 changed files with 257 additions and 13 deletions
File diff suppressed because one or more lines are too long
@@ -9,6 +9,28 @@ set -euo pipefail
DIR=/etc/orca/members
caller="${SUDO_USER:-}"
case "$caller" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac
# Hands the caller a one-shot copy of a member's git config (owned by them, removed by orca-git-as).
emit() {
local file
file="$DIR/$(printf '%s' "$1" | tr ':' '_').gitconfig"
[ -s "$file" ] || exit 3
out="$(sudo -u "$caller" mktemp)"
cat "$file" >"$out"
echo "$out"
exit 0
}
# GH-SOLO: a workspace only one person can use (the control plane's rule, member-git.ts pickActing) acts as that
# person whoever typed: a TUI typed into directly has no attested sender. The control plane writes `solo` only
# while that holds, and removes it before any other member's device is paired (grants.ts).
if [ -s "$DIR/solo" ]; then
solo="$(cat "$DIR/solo")"
case "$solo" in '' | *[!A-Za-z0-9_.:-]*) exit 3 ;; esac
if [ -n "${ORCA_GIT_AS:-}" ] && [ "$ORCA_GIT_AS" != "$solo" ]; then
echo "orca-git-as: only $solo uses this workspace, not $ORCA_GIT_AS; refusing to push as someone else." >&2
exit 4
fi
emit "$solo"
fi
# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).
orcad_pid="$(pgrep -u "$caller" -f orcad-server.js | head -n 1 || true)"
[ -n "$orcad_pid" ] || exit 3
@@ -42,9 +64,4 @@ if [ -n "${ORCA_GIT_AS:-}" ] && [ "$ORCA_GIT_AS" != "$member" ]; then
echo "orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else." >&2
exit 4
fi
file="$DIR/$(printf '%s' "$member" | tr ':' '_').gitconfig"
[ -s "$file" ] || exit 3
# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).
out="$(sudo -u "$caller" mktemp)"
cat "$file" >"$out"
echo "$out"
emit "$member"
@@ -51,6 +51,15 @@ done < <(jq -c '.[]' <<<"$coauthors")
DEVICES_JQ='add | [.[] | select(.userId | test("^[A-Za-z0-9_.:-]+$")) | .userId as $u | (.deviceIds // [])[] | select(test("^[A-Za-z0-9_-]{1,128}$")) | {key: ., value: $u}] | group_by(.key) | map(select((map(.value) | unique | length) == 1) | .[0]) | from_entries'
jq -c -s "$DEVICES_JQ" <(printf '%s' "$json") <(printf '%s' "$coauthors") >"$tmp/devices.json"
devices="$(jq 'length' "$tmp/devices.json")"
# GH-SOLO: ORCA_SOLO_MEMBER = the only person who can use this workspace (absent when shared). orca-git-identity
# then acts as them without an attested sender, matching the control plane.
solo="${ORCA_SOLO_MEMBER:-}"
solo_file=''
case "$solo" in '' | *[!A-Za-z0-9_.:-]*) solo='' ;; esac
if [ -n "$solo" ]; then
solo_file="$tmp/$(printf '%s' "$solo" | tr ':' '_').gitconfig"
if [ -s "$solo_file" ]; then printf '%s\n' "$solo" >"$tmp/solo"; else solo=''; solo_file=''; fi
fi
chmod 0700 "$tmp" && chmod 0600 "$tmp"/*
rm -rf "$DIR.old"
[ -d "$DIR" ] && mv "$DIR" "$DIR.old"
@@ -71,6 +80,21 @@ fi
user_home="$(getent passwd "$USER_NAME" | cut -d: -f6)"
[ -n "$orcad_pid" ] && user_home="$(tr '\0' '\n' <"/proc/$orcad_pid/environ" | sed -n 's/^HOME=//p' | head -n 1)"
[ -n "$user_home" ] && rm -rf "$user_home/.orca-sandbox/members"
# GH-SOLO: in a one-person workspace a plain `git commit` (no turn at all) is theirs too: the default author is
# the member's GitHub noreply identity. Marked, so a workspace that becomes shared goes back to Orca's.
if [ -n "$user_home" ]; then
as_user() { sudo -u "$USER_NAME" env HOME="$user_home" git config --global "$@"; }
solo_email="$( [ -n "$solo" ] && git config -f "$DIR/$(printf '%s' "$solo" | tr ':' '_').gitconfig" user.email 2>/dev/null || true)"
if [ -n "$solo_email" ]; then
as_user user.name "$(git config -f "$DIR/$(printf '%s' "$solo" | tr ':' '_').gitconfig" user.name)"
as_user user.email "$solo_email"
as_user orca.soloauthor true
elif [ "$(as_user --get orca.soloauthor 2>/dev/null || true)" = true ]; then
as_user user.name 'Orca'
as_user user.email 'noreply@orca.dev'
as_user --unset orca.soloauthor || true
fi
fi
# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).
if [ -n "$user_home" ]; then
sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.email >/dev/null 2>&1 \
+9 -1
View File
@@ -11,7 +11,7 @@ import { z } from 'zod'
import type { SandboxCaller } from './auth'
import { isDeviceSessionLive } from './device-sessions'
import { markRevoked, runVmRevoke, type GrantRow } from './grant-revokes'
import { LifecycleError, settleMemberGit, resumeSandbox, syncMemberGit, type LifecycleDeps, type Ready } from './lifecycle'
import { DROP_SOLO_SCRIPT, LifecycleError, settleMemberGit, resumeSandbox, syncMemberGit, type LifecycleDeps, type Ready } from './lifecycle'
import { ensureEntryPoints } from './golden-images'
import type { CommandResult } from './sandbox-provider'
import { ORCAD_PORT } from './sandbox-vm-commands'
@@ -133,6 +133,14 @@ export async function issueGrant(
.run()
let output: z.infer<typeof GrantOutputSchema>
try {
// GH-SOLO: anyone but a still-untransferred owner makes it (possibly) shared: drop the VM's one-person mark
// first, and refuse the grant if that fails (lifecycle.ts DROP_SOLO_SCRIPT).
if (caller.userId !== row.user_id || row.ownership_transferred_at != null) {
const dropped = await deps.provider.runCommand(live.sessionId, { command: 'bash', args: ['-c', DROP_SOLO_SCRIPT], sudo: true, timeoutMs: 15_000 })
if (dropped.exitCode !== 0) {
throw new Error(`drop_solo_exit_${dropped.exitCode}`)
}
}
const result = await withEntryPoints(deps, live.sessionId, GRANT_COMMAND, () =>
deps.provider.runCommand(live.sessionId, {
command: GRANT_COMMAND,
+20 -2
View File
@@ -25,7 +25,7 @@ import { applyQueuedRevokes } from './grant-revokes'
import { ENTRY_POINTS_PROBE, ensureEntryPoints, entryPointsBehind, installEntryPoints, parseEntryPointsProbe } from './golden-images'
import { RUNTIME_REFRESH_SCRIPT, type RuntimeBundle } from './runtime-bundles'
import { memberPlaceholder, type MemberGitIdentity } from './github-user-tokens'
import { connectedMembers, memberCoauthors, memberGitConfigs } from './member-git'
import { connectedMembers, memberCoauthors, memberGitConfigs, soloMember } from './member-git'
import type { RetentionConfig } from './retention'
import { ProviderError, type ProviderSandboxState, type SandboxProviderApi } from './sandbox-provider'
import { egressAccountRoutes, egressSecretHosts, placeholderValues, secretPlaceholder, type SecretEgressHost } from './secret-egress'
@@ -1245,23 +1245,41 @@ export async function syncMemberGit(deps: LifecycleDeps, row: SandboxRow, sessio
}
}
/**
* GH-SOLO: before another person's device is paired, the VM stops treating the workspace as one person's
* (orca-git-identity would otherwise act as the owner for that device's agents too). The members sync after
* the grant writes it back if it still holds.
*/
export const DROP_SOLO_SCRIPT = 'rm -f /etc/orca/members/solo'
/** Throws when the VM did not take the identities; on success the VM's setup reads ready. */
async function installMemberGit(deps: LifecycleDeps, row: SandboxRow, sessionId: string): Promise<number> {
await ensureEntryPoints(deps, sessionId)
await refreshGitCredentials(deps, row, sessionId)
const configs = await memberGitConfigs({ db: deps.db, identity: deps.memberIdentity! }, row)
const coauthors = await memberCoauthors(deps.db, row, new Set(configs.map((config) => config.userId)))
// GH-SOLO: the only person who can use the workspace acts as themselves in the VM with no attested sender
// (a TUI typed into directly has none), as the egress proxy already allows (memberMayAct).
const solo = await soloMember(deps.db, row)
const encode = (value: unknown) => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(value))))
const result = await deps.provider.runCommand(sessionId, {
command: MEMBERS_COMMAND,
// GIT-COAUTHOR: a separate variable, which an image's older members script simply ignores.
env: { ORCA_MEMBERS_B64: encode(configs), ORCA_COAUTHORS_B64: encode(coauthors) },
env: { ORCA_MEMBERS_B64: encode(configs), ORCA_COAUTHORS_B64: encode(coauthors), ...(solo ? { ORCA_SOLO_MEMBER: solo } : {}) },
sudo: true,
timeoutMs: 30_000
})
if (result.exitCode !== 0) {
throw new Error(`members_exit_${result.exitCode}`)
}
// GH-SOLO: a grant may have started between the read above and the VM write (it drops the mark first, and
// this write could have put it back). Re-check now; if it no longer holds, drop it, failing closed.
if (solo && (await soloMember(deps.db, row)) !== solo) {
const dropped = await deps.provider.runCommand(sessionId, { command: 'bash', args: ['-c', DROP_SOLO_SCRIPT], sudo: true, timeoutMs: 15_000 })
if (dropped.exitCode !== 0) {
throw new Error(`drop_solo_exit_${dropped.exitCode}`)
}
}
if (row.git_setup_failed_at) {
await deps.db.prepare('UPDATE sandboxes SET git_setup_failed_at = NULL WHERE id = ?').bind(row.id).run()
}
@@ -82,6 +82,30 @@ export async function actingMember(db: D1Database, row: SandboxRow, now: number,
return pickActing(row, grantees, latest, now, sharedMaxMs)
}
/**
* GH-SOLO: the one person who can use this workspace, or null. From the people set itself (active grantees, plus
* the untransferred owner, who may have no grant row: the create's own pairing code), never from "no expiry".
* Someone else's grant still being issued or revoked (their device may be pairing, or not yet unpaired) means not
* solo.
*/
export async function soloMember(db: D1Database, row: SandboxRow): Promise<string | null> {
const { results } = await db
.prepare(`SELECT DISTINCT user_id, status FROM workspace_grants WHERE sandbox_id = ? AND status IN ('issuing', 'active', 'revoking')`)
.bind(row.id)
.all<{ user_id: string; status: string }>()
const pick = pickActing(
row,
results.filter((r) => r.status === 'active').map((r) => r.user_id),
null,
0,
null
)
if (!('userId' in pick)) {
return null
}
return results.some((r) => r.user_id !== pick.userId) ? null : pick.userId
}
export type ActingMember = { userId: string; until: number | null } | { none: 'no_send' | 'stale' }
/** The rule itself, on already-read rows (the workspace list reads them for every row in one go). */
@@ -1,5 +1,6 @@
// In-memory Vercel Sandbox with the behaviours the bake-off measured: stop = reboot from an automatic
// snapshot, resume keeps the name and route, and delete leaves automatic snapshots behind.
import { DROP_SOLO_SCRIPT } from '../src/lifecycle'
import { createCipheriv, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, randomBytes } from 'node:crypto'
import { GRANT_COMMAND } from '../src/grants'
import { REVOKE_COMMAND } from '../src/grant-revokes'
@@ -408,6 +409,10 @@ export function createFakeVercel(now: () => number): FakeVercel {
}
return { exitCode: 0, stdout: 'synced\n', stderr: '' }
}
// GH-SOLO: dropping the one-person mark before a grant (rm -f: always succeeds in a VM).
if (script === DROP_SOLO_SCRIPT) {
return { exitCode: 0, stdout: '', stderr: '' }
}
if (params.command === DRAIN_COMMAND) {
return { exitCode: 0, stdout: '', stderr: '' }
}
@@ -0,0 +1,148 @@
// GH-SOLO regression (orca-plugins#89): in a workspace only one person can use, the server acts as that person
// (memberMayAct), but the VM picked a member only from an attested sender. Codex typed into directly in a
// terminal has none, so gh and git went out as the bot. Now the VM acts as the solo member with no sender too.
import { execFileSync, spawnSync } from 'node:child_process'
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, describe, expect, it } from 'vitest'
import { generateGrantRecipientKey } from '../../../../src/main/cloud-workspaces/sealed-grant-node'
import { GRANT_COMMAND } from '../src/grants'
import { DROP_SOLO_SCRIPT, MEMBERS_COMMAND } from '../src/lifecycle'
import { soloMember } from '../src/member-git'
import { getSandbox } from '../src/store'
import { createHarness } from './harness'
const IDENTITY = fileURLToPath(new URL('../image/vm/orca-git-identity', import.meta.url).href)
const dirs: string[] = []
afterEach(() => dirs.splice(0).forEach((dir) => rmSync(dir, { recursive: true, force: true })))
/** orca-git-identity as root would run it, against a scratch members dir, with no orcad (so no attested sender). */
function identity(members: { solo?: string; files: Record<string, string> }, env: Record<string, string> = {}) {
const root = mkdtempSync(join(tmpdir(), 'orca-git-solo-'))
dirs.push(root)
const dir = join(root, 'members')
mkdirSync(dir)
mkdirSync(join(root, 'bin'))
for (const [name, email] of Object.entries(members.files)) {
execFileSync('git', ['config', '-f', join(dir, `${name}.gitconfig`), 'user.email', email])
}
if (members.solo) {
writeFileSync(join(dir, 'solo'), `${members.solo}\n`)
}
// `sudo -u <caller> mktemp` and `pgrep` stand-ins: no orcad runs here.
writeFileSync(join(root, 'bin/sudo'), '#!/usr/bin/env bash\nshift 2\nexec "$@"\n')
writeFileSync(join(root, 'bin/pgrep'), '#!/usr/bin/env bash\nexit 1\n')
chmodSync(join(root, 'bin/sudo'), 0o755)
chmodSync(join(root, 'bin/pgrep'), 0o755)
const script = join(root, 'orca-git-identity')
writeFileSync(script, readFileSync(IDENTITY, 'utf8').replace('DIR=/etc/orca/members', `DIR=${dir}`))
const run = spawnSync('bash', [script], { env: { PATH: `${join(root, 'bin')}:/usr/bin:/bin`, SUDO_USER: 'vercel-sandbox', ...env }, encoding: 'utf8' })
const out = run.stdout.trim()
return { status: run.status, stderr: run.stderr, email: run.status === 0 ? execFileSync('git', ['config', '-f', out, 'user.email'], { encoding: 'utf8' }).trim() : null }
}
describe('orca-git-identity in a one-person workspace', () => {
it('acts as the solo member with no attested sender (a TUI typed into directly)', () => {
expect(identity({ solo: 'user_neil', files: { user_neil: '1+neil@users.noreply.github.com' } })).toMatchObject({ status: 0, email: '1+neil@users.noreply.github.com' })
expect(identity({ solo: 'user_neil', files: { user_neil: '1+neil@users.noreply.github.com' } }, { ORCA_GIT_AS: 'user_neil' }).status).toBe(0)
})
it('never for anyone else, and not at all once the workspace is shared (no solo mark)', () => {
const other = identity({ solo: 'user_neil', files: { user_neil: '1+neil@users.noreply.github.com' } }, { ORCA_GIT_AS: 'user_bob' })
expect(other.status).toBe(4)
expect(identity({ files: { user_neil: '1+neil@users.noreply.github.com' } }).status).toBe(3)
// A mark naming someone with no identity installed: the workspace identity.
expect(identity({ solo: 'user_ghost', files: {} }).status).toBe(3)
})
})
const OP = 'o'.repeat(40)
const REPO = 'https://github.com/acme/app'
async function workspace(extra: Record<string, string> = {}) {
const h = await createHarness(
{ EGRESS_PROXY_URL: 'https://sandbox.test/v1/egress/proxy', SECRETS_KEK: Buffer.alloc(32, 7).toString('base64'), OPERATOR_TOKEN: OP, ...extra },
{
credentials: { authorizationFor: async () => 'Bearer ghs_app' },
github: { tokenForRepo: async () => ({ token: 'ghs_repo', expiresAt: h.now() + 3_600_000 }), installationForRepo: async () => null } as never
}
)
const as = (sub: string) => h.token(sub, 'acme', 'sandbox', { org_role: 'member' })
const created = await h.call('POST', '/v1/sandboxes', { bearer: await as('alice'), body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: REPO }, visibility: 'team' } })
const id = created.body.sandbox.id as string
const connect = (userId: string, githubUserId: number) =>
h.call('POST', '/v1/internal/dev/member-github', { bearer: OP, body: { accountId: 'org:acme', userId, repoUrl: REPO, login: `${userId}-gh`, githubUserId, name: userId } })
const grant = async (userId: string) =>
h.call('POST', `/v1/team/workspaces/${id}/grants`, {
bearer: await as(userId),
body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: userId, deviceKind: 'desktop' }
})
const syncs = () => h.vercel.commands.filter((c) => c.command === MEMBERS_COMMAND)
const restart = async () => expect((await h.call('POST', `/v1/sandboxes/${id}/restart`, { bearer: await as('alice') })).status).toBe(200)
return { h, as, id, connect, grant, syncs, restart }
}
describe('the control plane marks a workspace solo only while one person can use it', () => {
it('sends ORCA_SOLO_MEMBER for the owner alone; drops the mark before pairing anyone else, then sends none', async () => {
const t = await workspace()
await t.connect('alice', 11)
await t.restart()
expect(t.syncs().at(-1)!.env.ORCA_SOLO_MEMBER).toBe('alice')
const before = t.h.vercel.commands.length
expect((await t.grant('bob')).status).toBe(200)
const after = t.h.vercel.commands.slice(before)
const drop = after.findIndex((c) => c.command === 'bash' && c.args?.includes(DROP_SOLO_SCRIPT))
const pair = after.findIndex((c) => c.command === GRANT_COMMAND)
expect(drop).toBeGreaterThanOrEqual(0)
expect(drop).toBeLessThan(pair)
expect(t.syncs().at(-1)!.env.ORCA_SOLO_MEMBER).toBeUndefined()
})
it('review HIGH: shared with the cap off, a grantee who sent last is never marked solo (the owner has no grant row)', async () => {
const t = await workspace({ MEMBER_GIT_SHARED_MAX_MINUTES: '0' })
await t.connect('alice', 11)
await t.connect('bob', 22)
expect((await t.grant('bob')).status).toBe(200)
expect((await t.h.call('POST', `/v1/team/workspaces/${t.id}/sent`, { bearer: await t.as('bob') })).status).toBe(200)
await t.restart()
expect(t.syncs().at(-1)!.env.ORCA_SOLO_MEMBER).toBeUndefined()
expect(await soloMember(t.h.env.SANDBOX_DB, (await getSandbox(t.h.env.SANDBOX_DB, t.id))!)).toBeNull()
})
it('review medium: a grant that starts while the members write is in flight drops the mark again after it', async () => {
const t = await workspace()
await t.connect('alice', 11)
// Bob's grant row appears (issuing) between the sync's read and its VM write.
t.h.vercel.commandHandler = (params) => {
if (params.command === MEMBERS_COMMAND) {
t.h.raw
.prepare(`INSERT INTO workspace_grants (id, sandbox_id, account_id, user_id, device_kind, device_label, status, created_at) VALUES ('grt_race', ?, 'org:acme', 'bob', 'desktop', 'b', 'issuing', 1)`)
.run(t.id)
return { exitCode: 0, stdout: '{"members":1,"devices":0}\n', stderr: '' }
}
return undefined
}
const before = t.h.vercel.commands.length
await t.restart()
const after = t.h.vercel.commands.slice(before)
const write = after.findIndex((c) => c.command === MEMBERS_COMMAND && c.env.ORCA_SOLO_MEMBER === 'alice')
const drop = after.findIndex((c, i) => i > write && c.command === 'bash' && c.args?.includes(DROP_SOLO_SCRIPT))
expect(write).toBeGreaterThanOrEqual(0)
expect(drop).toBeGreaterThan(write)
})
it('a teammate whose grant is still being revoked (device not yet unpaired) keeps it from being solo', async () => {
const t = await workspace()
await t.connect('alice', 11)
t.h.raw
.prepare(`INSERT INTO workspace_grants (id, sandbox_id, account_id, user_id, device_kind, device_label, status, created_at) VALUES ('grt_out', ?, 'org:acme', 'bob', 'desktop', 'b', 'revoking', 1)`)
.run(t.id)
const row = (await getSandbox(t.h.env.SANDBOX_DB, t.id))!
expect(await soloMember(t.h.env.SANDBOX_DB, row)).toBeNull()
t.h.raw.prepare(`UPDATE workspace_grants SET status = 'revoked' WHERE id = 'grt_out'`).run()
expect(await soloMember(t.h.env.SANDBOX_DB, row)).toBe('alice')
})
})
@@ -240,7 +240,7 @@ describe('GIT-ACTOR: githubActing and you on the workspace view (list and detail
}) as D1Database
const row = (await getSandbox(db, t.id))!
// Four rows of the same owner (ids differ): a list of any size.
const results = [row, ...[1, 2, 3].map((n) => ({ ...row, id: `${row.id.slice(0, -1)}${n}` }))]
const results = [row, ...[1, 2, 3].map((n) => ({ ...row, id: `${row.id}-copy${n}` }))]
const options = { enabled: () => true, sharedMaxMs: 60 * 60_000 }
const views = await githubActingViews(counting, results as never, 'alice', t.h.now(), options)
expect([...views.values()].map((v) => v.githubActing)).toEqual(Array(4).fill({ actingAs: 'member', userId: 'alice', login: 'alice-gh' }))