Skip to content

Commit 07dc391

Browse files
committed
feat(trigger-api): verify a hook's declared vendor signature (config.signature)
WIP: the verifier, the one-verifier-per-hook arming in start(), and the declared header read on both faces of the inbound-hook door. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WGufzeeFznzXxc61VmVH12
1 parent c618e89 commit 07dc391

3 files changed

Lines changed: 336 additions & 26 deletions

File tree

‎packages/triggers/trigger-api/src/api-trigger.ts‎

Lines changed: 154 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@
33
import { timingSafeEqual } from 'node:crypto';
44
import { HTTP_SIGNATURE_TOLERANCE_SECONDS, verifyHttpSignature } from '@objectstack/core';
55
import type { HttpSignatureVerdict } from '@objectstack/core';
6+
import { apiTriggerVerifierOf } from '@objectstack/spec/automation';
7+
import type { ApiTriggerSignature } from '@objectstack/spec/automation';
68
import type { AutomationContext } from '@objectstack/spec/contracts';
9+
import { verifyDeclaredSignature } from './declared-signature.js';
10+
import type { DeclaredSignatureCause } from './declared-signature.js';
711

812
/**
913
* Structural mirror of the automation engine's `FlowTriggerBinding` — same
@@ -66,16 +70,42 @@ type HookSecret =
6670
| { readonly kind: 'resolved'; readonly resolve: () => Promise<string | undefined> };
6771

6872
/**
69-
* One armed inbound hook. A secret is required by the type, not only by
73+
* The ONE verifier an armed hook has, decided at {@link ApiTrigger.start} by
74+
* `apiTriggerVerifierOf(binding.config)` (`@objectstack/spec/automation`), the
75+
* reader the engine and the lint share:
76+
*
77+
* - `objectstack-signature`: no `config.signature`. `x-objectstack-signature`
78+
* under the hook's secret, as before that key existed.
79+
* - `declared`: the sender's own scheme, under the key `config.secretRef`
80+
* names, read through the engine's reader (`resolve` only: a declared key is
81+
* never a literal). It REPLACES the platform check, so such a hook never
82+
* reads `x-objectstack-signature`.
83+
* - `unusable`: a `config.signature` the spec refuses. Armed so that every
84+
* post to it is refused with its own logged cause, before any secret is
85+
* read, with the one `401 INVALID_SIGNATURE`; ⛔ never read as
86+
* `objectstack-signature`, so a broken declaration cannot fall back to the
87+
* platform check, and it carries no secret, so it has nothing to verify with.
88+
*
89+
* A secret is required by the type for both verifying kinds, not only by
7090
* {@link ApiTrigger.start}'s check: ADR-0041's `trigger-api` acceptance
71-
* criteria name a per-flow secret and HMAC verification, so a hook without
72-
* one has no legal shape to be stored in, and {@link ApiTrigger.handleRequest}
73-
* has no unsigned branch to take.
91+
* criteria name a per-flow secret and HMAC verification, so a hook without one
92+
* has no legal shape to be stored in, and {@link ApiTrigger.handleRequest} has
93+
* no unsigned branch to take.
7494
*/
95+
type HookVerifier =
96+
| { readonly kind: 'objectstack-signature'; readonly secret: HookSecret }
97+
| {
98+
readonly kind: 'declared';
99+
readonly scheme: ApiTriggerSignature;
100+
readonly secret: Extract<HookSecret, { kind: 'resolved' }>;
101+
}
102+
| { readonly kind: 'unusable' };
103+
104+
/** One armed inbound hook. */
75105
interface ArmedHook {
76106
flowName: string;
77107
hookId: string;
78-
secret: HookSecret;
108+
verifier: HookVerifier;
79109
queue: string;
80110
callback: (ctx: AutomationContext) => Promise<void>;
81111
}
@@ -96,7 +126,12 @@ type UnverifiedSignatureCause =
96126
* so an operator can still tell a misconfigured sender's wrong URL from its
97127
* wrong secret, or from its retired signing form, while the sender cannot.
98128
*/
99-
type UnverifiedPostCause = 'unknown-flow' | 'wrong-hook-id' | UnverifiedSignatureCause;
129+
type UnverifiedPostCause =
130+
| 'unknown-flow'
131+
| 'wrong-hook-id'
132+
| UnverifiedSignatureCause
133+
| DeclaredSignatureCause
134+
| 'declared-unusable';
100135

