Multiplayer agent harness for work.
Gate env-delivered org credentials by service-cred grants (#548)
Regan Bellb702813382e6
diff --git a/src/api/routes/admin-resources.ts b/src/api/routes/admin-resources.tsindex c4ca6b5b0..dc502088d 100644--- a/src/api/routes/admin-resources.ts+++ b/src/api/routes/admin-resources.ts@@ -893,12 +893,6 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [});if (badGrantee !== undefined)return { error: `grantee must be this org or a valid personal:/team: scope (got ${badGrantee})` };- if (delivery === "env" && desired?.some((g) => g !== scope)) {- return {- error:- "env-delivery credentials are injected into every all-internal conversation — person/team grants don't gate them; share org-wide",- };- }const injection =b.injection && typeof b.injection === "object"? ({diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex b6c4a4c5c..4eb76c8cb 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -29,7 +29,11 @@ import { createBackgroundBroker } from "../connectors/background-exec-broker.ts"import { createMonitorBroker, readBackgroundOutputTail } from "../monitors/monitor-broker.ts";import { isPollSurface, isSilentPollReply } from "../triggers/run-trigger.ts";import { envKey } from "../credentials/connector-token.ts";-import { renderKeychainManifest, type MaterializedEnvCred } from "../credentials/keychain.ts";+import {+ renderKeychainManifest,+ type MaterializedEnvCred,+ type PublicServiceCredential,+} from "../credentials/keychain.ts";import { captureDeviceFlowLogins, deviceFlowCredOwner } from "../credentials/device-flow-persist.ts";import type { DeviceFlowCutoverMode } from "../credentials/device-flow-cutover.ts";import { type ResidentAuthConnector, RESIDENT_AUTH_CONNECTORS, mergeConnectors } from "../credentials/resident-auth.ts";@@ -1037,14 +1041,37 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {const authoredDetection =input.origin.kind === "ambient" && input.origin.live === true && conversation.kind !== "dm";const liveAuthorTurn = (humanTurn || authoredDetection) && allInternal;+ // Service credentials: one read of the org's credential list and one grant scan feed both+ // the env-delivery gate (below) and the broker token mint (further down). Same grants gate both.+ let serviceCredRecords: PublicServiceCredential[] = [];+ let grantedCredSlugs = new Set<string>();+ if (!strictReadOnly && deps.serviceCreds) {+ serviceCredRecords = await deps.serviceCreds.listServiceCredentials(resolution.orgScopeId);+ if (serviceCredRecords.length > 0) {+ grantedCredSlugs = new Set(+ (+ await deps.acl.grantsOfKind(+ "service-cred",+ conversation.audience,+ scopeId,+ resolution.orgScopeId,+ principalEntitledToScope,+ )+ ).map((g) => parseRef(g.ref).id),+ );+ }+ }if (!strictReadOnly && allInternal && deps.serviceCreds) {const orgScope = toScopeId("org", orgId());- for (const cred of await deps.serviceCreds.listServiceCredentials(orgScope)) {+ // Env delivery is gated by the same service-cred grants as the broker: the env var rides+ // only when every internal participant in this conversation is entitled to the credential.+ for (const cred of serviceCredRecords) {if (cred.delivery !== "env" ||!cred.envKey ||!cred.enabled ||!cred.hasSecret ||+ !grantedCredSlugs.has(cred.slug) ||cred.envKey in connectorEnv)continue;@@ -1128,19 +1155,12 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {deps.capabilitySecret ?? deps.signingSecret,);if (deps.serviceCreds) {- const records = await deps.serviceCreds.listServiceCredentials(resolution.orgScopeId);+ const records = serviceCredRecords;const enabled = new Set(records.filter((r) => r.enabled && r.hasSecret && r.delivery !== "env").map((r) => r.slug),);if (enabled.size > 0) {- const grants = await deps.acl.grantsOfKind(- "service-cred",- conversation.audience,- scopeId,- resolution.orgScopeId,- principalEntitledToScope,- );- const slugs = [...new Set(grants.map((g) => parseRef(g.ref).id))].filter((s) => enabled.has(s));+ const slugs = [...grantedCredSlugs].filter((s) => enabled.has(s));if (slugs.length > 0) {connectorEnv.AGENT_CREDENTIAL_TOKEN = await mintCapabilityToken({diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.tsindex a4520c019..f954ccf5e 100644--- a/test/orchestrator.test.ts+++ b/test/orchestrator.test.ts@@ -15,6 +15,9 @@ import { TURN_FILES_DIR, turnFileId } from "../src/core/attachments.ts";import { contextSummaryPayload } from "../src/harness/context-compaction.ts";import { egressDecision } from "../src/resolution/egress-policy.ts";import { hashId } from "../src/util/crypto.ts";+import { encodeRef, serviceCredRef } from "../src/acl/resource-ref.ts";+import type { AclStore } from "../src/acl/acl-store.ts";+import type { ScopeId } from "../src/types.ts";import type { SecurityScreener } from "../src/security/security-screener.ts";function freshApp(overrides: Partial<Config> = {}, securityScreener?: SecurityScreener) {@@ -64,6 +67,16 @@ function channel(text: string, extra: Partial<TurnRequest> = {}): TurnRequest {};}+async function grantCred(acl: AclStore, org: ScopeId, slug: string, grantee: ScopeId = org): Promise<void> {+ await acl.grant({+ ownerScopeId: org,+ ref: encodeRef(serviceCredRef(slug)),+ granteeScopeId: grantee,+ permission: "read",+ grantedBy: "admin@default-org",+ });+}+test("internal DM turn runs end-to-end and records the session", async () => {const { app } = freshApp();const res = await app.turn(dm("hello there"));@@ -441,7 +454,7 @@ test("org env-delivery credentials ride provision env under their envKey — reasigningSecret: "test-secret",apiBaseUrl: "https://core.example.com",});- const { app, sandbox, serviceCreds } = buildApp(config);+ const { app, sandbox, serviceCreds, acl } = buildApp(config);const org = scopeId("org", "default-org");await serviceCreds.setServiceCredential(org, {slug: "browse-steel",@@ -451,6 +464,8 @@ test("org env-delivery credentials ride provision env under their envKey — reasecret: "steel-org-key",host: "",});+ await grantCred(acl, org, "browse-steel");+ await grantCred(acl, org, "browse-model-key");await serviceCreds.setServiceCredential(org, {slug: "browse-model-key",name: "Browse model key",@@ -490,8 +505,10 @@ test("a disabled or broker-delivery credential never rides provision env", asyncsigningSecret: "test-secret",apiBaseUrl: "https://core.example.com",});- const { app, sandbox, serviceCreds } = buildApp(config);+ const { app, sandbox, serviceCreds, acl } = buildApp(config);const org = scopeId("org", "default-org");+ await grantCred(acl, org, "x-firehose");+ await grantCred(acl, org, "browse-steel");await serviceCreds.setServiceCredential(org, {slug: "x-firehose",name: "X",@@ -530,7 +547,7 @@ test("a credential flipped away from env between the metadata read and the secresigningSecret: "test-secret",apiBaseUrl: "https://core.example.com",});- const { app, sandbox, serviceCreds } = buildApp(config);+ const { app, sandbox, serviceCreds, acl } = buildApp(config);const org = scopeId("org", "default-org");await serviceCreds.setServiceCredential(org, {slug: "browse-steel",@@ -540,6 +557,7 @@ test("a credential flipped away from env between the metadata read and the secresecret: "steel-org-key",host: "",});+ await grantCred(acl, org, "browse-steel");const realGet = serviceCreds.getServiceCredentialSecret.bind(serviceCreds);serviceCreds.getServiceCredentialSecret = async (scope, slug) => {const rec = await realGet(scope, slug);@@ -563,7 +581,7 @@ test("env-delivery injection is all-internal only, and an existing env key (keycsigningSecret: "test-secret",apiBaseUrl: "https://core.example.com",});- const { app, sandbox, serviceCreds } = buildApp(config);+ const { app, sandbox, serviceCreds, acl } = buildApp(config);const org = scopeId("org", "default-org");await serviceCreds.setServiceCredential(org, {slug: "browse-steel",@@ -573,6 +591,7 @@ test("env-delivery injection is all-internal only, and an existing env key (keycsecret: "steel-org-key",host: "",});+ await grantCred(acl, org, "browse-steel");const captures: ProvisionOptions[] = [];const realProvision = sandbox.provision.bind(sandbox);sandbox.provision = (layers, opts) => {@@ -595,6 +614,48 @@ test("env-delivery injection is all-internal only, and an existing env key (keycassert.equal(captures.at(-1)?.env?.STEEL_API_KEY, undefined, "a room with externals gets no org env credentials");});+test("env-delivery credentials are gated by service-cred grants — no grant, no env var; a person grant admits only that person", async () => {+ const config = testConfig({+ dataDir: mkdtempSync(join(tmpdir(), "ap-")),+ signingSecret: "test-secret",+ apiBaseUrl: "https://core.example.com",+ });+ const { app, sandbox, serviceCreds, acl } = buildApp(config);+ const org = scopeId("org", "default-org");+ await serviceCreds.setServiceCredential(org, {+ slug: "browse-steel",+ name: "Steel",+ delivery: "env",+ envKey: "STEEL_API_KEY",+ secret: "steel-org-key",+ host: "",+ });+ const captures: ProvisionOptions[] = [];+ const realProvision = sandbox.provision.bind(sandbox);+ sandbox.provision = (layers, opts) => {+ if (opts) captures.push(opts);+ return realProvision(layers, opts);+ };++ let res = await app.turn(dm("!run echo keys", { conversation: { kind: "dm", threadRef: "dm:U1:gate1" } }));+ assert.equal(res.status, "ok");+ assert.equal(captures.at(-1)?.env?.STEEL_API_KEY, undefined, "ungranted env credential stays home");++ await grantCred(acl, org, "browse-steel", scopeId("personal", "somebody-else"));+ res = await app.turn(dm("!run echo keys", { conversation: { kind: "dm", threadRef: "dm:U1:gate2" } }));+ assert.equal(res.status, "ok");+ assert.equal(captures.at(-1)?.env?.STEEL_API_KEY, undefined, "a grant to someone else does not admit this actor");++ await grantCred(acl, org, "browse-steel", scopeId("personal", "U1"));+ res = await app.turn(dm("!run echo keys", { conversation: { kind: "dm", threadRef: "dm:U1:gate3" } }));+ assert.equal(res.status, "ok");+ assert.equal(+ captures.at(-1)?.env?.STEEL_API_KEY,+ "steel-org-key",+ "a personal grant to the actor admits the env var",+ );+});+test("admin-configured browse step limit rides provision env (BROWSE_LAB_MAX_STEPS)", async () => {const config = testConfig({dataDir: mkdtempSync(join(tmpdir(), "ap-")),diff --git a/test/service-credential-route.test.ts b/test/service-credential-route.test.tsindex cb6c40e48..e9a1f391d 100644--- a/test/service-credential-route.test.ts+++ b/test/service-credential-route.test.ts@@ -210,7 +210,7 @@ test("env-delivery credential: envKey validated, host refused, duplicates refuse}});-test("env-delivery refuses person/team grantees — grants don't gate env injection, so the ACL must not pretend otherwise", async () => {+test("env-delivery accepts person/team grantees — grants now gate env injection like broker calls", async () => {const srv = start();try {const narrowed = await putCred(srv.base, {@@ -221,18 +221,17 @@ test("env-delivery refuses person/team grantees — grants don't gate env injectsecret: "s1",grantees: ["personal:alice@default-org"],});- assert.equal(narrowed.status, 400);- assert.match(await narrowed.text(), /don't gate them/);+ assert.equal(narrowed.status, 200, "a person grant on an env credential is allowed");const orgWide = await putCred(srv.base, {- slug: "browse-steel",- name: "Steel",+ slug: "browse-steel-wide",+ name: "Steel wide",delivery: "env",- envKey: "STEEL_API_KEY",+ envKey: "STEEL_WIDE_API_KEY",secret: "s1",grantees: ["org:default-org"],});- assert.equal(orgWide.status, 200, "the org grant itself is fine");+ assert.equal(orgWide.status, 200, "the org grant is fine too");} finally {await srv.close();}