Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Restore atomic single-use credential grants (#1749)

Regan Bellb9c1e4581586
diff --git a/src/credentials/keychain.ts b/src/credentials/keychain.ts
index 6d175ea35..108bc9af1 100644
--- a/src/credentials/keychain.ts
+++ b/src/credentials/keychain.ts
@@ -122,9 +122,6 @@ export type KeychainCredentialMeta = Omit<KeychainCredential, "secretEnc"> & { c
export type GrantMode = "once" | "standing";
-// A one-time grant covers the command it was approved for, including re-runs of it, then expires.
-const ONCE_RETRY_WINDOW_MS = 15 * 60_000;
-
export interface KeychainGrant {
id: string;
credentialId: string;
@@ -487,6 +484,10 @@ function legacyUsernameEnvKey(passwordEnvKey: string): string {
return `${base || passwordEnvKey}_USERNAME`;
}
+function consumedGrant(grant: KeychainGrant): boolean {
+ return grant.status === "used" || (grant.mode === "once" && grant.usedAt !== undefined);
+}
+
function expired(rec: { expiresAt?: number }, now: number): boolean {
return typeof rec.expiresAt === "number" && rec.expiresAt < now;
}
@@ -597,7 +598,7 @@ export function createKeychain(deps: {
async function activeGrantsFor(scopeId: ScopeId): Promise<KeychainGrant[]> {
const t = now();
return (await deps.grants.all()).filter(
- (g) => g.audienceScopeId === scopeId && g.status === "active" && !expired(g, t),
+ (g) => g.audienceScopeId === scopeId && g.status === "active" && !consumedGrant(g) && !expired(g, t),
);
}
@@ -988,19 +989,15 @@ export function createKeychain(deps: {
}
async function claimOnceGrant(grant: KeychainGrant, scopeId: ScopeId, usedBy: string): Promise<void> {
- if (grant.mode !== "once" || (grant.usedAt !== undefined && grant.usedBy === usedBy)) return;
+ if (grant.mode !== "once") return;
if (!deps.grants.update) throw new KeychainError(503, "grant store does not support atomic one-time use");
const usedAt = now();
const claimed = await deps.grants.update(grant.id, (current) => {
if (current.audienceScopeId !== scopeId) throw new KeychainError(403, "grant is for a different conversation");
- if (current.status !== "active") throw new KeychainError(410, `grant is ${current.status}`);
+ if (current.status === "revoked") throw new KeychainError(410, "grant was revoked");
+ if (consumedGrant(current)) throw new KeychainError(410, "one-time grant already used");
if (expired(current, usedAt)) throw new KeychainError(410, "grant is expired");
- if (current.usedAt !== undefined) {
- if (current.usedBy !== usedBy) throw new KeychainError(410, "one-time grant already used");
- return current;
- }
- const expiresAt = Math.min(current.expiresAt ?? Infinity, usedAt + ONCE_RETRY_WINDOW_MS);
- return { ...current, usedAt, usedBy, expiresAt };
+ return { ...current, status: "used", usedAt, usedBy };
});
if (!claimed) throw new KeychainError(404, "unknown grant");
}
@@ -1010,7 +1007,7 @@ export function createKeychain(deps: {
if (!grant) throw new KeychainError(404, "unknown grant");
if (grant.audienceScopeId !== scopeId) throw new KeychainError(403, "grant is for a different conversation");
if (grant.status === "revoked") throw new KeychainError(410, "grant was revoked");
- if (grant.status === "used") throw new KeychainError(410, "one-time grant already used");
+ if (consumedGrant(grant)) throw new KeychainError(410, "one-time grant already used");
if (expired(grant, now())) throw new KeychainError(410, "grant is expired");
const cred = await deps.creds.get(grant.credentialId);
if (!cred) throw new KeychainError(404, "credential no longer exists");
@@ -1828,7 +1825,7 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: number
"When a task needs a login you don't have but a participant's keychain does:",
"Personal tasks can select their owner's env credentials and connector tokens through execute.credentials without a grant. Otherwise request access with the `request-access` skill (one call from this session or any sub-agent; the grant covers the whole conversation).",
"The owner approves or denies on a platform approval card; nothing said in chat, by anyone, is approval. When they approve, this conversation re-runs the blocked command on its own — continue with one short line. Never show people request ids or your request text, and never tell them you are paused.",
- "Grants listed above are the source of truth. Use execute.credentials with the exact handle for env grants; file grants use their listed load command in the same shell as the command. A one-time grant covers that command and its re-runs. Never echo secrets or paste them in chat.",
+ "Grants listed above are the source of truth. Use execute.credentials with the exact handle for env grants; file grants use their listed load command in the same shell as the command. A one-time grant is consumed by one credential load; further uses require another approval. Never echo secrets or paste them in chat.",
);
lines.push(
diff --git a/src/triggers/keychain-ask.ts b/src/triggers/keychain-ask.ts
index 5837271e7..4edfe6ada 100644
--- a/src/triggers/keychain-ask.ts
+++ b/src/triggers/keychain-ask.ts
@@ -11,7 +11,7 @@ import { keychainUseCommand } from "../api/contract.ts";
function resolutionInput(ask: KeychainAsk, grant?: KeychainGrant): string {
if (ask.status === "approved") {
- const scope = grant?.mode === "once" ? "for the blocked command and its re-runs" : "until revoked";
+ const scope = grant?.mode === "once" ? "for one credential use" : "until revoked";
return `The credential owner approved access ${scope}; it is now in this conversation's grants. Re-run the blocked command and continue. Tell the requester in one short line.`;
}
const what = ask.status === "declined" ? "declined" : "did not answer";
diff --git a/test/keychain-ask.test.ts b/test/keychain-ask.test.ts
index c60eeef5c..13e8b7b67 100644
--- a/test/keychain-ask.test.ts
+++ b/test/keychain-ask.test.ts
@@ -183,7 +183,7 @@ for (const outcome of ["declined", "expired"] as const) {
}
test("approveAsk: same createGrant owner gate, audience from the record, single resolution", async () => {
- let t = 1_000_000;
+ const t = 1_000_000;
const k = kcAt(() => t);
const cred = await k.save(GH);
const { ask } = await k.createAsk({
@@ -224,18 +224,10 @@ test("approveAsk: same createGrant owner gate, audience from the record, single
await assert.rejects(k.materialize(grant.id, "channel:OTHER", "U_BOB"), (e: KeychainError) => e.status === 403);
const m = await k.materialize(grant.id, "channel:C1", "U_BOB");
assert.ok(m.kind === "env" && m.env[0]!.value === "ghp_alice");
- t += 60_000;
- const retry = await k.materialize(grant.id, "channel:C1", "U_BOB");
- assert.ok(retry.kind === "env" && retry.env[0]!.value === "ghp_alice", "a once grant covers re-runs of its command");
const used = (await k.getGrant(grant.id))!;
- assert.equal(used.status, "active");
- assert.equal(used.usedAt, 1_000_000, "the first use starts the window; re-runs don't extend it");
- assert.equal(used.expiresAt, 1_000_000 + 15 * 60_000);
- t = used.expiresAt! + 1;
- await assert.rejects(
- k.materialize(grant.id, "channel:C1", "U_BOB"),
- (e: KeychainError) => e.status === 410 && /expired/.test(e.message),
- );
+ assert.equal(used.status, "used");
+ assert.equal(used.usedAt, 1_000_000);
+ await assert.rejects(k.materialize(grant.id, "channel:C1", "U_BOB"), (e: KeychainError) => e.status === 410);
});
test("declineAsk is owner-gated and single-resolution", async () => {
@@ -498,7 +490,7 @@ test("fireAskResolution: a turn that fires but doesn't land falls back to a plai
);
}
assert.match(prompts[0]!, /until revoked/, "mode comes from the looked-up grant");
- assert.match(prompts[1]!, /for the blocked command and its re-runs/);
+ assert.match(prompts[1]!, /for one credential use/);
for (const prompt of prompts) {
assert.match(prompt, /Re-run the blocked command/);
assert.ok(!/fa11bacc|g-standing|g-once/.test(prompt), "no ask or grant ids in the resume prompt");
@@ -887,7 +879,7 @@ describe("/v1/keychain/asks — card approval end to end", async () => {
assert.equal(used.status, 200);
assert.equal(await used.text(), "export GITHUB_TOKEN='ghp_alice'\n");
const rerun = await post("/v1/keychain/use", { grant: grant.id }, await bobInInfra());
- assert.equal(rerun.status, 200, "a sub-agent or retry re-runs the same command inside the window");
+ assert.equal(rerun.status, 410, "a child or retry needs a new approval after consumption");
});
it("deny on the card flips the ask and fires exactly one resolution turn into the asking channel", async () => {
@@ -1016,7 +1008,7 @@ describe("/v1/keychain/asks — card approval end to end", async () => {
assert.equal(resumed.length, 1);
assert.equal((await post("/v1/keychain/use", { grant: grant.id }, await capFor(requesterId))).status, 403);
assert.equal((await post("/v1/keychain/use", { grant: grant.id }, token)).status, 200);
- assert.equal((await post("/v1/keychain/use", { grant: grant.id }, token)).status, 200, "re-run in the window");
+ assert.equal((await post("/v1/keychain/use", { grant: grant.id }, token)).status, 410);
});
}
}
@@ -1136,12 +1128,14 @@ describe("/v1/keychain/asks — card approval end to end", async () => {
assert.equal(resumed.length, 1);
assert.equal((await post("/v1/keychain/use", { grant: approved.grant.id }, await capFor("U_BOB"))).status, 403);
assert.equal((await post("/v1/keychain/use", { grant: approved.grant.id }, token)).status, 200);
- assert.equal((await post("/v1/keychain/use", { grant: approved.grant.id }, token)).status, 200);
+ assert.equal(
+ (await post("/v1/keychain/use", { grant: approved.grant.id }, token)).status,
+ mode === "once" ? 410 : 200,
+ );
const after = (await built.keychain!.getGrant(approved.grant.id))!;
- assert.equal(after.status, "active");
- if (mode === "once") {
- assert.ok(after.usedAt !== undefined && after.expiresAt! <= after.usedAt + 15 * 60_000, "window capped");
- } else assert.equal(after.expiresAt, approved.grant.expiresAt, "standing grants are not capped by use");
+ assert.equal(after.status, mode === "once" ? "used" : "active");
+ if (mode === "once") assert.ok(after.usedAt !== undefined);
+ assert.equal(after.expiresAt, approved.grant.expiresAt);
if (mode === "standing") {
assert.equal((await post(`/v1/keychain/grants/${approved.grant.id}/revoke`, {}, live)).status, 200);
assert.equal((await post("/v1/keychain/use", { grant: approved.grant.id }, token)).status, 410);
diff --git a/test/keychain.test.ts b/test/keychain.test.ts
index 685b9ed3f..aa6559614 100644
--- a/test/keychain.test.ts
+++ b/test/keychain.test.ts
@@ -17,6 +17,7 @@ import {
renderUseScript,
KeychainError,
type Keychain,
+ type KeychainGrant,
} from "../src/credentials/keychain.ts";
import { createMemoryMap, type DurableMap, type DurableMapSelect } from "../src/persistence/durable-map.ts";
import { envKey } from "../src/credentials/connector-token.ts";
@@ -38,8 +39,6 @@ function kc(now?: () => number): Keychain {
});
}
-const ONCE_WINDOW_MS = 15 * 60_000;
-
const GH = {
ownerId: "U1",
service: "github",
@@ -143,9 +142,8 @@ test("envKey defaults from the service name (github → GITHUB_TOKEN)", async ()
assert.equal(meta.service, "github");
});
-test("only the owner can grant; materialize is scope-checked; once-grants cover re-runs for a window", async () => {
- let t = 1_000_000;
- const k = kc(() => t);
+test("only the owner can grant; materialize is scope-checked; once-grants are consumed", async () => {
+ const k = kc();
const cred = await k.save(GH);
await assert.rejects(
@@ -181,64 +179,55 @@ test("only the owner can grant; materialize is scope-checked; once-grants cover
);
assert.equal(m.purpose, "use my gh to clone the repo");
- t += ONCE_WINDOW_MS - 1;
- const rerun = await k.materialize(grant.id, "channel:C1", "U2");
- assert.ok(rerun.kind === "env" && rerun.env[0]!.value === "ghp_secret", "a retry of the same command still works");
- const claimed = (await k.getGrant(grant.id))!;
- assert.equal(claimed.status, "active", "once grants are no longer flipped to used");
- assert.equal(claimed.usedAt, 1_000_000);
- assert.equal(claimed.usedBy, "U2");
- assert.equal(claimed.expiresAt, 1_000_000 + ONCE_WINDOW_MS);
-
- t += 2;
await assert.rejects(
k.materialize(grant.id, "channel:C1", "U2"),
- (e: KeychainError) => e.status === 410 && e.message === "grant is expired",
- "after the window the once grant is expired",
+ (e: KeychainError) => e.status === 410,
+ "a once-grant is single-use",
);
});
-test("a once grant's window never outlives an earlier expiry the owner set", async () => {
- let t = 1_000_000;
- const k = kc(() => t);
+test("concurrent materialization consumes a once grant exactly once", async () => {
+ const k = kc();
const cred = await k.save(GH);
const grant = await k.createGrant({
credentialId: cred.id,
ownerId: "U1",
audienceScopeId: "channel:C1",
mode: "once",
- purpose: "short",
- expiresAt: t + 60_000,
+ purpose: "single use",
});
- await k.materialize(grant.id, "channel:C1", "U2");
- assert.equal((await k.getGrant(grant.id))!.expiresAt, t + 60_000);
- t += 60_001;
- await assert.rejects(k.materialize(grant.id, "channel:C1", "U2"), (e: KeychainError) => e.status === 410);
+ const results = await Promise.allSettled([
+ k.materialize(grant.id, "channel:C1", "U2"),
+ k.materialize(grant.id, "channel:C1", "U2"),
+ k.materialize(grant.id, "channel:C1", "U3"),
+ ]);
+ assert.equal(results.filter((result) => result.status === "fulfilled").length, 1);
+ assert.equal(
+ results.filter(
+ (result) =>
+ result.status === "rejected" && result.reason instanceof KeychainError && result.reason.status === 410,
+ ).length,
+ 2,
+ );
});
-test("a once grant serves concurrent parent + child loads by the same requester, not other members", async () => {
- let t = 1_000_000;
- const k = kc(() => t);
- const cred = await k.save(GH);
+test("legacy retry grants remain consumed and invalidate prepared uses", async () => {
+ const grants = createMemoryMap<KeychainGrant>();
+ const k = createKeychain({ creds: createMemoryMap(), grants, asks: createMemoryMap(), key: KEY });
+ const credential = await k.save(GH);
const grant = await k.createGrant({
- credentialId: cred.id,
+ credentialId: credential.id,
ownerId: "U1",
audienceScopeId: "channel:C1",
mode: "once",
- purpose: "single command",
+ purpose: "one use",
});
- const results = await Promise.all([
- k.materialize(grant.id, "channel:C1", "U2"),
- k.materialize(grant.id, "channel:C1", "U2"),
- ]);
- assert.ok(results.every((m) => m.kind === "env" && m.env[0]!.value === "ghp_secret"));
- const claimed = (await k.getGrant(grant.id))!;
- assert.equal(claimed.usedAt, 1_000_000);
- assert.equal(claimed.expiresAt, 1_000_000 + ONCE_WINDOW_MS);
- await assert.rejects(k.materialize(grant.id, "channel:C1", "U3"), (e: KeychainError) => e.status === 410);
- t += 5 * 60_000;
- await k.materialize(grant.id, "channel:C1", "U2");
- assert.equal((await k.getGrant(grant.id))!.expiresAt, 1_000_000 + ONCE_WINDOW_MS, "later uses don't extend it");
+ const prepared = await k.prepareMaterialize(grant.id, "channel:C1", "U2");
+ await grants.put(grant.id, { ...grant, status: "active", usedAt: Date.now(), usedBy: "U2" });
+ assert.equal((await k.grantsForScope("channel:C1")).length, 0);
+ for (const actor of ["U2", "U3"])
+ await assert.rejects(k.materialize(grant.id, "channel:C1", actor), (e: KeychainError) => e.status === 410);
+ await assert.rejects(prepared.commit(), (e: KeychainError) => e.status === 410);
});
test("materializeOwnById: the owner's own credential needs no grant — scope, ownership, expiry, and connectors enforced", async () => {
@@ -345,7 +334,7 @@ describe("connectors are grantable like any keychain record", () => {
);
});
- it("only the owner can grant a connector; materialize hands back the token under the host env var; once re-runs work", async () => {
+ it("only the owner can grant a connector; materialize hands back the token under the host env var; once is consumed", async () => {
const k = kc();
await k.setConnectorToken(GMAIL, "alex@x", { accessToken: "ya29.alex", expiresAt: Date.now() + 3_600_000 });
const cid = await cidOf(k, "alex@x");
@@ -368,8 +357,7 @@ describe("connectors are grantable like any keychain record", () => {
{ key: "VAULT_TOKEN_GMAIL_GOOGLEAPIS_COM", value: "ya29.alex" },
]);
assert.match(renderUseScript(m), /export VAULT_TOKEN_GMAIL_GOOGLEAPIS_COM=/);
- const rerun = await k.materialize(grant.id, G1, "carol@x");
- assert.deepEqual(rerun.kind === "env" ? rerun.env : null, m.kind === "env" ? m.env : null, "re-run in the window");
+ await assert.rejects(k.materialize(grant.id, G1, "carol@x"), (e: KeychainError) => e.status === 410);
});
it("an expired connector token is refreshed on materialize; with no refresh it 410s for reconnect", async () => {
@@ -1160,7 +1148,7 @@ describe("/v1/keychain routes (capability-authed)", () => {
assert.deepEqual(other.credentials, []);
});
- it("env grants expose the credential's execution handle; committing a once grant starts its re-run window", async () => {
+ it("env grants expose the credential's execution handle; committing a once grant consumes it", async () => {
const owner = "HANDLE_OWNER";
const cap = await capFor(owner, scopeId("personal", owner), { liveActor: true });
const saved = (await (
@@ -1182,8 +1170,9 @@ describe("/v1/keychain routes (capability-authed)", () => {
assert.equal(prepared.materialized.kind, "env");
await prepared.commit();
const claimed = (await built.keychain!.getGrant(grant.id))!;
- assert.equal(claimed.status, "active", "a used once grant stays usable for re-runs of its command");
- assert.ok(claimed.usedAt !== undefined && claimed.expiresAt === claimed.usedAt + 15 * 60_000);
+ assert.equal(claimed.status, "used");
+ assert.ok(claimed.usedAt !== undefined);
+ await assert.rejects(prepared.commit(), (e: KeychainError) => e.status === 410);
});
it("a participant's granted connector is materialized under the host env var", async () => {
@@ -1257,7 +1246,7 @@ describe("/v1/keychain routes (capability-authed)", () => {
assert.notEqual(res.status, 200);
});
- it("use is scope-bound, returns sourceable env text, and a once grant serves re-runs", async () => {
+ it("use is scope-bound, returns sourceable env text, and a once grant cannot be reused", async () => {
const { credential } = (await (
await post(
"/v1/keychain/credentials",
@@ -1277,7 +1266,7 @@ describe("/v1/keychain routes (capability-authed)", () => {
assert.equal(await used.text(), "export GH_GRANT='ghp_grant'\n");
const rerun = await post("/v1/keychain/use", { grant: g.grant.id }, await capFor("U3", "channel:C7"));
- assert.equal(rerun.status, 200, "a retry of the same command inside the window");
+ assert.equal(rerun.status, 410, "a consumed grant cannot authorize another credential load");
const usage = await built.credentialUsage.list({});
assert.ok(
@@ -1581,7 +1570,7 @@ test("prepared grants reject credential rotation without consuming a single use"
if (fresh.materialized.kind === "env") assert.equal(fresh.materialized.env[0]?.value, "rotated-execution-token");
await fresh.commit();
const committed = (await k.getGrant(grant.id))!;
- assert.equal(committed.status, "active");
+ assert.equal(committed.status, "used");
assert.equal(committed.usedBy, "U2", "only the committed materialization claims the once grant");
});
diff --git a/test/live-slack/scenarios-credential-approval.ts b/test/live-slack/scenarios-credential-approval.ts
index 80f84346c..70a707801 100644
--- a/test/live-slack/scenarios-credential-approval.ts
+++ b/test/live-slack/scenarios-credential-approval.ts
@@ -172,6 +172,10 @@ export const credentialApprovalScenarios: Scenario[] = (["once", "standing", "we
root,
`<@${env.botUserId}> run that exact command again and reply COUNT=<number>.`,
);
+ if (mode === "once") {
+ const next = await nextCard(ctx, channel.id, root, again, `demo-${mode}`);
+ await click(env, owner, channel.id, next, "keychain_allow_once");
+ }
const since2 = String(Date.now() / 1000);
await waitFor("re-run", async () =>
(await threadText(ctx, channel.id, root, again)).includes(`COUNT=${count}`) ? true : undefined,
diff --git a/test/shared-credential-resumption.test.ts b/test/shared-credential-resumption.test.ts
index cc8560603..cec240d10 100644
--- a/test/shared-credential-resumption.test.ts
+++ b/test/shared-credential-resumption.test.ts
@@ -113,7 +113,7 @@ for (const scope of ["channel:C_SHARED", "group:G_SHARED", "group:web-project-sh
assert.equal(request.unattendedGrants, undefined);
assert.equal(request.ownerKeychainUnion, undefined);
assert.deepEqual(request.triggerDestination, f.cron.destination);
- assert.match(request.text, /approved access for the blocked command and its re-runs/);
+ assert.match(request.text, /approved access for one credential use/);
assert.ok(!request.text.includes(f.ask.id) && !request.text.includes(f.ask.purpose));
assert.equal(f.grant.audienceScopeId, scope);
assert.equal(f.grant.ownerId, "U_CREDENTIAL_OWNER");
@@ -123,9 +123,6 @@ for (const scope of ["channel:C_SHARED", "group:G_SHARED", "group:web-project-sh
);
const materialized = await f.k.materialize(f.grant.id, scope, request.actor.externalId);
assert.ok(materialized.kind === "env" && materialized.env[0]!.value === "dummy-only-secret");
- const retried = await f.k.materialize(f.grant.id, scope, request.actor.externalId);
- assert.ok(retried.kind === "env" && retried.env[0]!.value === "dummy-only-secret", "a re-run inside the window");
- f.clock.t += 15 * 60_000 + 1;
await assert.rejects(
f.k.materialize(f.grant.id, scope, request.actor.externalId),
(error: KeychainError) => error.status === 410,