|
| 1 | +// Scheduled checkpoint anchoring (#9274, epic #9267). Ties #9272 (Rekor) and #9273 (git-commit) together into |
| 2 | +// a periodic job -- checkpoint cadence, not per-record, per the mechanism research on #9267: anchoring every |
| 3 | +// decision record is wrong on every axis (Rekor is a donated public good; a git commit per PR review is |
| 4 | +// noise; a naive per-record job has no natural batching anyway). |
| 5 | +import { errorMessage, nowIso } from "../utils/json"; |
| 6 | +import { buildLedgerAnchorPayload, currentAnchorKey, parseAnchorPublicKeys, signLedgerAnchorPayload, type SignedLedgerAnchor } from "./ledger-anchor"; |
| 7 | +import { loadDecisionLedgerTip } from "./decision-record"; |
| 8 | +import { loadLastLedgerAnchorAttempt, recordLedgerAnchorAttempt, type LedgerAnchorBackend } from "./ledger-anchor-persistence"; |
| 9 | +import { submitToRekor } from "./ledger-anchor-rekor"; |
| 10 | +import type { LedgerAnchorGitTarget } from "./ledger-anchor-git"; |
| 11 | + |
| 12 | +/** Bounds the unanchored window by record count, independent of the hourly clock -- a burst of activity |
| 13 | + * cannot sit unanchored for a full hour just because it happened between ticks. */ |
| 14 | +export const LEDGER_ANCHOR_SEQ_THRESHOLD = 256; |
| 15 | + |
| 16 | +export type LedgerAnchorScheduleDecision = |
| 17 | + | { shouldAnchor: false; reason: "empty_ledger" | "unchanged" } |
| 18 | + | { shouldAnchor: true; reason: "hourly" | "seq_threshold" }; |
| 19 | + |
| 20 | +/** |
| 21 | + * Pure scheduling decision: given the live tip and the last attempt (regardless of that attempt's own |
| 22 | + * success/failure -- see {@link loadLastLedgerAnchorAttempt}'s own reasoning), should THIS tick anchor? |
| 23 | + * |
| 24 | + * `seq_threshold` is checked treating a never-anchored ledger as starting from seq 0 -- a burst of >= the |
| 25 | + * threshold worth of activity before the very first anchor ever still fires immediately, rather than waiting |
| 26 | + * for the next hourly tick just because there is no prior anchor to compare against. |
| 27 | + */ |
| 28 | +export function decideLedgerAnchorSchedule(input: { |
| 29 | + isHourly: boolean; |
| 30 | + currentTip: { seq: number; rowHash: string }; |
| 31 | + lastAnchor: { seq: number; rowHash: string } | null; |
| 32 | + seqThreshold: number; |
| 33 | +}): LedgerAnchorScheduleDecision { |
| 34 | + if (input.currentTip.seq === 0) return { shouldAnchor: false, reason: "empty_ledger" }; |
| 35 | + |
| 36 | + const lastAnchorSeq = input.lastAnchor?.seq ?? 0; |
| 37 | + if (input.currentTip.seq - lastAnchorSeq >= input.seqThreshold) return { shouldAnchor: true, reason: "seq_threshold" }; |
| 38 | + |
| 39 | + const tipUnchanged = input.lastAnchor !== null && input.lastAnchor.rowHash === input.currentTip.rowHash; |
| 40 | + if (input.isHourly && !tipUnchanged) return { shouldAnchor: true, reason: "hourly" }; |
| 41 | + |
| 42 | + return { shouldAnchor: false, reason: "unchanged" }; |
| 43 | +} |
| 44 | + |
| 45 | +/** Reads the four `LOOPOVER_LEDGER_ANCHOR_GIT_*` config vars into a target, or `null` when the required |
| 46 | + * owner/repo pair is unset -- git anchoring is simply not configured yet, the same honest-degrade posture |
| 47 | + * as an unset signing key, not an error. */ |
| 48 | +export function resolveGitAnchorTarget(env: { |
| 49 | + LOOPOVER_LEDGER_ANCHOR_GIT_OWNER?: string; |
| 50 | + LOOPOVER_LEDGER_ANCHOR_GIT_REPO?: string; |
| 51 | + LOOPOVER_LEDGER_ANCHOR_GIT_BRANCH?: string; |
| 52 | + LOOPOVER_LEDGER_ANCHOR_GIT_PATH?: string; |
| 53 | +}): LedgerAnchorGitTarget | null { |
| 54 | + const owner = env.LOOPOVER_LEDGER_ANCHOR_GIT_OWNER; |
| 55 | + const repo = env.LOOPOVER_LEDGER_ANCHOR_GIT_REPO; |
| 56 | + if (!owner || !repo) return null; |
| 57 | + return { owner, repo, branch: env.LOOPOVER_LEDGER_ANCHOR_GIT_BRANCH || "main", path: env.LOOPOVER_LEDGER_ANCHOR_GIT_PATH || "anchors.jsonl" }; |
| 58 | +} |
| 59 | + |
| 60 | +export type LedgerAnchorSchedulerDeps = { |
| 61 | + /** Defaults to the real Rekor backend. Injectable so a test exercises the scheduler's own decision logic |
| 62 | + * without a real network call. */ |
| 63 | + submitRekor?: (signed: SignedLedgerAnchor, publicKeySpki: string) => Promise<void>; |
| 64 | + /** `null`/omitted when git anchoring isn't configured (no target, no installation) -- the scheduler simply |
| 65 | + * skips that backend, same posture as an unset signing key. The real caller (the queue processor) wraps |
| 66 | + * the actual `submitToGitAnchor` call in `withInstallationTokenRetry` here, so a stale token retries the |
| 67 | + * WHOLE attempt with a fresh one, matching every other GitHub write in this engine. */ |
| 68 | + submitGit?: ((signed: SignedLedgerAnchor) => Promise<void>) | null; |
| 69 | +}; |
| 70 | + |
| 71 | +/** |
| 72 | + * Run one scheduling tick. Never blocks a review: this has no caller in the live decision-record persist |
| 73 | + * path at all -- it exists only as a queued background job (#9274's own dispatch wiring) -- and neither |
| 74 | + * backend it calls ever rejects (each records its own `status: 'failed'` via #9271 instead of throwing), so |
| 75 | + * a total anchoring failure cannot propagate anywhere. Returns the scheduling decision so a caller/test can |
| 76 | + * observe WHY nothing happened, without needing a second query. |
| 77 | + */ |
| 78 | +export async function runScheduledLedgerAnchor(env: Env, options: { isHourly: boolean; now?: string }, deps: LedgerAnchorSchedulerDeps = {}): Promise<LedgerAnchorScheduleDecision> { |
| 79 | + const now = options.now ?? nowIso(); |
| 80 | + const [tip, lastAnchor] = await Promise.all([loadDecisionLedgerTip(env), loadLastLedgerAnchorAttempt(env)]); |
| 81 | + const decision = decideLedgerAnchorSchedule({ isHourly: options.isHourly, currentTip: tip, lastAnchor, seqThreshold: LEDGER_ANCHOR_SEQ_THRESHOLD }); |
| 82 | + if (!decision.shouldAnchor) return decision; |
| 83 | + |
| 84 | + const keys = parseAnchorPublicKeys(env.LOOPOVER_LEDGER_ANCHOR_KEYS); |
| 85 | + const current = currentAnchorKey(keys); |
| 86 | + if (!current || !env.LOOPOVER_LEDGER_ANCHOR_PRIVATE_KEY) { |
| 87 | + console.log( |
| 88 | + JSON.stringify({ |
| 89 | + event: "ledger_anchor_skipped_unconfigured", |
| 90 | + reason: !current ? "no_current_signing_key_published" : "no_private_key_configured", |
| 91 | + }), |
| 92 | + ); |
| 93 | + return decision; |
| 94 | + } |
| 95 | + |
| 96 | + const payload = buildLedgerAnchorPayload(tip, now); |
| 97 | + const signed = await signLedgerAnchorPayload(payload, env.LOOPOVER_LEDGER_ANCHOR_PRIVATE_KEY, current.keyId); |
| 98 | + |
| 99 | + const submitRekor = deps.submitRekor ?? ((s, publicKeySpki) => submitToRekor(env, s, publicKeySpki, fetch)); |
| 100 | + // guardedSubmit is the actual safety boundary, not a convention every injected function is trusted to |
| 101 | + // honor: #9272's real submitToRekor and #9273's real submitToGitAnchor never reject on their own, but an |
| 102 | + // INJECTED submitGit (the real caller wraps token-minting around submitToGitAnchor, and minting a fresh |
| 103 | + // installation token is a genuine IO call that CAN throw, unlike anything inside submitToGitAnchor itself) |
| 104 | + // is not something this module controls. Catching here, once, centrally, is what makes "neither backend |
| 105 | + // ever rejects" true structurally rather than by every call site's own discipline. |
| 106 | + const guardedSubmit = async (backend: LedgerAnchorBackend, submit: () => Promise<void>): Promise<void> => { |
| 107 | + try { |
| 108 | + await submit(); |
| 109 | + } catch (error) { |
| 110 | + await recordLedgerAnchorAttempt(env, { payload: signed.payload, signature: signed.signature, keyId: signed.keyId, backend, status: "failed", error: errorMessage(error) }); |
| 111 | + } |
| 112 | + }; |
| 113 | + |
| 114 | + const attempts: Promise<void>[] = [guardedSubmit("rekor", () => submitRekor(signed, current.publicKeySpki))]; |
| 115 | + if (deps.submitGit) { |
| 116 | + const submitGit = deps.submitGit; |
| 117 | + attempts.push(guardedSubmit("git", () => submitGit(signed))); |
| 118 | + } |
| 119 | + await Promise.all(attempts); |
| 120 | + |
| 121 | + return decision; |
| 122 | +} |
0 commit comments