From 07b790c234e82542d49a9a847d0939237b5592ac Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 22:13:38 -0600 Subject: [PATCH] feat(pm-orchestration): DSP-01 signed webhook fan-out to Fleet command acceptance (#9445) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Projector: add src/operation-forwarder.ts (semantic idempotency key from repo+issue+comment+verb, never the delivery GUID) and forward on every verified delivery through an injectable FleetOperationSink in ServerDeps. The already-applied duplicate branch now retries the forward instead of suppressing it; a forward failure after the projection is recorded applied answers 500 so GitHub redelivery reconciles. No sink configured = projection-only behavior unchanged. Fleet: add work::operations, the canonical command-acceptance contract — authenticated principal, per-verb/per-resource grants, and an acceptance ledger whose stored receipt is returned on repeat presentation regardless of delivery GUID. Tests: operation_forward_retries_after_projector_delivery_is_applied and pmo_dsp_01_existing_webhook_auth_fans_out_to_one_authorized_command (bun, 18/18 across the three webhook files); pmo_dsp_01_command_acceptance_is_durable_separate_from_projection_delivery (cargo, listed then run; work:: sweep 43/43). --- pkgs/fleet/crates/fleet-queue/src/work/mod.rs | 1 + .../crates/fleet-queue/src/work/operations.rs | 461 ++++++++++++++++++ pm-stack/projector/src/operation-forwarder.ts | 161 ++++++ pm-stack/projector/src/server.ts | 56 ++- .../test/webhook-delivery-id.test.ts | 123 +++++ .../test/webhook-operation-forwarding.test.ts | 221 +++++++++ 6 files changed, 1017 insertions(+), 6 deletions(-) create mode 100644 pkgs/fleet/crates/fleet-queue/src/work/operations.rs create mode 100644 pm-stack/projector/src/operation-forwarder.ts create mode 100644 pm-stack/projector/test/webhook-operation-forwarding.test.ts diff --git a/pkgs/fleet/crates/fleet-queue/src/work/mod.rs b/pkgs/fleet/crates/fleet-queue/src/work/mod.rs index 30d54bc5da..864628819c 100644 --- a/pkgs/fleet/crates/fleet-queue/src/work/mod.rs +++ b/pkgs/fleet/crates/fleet-queue/src/work/mod.rs @@ -7,6 +7,7 @@ pub mod authority; pub mod completion; pub mod degraded; +pub mod operations; pub mod routing; pub mod selection; #[cfg(feature = "queue-broker")] diff --git a/pkgs/fleet/crates/fleet-queue/src/work/operations.rs b/pkgs/fleet/crates/fleet-queue/src/work/operations.rs new file mode 100644 index 0000000000..a144ee552b --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/work/operations.rs @@ -0,0 +1,461 @@ +//! Canonical Fleet command acceptance — DSP-01 +//! (developing-today/code#9445; design parent #9203, program #9196). +//! +//! A signed GitHub webhook event can carry a `/fleet` command. The +//! projector that receives it is bounded transport: its delivery +//! table dedupes *projection application*, and that dedupe is not — +//! and must never be read as — command acceptance. This module is +//! the acceptance contract the queue-broker handler persists: +//! +//! * **Authenticated principal first.** An unauthenticated actor is +//! refused before any grant is consulted; nothing is recorded. +//! * **Per-verb, per-resource authorization.** A grant names one +//! principal, the verbs it may run, and the repositories it may +//! run them on. Any mismatch refuses with a distinct reason and +//! records nothing — a refusal is never a partial acceptance. +//! * **Durable idempotency, keyed semantically.** Acceptance is +//! keyed by the command's idempotency key (repo + issue + comment +//! + verb, minted by the forwarding projector). The GitHub +//! delivery GUID rides along as provenance only: two deliveries +//! of the same command — including a redelivery after the +//! projector already applied the projection — produce exactly one +//! effect and the second returns the stored receipt. +//! +//! This is a pure model, like its `work` siblings: it holds the +//! acceptance ledger in memory and does no I/O. The broker adapter +//! owns persisting the ledger; the projector's `pmp_deliveries` +//! keyspace is never consulted here. + +use std::collections::BTreeMap; + +/// An actor identity as proven by the verified provider context. +/// `authenticated` is false for an actor the intake could not +/// authenticate; such a principal can never be authorized. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Principal { + /// Stable actor login (e.g. the GitHub login from the signed + /// webhook payload). + pub login: String, + /// Whether the intake authenticated this actor. + pub authenticated: bool, +} + +impl Principal { + /// An actor the intake authenticated under `login`. + pub fn authenticated(login: impl Into) -> Self { + Principal { + login: login.into(), + authenticated: true, + } + } + + /// An actor the intake could not authenticate. + pub fn unauthenticated(login: impl Into) -> Self { + Principal { + login: login.into(), + authenticated: false, + } + } +} + +/// One verb of the /fleet command grammar (#9203 §3.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Verb { + Status, + Triage, + Start, + Resume, + Retry, + Park, + Unblock, + Priority, + DoNow, + Merge, + AgentStatus, +} + +impl Verb { + /// Parse the canonical token form used in command envelopes + /// (`agent status` travels as `agent-status`). + pub fn parse(token: &str) -> Option { + Some(match token { + "status" => Verb::Status, + "triage" => Verb::Triage, + "start" => Verb::Start, + "resume" => Verb::Resume, + "retry" => Verb::Retry, + "park" => Verb::Park, + "unblock" => Verb::Unblock, + "priority" => Verb::Priority, + "do-now" => Verb::DoNow, + "merge" => Verb::Merge, + "agent-status" => Verb::AgentStatus, + _ => return None, + }) + } + + /// The canonical token form. + pub fn token(self) -> &'static str { + match self { + Verb::Status => "status", + Verb::Triage => "triage", + Verb::Start => "start", + Verb::Resume => "resume", + Verb::Retry => "retry", + Verb::Park => "park", + Verb::Unblock => "unblock", + Verb::Priority => "priority", + Verb::DoNow => "do-now", + Verb::Merge => "merge", + Verb::AgentStatus => "agent-status", + } + } +} + +/// The resource a command acts on: one issue/PR in one repository. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ResourceRef { + /// `owner/repo`. + pub repo: String, + /// Issue or PR number within the repository. + pub number: u64, +} + +impl ResourceRef { + /// Parse the `owner/repo#number` form. + pub fn parse(text: &str) -> Option { + let (repo, number) = text.rsplit_once('#')?; + if repo.is_empty() || !repo.contains('/') { + return None; + } + Some(ResourceRef { + repo: repo.to_string(), + number: number.parse().ok()?, + }) + } +} + +/// One authorization grant: a principal, the verbs it may run, and +/// the repositories it may run them on (`"*"` matches any repo). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Grant { + /// Principal login this grant belongs to. + pub principal: String, + /// Verbs the principal may run under this grant. + pub verbs: Vec, + /// Repositories in scope: exact `owner/repo`, or `"*"`. + pub repos: Vec, +} + +/// Why a command was refused. Every variant is non-mutating: no +/// receipt is stored and no effect is recorded. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AuthorizationError { + /// The actor was not authenticated by the intake. + Unauthenticated, + /// No grant names this principal at all. + NoGrant, + /// The principal has grants, but none for this verb. + VerbDenied, + /// The principal may run this verb, but not on this repository. + ResourceDenied, +} + +/// The set of grants the authority decides against. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct AuthorizationPolicy { + /// All grants in force. + pub grants: Vec, +} + +impl AuthorizationPolicy { + /// Decide whether `principal` may run `verb` on `resource`. + /// Authentication is checked first; then a single grant must + /// cover both the verb and the repository. + pub fn authorize( + &self, + principal: &Principal, + verb: Verb, + resource: &ResourceRef, + ) -> Result<(), AuthorizationError> { + if !principal.authenticated { + return Err(AuthorizationError::Unauthenticated); + } + let mine: Vec<&Grant> = self + .grants + .iter() + .filter(|g| g.principal == principal.login) + .collect(); + if mine.is_empty() { + return Err(AuthorizationError::NoGrant); + } + if !mine.iter().any(|g| g.verbs.contains(&verb)) { + return Err(AuthorizationError::VerbDenied); + } + let covered = mine.iter().any(|g| { + g.verbs.contains(&verb) && g.repos.iter().any(|r| r == "*" || r == &resource.repo) + }); + if !covered { + return Err(AuthorizationError::ResourceDenied); + } + Ok(()) + } +} + +/// One command presented for acceptance. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Command { + /// Semantic idempotency key minted by the forwarder + /// (`ghcmd:v1:#:comment::`). This — never + /// the delivery GUID — is the acceptance identity. + pub idempotency_key: String, + /// The authenticated actor asking for the command. + pub principal: Principal, + /// The verb to run. + pub verb: Verb, + /// The resource the verb acts on. + pub resource: ResourceRef, + /// Provenance only: the GitHub delivery that carried this + /// attempt. Recorded on the effect for audit; never part of + /// acceptance identity, so projector delivery dedupe state can + /// neither create nor suppress an acceptance. + pub delivery_id: String, +} + +/// The stored proof that a command was accepted exactly once. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Receipt { + /// The command's idempotency key. + pub idempotency_key: String, + /// Monotonic acceptance sequence within the ledger. + pub sequence: u64, + /// The verb that was accepted. + pub verb: Verb, + /// The resource the verb acts on. + pub resource: ResourceRef, +} + +/// One applied command effect, appended on first acceptance only. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Effect { + /// The accepted command's idempotency key. + pub idempotency_key: String, + /// Who ran it. + pub principal: String, + /// The verb that ran. + pub verb: Verb, + /// The resource it acted on. + pub resource: ResourceRef, + /// Provenance: the delivery that carried the accepted attempt. + pub delivery_id: String, +} + +/// The outcome of an acceptance attempt. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AcceptOutcome { + /// The stored receipt for this command. + pub receipt: Receipt, + /// True when the receipt already existed: this attempt changed + /// nothing and the caller is being handed back the original + /// acceptance. + pub duplicate: bool, +} + +/// The canonical acceptance ledger. First acceptance of an +/// idempotency key appends exactly one effect and stores its +/// receipt; every later presentation of the same key returns the +/// stored receipt. Authorization is evaluated before the ledger is +/// touched, and a refusal leaves the ledger byte-identical. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct AcceptanceLedger { + receipts: BTreeMap, + effects: Vec, + next_sequence: u64, +} + +impl AcceptanceLedger { + /// An empty ledger. + pub fn new() -> Self { + Self::default() + } + + /// The effects applied so far, in acceptance order. + pub fn effects(&self) -> &[Effect] { + &self.effects + } + + /// The stored receipt for an idempotency key, if accepted. + pub fn receipt(&self, idempotency_key: &str) -> Option<&Receipt> { + self.receipts.get(idempotency_key) + } + + /// Authorize and accept `command`. A repeat of an already + /// accepted key returns the stored receipt with + /// `duplicate: true` and appends no effect — regardless of which + /// delivery carried the repeat. + pub fn accept( + &mut self, + policy: &AuthorizationPolicy, + command: &Command, + ) -> Result { + policy.authorize(&command.principal, command.verb, &command.resource)?; + if let Some(receipt) = self.receipts.get(&command.idempotency_key) { + return Ok(AcceptOutcome { + receipt: receipt.clone(), + duplicate: true, + }); + } + self.next_sequence += 1; + let receipt = Receipt { + idempotency_key: command.idempotency_key.clone(), + sequence: self.next_sequence, + verb: command.verb, + resource: command.resource.clone(), + }; + self.receipts + .insert(command.idempotency_key.clone(), receipt.clone()); + self.effects.push(Effect { + idempotency_key: command.idempotency_key.clone(), + principal: command.principal.login.clone(), + verb: command.verb, + resource: command.resource.clone(), + delivery_id: command.delivery_id.clone(), + }); + Ok(AcceptOutcome { + receipt, + duplicate: false, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn policy() -> AuthorizationPolicy { + AuthorizationPolicy { + grants: vec![ + Grant { + principal: "dezren39".to_string(), + verbs: vec![Verb::DoNow, Verb::Park, Verb::Status], + repos: vec!["developing-today/code".to_string()], + }, + Grant { + principal: "joyce".to_string(), + verbs: vec![Verb::Status], + repos: vec!["*".to_string()], + }, + ], + } + } + + fn command(key: &str, login: &str, verb: Verb, repo: &str, delivery: &str) -> Command { + Command { + idempotency_key: key.to_string(), + principal: Principal::authenticated(login), + verb, + resource: ResourceRef::parse(&format!("{repo}#754")).unwrap(), + delivery_id: delivery.to_string(), + } + } + + /// DSP-01 acceptance: authenticated principal + per-verb / + /// per-resource authorization, and durable command idempotency + /// that owes nothing to projector delivery dedupe — the same + /// command under a *different* delivery GUID still yields one + /// effect and the stored receipt. + #[test] + fn pmo_dsp_01_command_acceptance_is_durable_separate_from_projection_delivery() { + let policy = policy(); + let mut ledger = AcceptanceLedger::new(); + let key = "ghcmd:v1:developing-today/code#754:comment:92001:do-now"; + + // Unauthenticated actor: refused before grants, nothing stored. + let mut anon = command(key, "dezren39", Verb::DoNow, "developing-today/code", "d-0"); + anon.principal = Principal::unauthenticated("dezren39"); + assert_eq!( + ledger.accept(&policy, &anon), + Err(AuthorizationError::Unauthenticated) + ); + assert!(ledger.effects().is_empty()); + assert!(ledger.receipt(key).is_none()); + + // Authenticated but unknown principal: no grant. + let stranger = command(key, "mallory", Verb::DoNow, "developing-today/code", "d-0"); + assert_eq!( + ledger.accept(&policy, &stranger), + Err(AuthorizationError::NoGrant) + ); + + // Known principal, verb outside every grant. + let wrong_verb = command(key, "joyce", Verb::DoNow, "developing-today/code", "d-0"); + assert_eq!( + ledger.accept(&policy, &wrong_verb), + Err(AuthorizationError::VerbDenied) + ); + + // Known principal and verb, repository out of scope. + let wrong_repo = command( + key, + "dezren39", + Verb::DoNow, + "developing-today/other", + "d-0", + ); + assert_eq!( + ledger.accept(&policy, &wrong_repo), + Err(AuthorizationError::ResourceDenied) + ); + assert!(ledger.effects().is_empty()); + + // First authorized presentation — carried by delivery d-1, + // whose projection the projector has already applied. The + // ledger neither knows nor cares: acceptance is recorded. + let first = command(key, "dezren39", Verb::DoNow, "developing-today/code", "d-1"); + let accepted = ledger.accept(&policy, &first).unwrap(); + assert!(!accepted.duplicate); + assert_eq!(accepted.receipt.sequence, 1); + assert_eq!(ledger.effects().len(), 1); + assert_eq!(ledger.effects()[0].delivery_id, "d-1"); + + // Redelivery under a *different* delivery GUID (the + // projector's own dedupe keyed on d-1 can neither confirm + // nor deny this): same stored receipt, no second effect. + let redelivered = command(key, "dezren39", Verb::DoNow, "developing-today/code", "d-2"); + let again = ledger.accept(&policy, &redelivered).unwrap(); + assert!(again.duplicate); + assert_eq!(again.receipt, accepted.receipt); + assert_eq!(ledger.effects().len(), 1); + + // A genuinely different command from the same principal is a + // new acceptance with its own effect and sequence. + let other = command( + "ghcmd:v1:developing-today/code#754:comment:92002:park", + "dezren39", + Verb::Park, + "developing-today/code", + "d-3", + ); + let second = ledger.accept(&policy, &other).unwrap(); + assert!(!second.duplicate); + assert_eq!(second.receipt.sequence, 2); + assert_eq!(ledger.effects().len(), 2); + } + + #[test] + fn pmo_dsp_01_verb_and_resource_forms_parse() { + assert_eq!(Verb::parse("do-now"), Some(Verb::DoNow)); + assert_eq!(Verb::parse("agent-status"), Some(Verb::AgentStatus)); + assert_eq!(Verb::parse("frobnicate"), None); + assert_eq!(Verb::DoNow.token(), "do-now"); + assert_eq!( + ResourceRef::parse("developing-today/code#754"), + Some(ResourceRef { + repo: "developing-today/code".to_string(), + number: 754, + }) + ); + assert_eq!(ResourceRef::parse("no-number"), None); + assert_eq!(ResourceRef::parse("repo#12"), None); + } +} diff --git a/pm-stack/projector/src/operation-forwarder.ts b/pm-stack/projector/src/operation-forwarder.ts new file mode 100644 index 0000000000..c2bb0159fa --- /dev/null +++ b/pm-stack/projector/src/operation-forwarder.ts @@ -0,0 +1,161 @@ +// Operation forwarder — DSP-01 (developing-today/code#9445). +// +// The projector is bounded transport/projection glue: its HMAC-verified +// webhook intake (src/webhook.ts) proves a delivery really came from +// GitHub, and its pmp_deliveries rows dedupe *projection* application. +// Neither is canonical command acceptance. When a signed event carries +// an actionable Fleet command (the /fleet grammar of #9203), this +// module builds the operation envelope and hands it to the +// authoritative Fleet operation interface through an injected sink. +// +// Two separations are load-bearing: +// * The idempotency key is semantic — repo + issue + comment id + +// verb — never the GitHub delivery GUID. A redelivery, or a second +// delivery of the same comment, therefore maps to the same command +// and the Fleet side returns the stored receipt without a second +// effect. +// * The projector stores no acceptance state. The sink owns +// authorization (authenticated principal, per-verb/resource) and +// durable acceptance; this module only forwards envelopes and +// surfaces receipts. No sink is configured in the default serve() +// wiring yet, so forwarding stays inert until the Fleet authority +// adapter is attached — no second ingress, no new service. + +/** Canonical verb tokens of the /fleet command grammar (#9203 §3.1). */ +export type OperationVerb = + | "status" + | "triage" + | "start" + | "resume" + | "retry" + | "park" + | "unblock" + | "priority" + | "do-now" + | "merge" + | "agent-status"; + +const SINGLE_TOKEN_VERBS: ReadonlySet = new Set([ + "status", + "triage", + "start", + "resume", + "retry", + "park", + "unblock", + "priority", + "do-now", + "merge", +]); + +/** + * Parse a comment body as a /fleet command. Only a leading `/fleet` + * token counts — a command quoted mid-comment is discussion, not a + * command. Returns the canonical verb and the remaining argument text, + * or null when the body carries no command. + */ +export function parseFleetCommand(body: string): { verb: OperationVerb; args: string } | null { + const text = body.trim(); + const head = /^\/fleet(?:\s+|$)/.exec(text); + if (!head) return null; + const rest = text.slice(head[0].length).trim(); + if (!rest) return null; + const lower = rest.toLowerCase(); + if (lower === "agent status" || lower.startsWith("agent status ")) { + return { verb: "agent-status", args: rest.slice("agent status".length).trim() }; + } + const token = lower.split(/\s+/, 1)[0]; + if (SINGLE_TOKEN_VERBS.has(token)) { + return { verb: token as OperationVerb, args: rest.slice(token.length).trim() }; + } + return null; +} + +/** A signed-source event envelope handed to the Fleet authority. */ +export interface OperationEnvelope { + /** Semantic command identity; never derived from the delivery GUID. */ + idempotencyKey: string; + /** Provenance only: the GitHub delivery that carried this attempt. */ + deliveryId: string; + event: string; + /** Authenticated actor from the verified provider payload. */ + actor: string; + verb: OperationVerb; + args: string; + /** "owner/repo" the command acts on. */ + repo: string; + /** Issue/PR number the command acts on. */ + issue: number; + /** GitHub comment id the command was read from. */ + commentId: number; +} + +/** The Fleet authority's stored acceptance receipt for one command. */ +export interface OperationReceipt { + receiptId: string; + idempotencyKey: string; + /** True when this receipt was already stored by an earlier forward. */ + duplicate: boolean; +} + +/** + * The authoritative Fleet operation interface, as a sink the server + * injects. Implementations authorize the envelope's actor per + * verb/resource and record durable acceptance keyed by + * `envelope.idempotencyKey`, returning the stored receipt on repeats. + * A rejected command or an unavailable authority is an error throw, + * never a fabricated receipt. + */ +export interface FleetOperationSink { + accept(envelope: OperationEnvelope): Promise; +} + +/** + * Build the operation envelope for a verified webhook payload, or + * null when the event carries no command. Only issue_comment events + * are actionable in this slice: the command text, actor, and resource + * all come from the signed payload itself. + */ +export function operationEnvelopeFor(input: { + deliveryId: string; + event: string; + payload: Record; +}): OperationEnvelope | null { + const { deliveryId, event, payload } = input; + if (event !== "issue_comment") return null; + if (payload?.action !== "created" && payload?.action !== "edited") return null; + const comment = payload?.comment; + const repo = payload?.repository?.full_name; + const issue = payload?.issue?.number; + const actor = comment?.user?.login ?? payload?.sender?.login; + if (typeof comment?.body !== "string") return null; + if (typeof repo !== "string" || typeof issue !== "number") return null; + if (typeof comment?.id !== "number" || typeof actor !== "string") return null; + const command = parseFleetCommand(comment.body); + if (!command) return null; + return { + idempotencyKey: `ghcmd:v1:${repo}#${issue}:comment:${comment.id}:${command.verb}`, + deliveryId, + event, + actor, + verb: command.verb, + args: command.args, + repo, + issue, + commentId: comment.id, + }; +} + +/** + * Thin forwarding seam: the server calls this on every verified + * delivery that carries a command — including redeliveries whose + * projection is already applied — and the sink's semantic dedup, not + * the projector's delivery table, decides whether an effect repeats. + */ +export class OperationForwarder { + constructor(private readonly sink: FleetOperationSink) {} + + async forward(envelope: OperationEnvelope): Promise { + return this.sink.accept(envelope); + } +} diff --git a/pm-stack/projector/src/server.ts b/pm-stack/projector/src/server.ts index 3fba901353..a33e292655 100644 --- a/pm-stack/projector/src/server.ts +++ b/pm-stack/projector/src/server.ts @@ -6,6 +6,11 @@ import { applyEvent, type ProjectorStore } from "./projector"; import { validSignature, readBoundedBody, jsonResponse } from "./webhook"; import * as store from "./store"; import { reconcileRepos } from "./reconcile"; +import { + operationEnvelopeFor, + type FleetOperationSink, + type OperationReceipt, +} from "./operation-forwarder"; export interface ServerEnv extends Record { GITHUB_WEBHOOK_SECRET?: string; @@ -201,6 +206,11 @@ export interface ServerDeps { * serve(): beginReconcile returns false while a pass is in flight. */ beginReconcile?: () => boolean; endReconcile?: () => void; + /** DSP-01 (#9445) Fleet operation authority sink. When set, signed + * webhook events carrying a /fleet command are forwarded for + * canonical command acceptance; when absent, forwarding is inert + * and webhook behavior is exactly the projection-only behavior. */ + operationSink?: FleetOperationSink; } /** A point-in-time row-count snapshot served by /health (#9850 round 2). */ @@ -325,10 +335,6 @@ async function routeRequest(req: Request, db: Client, env: ServerEnv, deps: Serv if (!(await validSignature(body, signature, env.GITHUB_WEBHOOK_SECRET))) { return jsonResponse(401, { error: "invalid_signature" }); } - const already = await store.deliveryApplied(db, deliveryId); - if (already) { - return jsonResponse(200, { status: "duplicate" }); - } let payload: Record; try { payload = JSON.parse(new TextDecoder().decode(body)); @@ -336,8 +342,32 @@ async function routeRequest(req: Request, db: Client, env: ServerEnv, deps: Serv await store.recordDelivery(db, { deliveryId, event, outcome: "error", detail: "invalid_json" }); return jsonResponse(400, { error: "invalid_json" }); } + // DSP-01 (#9445): a signed event may also carry a Fleet command. + // Projection delivery dedupe is not command acceptance, so the + // forward runs on every verified delivery — including a redelivery + // whose projection is already applied — and the Fleet sink's + // semantic idempotency key, not this delivery GUID, decides + // whether the command effect repeats. No sink is configured in + // the default wiring yet; forwarding is inert until the Fleet + // authority adapter is attached (no second ingress is created). + const envelope = deps.operationSink ? operationEnvelopeFor({ deliveryId, event, payload }) : null; + const forwardOperation = async (): Promise => { + if (!envelope || !deps.operationSink) return null; + return deps.operationSink.accept(envelope); + }; + const already = await store.deliveryApplied(db, deliveryId); + if (already) { + let receipt: OperationReceipt | null; + try { + receipt = await forwardOperation(); + } catch { + return jsonResponse(500, { error: "operation_forward_failed" }); + } + return jsonResponse(200, receipt ? { status: "duplicate", operation: receipt } : { status: "duplicate" }); + } + let result: Awaited>; try { - const result = await applyEvent(libsqlStore(db), event, payload, repos(env), deliveryId); + result = await applyEvent(libsqlStore(db), event, payload, repos(env), deliveryId); if (result.wrote && result.refs.length > 0) { // Append before recording this delivery as applied. If the // aggregator is unavailable, GitHub's retry re-applies the @@ -359,11 +389,25 @@ async function routeRequest(req: Request, db: Client, env: ServerEnv, deps: Serv outcome: result.wrote ? "applied" : "ignored", detail: result.wrote ? undefined : "no_writes", }); - return jsonResponse(200, { status: result.wrote ? "applied" : "ignored", refs: result.refs }); } catch (e) { await store.recordDelivery(db, { deliveryId, event, outcome: "error", detail: String((e as Error).message) }); return jsonResponse(500, { error: "apply_failed" }); } + let receipt: OperationReceipt | null; + try { + receipt = await forwardOperation(); + } catch { + // The projection is recorded applied. GitHub's redelivery of + // this same delivery re-enters through the already-applied + // branch above, which retries the forward instead of letting + // the delivery shortcut suppress it. + return jsonResponse(500, { error: "operation_forward_failed" }); + } + return jsonResponse(200, { + status: result.wrote ? "applied" : "ignored", + refs: result.refs, + ...(receipt ? { operation: receipt } : {}), + }); } // -- read: items ---------------------------------------------------------- diff --git a/pm-stack/projector/test/webhook-delivery-id.test.ts b/pm-stack/projector/test/webhook-delivery-id.test.ts index 7146ea7892..122e519468 100644 --- a/pm-stack/projector/test/webhook-delivery-id.test.ts +++ b/pm-stack/projector/test/webhook-delivery-id.test.ts @@ -6,6 +6,11 @@ import { join, dirname } from "node:path"; import { fileURLToPath } from "node:url"; import { migrate } from "../src/store"; import { handleRequest, type ServerEnv } from "../src/server"; +import { + type FleetOperationSink, + type OperationEnvelope, + type OperationReceipt, +} from "../src/operation-forwarder"; const __dirname = dirname(fileURLToPath(import.meta.url)); const FIXTURES = join(__dirname, "..", "fixtures"); @@ -183,3 +188,121 @@ describe("GitHub webhook delivery ID validation", () => { } }); }); + +// DSP-01 (#9445): the existing signed webhook intake fans out to one +// authorized Fleet command; authentication failures produce zero +// Fleet effects. Appended as its own describe so the delivery-ID +// guarantees above stay byte-for-byte the original tests. +describe("DSP-01 webhook auth fan-out", () => { + class FanoutSink implements FleetOperationSink { + envelopes: OperationEnvelope[] = []; + private receipts = new Map(); + + async accept(envelope: OperationEnvelope): Promise { + const existing = this.receipts.get(envelope.idempotencyKey); + if (existing) return { ...existing, duplicate: true }; + const receipt: OperationReceipt = { + receiptId: `rcpt-${this.receipts.size + 1}`, + idempotencyKey: envelope.idempotencyKey, + duplicate: false, + }; + this.receipts.set(envelope.idempotencyKey, receipt); + this.envelopes.push(envelope); + return receipt; + } + } + + async function sendCommand( + sink: FanoutSink, + opts: { deliveryId: string; signature: string | null; mutate?: (p: any) => void }, + ): Promise { + const payload = JSON.parse(readFileSync(join(FIXTURES, "03-issue-comment.json"), "utf8")); + payload.comment.id = 92001; + payload.comment.body = "/fleet do-now"; + opts.mutate?.(payload); + const bytes = new TextEncoder().encode(JSON.stringify(payload)); + const headers = new Headers({ + "content-type": "application/json", + "x-github-event": "issue_comment", + "x-github-delivery": opts.deliveryId, + }); + if (opts.signature !== null) headers.set("x-hub-signature-256", opts.signature); + return handleRequest( + new Request("http://127.0.0.1/github/webhook", { method: "POST", headers, body: bytes }), + db, + env, + { operationSink: sink }, + ); + } + + test("pmo_dsp_01_existing_webhook_auth_fans_out_to_one_authorized_command", async () => { + const sink = new FanoutSink(); + const body = JSON.parse(readFileSync(join(FIXTURES, "03-issue-comment.json"), "utf8")); + body.comment.id = 92001; + body.comment.body = "/fleet do-now"; + const bytes = new TextEncoder().encode(JSON.stringify(body)); + const goodSignature = `sha256=${await hmacSha256Hex(bytes)}`; + + // A validly signed command event fans out to exactly one command. + const ok = await sendCommand(sink, { deliveryId: "fanout-ok", signature: goodSignature }); + expect(ok.status).toBe(200); + const okBody = await ok.json(); + expect(okBody.status).toBe("applied"); + expect(okBody.operation.receiptId).toBe("rcpt-1"); + expect(sink.envelopes.length).toBe(1); + expect(sink.envelopes[0]).toMatchObject({ + actor: "dezren39", + verb: "do-now", + repo: "developing-today/code", + issue: 754, + commentId: 92001, + deliveryId: "fanout-ok", + }); + // The idempotency key is semantic: it names the comment + verb, + // not the delivery GUID. + expect(sink.envelopes[0].idempotencyKey).toBe( + "ghcmd:v1:developing-today/code#754:comment:92001:do-now", + ); + + // Tampered signature: rejected before any Fleet effect. + const tampered = await sendCommand(sink, { + deliveryId: "fanout-tampered", + signature: `sha256=${"00".repeat(32)}`, + }); + expect(tampered.status).toBe(401); + expect(await tampered.json()).toEqual({ error: "invalid_signature" }); + expect(sink.envelopes.length).toBe(1); + + // Missing signature: rejected before any Fleet effect. + const missing = await sendCommand(sink, { deliveryId: "fanout-missing", signature: null }); + expect(missing.status).toBe(401); + expect(await missing.json()).toEqual({ error: "invalid_signature" }); + expect(sink.envelopes.length).toBe(1); + + // Oversized body (over the 10 MB intake bound): rejected before + // any Fleet effect, even with a signature valid for that body. + const bigPayload = JSON.parse(readFileSync(join(FIXTURES, "03-issue-comment.json"), "utf8")); + bigPayload.comment.id = 92001; + bigPayload.comment.body = `/fleet do-now ${"x".repeat(10_000_001)}`; + const bigBytes = new TextEncoder().encode(JSON.stringify(bigPayload)); + const bigSignature = `sha256=${await hmacSha256Hex(bigBytes)}`; + const tooLarge = await handleRequest( + new Request("http://127.0.0.1/github/webhook", { + method: "POST", + headers: { + "content-type": "application/json", + "x-github-event": "issue_comment", + "x-github-delivery": "fanout-oversized-signed", + "x-hub-signature-256": bigSignature, + }, + body: bigBytes, + }), + db, + env, + { operationSink: sink }, + ); + expect(tooLarge.status).toBe(413); + expect(await tooLarge.json()).toEqual({ error: "body_too_large" }); + expect(sink.envelopes.length).toBe(1); + }); +}); diff --git a/pm-stack/projector/test/webhook-operation-forwarding.test.ts b/pm-stack/projector/test/webhook-operation-forwarding.test.ts new file mode 100644 index 0000000000..1ac967bb2b --- /dev/null +++ b/pm-stack/projector/test/webhook-operation-forwarding.test.ts @@ -0,0 +1,221 @@ +// DSP-01 (#9445): signed webhook intake fans out to canonical Fleet +// command acceptance, and projection delivery dedupe must never +// suppress that forward. The Fleet authority is an injected sink in +// these tests; its contract (authorization + durable acceptance keyed +// by the semantic command id, not the delivery GUID) is pinned on the +// Rust side by pmo_dsp_01_command_acceptance_is_durable_separate_from_projection_delivery. +import { describe, test, expect, beforeAll, afterAll } from "bun:test"; +import { createClient, type Client } from "@libsql/client"; +import { mkdtempSync, rmSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { migrate } from "../src/store"; +import { handleRequest, type ServerEnv } from "../src/server"; +import { + parseFleetCommand, + type FleetOperationSink, + type OperationEnvelope, + type OperationReceipt, +} from "../src/operation-forwarder"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const FIXTURES = join(__dirname, "..", "fixtures"); +const SECRET = "test-webhook-secret"; +const env: ServerEnv = { + GITHUB_WEBHOOK_SECRET: "test-webhook-secret", + PM_PROJECTOR_API_TOKEN: "test-api-token", + PM_REPOS: "developing-today/code,developing-today/openchamber", +}; + +let db: Client; +let dir: string; + +/** In-memory Fleet authority: dedupes by semantic idempotency key and + * returns the stored receipt on repeats, exactly as the canonical + * acceptance contract requires. `failNext` simulates the authority + * being unavailable for the first N accepts. */ +class FakeFleetSink implements FleetOperationSink { + receipts = new Map(); + effects: OperationEnvelope[] = []; + calls = 0; + failNext = 0; + + async accept(envelope: OperationEnvelope): Promise { + this.calls += 1; + if (this.failNext > 0) { + this.failNext -= 1; + throw new Error("fleet_unavailable"); + } + const existing = this.receipts.get(envelope.idempotencyKey); + if (existing) return { ...existing, duplicate: true }; + const receipt: OperationReceipt = { + receiptId: `rcpt-${this.receipts.size + 1}`, + idempotencyKey: envelope.idempotencyKey, + duplicate: false, + }; + this.receipts.set(envelope.idempotencyKey, receipt); + this.effects.push(envelope); + return receipt; + } +} + +async function hmacSha256Hex(body: Uint8Array): Promise { + const key = await crypto.subtle.importKey( + "raw", + new TextEncoder().encode(SECRET), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"], + ); + const signature = new Uint8Array( + await crypto.subtle.sign( + "HMAC", + key, + body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength) as ArrayBuffer, + ), + ); + return Array.from(signature, (byte) => byte.toString(16).padStart(2, "0")).join(""); +} + +async function sendComment( + input: { deliveryId: string; commentId: number; body: string }, + sink?: FakeFleetSink, +): Promise { + const payload = JSON.parse(readFileSync(join(FIXTURES, "03-issue-comment.json"), "utf8")); + payload.comment.id = input.commentId; + payload.comment.body = input.body; + const bytes = new TextEncoder().encode(JSON.stringify(payload)); + const signature = await hmacSha256Hex(bytes); + return handleRequest( + new Request("http://127.0.0.1/github/webhook", { + method: "POST", + headers: { + "content-type": "application/json", + "x-github-event": "issue_comment", + "x-github-delivery": input.deliveryId, + "x-hub-signature-256": `sha256=${signature}`, + }, + body: bytes, + }), + db, + env, + sink ? { operationSink: sink } : {}, + ); +} + +async function deliveryOutcome(deliveryId: string): Promise { + const result = await db.execute({ + sql: "SELECT outcome FROM pmp_deliveries WHERE delivery_id = ?", + args: [deliveryId], + }); + return result.rows.length ? String((result.rows[0] as unknown as { outcome: string }).outcome) : null; +} + +beforeAll(async () => { + dir = mkdtempSync(join(tmpdir(), "pm-projector-op-forward-")); + db = createClient({ url: `file:${join(dir, "op-forward.db")}` }); + await migrate(db); +}); + +afterAll(() => { + db.close(); + rmSync(dir, { recursive: true, force: true }); +}); + +describe("webhook operation forwarding (DSP-01)", () => { + test("operation_forward_retries_after_projector_delivery_is_applied", async () => { + const sink = new FakeFleetSink(); + sink.failNext = 1; // first Fleet acceptance attempt fails + + // First delivery: projection applies, Fleet acceptance fails. + const first = await sendComment( + { deliveryId: "op-delivery-1", commentId: 91001, body: "/fleet do-now" }, + sink, + ); + expect(first.status).toBe(500); + expect(await first.json()).toEqual({ error: "operation_forward_failed" }); + // The projection WAS applied and recorded — this is the state the + // old delivery shortcut would have hidden behind "duplicate". + expect(await deliveryOutcome("op-delivery-1")).toBe("applied"); + expect(sink.effects.length).toBe(0); + + // Redelivery of the same GUID: the already-applied branch must + // retry the forward instead of suppressing it. + const second = await sendComment( + { deliveryId: "op-delivery-1", commentId: 91001, body: "/fleet do-now" }, + sink, + ); + expect(second.status).toBe(200); + const secondBody = await second.json(); + expect(secondBody.status).toBe("duplicate"); + expect(secondBody.operation.receiptId).toBe("rcpt-1"); + expect(secondBody.operation.duplicate).toBe(false); + expect(sink.effects.length).toBe(1); + expect(sink.effects[0].verb).toBe("do-now"); + expect(sink.effects[0].actor).toBe("dezren39"); + expect(sink.effects[0].repo).toBe("developing-today/code"); + expect(sink.effects[0].issue).toBe(754); + + // A third delivery: exactly one command effect ever; the stored + // Fleet receipt comes back marked as a duplicate. + const third = await sendComment( + { deliveryId: "op-delivery-1", commentId: 91001, body: "/fleet do-now" }, + sink, + ); + expect(third.status).toBe(200); + const thirdBody = await third.json(); + expect(thirdBody.operation.receiptId).toBe("rcpt-1"); + expect(thirdBody.operation.duplicate).toBe(true); + expect(sink.effects.length).toBe(1); + + // A *different* delivery GUID carrying the same comment is a new + // projection delivery but the same semantic command: still one + // effect, same stored receipt. + const other = await sendComment( + { deliveryId: "op-delivery-2", commentId: 91001, body: "/fleet do-now" }, + sink, + ); + expect(other.status).toBe(200); + const otherBody = await other.json(); + expect(otherBody.operation.receiptId).toBe("rcpt-1"); + expect(otherBody.operation.duplicate).toBe(true); + expect(sink.effects.length).toBe(1); + }); + + test("non-command comments project without forwarding", async () => { + const sink = new FakeFleetSink(); + const response = await sendComment( + { deliveryId: "op-delivery-plain", commentId: 91002, body: "Reproducing with the projector fixture." }, + sink, + ); + expect(response.status).toBe(200); + expect((await response.json()).status).toBe("applied"); + expect(sink.calls).toBe(0); + }); + + test("without a sink, webhook behavior is projection-only and unchanged", async () => { + const first = await sendComment({ deliveryId: "op-delivery-nosink", commentId: 91003, body: "/fleet do-now" }); + expect(first.status).toBe(200); + expect((await first.json()).status).toBe("applied"); + + const duplicate = await sendComment({ + deliveryId: "op-delivery-nosink", + commentId: 91003, + body: "/fleet do-now", + }); + expect(duplicate.status).toBe(200); + expect(await duplicate.json()).toEqual({ status: "duplicate" }); + }); + + test("parseFleetCommand recognizes only a leading /fleet command", () => { + expect(parseFleetCommand("/fleet do-now")).toEqual({ verb: "do-now", args: "" }); + expect(parseFleetCommand("/fleet priority high")).toEqual({ verb: "priority", args: "high" }); + expect(parseFleetCommand("/fleet agent status")).toEqual({ verb: "agent-status", args: "" }); + expect(parseFleetCommand(" /fleet park ")).toEqual({ verb: "park", args: "" }); + expect(parseFleetCommand("please run /fleet do-now")).toBeNull(); + expect(parseFleetCommand("/fleet frobnicate")).toBeNull(); + expect(parseFleetCommand("/fleet")).toBeNull(); + expect(parseFleetCommand("ordinary comment")).toBeNull(); + }); +});