101136
const UNVERIFIED_POST_CAUSE_TEXT: Readonly<Record<UnverifiedPostCause, string>> = {
102137
'unknown-flow': 'no hook is armed for the flow it names',
@@ -112,6 +147,24 @@ const UNVERIFIED_POST_CAUSE_TEXT: Readonly<Record<UnverifiedPostCause, string>>
112147
`this door does not accept because it signs no time. The sender signs the timestamped form instead: ` +
113148
`t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">, refused once t is more than ` +
114149
`${HTTP_SIGNATURE_TOLERANCE_SECONDS}s from this server's clock (@objectstack/core signHttpBodyAt)`,
150+
// A hook that declares its sender's scheme (`config.signature`): the
151+
// causes name the declared header, never its value.
152+
'declared-header-absent': "it carries no value in the header its hook's config.signature declares",
153+
'declared-header-malformed':
154+
"the header its hook's config.signature declares does not hold the declared form: a digest that does not " +
155+
'decode to 32 bytes in the declared encoding (a body-only header sent twice is one of these), or a ' +
156+
'timestamp element that is missing, repeated or not whole unix seconds',
157+
'declared-prefix-missing': "the header its hook's config.signature declares does not start with the declared prefix",
158+
'declared-no-digest': "the header its hook's config.signature declares carries no element named as its digest",
159+
'declared-mismatch':
160+
"no digest in the header its hook's config.signature declares is the HMAC-SHA256, under the key " +
161+
'config.secretRef names, of what that scheme signs',
162+
'declared-outside-window':
163+
`its declared timestamped signature verified, with a timestamp more than ${HTTP_SIGNATURE_TOLERANCE_SECONDS}s ` +
164+
`from this server's clock (a replay, or a sender clock that is wrong)`,
165+
'declared-unusable':
166+
"its hook's config.signature is one the flow parse refuses (apiTriggerVerifierOf answers unusable), so " +
167+
'the hook admits no post at all and never falls back to x-objectstack-signature',
115168
};
116169

