Multiplayer agent harness for work.
Let scheduled tasks request owner approval for credentials (#1381)
Regan Bell570db4400db1
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.tsindex 2f80cf6d7..2ac1e3a8b 100644--- a/src/api/agent-api-catalog.ts+++ b/src/api/agent-api-catalog.ts@@ -607,7 +607,8 @@ const FAMILIES: AgentApiFamily[] = [{method: "POST|GET",path: "/v1/keychain/asks",- summary: "ask a credential's owner for access (purpose-bound; refused on trigger-fired turns) / list asks",+ summary:+ "ask a credential's owner for access, including scheduled turns in personal or shared conversations for discoverable credentials (no access until owner approval) / list asks",},{ method: "POST", path: "/v1/keychain/asks/:id/decline", summary: "decline an ask" },{diff --git a/src/api/routes/keychain.ts b/src/api/routes/keychain.tsindex 70d8b049c..daa24fc22 100644--- a/src/api/routes/keychain.ts+++ b/src/api/routes/keychain.ts@@ -14,6 +14,7 @@ import { normalizeInboundExpiresAt } from "../expiry.ts";import type { ApiCtx, Route } from "./route.ts";import { audit, resolveCapabilityDestination, verifiedConversationSpeaker } from "./shared.ts";import { swallow, swallowAs } from "../../util/errors.ts";+import { cronIdOf } from "../../sessions/session-store.ts";import { keychainUseCommand } from "../contract.ts";const CONSENT_ON_TRIGGERED_TURN =@@ -234,12 +235,9 @@ async function handleKeychain(ctx: ApiCtx): Promise<void> {return sendJson(res, 200, {grant,ask,- use:- grant.audienceScopeId === capability.scopeId- ? useBlock(grant)- : {- note: `Grant is active in ${grant.audienceScopeId} — the asking conversation. It cannot be used from here; that conversation resumes on its own.`,- },+ use: {+ note: `Grant is active in ${grant.audienceScopeId} — the asking conversation resumes automatically. Do not load or consume the grant on this approval turn.`,+ },});}let granter = actorId;@@ -298,12 +296,6 @@ async function handleKeychain(ctx: ApiCtx): Promise<void> {}if (method === "POST" && pathname === "/v1/keychain/asks") {- if (capability.triggered) {- return sendJson(res, 403, {- error: "forbidden",- message: "asks can only be sent on a turn a person sent — this turn was fired by a trigger",- });- }const b = body as { credential?: unknown; purpose?: unknown; requestedMode?: unknown; expiresAt?: unknown };const expiresAt = normalizeInboundExpiresAt(b.expiresAt);if (!expiresAt.ok) return sendJson(res, 400, { error: "bad_request", message: expiresAt.message });@@ -318,32 +310,29 @@ async function handleKeychain(ctx: ApiCtx): Promise<void> {});}const scope = parseScopeId(capability.scopeId);- if (scope.kind !== "channel") {- return sendJson(res, 403, {- error: "forbidden",- message: "asks can only be sent from a channel — in a DM or group, ask the owner directly",- });+ if (scope.kind !== "channel" && scope.kind !== "personal" && scope.kind !== "group") {+ return sendJson(res, 403, { error: "forbidden", message: "asks require a personal or shared conversation" });}const cred = await kc.getCredential(b.credential);if (!cred) return sendJson(res, 404, { error: "not_found", message: "unknown credential" });- const ch = await app.resolveChannel(scope.ref);- if (ch.kind !== "one") {- return sendJson(res, 403, {- error: "forbidden",- message: "this channel isn't in the directory yet — try again in a minute",- });- }- const ownerIsMember = ch.channel.isPrivate- ? await app.channelMember(ch.channel.channelId, cred.ownerId)- : (await app.directoryMember(cred.ownerId))?.type === "internal";- if (!ownerIsMember) {+ const requester = await app.directoryMember(actorId);+ if (+ !(await app.belongsToScope(actorId, capability.scopeId)) ||+ !(await app.belongsToScope(cred.ownerId, capability.scopeId)) ||+ (scope.kind !== "personal" &&+ (requester?.type !== "internal" || (await app.directoryMember(cred.ownerId))?.type !== "internal"))+ ) {return sendJson(res, 403, {error: "forbidden",- message: "the credential's owner isn't a verified member of this conversation",+ message: "the requester and credential owner must have current access to this conversation",});}+ const context = (await app.listContexts(cred.ownerId)).find((c) => c.scopeId === capability.scopeId);+ const cronId = cronIdOf(capability.threadRef);+ const cron = cronId ? await app.getCron(cronId) : null;const dest = resolveCapabilityDestination(capability, undefined);const { ask, existing } = await kc.createAsk({+ ...(capability.triggered ? { triggered: true } : {}),credentialId: cred.id,requesterId: actorId,requesterScopeId: capability.scopeId,@@ -353,12 +342,13 @@ async function handleKeychain(ctx: ApiCtx): Promise<void> {...(b.requestedMode !== undefined ? { requestedMode: b.requestedMode as GrantMode } : {}),...(expiresAt.value !== undefined ? { expiresAt: expiresAt.value } : {}),});- const requester = await app.directoryMember(actorId);const notice = renderAskNotice({ask,credential: cred,...(requester?.displayName ? { requesterName: requester.displayName } : {}),- channelName: ch.channel.name,+ ...(scope.kind === "channel" && context?.name ? { channelName: context.name } : {}),+ ...(scope.kind === "group" && context?.name ? { scopeName: context.name } : {}),+ ...(cron?.ownerScopeId === capability.scopeId ? { taskTitle: cron.title ?? cron.id } : {}),});await deps.deliveries?.enqueue({destination: principalDestination(cred.ownerId, actorId),@@ -425,7 +415,7 @@ async function handleKeychain(ctx: ApiCtx): Promise<void> {return sendJson(res, 403, {error: "forbidden",message:- "own-credential use is implied only on a turn its owner themself sent live — this turn wasn't; use a grant instead",+ "own-credential use is implied only on a turn its owner themself sent live — this turn wasn't; use an existing grant or POST /v1/keychain/asks to request owner approval, then wait",});}m = await kc.materializeOwnById(actorId, b.credential as string, capability.scopeId);diff --git a/src/credentials/keychain.ts b/src/credentials/keychain.tsindex d456b6757..33aaf2df3 100644--- a/src/credentials/keychain.ts+++ b/src/credentials/keychain.ts@@ -1,11 +1,12 @@import { orgId as configOrgId } from "../config.ts";import { randomBytes } from "node:crypto";-import { scopeId as toScopeId, type Destination, type ScopeId } from "../types.ts";+import { scopeId as toScopeId, parseScopeId, type Destination, type ScopeId } from "../types.ts";import { CAPABILITY_CURL_AUTH, keychainUseCommand } from "../api/contract.ts";import type { DurableMap } from "../persistence/durable-map.ts";import { encryptSecret, decryptSecret, type SecretKey } from "../connectors/connector-client-store.ts";import { errMessage } from "../util/errors.ts";import { personKey, samePerson } from "../directory/person.ts";+import { cronIdOf } from "../sessions/session-store.ts";import { hashId } from "../util/crypto.ts";import { shq } from "../util/shell.ts";import { homeRelativePath } from "./paths.ts";@@ -310,6 +311,7 @@ interface CreateGrantInput {}interface CreateAskInput {+ triggered?: boolean;credentialId: string;requesterId: string;requesterScopeId: ScopeId;@@ -1094,13 +1096,25 @@ export function createKeychain(deps: {const t = now();if (!cred.managed && credExpired(cred, t))throw new KeychainError(410, "credential is expired — its owner must re-auth before it can be asked for");- if (samePerson(cred.ownerId, input.requesterId)) {- throw new KeychainError(400, "you own this credential — grant it directly instead of asking yourself");+ const scope = parseScopeId(input.requesterScopeId);+ if (+ scope.kind === "personal" &&+ (!samePerson(scope.ref, input.requesterId) || !samePerson(cred.ownerId, input.requesterId))+ ) {+ throw new KeychainError(403, "personal requests require the credential owner's own conversation");}- for (const rec of await deps.asks.all()) {+ const origin = cronIdOf(input.requesterThreadRef) ?? input.requesterThreadRef;+ for (const rec of (await deps.asks.all()).reverse().sort((a, b) => b.createdAt - a.createdAt)) {const a = await freshAsk(rec, t);- if (a.status === "pending" && a.credentialId === cred.id && a.requesterScopeId === input.requesterScopeId) {- return { ask: a, existing: true };+ const sameOrigin = (cronIdOf(a.requesterThreadRef) ?? a.requesterThreadRef) === origin;+ if (a.credentialId !== cred.id || a.requesterScopeId !== input.requesterScopeId || !sameOrigin) continue;+ if (a.status === "pending") return { ask: a, existing: true };+ if (a.status === "approved") break;+ if (input.triggered && (a.status === "declined" || a.status === "expired")) {+ throw new KeychainError(+ 409,+ "the owner declined or did not answer this task's request — wait for a live owner turn instead of asking again",+ );}}const ask: KeychainAsk = {@@ -1176,11 +1190,17 @@ export function createKeychain(deps: {async unnotifiedResolvedAsks(nowAt) {const out: KeychainAsk[] = [];- for (const rec of await deps.asks.all()) {+ const taskDecisions = new Set<string>();+ for (const rec of (await deps.asks.all()).reverse().sort((a, b) => b.createdAt - a.createdAt)) {const a = await freshAsk(rec, nowAt);+ const origin = cronIdOf(a.requesterThreadRef) ?? a.requesterThreadRef;+ const task = JSON.stringify([a.credentialId, a.requesterScopeId, origin]);+ const retainDecision =+ origin !== undefined && !taskDecisions.has(task) && !!(await deps.creds.get(a.credentialId));+ taskDecisions.add(task);if (a.status === "pending") continue;if (a.notifiedAt === undefined) out.push(a);- else if (a.notifiedAt < nowAt - ASK_PRUNE_AFTER_MS) await deps.asks.delete(a.id);+ else if (!retainDecision && a.notifiedAt < nowAt - ASK_PRUNE_AFTER_MS) await deps.asks.delete(a.id);}return out;},@@ -1486,7 +1506,14 @@ function agoNote(createdAt: number, now: number): string {}export function renderAskNotice(- input: { ask: KeychainAsk; credential: KeychainCredentialMeta; requesterName?: string; channelName?: string },+ input: {+ ask: KeychainAsk;+ credential: KeychainCredentialMeta;+ requesterName?: string;+ channelName?: string;+ scopeName?: string;+ taskTitle?: string;+ },now: number = Date.now(),): string {const { ask, credential } = input;@@ -1494,14 +1521,16 @@ export function renderAskNotice(// Never surface a raw Slack scope id to a person — describe the place instead.let where: string;if (input.channelName) where = `**#${input.channelName.replace(/^#/, "")}**`;- else if (ask.requesterScopeId.startsWith("group:")) where = "a group DM";+ else if (input.scopeName) where = `**${input.scopeName}**`;+ else if (ask.requesterScopeId.startsWith("group:")) where = "a group conversation";else if (ask.requesterScopeId.startsWith("channel:")) where = "a Slack channel";else if (ask.requesterScopeId.startsWith("personal:")) where = "their own conversation";else where = "a shared conversation";+ const task = input.taskTitle ? `Scheduled task "${input.taskTitle}": ` : "";const account = credential.accountLabel ? ` (${credential.accountLabel})` : "";const mode = ask.requestedMode === "standing" ? "as a standing grant for that conversation" : "one time";return (- `${who} asked in ${where} to use your **${credential.service}** credential${account}, ${mode}, for: ` ++ `${task}${ask.requesterScopeId.startsWith("personal:") && samePerson(ask.ownerId, ask.requesterId) ? "A task in your personal conversation is asking" : `${who} asked in ${where}`} to use your **${credential.service}** credential${account}, ${mode}, for: ` +`"${ask.purpose}". Reply here to approve or decline — only your own reply counts; a yes relayed through ` +`anyone else doesn't. (ask \`${ask.id}\`, expires in ${hoursLeft(ask.expiresAt, now)}h)`);@@ -1593,7 +1622,7 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: numberinput.openSpeakerKeychain === true && (input.conversationKind === "channel" || input.conversationKind === "group");const OWN_NOTE = openSpeaker? 'their own — available with execute scope:"owner" for this live Open turn; no grant needed'- : "their own — no grant needed in this personal conversation";+ : "their own — no grant needed on their live turn; background turns need a grant";const memberLines: string[] = [];let hasOwn = false;for (const member of input.members) {@@ -1623,7 +1652,7 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: number"Using one here requires a grant from its OWNER — you never see another person's secret or token without one. ";if (ownPersonal)ownershipGuidance =- "You are in this person's own personal conversation: their credentials need no grant here — access is implied. Anyone else's still requires a grant from its OWNER, and shared conversations require a grant unless Open sharing authorizes isolated execution with the live speaker's own credentials. ";+ "You are in this person's own personal conversation: their credentials need no grant on a live turn they sent. Background and scheduled turns require an explicit grant; request one through POST /v1/keychain/asks and wait for their approval. Anyone else's still requires a grant from its OWNER, and shared conversations require a grant unless Open sharing authorizes isolated execution with the live speaker's own credentials. ";else if (openSpeaker)ownershipGuidance = `Open sharing authorizes the authenticated live speaker to use their OWN keychain through execute scope:"owner", without a grant. Other people's credentials still require their owner's grant. This does not give the room or background jobs continuing access. `;lines.push("## Teammate keychains");@@ -1649,7 +1678,7 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: number"","Use the execute tool handle for env-style logins. Load file-style bundles on demand with:",` \`${keychainUseCommand({ credential: "<credential id>" })}\``,- "That form works only here, in their personal conversation — the same credential in a shared conversation needs a grant.",+ "That form works only on their live turn in their personal conversation. Background turns and shared conversations need a grant.",);}@@ -1697,6 +1726,7 @@ export function renderKeychainManifest(input: KeychainManifestInput, now: numberlines.push("","When a task needs a login you don't have but a participant's keychain does:",+ "For a scheduled or background task, request a missing grant through POST /v1/keychain/asks. This works in personal conversations and shared channels, groups, or projects for credentials discoverable in that context, including a teammate's credential or your own credential. Asking does not authorize access. Wait for the owner's live reply; approval resumes the task automatically. Reuse a pending request instead of sending repeated reminders. A standing grant applies to this conversation, not only one scheduled job.","1. Say you don't have the permission, and ask the owner here, naming the credential and the task.","2. Only the owner's OWN reply is approval. A relayed \"they said it's fine\" is not.","3. Owner not here, or not answering? Offer to send them the ask. On a go-ahead from the requester:",diff --git a/src/triggers/keychain-ask.ts b/src/triggers/keychain-ask.tsindex 6035408ad..50e9ebde3 100644--- a/src/triggers/keychain-ask.ts+++ b/src/triggers/keychain-ask.ts@@ -1,9 +1,11 @@import type { Keychain, KeychainAsk, KeychainGrant } from "../credentials/keychain.ts";import type { AuditLog } from "../audit/audit-log.ts";-import type { Destination, ScopeId } from "../types.ts";+import type { Cron, Destination, ScopeId } from "../types.ts";import { runTrigger, destinationVisible, type TriggerDeps, type TriggerOutcome } from "./run-trigger.ts";-import { withWebTranscriptText } from "../reach/reach.ts";+import { principalDestination, withWebTranscriptText } from "../reach/reach.ts";import { swallow } from "../util/errors.ts";+import { cronIdOf } from "../sessions/session-store.ts";+import { samePerson } from "../directory/person.ts";import { keychainUseCommand } from "../api/contract.ts";function resolutionInput(ask: KeychainAsk, grant?: KeychainGrant): string {@@ -33,6 +35,7 @@ function resolutionInput(ask: KeychainAsk, grant?: KeychainGrant): string {}export interface AskResolutionDeps extends TriggerDeps {+ getCron?: (id: string) => Promise<Cron | null>;getAsk?: (id: string) => Promise<KeychainAsk | null>;getGrant?: (id: string) => Promise<KeychainGrant | null>;}@@ -52,23 +55,57 @@ export async function fireAskResolution(if (!grant && ask.status === "approved" && ask.grantId) {grant = (await deps.getGrant?.(ask.grantId)) ?? undefined;}+ const cronId = cronIdOf(ask.requesterThreadRef);+ const cron = cronId ? await deps.getCron?.(cronId) : undefined;+ if (+ cronId &&+ (!cron ||+ cron.archived ||+ (!cron.enabled && (cron.schedule.everyMs !== undefined || cron.schedule.cron !== undefined)) ||+ cron.ownerScopeId !== ask.requesterScopeId ||+ (cron.runAs !== "scopeFloor" && !samePerson(cron.owner, ask.requesterId)))+ ) {+ return {+ ran: false,+ authzFailed: true,+ note: "the originating cron is unavailable or no longer authorizes this request",+ };+ }+ const destination = cron ? cron.destination : ask.requesterDestination;const outcome = await runTrigger(deps, {- owner: ask.requesterId,+ owner: cron?.owner ?? ask.requesterId,ownerScopeId: ask.requesterScopeId,input: resolutionInput(ask, grant),fireKey: `ask:${ask.id}:${ask.status}`,surface: "keychain-ask",- ...(ask.requesterDestination ? { destination: ask.requesterDestination } : {}),+ deferWhenBusy: true,+ ...(cron+ ? {+ ...(cron.runAs ? { runAs: cron.runAs } : {}),+ ...(cron.members ? { members: cron.members } : {}),+ ...(cron.unattendedGrants ? { unattendedGrants: cron.unattendedGrants } : {}),+ ...(cron.recipientConsent ? { recipientConsent: cron.recipientConsent } : {}),+ recipientConsentRequired: cron.schedule.everyMs !== undefined || cron.schedule.cron !== undefined,+ }+ : {}),+ ...(destination ? { destination } : {}),...(ask.requesterThreadRef ? { threadRef: ask.requesterThreadRef } : {}),});+ if (+ outcome.deferred ||+ (!outcome.ran && !outcome.authzFailed && !(await deps.idempotency.committed(`ask:${ask.id}:${ask.status}`)))+ )+ throw new Error("credential approval resume is waiting for the original conversation to become idle");if (outcome.ran && outcome.status === "ok") return outcome;+ if (cronId && (!outcome.ran || outcome.status === "refused")) return outcome;if (!outcome.ran && !outcome.authzFailed) {const cur = await deps.getAsk?.(ask.id);if (cur?.notifiedAt !== undefined) return outcome;}- if (ask.requesterDestination && (await destinationVisible(deps, ask.requesterId, ask.requesterDestination))) {+ const fallbackDestination = cronId ? principalDestination(ask.ownerId, ask.ownerId) : ask.requesterDestination;+ if (fallbackDestination && (await destinationVisible(deps, ask.requesterId, fallbackDestination))) {await deps.deliveries.enqueue({- destination: withWebTranscriptText(ask.requesterDestination),+ destination: withWebTranscriptText(fallbackDestination),text: fallbackText(ask),idempotencyKey: `ask:${ask.id}:${ask.status}:fallback`,});diff --git a/src/wiring.ts b/src/wiring.tsindex a2e4a6dfb..cda80aba4 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -2105,6 +2105,9 @@ export function buildApp(identity,run: (req) => app.turn(req),directory,+ currentScopeMembers,+ sessions,+ getCron: (id) => crons.get(id),getAsk: (id) => keychain.getAsk(id),getGrant: (id) => keychain.getGrant(id),},diff --git a/test/cron-credential-resumption.test.ts b/test/cron-credential-resumption.test.tsnew file mode 100644index 000000000..8ede5caf5--- /dev/null+++ b/test/cron-credential-resumption.test.ts@@ -0,0 +1,218 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createCronStore } from "../src/cron/cron-store.ts";+import { createDeliveryStore } from "../src/delivery/delivery-store.ts";+import { createIdempotencyStore } from "../src/idempotency/idempotency-store.ts";+import { createIdentityService } from "../src/identity/identity-service.ts";+import { fireAskResolution, type AskResolutionDeps } from "../src/triggers/keychain-ask.ts";+import { runTrigger } from "../src/triggers/run-trigger.ts";+import type { KeychainAsk } from "../src/credentials/keychain.ts";+import type { Cron, Destination, RecipientConsent, TurnRequest } from "../src/types.ts";++const recipient: Destination = {+ type: "principal",+ target: "U_BOB",+ audienceScopeId: "personal:U_BOB",+ onBehalfOf: "U_ALICE",+};++async function fixture(consent?: RecipientConsent) {+ const crons = createCronStore();+ const cron = await crons.create({+ owner: "U_ALICE",+ createdBy: "U_ALICE",+ ownerScopeId: "personal:U_ALICE",+ schedule: { everyMs: 60_000 },+ action: "read the dummy account and report the result",+ destination: recipient,+ ...(consent ? { recipientConsent: consent } : {}),+ });+ const deliveries = createDeliveryStore();+ const requests: TurnRequest[] = [];+ const deps: AskResolutionDeps = {+ deliveries,+ idempotency: createIdempotencyStore(),+ identity: createIdentityService(),+ getCron: (id) => crons.get(id),+ run: async (request) => {+ requests.push(request);+ return { status: "ok", reply: "dummy scheduled result" };+ },+ };+ const ask: KeychainAsk = {+ id: "dummy-ask",+ credentialId: "dummy-credential",+ ownerId: "U_ALICE",+ requesterId: "U_ALICE",+ orgId: "test",+ requesterScopeId: "personal:U_ALICE",+ requesterThreadRef: `cron:${cron.id}:fire:123456789abc`,+ requesterDestination: recipient,+ purpose: cron.action!,+ status: "approved",+ grantId: "dummy-grant",+ createdAt: Date.now(),+ expiresAt: Date.now() + 60_000,+ };+ return { crons, cron, deps, ask, deliveries, requests };+}++for (const status of [undefined, "pending", "declined"] as const) {+ test(`cron credential approval cannot deliver without recipient consent (${status ?? "missing"})`, async () => {+ const f = await fixture(status ? { recipientId: "U_BOB", status } : undefined);+ await runTrigger(f.deps, {+ owner: f.cron.owner,+ ownerScopeId: f.cron.ownerScopeId,+ input: f.cron.action!,+ fireKey: "original-cron-fire",+ surface: "cron",+ threadRef: f.ask.requesterThreadRef,+ destination: recipient,+ recipientConsentRequired: true,+ ...(f.cron.recipientConsent ? { recipientConsent: f.cron.recipientConsent } : {}),+ });+ assert.equal((await f.deliveries.pending("principal")).filter((d) => d.destination.target === "U_BOB").length, 0);++ await fireAskResolution(f.deps, f.ask);++ const pending = await f.deliveries.pending("principal");+ assert.equal(pending.filter((d) => d.destination.target === "U_BOB").length, 0);+ assert.equal(pending.filter((d) => d.idempotencyKey?.endsWith(":fallback")).length, 0);+ });+}++test("cron credential approval rechecks consent revoked while the ask was pending", async () => {+ const f = await fixture({ recipientId: "U_BOB", status: "accepted" });+ await f.crons.setRecipientConsent(f.cron.id, {+ recipientId: "U_BOB",+ status: "declined",+ decidedAt: Date.now(),+ });++ await fireAskResolution(f.deps, f.ask);++ assert.equal((await f.deliveries.pending("principal")).filter((d) => d.destination.target === "U_BOB").length, 0);+});++test("cron credential approval resumes the original fire once and delivers to the current consented destination", async () => {+ const f = await fixture({ recipientId: "U_BOB", status: "accepted" });+ const destination: Destination = {+ type: "principal",+ target: "U_CAROL",+ audienceScopeId: "personal:U_CAROL",+ onBehalfOf: "U_ALICE",+ };+ await f.crons.setDestination(f.cron.id, destination);+ await f.crons.setRecipientConsent(f.cron.id, { recipientId: "U_CAROL", status: "accepted" });+ await f.crons.update(f.cron.id, { unattendedGrants: ["allowed-job-grant"] });++ await fireAskResolution(f.deps, f.ask);+ await fireAskResolution(f.deps, f.ask);++ assert.equal(f.requests.length, 1);+ const request = f.requests[0]!;+ assert.equal(request.triggered, true);+ assert.equal(request.actor.externalId, "U_ALICE");+ assert.equal(request.conversation.threadRef, f.ask.requesterThreadRef);+ assert.deepEqual(request.triggerDestination, destination);+ assert.deepEqual(request.unattendedGrants, ["allowed-job-grant"]);+ assert.match(request.text, /dummy-grant/);+ const pending = await f.deliveries.pending("principal");+ assert.equal(pending.length, 1);+ assert.equal(pending[0]!.destination.target, "U_CAROL");+ assert.equal(pending[0]!.text, "dummy scheduled result");+ assert.equal(pending[0]!.provenance?.sourceThreadRef, f.ask.requesterThreadRef);+});++for (const changed of ["missing", "archived", "scope", "owner"] as const) {+ test(`cron credential approval fails closed when the original cron is ${changed}`, async () => {+ const f = await fixture({ recipientId: "U_BOB", status: "accepted" });+ if (changed === "missing") await f.crons.delete(f.cron.id);+ else if (changed === "archived") await f.crons.update(f.cron.id, { archived: true });+ else {+ const current: Cron = {+ ...f.cron,+ ...(changed === "scope" ? { ownerScopeId: "personal:U_BOB" as const } : { owner: "U_BOB" }),+ };+ f.deps.getCron = async () => current;+ }++ const outcome = await fireAskResolution(f.deps, f.ask);++ assert.equal(outcome.ran, false);+ assert.equal(f.requests.length, 0);+ assert.equal((await f.deliveries.pending("principal")).length, 0);+ });+}++test("cron credential approval fails closed when no cron lookup is available", async () => {+ const f = await fixture({ recipientId: "U_BOB", status: "accepted" });+ delete f.deps.getCron;++ const outcome = await fireAskResolution(f.deps, f.ask);++ assert.equal(outcome.ran, false);+ assert.equal(f.requests.length, 0);+ assert.equal((await f.deliveries.pending("principal")).length, 0);+});++test("cron credential approval does not restore a removed delivery destination", async () => {+ const f = await fixture({ recipientId: "U_BOB", status: "accepted" });+ await f.crons.setDestination(f.cron.id, undefined);++ await fireAskResolution(f.deps, f.ask);++ assert.equal(f.requests.length, 1);+ assert.equal(f.requests[0]!.triggerDestination, undefined);+ assert.equal((await f.deliveries.pending("principal")).length, 0);+});++test("cron credential approval preserves scopeShared execution and checks current membership", async () => {+ const f = await fixture({ recipientId: "U_BOB", status: "accepted" });+ await f.crons.update(f.cron.id, {+ runAs: "scopeShared",+ members: [{ id: "U_ALICE", type: "internal" }],+ unattendedGrants: ["owner-only-grant"],+ });+ f.deps.currentScopeMembers = async () => [{ id: "U_ALICE", type: "internal" }];++ await fireAskResolution(f.deps, f.ask);++ assert.equal(f.requests.length, 1);+ assert.equal(f.requests[0]!.ownerKeychainUnion, true);+ assert.equal(f.requests[0]!.unattendedGrants, undefined);++ f.deps.currentScopeMembers = async () => [{ id: "U_BOB", type: "internal" }];+ const outcome = await fireAskResolution(f.deps, { ...f.ask, id: "later-ask" });++ assert.equal(outcome.ran, false);+ assert.equal(f.requests.length, 1);+ assert.equal((await f.deliveries.pending("principal")).length, 1);+});++for (const schedule of [{ everyMs: 60_000 }, { cron: "0 9 * * *", timezone: "UTC" }]) {+ test(`cron credential approval does not resume a paused recurring job (${JSON.stringify(schedule)})`, async () => {+ const f = await fixture({ recipientId: "U_BOB", status: "accepted" });+ await f.crons.update(f.cron.id, { schedule });+ await f.crons.setEnabled(f.cron.id, false);++ const outcome = await fireAskResolution(f.deps, f.ask);++ assert.equal(outcome.ran, false);+ assert.equal(f.requests.length, 0);+ assert.equal((await f.deliveries.pending("principal")).length, 0);+ });+}++test("cron credential approval resumes a disabled one-shot job in its original fire", async () => {+ const f = await fixture({ recipientId: "U_BOB", status: "accepted" });+ await f.crons.update(f.cron.id, { schedule: { firstFireAt: Date.now() + 60_000 } });+ await f.crons.setEnabled(f.cron.id, false);++ const outcome = await fireAskResolution(f.deps, f.ask);++ assert.equal(outcome.ran, true);+ assert.equal(f.requests.length, 1);+ assert.equal(f.requests[0]!.conversation.threadRef, f.ask.requesterThreadRef);+ assert.equal((await f.deliveries.pending("principal")).length, 1);+});diff --git a/test/cron-credential-retry.test.ts b/test/cron-credential-retry.test.tsnew file mode 100644index 000000000..a074177d8--- /dev/null+++ b/test/cron-credential-retry.test.ts@@ -0,0 +1,144 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createCronStore } from "../src/cron/cron-store.ts";+import { createDeliveryStore } from "../src/delivery/delivery-store.ts";+import { createIdempotencyStore } from "../src/idempotency/idempotency-store.ts";+import { createIdentityService } from "../src/identity/identity-service.ts";+import { createAskExpirySweep, fireAskResolution, type AskResolutionDeps } from "../src/triggers/keychain-ask.ts";+import { createKeychain, type KeychainAsk } from "../src/credentials/keychain.ts";+import { deriveConnectorKey } from "../src/connectors/connector-client-store.ts";+import { createMemoryMap } from "../src/persistence/durable-map.ts";+import type { TurnRequest, TurnResult } from "../src/types.ts";++async function fixture(run: (request: TurnRequest) => Promise<TurnResult>) {+ const crons = createCronStore();+ const cron = await crons.create({+ owner: "U_ALICE",+ createdBy: "U_ALICE",+ ownerScopeId: "personal:U_ALICE",+ schedule: { everyMs: 60_000 },+ action: "read a private dummy account",+ destination: {+ type: "principal",+ target: "U_BOB",+ audienceScopeId: "personal:U_BOB",+ onBehalfOf: "U_ALICE",+ },+ recipientConsent: { recipientId: "U_BOB", status: "declined" },+ });+ const deliveries = createDeliveryStore();+ const idempotency = createIdempotencyStore();+ const ask: KeychainAsk = {+ id: "retry-ask",+ credentialId: "dummy-credential",+ ownerId: "U_ALICE",+ requesterId: "U_ALICE",+ orgId: "test",+ requesterScopeId: "personal:U_ALICE",+ requesterThreadRef: `cron:${cron.id}:fire:123456789abc`,+ requesterDestination: cron.destination,+ purpose: "read a private dummy account",+ status: "approved",+ grantId: "dummy-grant",+ createdAt: Date.now(),+ expiresAt: Date.now() + 60_000,+ };+ const deps: AskResolutionDeps = {+ deliveries,+ idempotency,+ identity: createIdentityService(),+ getCron: (id) => crons.get(id),+ run,+ };+ return { crons, cron, deliveries, idempotency, ask, deps };+}++test("busy cron credential resolution leaves its fire retryable and resumes exactly once when available", async () => {+ const requests: TurnRequest[] = [];+ const f = await fixture(async (request) => {+ requests.push(request);+ return requests.length === 1+ ? { status: "refused", refusalKind: "session_busy", reason: "conversation is busy" }+ : { status: "ok", reply: "dummy scheduled result" };+ });+ await f.crons.setRecipientConsent(f.cron.id, { recipientId: "U_BOB", status: "accepted" });+ const fireKey = `ask:${f.ask.id}:approved`;++ await assert.rejects(fireAskResolution(f.deps, f.ask));++ assert.equal(await f.idempotency.committed(fireKey), false);+ assert.equal((await f.deliveries.pending("principal")).length, 0);+ const resumed = await fireAskResolution(f.deps, f.ask);+ assert.equal(resumed.status, "ok");+ assert.equal(await f.idempotency.committed(fireKey), true);+ await fireAskResolution(f.deps, f.ask);++ assert.equal(requests.length, 2);+ assert.ok(requests.every((request) => request.conversation.threadRef === f.ask.requesterThreadRef));+ assert.ok(requests.every((request) => request.triggered === true));+ const pending = await f.deliveries.pending("principal");+ assert.equal(pending.length, 1);+ assert.equal(pending[0]!.destination.target, "U_BOB");+ assert.equal(pending[0]!.text, "dummy scheduled result");+});++test("failed cron credential resolution notifies only the owner even when its recipient declined delivery", async () => {+ let runs = 0;+ const f = await fixture(async () => {+ runs++;+ return { status: "failed", reason: "model unavailable" };+ });++ const failed = await fireAskResolution(f.deps, f.ask);+ await fireAskResolution(f.deps, f.ask);++ assert.equal(failed.status, "failed");+ assert.equal(runs, 1);+ const pending = await f.deliveries.pending("principal");+ assert.equal(pending.length, 1);+ assert.equal(pending[0]!.destination.target, "U_ALICE");+ assert.equal(pending[0]!.destination.audienceScopeId, "personal:U_ALICE");+ assert.match(pending[0]!.text, /couldn't resume the task automatically/);+ assert.match(pending[0]!.text, /retry-ask/);+ assert.equal(pending.filter((delivery) => delivery.destination.target === "U_BOB").length, 0);+});++test("a concurrent sweep cannot mark an in-flight busy resume notified before it becomes retryable", async () => {+ const entered = Promise.withResolvers<void>();+ const release = Promise.withResolvers<TurnResult>();+ let runs = 0;+ const f = await fixture(async () => {+ runs++;+ if (runs > 1) return { status: "ok", reply: "dummy scheduled result" };+ entered.resolve();+ return release.promise;+ });+ await f.crons.setRecipientConsent(f.cron.id, { recipientId: "U_BOB", status: "accepted" });+ const asks = createMemoryMap<KeychainAsk>();+ await asks.put(f.ask.id, f.ask);+ const keychain = createKeychain({+ creds: createMemoryMap(),+ grants: createMemoryMap(),+ asks,+ key: deriveConnectorKey("concurrent-cron-resume-test"),+ });+ const sweep = createAskExpirySweep({ keychain, fire: (ask) => fireAskResolution(f.deps, ask) });+ const initial = assert.rejects(fireAskResolution(f.deps, f.ask), /waiting for the original conversation/);+ await entered.promise;++ await sweep(Date.now());+ assert.equal((await keychain.getAsk(f.ask.id))?.notifiedAt, undefined);+ release.resolve({ status: "refused", refusalKind: "session_busy", reason: "conversation is busy" });+ await initial;+ assert.equal(await f.idempotency.committed(`ask:${f.ask.id}:approved`), false);++ await sweep(Date.now());+ await sweep(Date.now());++ assert.equal(runs, 2);+ assert.notEqual((await keychain.getAsk(f.ask.id))?.notifiedAt, undefined);+ assert.equal(await f.idempotency.committed(`ask:${f.ask.id}:approved`), true);+ const pending = await f.deliveries.pending("principal");+ assert.equal(pending.length, 1);+ assert.equal(pending[0]!.destination.target, "U_BOB");+});diff --git a/test/keychain-ask.test.ts b/test/keychain-ask.test.tsindex 44a04afc2..4d3f1224a 100644--- a/test/keychain-ask.test.ts+++ b/test/keychain-ask.test.ts@@ -53,7 +53,7 @@ const GH = {accountLabel: "alice-acme",};-test("createAsk: owner derived from the credential, purpose frozen, dedup per (credential, scope)", async () => {+test("createAsk: owner derived from the credential, purpose frozen, dedup per (credential, scope, task)", async () => {const k = kcAt(() => 1_000_000);const cred = await k.save(GH);@@ -61,10 +61,16 @@ test("createAsk: owner derived from the credential, purpose frozen, dedup per (ck.createAsk({ credentialId: "nope", requesterId: "U_BOB", requesterScopeId: "channel:C1", purpose: "x" }),(e: KeychainError) => e.status === 404,);+ const self = await k.createAsk({+ credentialId: cred.id,+ requesterId: "U_ALICE",+ requesterScopeId: "personal:U_ALICE",+ purpose: "scheduled check",+ });+ assert.equal(self.ask.status, "pending");await assert.rejects(- k.createAsk({ credentialId: cred.id, requesterId: "U_ALICE", requesterScopeId: "channel:C1", purpose: "x" }),- (e: KeychainError) => e.status === 400,- "asking for your own credential is a grant, not an ask",+ k.createAsk({ credentialId: cred.id, requesterId: "U_BOB", requesterScopeId: "personal:U_BOB", purpose: "x" }),+ (e: KeychainError) => e.status === 403,);const { ask, existing } = await k.createAsk({@@ -85,9 +91,10 @@ test("createAsk: owner derived from the credential, purpose frozen, dedup per (crequesterId: "U_BOB",requesterScopeId: "channel:C1",purpose: "different words",+ requesterThreadRef: "ch:C1-t1",});assert.equal(again.existing, true);- assert.equal(again.ask.id, ask.id, "one pending ask per (credential, scope) — re-asks are silent");+ assert.equal(again.ask.id, ask.id, "one pending ask per (credential, scope, task) — re-asks are silent");assert.equal(again.ask.purpose, "clone acme/payments and run the tests", "the original purpose stays frozen");const elsewhere = await k.createAsk({@@ -99,6 +106,79 @@ test("createAsk: owner derived from the credential, purpose frozen, dedup per (cassert.equal(elsewhere.existing, false, "a different scope is a different ask");});+test("personal cron asks deduplicate recurring fires without combining jobs or re-asking after denial", async () => {+ let now = 1000000;+ const k = kcAt(() => now++);+ const cred = await k.save(GH);+ const base = {+ credentialId: cred.id,+ requesterId: "U_ALICE",+ requesterScopeId: "personal:U_ALICE" as const,+ purpose: "first task",+ triggered: true,+ };+ const first = await k.createAsk({ ...base, requesterThreadRef: "cron:first:fire:one" });+ const second = await k.createAsk({ ...base, requesterThreadRef: "cron:second:fire:one", purpose: "second task" });+ assert.notEqual(first.ask.id, second.ask.id);+ const retry = await k.createAsk({ ...base, requesterThreadRef: "cron:first:fire:two" });+ assert.equal(retry.ask.id, first.ask.id);+ assert.equal(retry.ask.requesterThreadRef, "cron:first:fire:one");+ assert.equal(retry.existing, true);+ await k.declineAsk({ askId: first.ask.id, ownerId: "U_ALICE", note: "no" });+ await assert.rejects(+ k.createAsk({ ...base, requesterThreadRef: "cron:first:fire:three" }),+ (e: KeychainError) => e.status === 409,+ );+ const revived = await k.createAsk({ ...base, triggered: false, requesterThreadRef: "cron:first:fire:four" });+ const waiting = await k.createAsk({ ...base, requesterThreadRef: "cron:first:fire:five" });+ assert.equal(waiting.ask.id, revived.ask.id);+ await k.approveAsk({ askId: revived.ask.id, ownerId: "U_ALICE", mode: "once", purpose: "yes" });+ assert.equal((await k.getAsk(second.ask.id))?.status, "pending");+ now += ASK_TTL_MS + 1;+ await assert.rejects(+ k.createAsk({ ...base, requesterThreadRef: "cron:second:fire:two" }),+ (e: KeychainError) => e.status === 409,+ );+});++for (const outcome of ["declined", "expired"] as const) {+ test(`task ${outcome} decisions survive pruning and a later approval supersedes them`, async () => {+ let now = 1_000_000;+ const k = kcAt(() => now++);+ const credential = await k.save(GH);+ const input = {+ credentialId: credential.id,+ requesterId: "U_ALICE",+ requesterScopeId: "personal:U_ALICE" as const,+ requesterThreadRef: "cron:retained:fire:first",+ purpose: "scheduled check",+ triggered: true,+ };+ const { ask } = await k.createAsk(input);+ if (outcome === "declined") await k.declineAsk({ askId: ask.id, ownerId: "U_ALICE" });+ else now += ASK_TTL_MS + 1;+ const sweep = createAskExpirySweep({ keychain: k, fire: async () => undefined });+ await sweep(now);+ now += ASK_PRUNE_AFTER_MS + 1;+ await sweep(now);+ assert.equal((await k.getAsk(ask.id))?.status, outcome);+ await assert.rejects(+ k.createAsk({ ...input, requesterThreadRef: "cron:retained:fire:later" }),+ (e: KeychainError) => e.status === 409,+ );+ const revived = await k.createAsk({ ...input, triggered: false });+ await k.approveAsk({ askId: revived.ask.id, ownerId: "U_ALICE", mode: "once", purpose: "retry it" });+ await sweep(now);+ now += ASK_PRUNE_AFTER_MS + 1;+ await sweep(now);+ assert.equal(await k.getAsk(ask.id), null);+ assert.equal((await k.getAsk(revived.ask.id))?.status, "approved");+ const next = await k.createAsk({ ...input, requesterThreadRef: "cron:retained:fire:next" });+ assert.equal(next.existing, false);+ assert.equal(next.ask.status, "pending");+ });+}+test("approveAsk: same createGrant owner gate, audience from the record, single resolution", async () => {const k = kcAt(Date.now);const cred = await k.save(GH);@@ -606,7 +686,7 @@ describe("/v1/keychain/asks — the consent ladder end to end", async () => {await new Promise<void>((resolve) => server.close(() => resolve()));});- it("gates creation: channels only, owner must be a directory-verified member (fail closed)", async () => {+ it("gates creation: personal ownership and directory-verified channel membership", async () => {const { credential } = (await (await post("/v1/keychain/credentials",@@ -889,7 +969,287 @@ describe("/v1/keychain/asks — the consent ladder end to end", async () => {{ credential: gh.id, purpose: "p" },await capFor("U_BOB", "channel:C_INFRA", { triggered: true }),);- assert.equal(send.status, 403);+ assert.equal(send.status, 200, "background requests may ask but cannot approve");+ });++ for (const kind of ["channel", "group", "project"] as const) {+ for (const requesterId of ["U_ALICE", "U_BOB"]) {+ it(`${kind} scheduled request for ${requesterId === "U_ALICE" ? "own" : "another person's"} credential requires approval and resumes in place`, async () => {+ let scope: CapabilityClaims["scopeId"] = "channel:C_INFRA";+ let scopeVersion: string | undefined;+ if (kind === "group") {+ scope = "group:G_SHARED";+ await built.app.upsertGroups([+ { groupId: "G_SHARED", principalId: "U_ALICE" },+ { groupId: "G_SHARED", principalId: "U_BOB" },+ ]);+ } else if (kind === "project") {+ const project = await built.app.createProject("U_ALICE", `Approval QA ${requesterId}`);+ assert.ok(project);+ assert.equal((await built.app.addProjectMember(project.id, "U_ALICE", "U_BOB")).status, "ok");+ scope = project.scopeId;+ scopeVersion = await built.projects.version(scope.slice("group:".length));+ }+ const credential = await built.keychain!.save({+ ownerId: "U_ALICE",+ service: `shared-${kind}-${requesterId}`,+ secret: "synthetic-shared-value",+ envKey: "SHARED_QA_TOKEN",+ });+ const cron = await built.app.createCron({+ owner: requesterId,+ createdBy: requesterId,+ ownerScopeId: scope,+ title: "Shared credential QA",+ action: "run the synthetic shared check",+ schedule: { firstFireAt: Date.now() + 3600000 },+ });+ const threadRef = `cron:${cron.id}:fire:first`;+ const token = await capFor(requesterId, scope, {+ triggered: true,+ threadRef,+ ...(scopeVersion ? { scopeVersion } : {}),+ });+ const liveOwner = await capFor("U_ALICE", "personal:U_ALICE", { liveActor: true });+ const seed = await built.app.turn({+ surface: "cron",+ triggered: true,+ actor: { externalId: requesterId },+ conversation: {+ kind: kind === "channel" ? "channel" : "group",+ threadRef,+ channelRef: scope.slice(scope.indexOf(":") + 1),+ audience: [{ externalId: "U_ALICE" }, { externalId: "U_BOB" }],+ },+ text: "waiting for permission for a synthetic shared job",+ } as TurnRequest);+ assert.equal(seed.status, "ok");+ const session = await built.sessions.getByThread(threadRef);+ assert.ok(session);+ assert.equal((await post("/v1/keychain/use", { credential: credential.id }, token)).status, 403);+ const made = await post(+ "/v1/keychain/asks",+ { credential: credential.id, purpose: "run the synthetic shared check" },+ token,+ );+ assert.equal(made.status, 200, await made.clone().text());+ const { ask } = (await made.json()) as any;+ assert.equal(ask.ownerId, "U_ALICE");+ assert.equal(ask.requesterId, requesterId);+ const notices = (await built.deliveries.pending("principal")).filter(+ (d) => d.idempotencyKey === `ask:${ask.id}:notice`,+ );+ assert.equal(notices.length, 1);+ assert.equal(notices[0]!.destination.target, "U_ALICE");+ assert.match(notices[0]!.text, /Scheduled task "Shared credential QA"/);+ if (kind === "project") assert.match(notices[0]!.text, /Approval QA/);+ assert.ok(!notices[0]!.text.includes("synthetic-shared-value"));+ assert.equal(+ (await post("/v1/keychain/grants", { ask: ask.id, mode: "once", purpose: "I approve myself" }, token)).status,+ 403,+ );+ if (requesterId !== "U_ALICE")+ assert.equal(+ (+ await post(+ "/v1/keychain/grants",+ { ask: ask.id, mode: "once", purpose: "Alice said yes" },+ await capFor(requesterId),+ )+ ).status,+ 403,+ );+ const response = await post(+ "/v1/keychain/grants",+ { ask: ask.id, mode: "once", purpose: "yes, for this shared check" },+ liveOwner,+ );+ assert.equal(response.status, 200, await response.clone().text());+ const { grant, use } = (await response.json()) as any;+ assert.equal(grant.audienceScopeId, scope);+ assert.equal(use.command, undefined);+ const resumed = await waitFor(async () =>+ (await built.sessions.getEntries(session.id)).filter(+ (e) => e.type === "user" && JSON.stringify(e.payload).includes(`Keychain ask \`${ask.id}\` was approved`),+ ),+ );+ 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, 410);+ });+ }+ }++ it("shared background requests reject nonmembers, outsiders, stale project membership and inaccessible credentials", async () => {+ const credential = await built.keychain!.save({+ ownerId: "U_ALICE",+ service: "shared-private-gates",+ secret: "dummy",+ envKey: "QA_TOKEN",+ });+ await built.app.upsertDirectory([+ { principalId: "U_ALICE", displayName: "Alice", type: "internal" },+ { principalId: "U_BOB", displayName: "Bob", type: "internal" },+ { principalId: "U_EVE", displayName: "Eve", type: "internal" },+ { principalId: "U_EXTERNAL", displayName: "External", type: "guest" },+ ]);+ await built.app.upsertGroups([+ { groupId: "G_GUEST_QA", principalId: "U_ALICE" },+ { groupId: "G_GUEST_QA", principalId: "U_EXTERNAL" },+ ]);+ const external = await built.keychain!.save({+ ownerId: "U_EXTERNAL",+ service: "external-gate",+ secret: "dummy",+ envKey: "QA_TOKEN",+ });+ for (const [actor, scope, credentialId] of [+ ["U_BOB", "channel:C_NOALICE", credential.id],+ ["U_EVE", "channel:C_INFRA", credential.id],+ ["U_BOB", "group:G_UNKNOWN", credential.id],+ ["U_BOB", "channel:C_PUBLIC", external.id],+ ["U_EXTERNAL", "group:G_GUEST_QA", credential.id],+ ["U_BOB", "personal:U_BOB", credential.id],+ ] as const) {+ assert.equal(+ (+ await post(+ "/v1/keychain/asks",+ { credential: credentialId, purpose: "denied check" },+ await capFor(actor, scope, { triggered: true }),+ )+ ).status,+ 403,+ `${actor} in ${scope} requesting ${credentialId}`,+ );+ }+ const project = await built.app.createProject("U_BOB", "Membership check");+ assert.ok(project);+ await built.app.addProjectMember(project.id, "U_BOB", "U_ALICE");+ const scopeVersion = await built.projects.version(project.scopeId.slice("group:".length));+ const stale = await capFor("U_BOB", project.scopeId, { triggered: true, scopeVersion });+ await built.app.removeProjectMember(project.id, "U_BOB", "U_ALICE");+ assert.equal(+ (await post("/v1/keychain/asks", { credential: credential.id, purpose: "stale check" }, stale)).status,+ 403,+ );+ });++ for (const mode of ["once", "standing"] as const) {+ it(`personal scheduled request waits for approval, resumes its original thread, and respects ${mode} grants`, async () => {+ const threadRef = `dm:U_ALICE-cron-${mode}`;+ const personal = scopeId("personal", "U_ALICE");+ const token = await capFor("U_ALICE", personal, { triggered: true, threadRef });+ const live = await capFor("U_ALICE", personal, { liveActor: true });+ const { credential } = (await (+ await post(+ "/v1/keychain/credentials",+ { service: `cron-${mode}`, secret: "dummy-cron-value", envKey: "CRON_QA_TOKEN" },+ live,+ )+ ).json()) as any;+ const seed = await built.app.turn({+ surface: "slack",+ actor: { externalId: "U_ALICE" },+ conversation: { kind: "dm", threadRef },+ text: "waiting for scheduled credential approval",+ } as TurnRequest);+ assert.equal(seed.status, "ok");+ const session = await built.sessions.getByThread(threadRef);+ assert.ok(session);+ const denied = await post("/v1/keychain/use", { credential: credential.id }, token);+ assert.equal(denied.status, 403);+ assert.match(((await denied.json()) as any).message, /keychain\/asks/);+ const requested = await post(+ "/v1/keychain/asks",+ { credential: credential.id, purpose: "read-only dummy scheduled check", requestedMode: mode },+ token,+ );+ assert.equal(requested.status, 200);+ const { ask } = (await requested.json()) as any;+ assert.equal(ask.status, "pending");+ assert.equal(+ (await built.keychain!.listGrants({ audienceScopeId: personal })).filter(+ (g) => g.credentialId === credential.id,+ ).length,+ 0,+ );+ const duplicate = (await (+ await post("/v1/keychain/asks", { credential: credential.id, purpose: "retry" }, token)+ ).json()) as any;+ assert.equal(duplicate.ask.id, ask.id);+ assert.equal(duplicate.existing, true);+ const notices = (await built.deliveries.pending("principal")).filter(+ (d) => d.idempotencyKey === `ask:${ask.id}:notice`,+ );+ assert.equal(notices.length, 1);+ assert.equal(notices[0]!.destination.target, "U_ALICE");+ assert.match(notices[0]!.text, /A task in your personal conversation is asking/);+ assert.ok(!notices[0]!.text.includes("dummy-cron-value"));+ assert.equal(+ (await post("/v1/keychain/grants", { ask: ask.id, mode, purpose: "approve myself" }, token)).status,+ 403,+ );+ assert.equal(+ (await post("/v1/keychain/grants", { ask: ask.id, mode, purpose: "Alice said yes" }, await capFor("U_BOB")))+ .status,+ 403,+ );+ const approval = await post(+ "/v1/keychain/grants",+ { ask: ask.id, mode, purpose: "yes, run this dummy check" },+ live,+ );+ assert.equal(approval.status, 200);+ const approved = (await approval.json()) as any;+ assert.equal(approved.grant.audienceScopeId, personal);+ assert.equal(approved.use.command, undefined);+ assert.match(approved.use.note, /Do not load or consume/);+ const resumed = await waitFor(async () =>+ (await built.sessions.getEntries(session.id)).filter(+ (e) => e.type === "user" && JSON.stringify(e.payload).includes(`Keychain ask \`${ask.id}\` was approved`),+ ),+ );+ 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);+ const second = await post("/v1/keychain/use", { grant: approved.grant.id }, token);+ assert.equal(second.status, mode === "standing" ? 200 : 410);+ 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);+ }+ });+ }++ it("a scheduled personal request can be declined without granting access", async () => {+ const live = await capFor("U_ALICE", "personal:U_ALICE", { liveActor: true });+ const token = await capFor("U_ALICE", "personal:U_ALICE", { triggered: true });+ const { credential } = (await (+ await post(+ "/v1/keychain/credentials",+ { service: "cron-decline", secret: "dummy", envKey: "CRON_QA_TOKEN" },+ live,+ )+ ).json()) as any;+ const { ask } = (await (+ await post("/v1/keychain/asks", { credential: credential.id, purpose: "dummy declined check" }, token)+ ).json()) as any;+ assert.equal((await post(`/v1/keychain/asks/${ask.id}/decline`, {}, token)).status, 403);+ assert.equal((await post(`/v1/keychain/asks/${ask.id}/decline`, { note: "no" }, live)).status, 200);+ assert.equal((await built.keychain!.getAsk(ask.id))?.status, "declined");+ assert.equal((await post("/v1/keychain/use", { credential: credential.id }, token)).status, 403);+ assert.equal(+ (+ await post(+ "/v1/keychain/asks",+ { credential: credential.id, purpose: "wrong scope" },+ await capFor("U_ALICE", "personal:U_BOB", { triggered: true }),+ )+ ).status,+ 403,+ );});it("expiry: the scheduler sweep fires exactly one expired-resolution turn into the asking channel", async () => {diff --git a/test/keychain.test.ts b/test/keychain.test.tsindex bdbfe4275..df6efe1e8 100644--- a/test/keychain.test.ts+++ b/test/keychain.test.ts@@ -984,10 +984,10 @@ test("manifest: in the owner's personal scope their own credentials need no granscopeGrants: [],injected: [],});- assert.match(own, /their own — no grant needed in this personal conversation/);- assert.match(own, /access is implied/);+ assert.match(own, /their own — no grant needed on their live turn/);+ assert.match(own, /Background and scheduled turns require an explicit grant/);assert.match(own, /"credential":"<credential id>"/);- assert.match(own, /works only here, in their personal conversation/);+ assert.match(own, /works only on their live turn in their personal conversation/);assert.ok(!own.includes("no grant for this conversation"));assert.match(own,diff --git a/test/shared-credential-resumption.test.ts b/test/shared-credential-resumption.test.tsnew file mode 100644index 000000000..95d4f6717--- /dev/null+++ b/test/shared-credential-resumption.test.ts@@ -0,0 +1,236 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createCronStore } from "../src/cron/cron-store.ts";+import { createKeychain, KeychainError, ASK_TTL_MS } from "../src/credentials/keychain.ts";+import { deriveConnectorKey } from "../src/connectors/connector-client-store.ts";+import { createDeliveryStore } from "../src/delivery/delivery-store.ts";+import { createIdempotencyStore } from "../src/idempotency/idempotency-store.ts";+import { createIdentityService } from "../src/identity/identity-service.ts";+import { createMemoryMap } from "../src/persistence/durable-map.ts";+import { fireAskResolution, type AskResolutionDeps } from "../src/triggers/keychain-ask.ts";+import { runTrigger } from "../src/triggers/run-trigger.ts";+import type { Principal, ScopeId, TurnRequest } from "../src/types.ts";++function keychain(now = Date.now) {+ return createKeychain({+ creds: createMemoryMap(),+ grants: createMemoryMap(),+ asks: createMemoryMap(),+ key: deriveConnectorKey("shared-credential-resumption-test"),+ now,+ });+}++async function fixture(scope: ScopeId = "channel:C_SHARED") {+ const k = keychain();+ const credential = await k.save({+ ownerId: "U_CREDENTIAL_OWNER",+ service: "dummy",+ secret: "dummy-only-secret",+ envKey: "DUMMY_TOKEN",+ });+ const crons = createCronStore();+ const cron = await crons.create({+ owner: "U_JOB_OWNER",+ createdBy: "U_JOB_OWNER",+ ownerScopeId: scope,+ runAs: "scopeFloor",+ members: [{ id: "U_JOB_OWNER", type: "internal" }],+ unattendedGrants: ["private-owner-grant"],+ schedule: { everyMs: 60_000 },+ action: "read the dummy account",+ destination: {+ type: "principal",+ target: "U_REQUESTER",+ audienceScopeId: "personal:U_REQUESTER",+ onBehalfOf: "U_JOB_OWNER",+ },+ recipientConsent: { recipientId: "U_REQUESTER", status: "accepted" },+ });+ const state: { members: Principal[] } = { members: [{ id: "U_REQUESTER", type: "internal" }] };+ const requests: TurnRequest[] = [];+ const deliveries = createDeliveryStore();+ const deps: AskResolutionDeps = {+ deliveries,+ idempotency: createIdempotencyStore(),+ identity: createIdentityService(),+ currentScopeMembers: async () => state.members,+ getCron: (id) => crons.get(id),+ getGrant: (id) => k.getGrant(id),+ run: async (request) => {+ requests.push(request);+ return request.surface === "cron" ? { status: "silent" } : { status: "ok", reply: "dummy result" };+ },+ };+ await deps.identity.deactivate(cron.owner);+ const threadRef = `cron:${cron.id}:fire:first`;+ await runTrigger(deps, {+ ...cron,+ input: cron.action!,+ fireKey: "original-fire",+ threadRef,+ surface: "cron",+ recipientConsentRequired: true,+ });+ assert.equal(requests.length, 1);+ assert.equal(requests[0]!.actor.externalId, "U_REQUESTER");+ const { ask } = await k.createAsk({+ credentialId: credential.id,+ requesterId: requests[0]!.actor.externalId,+ requesterScopeId: scope,+ requesterThreadRef: requests[0]!.conversation.threadRef,+ requesterDestination: requests[0]!.triggerDestination,+ triggered: true,+ purpose: cron.action!,+ });+ const approved = await k.approveAsk({+ askId: ask.id,+ ownerId: credential.ownerId,+ mode: "once",+ purpose: "read only the dummy account",+ });+ requests.length = 0;+ return { k, credential, crons, cron, state, requests, deliveries, deps, ...approved };+}++for (const scope of ["channel:C_SHARED", "group:G_SHARED", "group:web-project-shared"] as const) {+ test(`scopeFloor approval resumes another person's credential in ${scope} after the job owner departs`, async () => {+ const f = await fixture(scope);++ const outcome = await fireAskResolution(f.deps, f.ask);+ await fireAskResolution(f.deps, f.ask);++ assert.equal(outcome.status, "ok");+ assert.equal(f.requests.length, 1);+ const request = f.requests[0]!;+ assert.equal(request.actor.externalId, "U_REQUESTER");+ assert.equal(request.triggered, true);+ assert.equal(request.conversation.threadRef, f.ask.requesterThreadRef);+ assert.equal(request.conversation.kind, scope.startsWith("channel:") ? "channel" : "group");+ assert.equal(request.conversation.channelRef, scope.slice(scope.indexOf(":") + 1));+ assert.deepEqual(request.conversation.audience, [{ externalId: "U_REQUESTER" }]);+ assert.equal(request.unattendedGrants, undefined);+ assert.equal(request.ownerKeychainUnion, undefined);+ assert.deepEqual(request.triggerDestination, f.cron.destination);+ assert.match(request.text, /read only the dummy account/);+ assert.ok(request.text.includes(f.grant.id));+ assert.equal(f.grant.audienceScopeId, scope);+ assert.equal(f.grant.ownerId, "U_CREDENTIAL_OWNER");+ await assert.rejects(+ f.k.materialize(f.grant.id, "channel:C_OTHER", request.actor.externalId),+ (error: KeychainError) => error.status === 403,+ );+ 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");+ await assert.rejects(+ f.k.materialize(f.grant.id, scope, request.actor.externalId),+ (error: KeychainError) => error.status === 410,+ );+ const pending = await f.deliveries.pending("principal");+ assert.equal(pending.length, 1);+ assert.equal(pending[0]!.destination.target, "U_REQUESTER");+ });+}++test("scopeFloor approval reselects the current actor when the original requester also departed", async () => {+ const f = await fixture();+ f.state.members = [{ id: "U_NEW_MEMBER", type: "internal" }];+ await f.deps.identity.deactivate("U_REQUESTER");++ await fireAskResolution(f.deps, f.ask);++ assert.equal(f.requests.length, 1);+ assert.equal(f.requests[0]!.actor.externalId, "U_NEW_MEMBER");+});++test("scopeFloor approval selects the stored job owner again when they return", async () => {+ const f = await fixture();+ await f.deps.identity.reactivate(f.cron.owner);+ f.state.members = [+ { id: "U_REQUESTER", type: "internal" },+ { id: f.cron.owner, type: "internal" },+ ];++ await fireAskResolution(f.deps, f.ask);++ assert.equal(f.requests[0]!.actor.externalId, f.cron.owner);+});++for (const members of [[], [{ id: "U_JOB_OWNER", type: "internal" as const }]]) {+ test(`scopeFloor approval fails closed with no active internal member (${members.length} stale members)`, async () => {+ const f = await fixture();+ f.state.members = members;++ const outcome = await fireAskResolution(f.deps, f.ask);++ assert.equal(outcome.authzFailed, true);+ assert.equal(outcome.ran, false);+ assert.equal(f.requests.length, 0);+ assert.equal((await f.deliveries.pending("principal")).length, 0);+ assert.equal((await f.k.getGrant(f.grant.id))?.status, "active");+ });+}++test("substituted scopeFloor requester still needs recipient consent for delivery to themselves", async () => {+ const f = await fixture();+ await f.crons.setRecipientConsent(f.cron.id, { recipientId: "U_REQUESTER", status: "declined" });++ const outcome = await fireAskResolution(f.deps, f.ask);++ assert.equal(outcome.status, "refused");+ assert.equal(f.requests.length, 1);+ const pending = await f.deliveries.pending("principal");+ assert.equal(pending.length, 1);+ assert.equal(pending[0]!.destination.target, "U_JOB_OWNER");+ assert.ok(pending.every((delivery) => !delivery.idempotencyKey?.endsWith(":fallback")));+});++for (const runAs of ["owner", "scopeShared"] as const) {+ test(`approval cannot substitute a requester after the cron changes to ${runAs}`, async () => {+ const f = await fixture();+ await f.crons.update(f.cron.id, { runAs });++ const outcome = await fireAskResolution(f.deps, f.ask);++ assert.equal(outcome.authzFailed, true);+ assert.equal(f.requests.length, 0);+ assert.equal((await f.deliveries.pending("principal")).length, 0);+ });+}++for (const scope of ["channel:C_SHARED", "group:G_SHARED", "group:web-project-shared"] as const) {+ test(`shared asks in ${scope} deduplicate by job across actors and keep live requests separate`, async () => {+ let now = 1_000_000;+ const k = keychain(() => now++);+ const credential = await k.save({ ownerId: "U_OWNER", service: "dummy", secret: "fake", envKey: "DUMMY_TOKEN" });+ const base = {+ credentialId: credential.id,+ requesterId: "U_OWNER",+ requesterScopeId: scope,+ purpose: "read dummy account",+ triggered: true,+ };+ const first = await k.createAsk({ ...base, requesterThreadRef: "cron:first:fire:one" });+ const second = await k.createAsk({ ...base, requesterThreadRef: "cron:second:fire:one" });+ const live = await k.createAsk({ ...base, triggered: false, requesterThreadRef: "live-thread" });+ assert.equal(new Set([first.ask.id, second.ask.id, live.ask.id]).size, 3);+ const retry = await k.createAsk({ ...base, requesterId: "U_OTHER", requesterThreadRef: "cron:first:fire:two" });+ assert.equal(retry.existing, true);+ assert.equal(retry.ask.id, first.ask.id);+ assert.equal(retry.ask.requesterThreadRef, first.ask.requesterThreadRef);+ await k.declineAsk({ askId: first.ask.id, ownerId: "U_OWNER" });+ await k.approveAsk({ askId: live.ask.id, ownerId: "U_OWNER", mode: "once", purpose: "live use only" });+ await assert.rejects(+ k.createAsk({ ...base, requesterThreadRef: "cron:first:fire:three" }),+ (error: KeychainError) => error.status === 409,+ );+ const revived = await k.createAsk({ ...base, triggered: false, requesterThreadRef: "cron:first:fire:four" });+ assert.notEqual(revived.ask.id, first.ask.id);+ assert.equal((await k.getAsk(second.ask.id))?.status, "pending");+ now += ASK_TTL_MS + 1;+ await assert.rejects(+ k.createAsk({ ...base, requesterThreadRef: "cron:second:fire:two" }),+ (error: KeychainError) => error.status === 409,+ );+ });+}