117170
/**
@@ -234,6 +287,15 @@ export function verifySignature(secret: string, rawBody: string, header: string
234287
* unreadable held secret. This trigger never reads the name
235288
* itself — a host that binds without that engine has no
236289
* `resolveSecret`, and the flow is refused as above.
290+
* - `signature` — a third-party sender's own scheme (DocuSign Connect's
291+
* `X-DocuSign-Signature-1`, a Stripe-style `t=…,v1=…`), keyed by
292+
* `secretRef` (`@objectstack/spec/automation`,
293+
* `api-trigger-signature.zod.ts`). It REPLACES the
294+
* `x-objectstack-signature` check for its hook: the hook has
295+
* that one verifier (`verifyDeclaredSignature`), never both.
296+
* A declaration the spec refuses arms a hook that refuses
297+
* every post with the same `401`, before any secret is read,
298+
* and never falls back to the platform check.
237299
*/
238300
export class ApiTrigger implements FlowTrigger {
239301
readonly type = 'api';
@@ -247,7 +309,8 @@ export class ApiTrigger implements FlowTrigger {
247309

248310
/** Currently armed hooks (for diagnostics/tests). */
249311
listHooks(): Array<{ flowName: string; hookId: string; signed: boolean }> {
250-
// Every armed hook is signed: the type admits no unsigned one.
312+
// Every armed hook is signed: the type admits no unsigned one, and a
313+
// hook with an unusable declaration admits nothing at all.
251314
return [...this.hooks.values()].map(h => ({
252315
flowName: h.flowName, hookId: h.hookId, signed: true,
253316
}));
@@ -256,8 +319,49 @@ export class ApiTrigger implements FlowTrigger {
256319
start(binding: FlowTriggerBinding, callback: (ctx: AutomationContext) => Promise<void>): void {
257320
const cfg = (binding.config ?? {}) as Record<string, unknown>;
258321
const hookId = typeof cfg.hookId === 'string' && cfg.hookId.trim() ? cfg.hookId.trim() : 'default';
259-
const literal = usableSecret(cfg.secret);
322+
const queue = `${QUEUE_PREFIX}:${binding.flowName}`;
323+
// Which verifier this hook has, decided once, by the spec's one reader.
324+
// It decides on the PRESENCE of `config.signature`, so a declaration
325+
// that is present and broken is `unusable`, never the platform check.
326+
const declaration = apiTriggerVerifierOf(cfg);
327+
if (declaration.kind === 'unusable') {
328+
// Armed to refuse: every post gets the one unverified-post answer,
329+
// with its own cause in the log, before any secret is read. Nothing
330+
// is subscribed, because nothing can ever be enqueued for it.
331+
this.hooks.set(binding.flowName, {
332+
flowName: binding.flowName, hookId, verifier: { kind: 'unusable' }, queue, callback,
333+
});
334+
this.logger.warn(
335+
`[trigger-api] flow '${binding.flowName}' armed to refuse every post: its start node's ` +
336+
`\`config.signature\` is one the flow parse refuses, so its hook admits no post (401 ` +
337+
`INVALID_SIGNATURE) and never falls back to x-objectstack-signature. Fix the declaration ` +
338+
`(\`os validate\` names what is wrong), or remove it to verify x-objectstack-signature.`,
339+
);
340+
return;
341+
}
260342
const resolve = typeof binding.resolveSecret === 'function' ? binding.resolveSecret : undefined;
343+
if (declaration.kind === 'declared') {
344+
// The declared key is only ever the one `config.secretRef` names,
345+
// which only the automation engine's reader resolves; a host that
346+
// binds without it has no key to verify the sender's scheme with.
347+
if (!resolve) {
348+
throw new Error(
349+
`[trigger-api] flow '${binding.flowName}' not armed: its start node declares its sender's ` +
350+
`signature (\`config.signature\`), verified under the key \`config.secretRef\` names, and ` +
351+
`this binding carries no reader for that key. Bind the flow through the automation engine, ` +
352+
`which resolves \`config.secretRef\` at every post.`,
353+
);
354+
}
355+
this.arm(binding.flowName, hookId, queue, callback, {
356+
kind: 'declared', scheme: declaration.signature, secret: { kind: 'resolved', resolve },
357+
});
358+
this.logger.info(
359+
`[trigger-api] armed: POST .../automation/hooks/${binding.flowName}/${hookId} ` +
360+
`(HMAC required: the sender's own scheme in ${declaration.signature.header}, declared)`,
361+
);
362+
return;
363+
}
364+
const literal = usableSecret(cfg.secret);
261365
// ADR-0041 (`trigger-api` acceptance criteria): a per-flow secret and
262366
// HMAC verification. Refused BEFORE anything is stored or subscribed,
263367
// so a refused flow leaves no hook behind; the engine's bind catch
@@ -271,16 +375,29 @@ export class ApiTrigger implements FlowTrigger {
271375
`resolves that name at every post.`,
272376
);
273377
}
274-
const queue = `${QUEUE_PREFIX}:${binding.flowName}`;
275-
276378
const secret: HookSecret = resolve ? { kind: 'resolved', resolve } : { kind: 'literal', secret: literal! };
277-
const hook: ArmedHook = { flowName: binding.flowName, hookId, secret, queue, callback };
278-
this.hooks.set(binding.flowName, hook);
379+
this.arm(binding.flowName, hookId, queue, callback, { kind: 'objectstack-signature', secret });
380+
381+
this.logger.info(
382+
`[trigger-api] armed: POST .../automation/hooks/${binding.flowName}/${hookId} (HMAC required)`,
383+
);
384+
}
385+
386+
/** Store a verifying hook and subscribe its queue consumer, which runs the flow. */
387+
private arm(
388+
flowName: string,
389+
hookId: string,
390+
queue: string,
391+
callback: (ctx: AutomationContext) => Promise<void>,
392+
verifier: Exclude<HookVerifier, { kind: 'unusable' }>,
393+
): void {
394+
const hook: ArmedHook = { flowName, hookId, verifier, queue, callback };
395+
this.hooks.set(flowName, hook);
279396

280397
const q = this.getQueue();
281398
if (!q) {
282399
this.logger.warn(
283-
`[trigger-api] no queue service — inbound posts for flow '${binding.flowName}' will be rejected until one is registered`,
400+
`[trigger-api] no queue service — inbound posts for flow '${flowName}' will be rejected until one is registered`,
284401
);
285402
} else {
286403
void q.subscribe<{ payload: Record<string, unknown> }>(queue, async (message) => {
@@ -297,10 +414,6 @@ export class ApiTrigger implements FlowTrigger {
297414
this.logger.warn(`[trigger-api] subscribe failed for '${queue}': ${err?.message ?? err}`);
298415
});
299416
}
300-
301-
this.logger.info(
302-
`[trigger-api] armed: POST .../automation/hooks/${binding.flowName}/${hookId} (HMAC required)`,
303-
);
304417
}
305418

306419
stop(flowName: string): void {
@@ -323,7 +436,16 @@ export class ApiTrigger implements FlowTrigger {
323436
flowName: string;
324437
hookId: string;
325438
rawBody: string;
439+
/** The `x-objectstack-signature` value, read only by a hook that declares no scheme of its own. */
326440
signatureHeader?: string;
441+
/**
442+
* Reads one request header by name, its value as `Headers.get` answers
443+
* it (a repeated field is ONE value, joined with `, `), `undefined`
444+
* when absent. A hook that declares its sender's scheme reads its
445+
* declared header through it, and nothing else; without it that hook
446+
* finds no header and refuses the post.
447+
*/
448+
readHeader?: (name: string) => string | undefined;
327449
idempotencyKey?: string;
328450
}): Promise<{ status: number; body: Record<string, unknown> }> {
329451
const hook = this.hooks.get(input.flowName);
@@ -336,14 +458,20 @@ export class ApiTrigger implements FlowTrigger {
336458
// post that names an armed flow AND its hookId.
337459
if (!hook) return this.refuseUnverified('unknown-flow', input.flowName);
338460
if (!safeEqual(hook.hookId, input.hookId)) return this.refuseUnverified('wrong-hook-id', hook.flowName);
461+
// A declaration the spec refuses admits nothing: refused here, before
462+
// any secret is read, so it is the one 401 and never the 503 below.
463+
const verifier = hook.verifier;
464+
if (verifier.kind === 'unusable') return this.refuseUnverified('declared-unusable', hook.flowName);
339465
// The secret, read now: a rotation applies to the next post. One that
340466
// cannot be read is the deployment's fault, not the sender's, and is
341467
// never read as "no secret" — the post is refused without verifying.
342468
// A 5xx on purpose: a sender retries it, and the fault lasts only
343469
// while the secret cannot be read.
344470
let secret: string | undefined;
345471
try {
346-
secret = hook.secret.kind === 'literal' ? hook.secret.secret : usableSecret(await hook.secret.resolve());
472+
secret = verifier.secret.kind === 'literal'
473+
? verifier.secret.secret
474+
: usableSecret(await verifier.secret.resolve());
347475
} catch (err: any) {
348476
this.logger.warn(`[trigger-api] the secret of flow '${hook.flowName}' could not be read: ${err?.message ?? err}`);
349477
secret = undefined;
@@ -354,10 +482,14 @@ export class ApiTrigger implements FlowTrigger {
354482
body: { success: false, error: { code: 'SERVICE_UNAVAILABLE', message: 'The hook secret is unavailable.' } },
355483
};
356484
}
357-
// Verified before the body is parsed or anything is enqueued; a
358-
// body-only signature is refused here like any other that does not
359-
// verify, with its own cause in the log.
360-
const verdict = verifyInboundSignature(input.rawBody, secret, input.signatureHeader);
485+
// Verified before the body is parsed or anything is enqueued, by the
486+
// hook's ONE verifier. A declared scheme reads its own header and never
487+
// `x-objectstack-signature`, so a valid platform signature admits
488+
// nothing there. A body-only `x-objectstack-signature` is refused like
489+
// any other that does not verify, with its own cause in the log.
490+
const verdict = verifier.kind === 'declared'
491+
? verifyDeclaredSignature(verifier.scheme, secret, input.rawBody, input.readHeader?.(verifier.scheme.header))
492+
: verifyInboundSignature(input.rawBody, secret, input.signatureHeader);
361493
if (!verdict.valid) return this.refuseUnverified(verdict.cause, hook.flowName);
362494

363495
let payload: Record<string, unknown>;

0 commit comments

Comments
 (0)