import z from "zod" import { createHmac, createHash } from "node:crypto" import { Finding, ReviewCategory, Severity, catalogRuleId, findingOrigin, normalizeRuleId } from "./finding" import { Rubric, DEFAULT_RUBRIC, blockingCategories } from "./rubric" /** Where a convention came from (the file format); the envelope schema accepts only these. */ export const CONVENTION_SOURCES = [ "altimate", "review_md", "agents_md", "claude_md", "coderabbit", "cursor", "cursorrules", "copilot", "contributing", ] as const /** Why a convention file (or one entry of it) was not given to the finder. */ export const CONVENTION_SKIP_REASONS = [ /** A symlink at the base commit. */ "symlink", /** The file holds key material (a private or service-account key). */ "key_material", /** The YAML file does not parse. */ "invalid_yaml", /** Past the total character cap over all conventions. */ "over_total_cap", /** git could not read the file at the base commit. */ "unreadable", /** A glob with too many brace alternatives, or past the total glob cap. */ "glob_too_complex", ] as const /** * The verdict contract — the signed, replayable artifact that is altimate's * stated moat. Every verdict is mechanically derived from the findings + the * rubric (never from model free-text) and signed so it is tamper-evident and * reproducible against the customer's manifest. */ /** The ideal verdict before mode-gating. */ export const Verdict = z.enum(["APPROVE", "COMMENT", "REQUEST_CHANGES"]) export type Verdict = z.infer /** How aggressively the verdict is enforced on the PR. */ export const ReviewMode = z.enum([ "comment", // never block; post findings as comments (default, frictionless) "gate", // map REQUEST_CHANGES to a blocking review + failing check ]) export type ReviewMode = z.infer /** Maps a Verdict to a VCS review event. * * An `APPROVE` verdict posts a **COMMENT** review event, NOT a GitHub "APPROVE". * The reviewer is a bot: it must never submit a formal approval that could * satisfy branch protection / required reviews and let a PR merge without human * sign-off (review bots comment but never approve). * The "approved — no findings" outcome is conveyed in the comment body instead. * `REQUEST_CHANGES` still maps through (in `gate` mode it blocks; `comment` mode * softens it to COMMENT via {@link applyMode}). * * The value type deliberately EXCLUDES `"APPROVE"`: the no-formal-approval * invariant is enforced at compile time, so no future edit can map a verdict * back to a GitHub APPROVE without breaking the build. (The narrower union is * still assignable to Octokit's `createReview` event param.) */ export const VCS_EVENT: Record = { APPROVE: "COMMENT", COMMENT: "COMMENT", REQUEST_CHANGES: "REQUEST_CHANGES", } /** A regex PII twin (`pii_into_mart`, `select-pii-columns`) that the review * marked as proven new without a compiled base. Only the orchestrator sets the * mark, and only on those two rules. */ export function provenNewPii(f: Pick): boolean { if (f.category !== "pii_exposure") return false const result = f.evidence?.result as { rule?: unknown; provenNew?: unknown } | undefined return result?.provenNew === true && (result.rule === "pii_into_mart" || result.rule === "select-pii-columns") } /** Whether a finding may influence the verdict: deterministic engine * findings always; catalog (pattern) findings only when the rubric names the * rule in `blockingRules`; advisory AI findings never. * * One catalog finding counts without being named: a PII twin the review * proved new against a base it could not compile (`provenNewPii`). The engine * cannot decide that case, and an unreported new SSN is the costlier error. * * A finding marked `preExisting` never counts: only the whole-file scanning * lanes (catalog, regex, lexical) mark findings so, and the PR did not * introduce them. Engine findings are diff-scoped and never marked. */ export function verdictEligible(f: Finding, rubric: Rubric = DEFAULT_RUBRIC): boolean { if (f.preExisting) return false const origin = findingOrigin(f) if (origin === "engine") return true if (origin === "ai") return false if (provenNewPii(f)) return true const rule = catalogRuleId(f) if (!rule) return false const id = normalizeRuleId(rule) return rubric.blockingRules.some((r) => normalizeRuleId(r) === id) } /** * Compute the verdict purely from findings + rubric. Faithful to Cloudflare's * bias-toward-approval rubric: * - any blocking-category `critical` → REQUEST_CHANGES * - >= warningPatternThreshold warnings → REQUEST_CHANGES (risk pattern) * - any finding at all → COMMENT * - nothing → APPROVE * Only verdict-eligible findings (see verdictEligible) count toward a block: * the docs promise that only the deterministic engine blocks, so a regex rule * or the AI lane can comment but never fail the gate on its own. */ export function computeIdealVerdict(findings: Finding[], rubric: Rubric = DEFAULT_RUBRIC): Verdict { if (findings.length === 0) return "APPROVE" const blockers = blockingCategories(rubric) const eligible = findings.filter((f) => verdictEligible(f, rubric)) const hasBlockingCritical = eligible.some((f) => f.severity === "critical" && blockers.has(f.category)) if (hasBlockingCritical) return "REQUEST_CHANGES" // Count only confidently-warned findings toward the risk pattern. Undecidable // ("unknown") warnings — e.g. equivalence that couldn't be proven — must not // accumulate into a block; that would let unprovable refactors fail the gate. const warningCount = eligible.filter((f) => f.severity === "warning" && f.confidence !== "unknown").length if (warningCount >= rubric.warningPatternThreshold) return "REQUEST_CHANGES" return "COMMENT" } /** Apply mode-gating: in `comment` mode, REQUEST_CHANGES is softened to COMMENT. */ export function applyMode(verdict: Verdict, mode: ReviewMode): Verdict { if (mode === "comment" && verdict === "REQUEST_CHANGES") return "COMMENT" // APPROVE and COMMENT pass through unchanged in both modes — the no-formal- // approval guarantee for APPROVE lives solely in the VCS_EVENT map, not here. return verdict } export const RiskTier = z.enum(["trivial", "lite", "full"]) export type RiskTier = z.infer export const EngineVersions = z.object({ reviewer: z.string().default("dbt-pr-review/1"), core: z.string().optional(), model: z.string().optional(), /** The altimate-code CLI release that generated this verdict — lets an * auditor reconstruct which policy version applied months later, when * the verdict envelope has outlived the running binary. */ cliVersion: z.string().optional(), }) export type EngineVersions = z.infer /** The kind of a failure, as public output shows it (see `failure.ts`): * an engine call failed; the review's own code threw; a side of a changed file * could not be read; `git fetch` failed or ran out of time; the AI lane failed; * a GitHub API call made while posting the review failed. */ export const FailureCategory = z.enum([ "engine_error", "internal_error", "file_unreadable", "git_fetch_failed", "git_fetch_timeout", "ai_error", "post_failed", ]) export type FailureCategory = z.infer /** How findings reach the PR: at most `inlineBudget` new inline comments per * run, none below `inlineSeverityFloor`, and no comment at all on a clean run * when `silentWhenClean` is set. */ export const PostingPolicy = z.object({ inlineBudget: z.number().int().min(0), inlineSeverityFloor: Severity, silentWhenClean: z.boolean(), }) export type PostingPolicy = z.infer export const DEFAULT_POSTING_POLICY: PostingPolicy = { inlineBudget: 10, inlineSeverityFloor: "warning", silentWhenClean: true, } /** What the review looked at: the resolved base, and files it deliberately * did not review. Signed with the rest of the envelope so a verdict computed * against the wrong base, or with models left unverified, is auditable. */ export const ReviewScope = z.object({ /** Ref the base was resolved from (e.g. `origin/deployment`). */ baseRef: z.string().optional(), /** Merge-base commit the diff and the old file versions were taken from. */ baseSha: z.string().optional(), baseSource: z .enum(["flag", "github_event", "github_env", "gitlab_env", "remote_default", "default_branch", "parent"]) .optional(), /** dbt project directory relative to the repository root ("" = root). */ projectRoot: z.string().optional(), /** Changed files outside the dbt project: counted; no deterministic check covers them. */ outOfScopeFiles: z.number().int().nonnegative().optional(), /** Of those, the files the advisory AI lane reviewed (opt-in `pythonFiles`): not listed in * `notReviewed`, still counted in `outOfScopeFiles`. */ aiReviewedOutside: z.array(z.string()).optional(), /** Non-model renames with unchanged content, name, role and layer (pure moves): not re-reviewed. */ movedUnchangedFiles: z.number().int().nonnegative().optional(), /** Changed models the manifest marks disabled: dbt does not build them, so * missing compiled SQL is not a gap. Their own SQL is still checked. */ disabledModels: z.array(z.string()).optional(), /** Models the engine lanes could not verify, with the reason and its kind: * `failed` (the file's review threw, or a side the diff names could not be * read), `abstained` (a check could not analyse * the SQL), `not_compiled` (no compiled SQL; engine lanes skipped). `side` * says which version lacked compiled SQL. */ unverified: z .array( z.object({ path: z.string(), reason: z.string(), kind: z.enum(["failed", "abstained", "not_compiled"]).optional(), /** For a `failed` entry: the failure category. */ category: FailureCategory.optional(), side: z.enum(["head", "base"]).optional(), }), ) .optional(), /** Every changed file the review did not look at (excluded, outside the * project, moved, not a dbt file, no check at this tier, no manifest), with * the reason; also repeats the `unverified` entries. */ /** Optional (no default) so an envelope from an older release still verifies after a parse. */ notReviewed: z.array(z.object({ path: z.string(), reason: z.string() })).optional(), /** Multi-project review (`--all-projects`): each dbt project the PR touches * (projects are taken from the base commit), its changed-file count and its * own verdict. Empty when the PR touches no project. */ projects: z .array( z.object({ root: z.string(), files: z.number().int().nonnegative(), verdict: Verdict, mode: ReviewMode.optional(), /** The project's own manifest and policy (the top level keeps one only when all agree). */ manifestHash: z.string().optional(), policyHash: z.string().optional(), /** `budget`: not reviewed, the run's time budget ran out before it started; * `failed`: its review threw. Either keeps the run from approving. */ status: z.enum(["budget", "failed"]).optional(), /** The project does not exist at the base commit (this PR adds it). */ added: z.literal(true).optional(), /** This PR removes (or moves away) the project's directory: nothing was reviewed in it. */ removed: z.literal(true).optional(), /** Reviewed without a manifest (lint-only). */ lintOnly: z.literal(true).optional(), }), ) .optional(), }) export type ReviewScope = z.infer /** Tokens spent by model calls (`input` excludes cached tokens). */ /** Why a finding was not posted (see `withheld`). */ export const WithheldReason = z.enum(["rule_off", "not_posted", "refuted"]) export type WithheldReason = z.infer const AiTokensSchema = z.object({ input: z.number().nonnegative(), inputTotal: z.number().nonnegative(), output: z.number().nonnegative(), reasoning: z.number().nonnegative(), cacheRead: z.number().nonnegative(), }) export const VerdictEnvelope = z.object({ version: z.literal("1"), verdict: Verdict, /** The verdict before mode-gating, for audit (e.g. would-have-blocked). */ idealVerdict: Verdict, mode: ReviewMode, tier: RiskTier, /** G1 — reasons the classifier assigned this tier (only when --explain-tier). */ tierReasons: z.array(z.string()).optional(), /** G2 — true when --force-tier bypassed the classifier. Included in signature so * a tampered envelope claiming natural tier can't fake a forced run. */ tierForced: z.boolean().optional(), /** The classifier's original tier before --force-tier overrode it (G2). */ tierClassified: RiskTier.optional(), findings: z.array(Finding), summary: z.object({ critical: z.number().int().nonnegative(), warning: z.number().int().nonnegative(), suggestion: z.number().int().nonnegative(), /** True when the review ran without a manifest/warehouse (lint-only). */ degraded: z.boolean(), }), engine: EngineVersions, /** Hash of the dbt manifest the verdict was computed against, when present. */ manifestHash: z.string().optional(), /** True when a change-affecting source file was modified after the manifest * was written (checked via mtime; see run.ts::detectStaleManifest). Durably * records in the signed envelope that the verdict may have been computed * against out-of-date metadata — a stderr warning alone is easy for CI to * swallow. */ staleManifest: z.boolean().optional(), /** Base resolution and review coverage (see ReviewScope). */ scope: ReviewScope.optional(), /** Engine calls that failed during the review. Their checks did not run, so * the verdict is never a clean APPROVE when this is present. */ engineErrors: z .array( z.object({ method: z.string(), reason: z.string(), count: z.number().int().positive(), category: FailureCategory.optional(), }), ) .optional(), /** True when the review itself hit an internal exception (a file whose * review failed, a lane that threw). The CLI then exits non-zero in every * mode, as an uncaught exception did before these were caught and reported. */ internalFailure: z.literal(true).optional(), /** Findings not posted, per rule and reason: `rule_off` (`rules:` or the * default tier table sets the rule `off`), `not_posted` (the rule is on the * not-posted list and the AI lane reviewed the file, rules-off.ts) or * `refuted` (the rule verifier refuted it with a tool result). `verdict` is * how many of them still count toward the verdict: hiding a finding never * removes it from the verdict. `findings` lists every one. */ withheld: z .array( z.object({ rule: z.string(), /** Absent on envelopes from older releases: `rule_off`. */ reason: WithheldReason.optional(), count: z.number().int().positive(), verdict: z.number().int().nonnegative(), /** Where the verdict-counting ones are (`file` or `file:line`), at most five. */ at: z.array(z.string()).optional(), /** `rule_off` from the default tier table, not from a `rules:` entry. Absent on * envelopes from older releases. */ byDefault: z.literal(true).optional(), /** Every withheld finding of this rule and reason. */ findings: z .array( z.object({ id: z.string(), file: z.string(), line: z.number().int().positive().optional(), severity: Severity, /** Counts toward the verdict (verdict-eligible). */ verdict: z.boolean(), }), ) .optional(), }), ) .optional(), /** Whether the hidden (withheld) findings change the verdict: false when the verdict is the * same without them. Absent on envelopes from older releases and when nothing is hidden. */ withheldDecides: z.boolean().optional(), /** The review policy applied: from the base branch, the working tree, or * defaults; its hash; and settings the PR changes but that were not applied. */ policy: z .object({ source: z.enum(["base", "working_tree", "default"]), hash: z.string(), changedInPr: z.array(z.string()).optional(), /** Posting policy applied to this run (see PostingPolicy). Absent on * envelopes from older releases; renderers then use the defaults. */ posting: PostingPolicy.optional(), }) .optional(), /** Advisory AI lane outcome: ran, skipped, timed out or failed, and why. */ ai: z .object({ state: z.enum(["ok", "skipped", "timeout", "error"]), reason: z.string().optional(), model: z.string().optional(), durationMs: z.number().int().nonnegative().optional(), /** Tokens spent by the lane's model calls (`input` excludes cached tokens). */ tokens: AiTokensSchema.optional(), /** Estimated USD cost from the model's price table. */ cost: z.number().nonnegative().optional(), calls: z.number().int().nonnegative().optional(), /** Multi-project review (`--all-projects`): each project's AI lane state. */ projects: z .array( z.object({ root: z.string(), state: z.string(), reason: z.string().optional(), calls: z.number().int().nonnegative().optional(), }), ) .optional(), /** Generator findings replayed from an earlier envelope: tokens, cost and calls are that run's. */ replayed: z.boolean().optional(), /** The replayed envelope did not list every generator finding. */ replayIncomplete: z.boolean().optional(), /** What each file sent to the model carried (coverage, focused batching, context cards or dry run). */ input: z .array( z.object({ path: z.string(), kind: z.string(), chars: z.number().int().nonnegative(), truncated: z.boolean(), hunksSent: z.number().int().nonnegative(), hunksTotal: z.number().int().nonnegative(), card: z.boolean(), /** The file had a card, left out for the per-call card budget. */ cardOmitted: z.boolean().optional(), /** Seed data rows not sent. */ rowsOmitted: z.number().int().nonnegative().optional(), /** Index of the call that carried the file (focused batching only). */ batch: z.number().int().nonnegative().optional(), /** The call that carried the file failed: the AI did not review it. */ failed: z.boolean().optional(), /** Convention paths the call carried (first file of each call that carried any). */ conventions: z.array(z.string()).optional(), }), ) .optional(), /** Sendable files the coverage quotas kept from the model (the deterministic lanes are unaffected). */ unsent: z.array(z.string()).optional(), /** Changed files never sent to the AI provider: a symlink (working tree), a file renamed from a * credential name, or content holding key material. The deterministic lanes are unaffected. */ notSent: z.array(z.string()).optional(), /** The same files, each with the fixed reason it was withheld. */ notSentReasons: z .array(z.object({ path: z.string(), reason: z.enum(["symlink", "credential_name", "key_material"]) })) .optional(), /** Reviewed files the model saw cut to fit: the not-posted list does not apply to them. */ truncated: z.array(z.string()).optional(), /** Files whose dbt context card could not be built: sent without one. */ cardsFailed: z.number().int().nonnegative().optional(), /** Calls that failed (threw, timed out, or answered without a usable finding). */ failedCalls: z.number().int().nonnegative().optional(), /** A call's answer held more findings than the core parser keeps (8 per call); the rest were dropped. */ capped: z.boolean().optional(), /** Findings of usable answers that named a file outside their call: dropped. */ foreignDropped: z.number().int().nonnegative().optional(), /** Files in the failed calls (all of them when every call failed): not reviewed by the AI. */ unreviewed: z.array(z.string()).optional(), /** Team convention files from the base commit (no text): those given to the finder, and * those dropped with the reason (`skipped`). */ conventions: z .array( z.object({ path: z.string(), source: z.enum(CONVENTION_SOURCES), scope: z.string(), globs: z.array(z.string()).optional(), chars: z.number().int().nonnegative(), skipped: z.enum(CONVENTION_SKIP_REASONS).optional(), }), ) .optional(), /** The not-posted rule list applied on files the AI lane reviewed (rules-off.ts): its rule * ids, where it came from, and a fixed-text error when its file could not be used. */ notPosted: z .object({ source: z.enum(["default", "file"]), rules: z.array(z.string()), error: z.string().optional(), }) .optional(), /** The rule verifier (the `verifyRules` switch): what it was given, sent, and hid. Reasons are * fixed text; `evidence` is masked, capped model text. */ ruleVerifier: z .object({ state: z.enum(["ok", "skipped", "timeout", "error", "budget"]), reason: z.string().optional(), model: z.string().optional(), durationMs: z.number().int().nonnegative().optional(), tokens: AiTokensSchema.optional(), cost: z.number().nonnegative().optional(), turns: z.number().int().nonnegative(), toolCalls: z.number().int().nonnegative(), toolErrors: z.number().int().nonnegative().optional(), candidates: z.number().int().nonnegative(), sent: z.number().int().nonnegative(), reviewed: z.number().int().nonnegative(), withheld: z.number().int().nonnegative(), verdicts: z .array( z.object({ id: z.string(), file: z.string(), rule: z.string().optional(), verdict: z.enum(["confirmed", "refuted", "unverifiable"]).nullable(), evidence: z.string(), toolsUsed: z.array(z.string()), batch: z.number().int().nonnegative().optional(), grounded: z.boolean(), }), ) .optional(), batches: z .array( z.object({ findings: z.number().int().nonnegative(), state: z.enum(["ok", "timeout", "error", "budget", "not_sent"]), turns: z.number().int().nonnegative(), toolCalls: z.number().int().nonnegative(), }), ) .optional(), }) .optional(), /** The dbt-grounded verifier (the `verify` switch, on by default): what it kept and dropped. */ verifier: z .object({ state: z.enum(["ok", "skipped", "timeout", "error", "budget"]), reason: z.string().optional(), durationMs: z.number().int().nonnegative().optional(), tokens: AiTokensSchema.optional(), cost: z.number().nonnegative().optional(), turns: z.number().int().nonnegative().optional(), toolCalls: z.number().int().nonnegative().optional(), reviewed: z.number().int().nonnegative().optional(), kept: z.number().int().nonnegative().optional(), discarded: z.number().int().nonnegative().optional(), summary: z.number().int().nonnegative().optional(), unreviewed: z.number().int().nonnegative().optional(), /** Verifier tool and engine calls that failed (details in the job log). */ toolErrors: z.number().int().nonnegative().optional(), /** Discarded findings (at most 20), for auditing the verifier's precision. */ dropped: z .array( z.object({ id: z.string(), file: z.string(), startLine: z.number().int().positive().optional(), title: z.string(), body: z.string(), category: z.string(), severity: z.string(), decision: z.enum(["keep", "discard", "summary"]), rule: z.string(), verdict: z.string().optional(), claimType: z.string().optional(), evidence: z.string().optional(), }), ) .optional(), /** Every AI finding's features, verdict (absent when unreviewed) and outcome, uncapped, for offline re-triage. */ decisions: z .array( z.object({ id: z.string(), category: ReviewCategory, decision: z.enum(["keep", "discard", "summary"]), rule: z.string(), ts: z.object({ evidenceLineValid: z.boolean().nullable(), targetsUnchangedCode: z.boolean(), restatesGrounding: z.boolean(), possibleDuplicate: z.boolean().optional(), claimsOtherFile: z.boolean(), styleOnly: z.boolean(), lowConfidence: z.boolean(), hedgedDataDiff: z.boolean(), }), model: z .object({ claimType: z.enum(["code_fact", "cross_file", "convention", "intent", "test_gap", "speculation"]), verdict: z.enum(["confirmed", "refuted", "unverifiable"]), value: z.enum(["actionable", "informational", "nit"]), requiresAssumedInput: z.boolean(), toolsUsed: z.array(z.string()), hasEvidence: z.boolean(), }) .optional(), }), ) .optional(), }) .optional(), }) .optional(), /** ISO timestamp; injected by the caller (no clock access in pure code). */ generatedAt: z.string().optional(), /** Optional break-glass override record. */ override: z .object({ by: z.string(), reason: z.string(), priorVerdict: Verdict, }) .optional(), /** HMAC-SHA256 over the canonical body (added by signEnvelope). */ signature: z.string().optional(), }).superRefine((env, ctx) => { // G2 audit invariant — enforced at the envelope boundary so a hand-built // envelope (bypassing runReview) can't sign inconsistent forced-tier // metadata. When --force-tier is used, BOTH tierForced=true AND // tierClassified must be present (per PR #1027 consensus MINOR #2). const hasForced = env.tierForced === true const hasClassified = env.tierClassified !== undefined if (hasForced !== hasClassified) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: "tierForced and tierClassified must both be present or both absent: " + `tierForced=${env.tierForced}, tierClassified=${env.tierClassified ?? "undefined"}`, path: ["tierForced"], }) } // tierForced: false is not a legitimate state — the flag records // "was --force-tier used?" as a positive marker; false is indistinguishable // from a natural (unforced) run and only adds noise to the canonical body. if (env.tierForced === false) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: "tierForced must be true or undefined, not false", path: ["tierForced"], }) } }) export type VerdictEnvelope = z.infer export interface BuildEnvelopeInput { findings: Finding[] /** Every instance before same-rule repeats were merged for display. The verdict * and severity counts come from this list, so merging never softens the gate. */ verdictFindings?: Finding[] tier: RiskTier mode: ReviewMode rubric?: Rubric engine?: Partial manifestHash?: string generatedAt?: string degraded?: boolean /** G1 — classifier reasons for the tier (only surfaced when explainTier=true). */ tierReasons?: string[] /** G2 — set when --force-tier was applied. */ tierForced?: boolean /** G2 — classifier's original tier before the force override. */ tierClassified?: RiskTier /** True when mtime signals the manifest predates a change-affecting file. */ staleManifest?: boolean scope?: z.input ai?: VerdictEnvelope["ai"] policy?: VerdictEnvelope["policy"] engineErrors?: VerdictEnvelope["engineErrors"] internalFailure?: boolean withheld?: VerdictEnvelope["withheld"] withheldDecides?: boolean } /** Severity counts for the headline. A pre-existing finding is not counted: * the PR did not introduce it, and it is listed in its own collapsed block. */ function summarize(findings: Finding[], degraded: boolean): VerdictEnvelope["summary"] { const tally: Record = { critical: 0, warning: 0, suggestion: 0 } for (const f of findings) if (!f.preExisting) tally[f.severity]++ return { critical: tally.critical, warning: tally.warning, suggestion: tally.suggestion, degraded } } /** A credential-named key (`password`, ODBC `PWD`, `passphrase`, `private_key`, * `AccountKey`, `credentials`, npm `_auth`, …), also with a short prefix * (`db_password`, `PGPASSWORD`, `aws_secret_access_key`), or a whole-word SAS * `sig`, `pass` or `pw` (`bypass=1` is not a key), or a whole-word token * count (`max_tokens`: a value its exemption does not cover is masked), a * `:`, `=` or `=>` separator, and its whole value: a quoted value with spaces and escaped * quotes (to the end of the text when the quote is unterminated), an ODBC * `{…}` value (a `}` in it is written `}}`), or a bare value to the next * whitespace, carried on (never across a line) over a separator that spaces * cut off: `PWD = a;TOKEN = b`, and `PWD: a;TOKEN: b` after a `;`/`&` field. Quantifiers are bounded so the * pattern stays linear on any input. */ const SECRET_VALUE_RE = /(["']?)\b((?:[\w-]{0,40}?(?:pwd|passw(?:or)?d|passphrase|private[-_]?key|(?:secret|account|access)[-_]?key|client[-_]?secret|secret|api[-_]?key|(?:auth|access)[-_]?token|token|credentials|sharedaccesssignature|_auth))|sig|pass|pw|(?:max|total)[-_]?tokens)\1(\s{0,16}(?:=>|[:=])\s{0,16})("(?:[^"\\]|\\.)*(?:"|$)|'(?:[^'\\]|\\.|'')*(?:'|$)|\{(?:[^}]|\}\})*(?:\}|$)|\S+(?:[ \t]{0,16}(?:=>|[:=])[ \t]{0,16}\S+|(?<=[;&,"'{}()\[\]|!][\w .-]{1,64}["']?[:=>])[ \t]{1,16}\S+){0,64})/gi /** A PEM or PGP private key, to its END line or to the end of the text. */ const PEM_KEY_RE = /-----BEGIN [A-Z0-9 ]{0,40}KEY(?: BLOCK)?-----[\s\S]*?(?:-----END [A-Z0-9 ]{0,40}KEY(?: BLOCK)?-----|$)/g /** A three-part JSON Web Token. */ const JWT_RE = /\beyJ[\w-]{2,}\.[\w-]{2,}\.[\w-]{2,}/g /** Not a credential although the key names one: a count (`max_token=4096`, * `TOTAL_TOKEN: 5`), the shell's working directory (`PWD=/home/runner` or * `OLDPWD=…` as a variable of its own, at the start or after whitespace: an * ODBC `;PWD=/…`, `MYSQL_PWD=~…` or `key_file_pwd=/…` is a password), or a * parser naming a token (`Unexpected token: FROM`, `expected token: identifier`, * `column token: expected string`). */ function notASecret(key: string, value: string, before: string): boolean { if (/^(?:max|total)[-_]?tokens?$/i.test(key) && /^\d+$/.test(value)) return true if (/^(?:OLD)?PWD$/.test(key) && /^[/~]/.test(value) && (before === "" || /\s$/.test(before))) return true if (!/^token$/i.test(key)) return false return /\b(?:un)?expected\s+$/i.test(before) || /^(?:(?:un)?expected|found|got)$/i.test(value) } /** Words a diagnostic puts after `Basic` or `Bearer` (`Bearer token missing`, * `expected Bearer but got Basic`, `basic authentication is not enabled`, a * `WWW-Authenticate: Bearer realm="api"` challenge). Any other value is * masked, whatever its shape: no decoding or length rule can tell every * credential (Latin-1 or truncated base64, a raw token) from a word, so an * unlisted word is masked too, which is the safe direction. */ const AUTH_SCHEME_WORDS = new Set([ "token", "tokens", "missing", "required", "realm", "authentication", "auth", "credentials", "invalid", "expired", "error", "failed", "header", "scheme", "type", "value", "basic", "bearer", "present", "prefix", "supported", "is", "but", "not", "in", "on", "got", "expected", "allowed", "accepted", "rejected", "only", "or", "and", "authorization", "syntax", "has", "was", "were", "are", "for", "from", "could", "must", "with", "signature", "audience", "format", "cannot", "does", ]) /** True when the value after `Basic`/`Bearer` is a diagnostic word. Trailing * punctuation and quotes are ignored for the lookup (`Bearer token.`), and so * is an auth-param's `=` (`realm=`). */ function authSchemeWord(value: string): boolean { return AUTH_SCHEME_WORDS.has(value.replace(/[.,;:!?)\]}"'=]+$/, "").toLowerCase()) } /** `Bearer`/`Basic` and the up to four words after it. */ const AUTH_PHRASE_RE = /\b(?:bearer|basic)(?:(?:\s{0,16}[:,;]\s{0,16}|\s{1,16})["']?[^\s"',;:]+["']?){1,4}/gi const AUTH_PHRASE_WORD = /(\s{0,16}[:,;]?\s{0,16})(["']?)([^\s"',;:]+)(["']?)/g /** An opaque credential: 20+ token characters (base64 padding only at the * end) with a digit and either mixed case or `+`, `/` or `=`. Hostnames, * error codes (`ErrorCode=AADSTS700082`) and class names do not fit. */ function credentialShaped(word: string): boolean { return ( /^[A-Za-z0-9+/_-]{20,}={0,2}$/.test(word) && /\d/.test(word) && (/[a-z]/.test(word) && /[A-Z]/.test(word) || /[+/=]/.test(word)) ) } /** In a `Bearer`/`Basic` phrase, after up to three listed words, a * credential-shaped word is masked (`Bearer token is `). */ function maskShapedAfterWords(phrase: string): string { const head = /^(?:bearer|basic)/i.exec(phrase)![0] let listed = 0 let done = false const rest = phrase.slice(head.length).replace(AUTH_PHRASE_WORD, (whole, sep, q1, word: string, q2) => { if (done) return whole if (authSchemeWord(word) && listed < 3) { listed++ return whole } done = true // Sentence punctuation after the value is not part of it (`… is .`). const tail = /[.,;:!?)\]}]*$/.exec(word)![0] const value = tail ? word.slice(0, -tail.length) : word return listed && credentialShaped(value) ? `${sep}${q1}[REDACTED]${tail}${q2}` : whole }) return head + rest } /** Mask the value of every credential-keyed field. A bare value is masked to * the next whitespace as one span, later `;k=v` / `&k=v` fields included: * any split point can sit inside a secret, so `Server=x` after it is lost. A * quoted or `{…}` value ends at its closing quote, and the scan goes on to * the fields after it. An exempt value (a count, a directory, a parser word) * is exempt only when, minus trailing punctuation, it is one clean token, so * nothing can hide behind it (`PWD=/home/runner,password=…`). */ function maskSecretValues(text: string): string { return text.replace(SECRET_VALUE_RE, (whole, q: string, key: string, sep: string, value: string, offset: number) => { const before = text.slice(Math.max(0, offset - 32), offset) const bare = !/^["'{]/.test(value) const core = bare ? value.replace(/[.,;:!?)\]}"']+$/, "") : value if (!(bare && /[\s;&,"'{}=:>]/.test(core)) && notASecret(key, core, before)) return whole return `${q}${key}${q}${sep}[REDACTED]` }) } // Known limits of `errorReason` (not masked): more than 16 spaces or tabs // between a key, its separator and its value, or after `Bearer`; a quoted // `"Authorization"` key; `Cookie:`/`Set-Cookie:` values; a key with a suffix // after the credential word (`SNOWFLAKE_PASSWORD_DEV`) and singular // `credential`; AWS `AKIA…`/`ASIA…` key ids and `X-Amz-Credential=`; Google // `AIza…` and Stripe `sk_live_…` keys; a value after `Bearer`/`Basic` and listed // words that is not credential-shaped (`Bearer token provided is invalid: ` // masks `provided`, not the value); an Oracle `scott/@db` string and a // schemeless `user:@host`; netrc `password `, `mysql -p` and a // pgpass line; a YAML block scalar; URL-encoded keys; look-alike characters in // a key; double-encoded JSON; a short value after `Bearer,` or `Bearer token,`; // a credential key followed by a quoted value with no separator (`password // "" rejected`); and the rest of a bare value followed by a quoted or // braced one with spaces (the job-log sink in `failure.ts` withholds // everything after the first masked value for that reason). It also // over-masks: a long absolute file path reads as a blob, and the word after a // credential key is taken as its value. That limits how useful the job log is: // long paths are over-masked, so the rest of the line is withheld (a CI // runner's path to a compiled model loses its file name). /** An error as one bounded line, for the job log only. No reason, comment, * envelope or telemetry field carries its output: those hold a failure * category and fixed text (`failure.ts`). A driver error can quote a * connection string, so credentials are masked before the cut: truncating * first could split a secret past the pattern that recognises it. * * `redactSecrets` (the upgrade logs' masker) is not used: it masks the word * after `token`, which turns an engine's `unexpected token FROM` into noise, * and stops a value at the first space (`password='a b'` would keep `b'`). * Its credential shapes that apply here are below. */ export function errorReason(err: unknown, max = 200): string { return maskSecretValues((err instanceof Error ? err.message : String(err)).replace(PEM_KEY_RE, "[REDACTED]")) .replace(/((?:proxy-)?authorization\s{0,16}[:=]\s{0,16})(["']?)\S+.*$/gim, "$1$2[REDACTED]") // Listed words never let a credential-shaped word after them through // (`Bearer token is `, `Bearer credentials for `). .replace(AUTH_PHRASE_RE, maskShapedAfterWords) // A credential can follow a naming word (`Bearer token `, // `Basic auth: `): the word after it is checked too. After a `,` // or `;` the next word usually starts a new clause, so only a // credential-shaped one is masked there. .replace( /\b((?:bearer|basic)(?:\s{0,16}:\s{0,16}|\s{1,16})(?:tokens?|auth|credentials)(?:\s{0,16}:\s{0,16}|\s{1,16}))(["']?)([^\s"',;]+)/gi, (whole, lead, q, value) => (authSchemeWord(value) ? whole : `${lead}${q}[REDACTED]`), ) // The whole value up to a delimiter, so a `%`, `:` or `!` inside it does // not leave its tail behind. .replace(/\b((?:bearer|basic)(?:\s{0,16}:\s{0,16}|\s{1,16}))(["']?)([^\s"',;]+)/gi, (whole, kw, q, value) => authSchemeWord(value) ? whole : `${kw}${q}[REDACTED]`, ) // userinfo in a URL of any scheme (`postgresql://user:pass@host`). A driver // prints the password as given, so it may hold `@` or `/`: everything up to // the last `@` of the URL is masked (a path with `@` loses its start too). .replace(/\b([a-z][a-z0-9+.-]{0,30}:\/\/)\S{0,256}@/gi, "$1[REDACTED]@") // An `@` the bounded pass could not reach (userinfo longer than its bound): // the whole URL goes. One greedy match per URL keeps this linear. .replace(/\b([a-z][a-z0-9+.-]{0,30}:\/\/)(\S*)/gi, (whole, scheme: string, rest: string) => rest.replace(/^\[REDACTED\]@/, "").includes("@") ? `${scheme}[REDACTED]` : whole, ) .replace(JWT_RE, "[REDACTED]") // provider-prefixed tokens, which are not key=value shaped .replace(/\b(gh[pousr]_|github_pat_|glpat-|npm_|sk-|xox[baprs]-)[A-Za-z0-9_-]{8,}/g, "$1[REDACTED]") .replace(/\b(dapi)[0-9a-f]{32}/gi, "$1[REDACTED]") // long opaque blobs: hex digests and base64-ish secrets. Exactly 40 hex // characters is a git commit SHA, which reasons quote and which is public. .replace(/\b(?![0-9a-f]{40}\b)[0-9a-f]{32,}\b/gi, "[REDACTED]") .replace(/\b(?![0-9a-f]{40}\b)[A-Za-z0-9+/]{40,}={0,2}\b/gi, "[REDACTED]") .replace(/\s+/g, " ") .trim() .slice(0, max) } /** Whether a `scope.notReviewed` reason marks a file outside the dbt project: one project's * `outside the dbt project ()` (run.ts) or the merge's `outside the dbt projects reviewed`. */ export function isOutsideProjectReason(reason: string): boolean { return /^outside the dbt project/.test(reason) } /** True when the run itself broke: an engine call failed, a file's review * threw or its content could not be read, the review's own code threw * (`internalFailure`), or a model had no compiled head SQL (its engine and PII * checks were skipped). Missing findings then mean "not * checked", so the run cannot APPROVE. A check that could not parse a model * (`abstained`) is not a broken run: SQL the engine does not support is * common, and blocking every such PR from approval would teach people to * ignore the gate. It is listed as not fully verified instead. A base without * compiled SQL likewise only weakens the base comparison. */ export function reviewIncomplete( input: Pick, ): boolean { if (input.engineErrors?.length || input.internalFailure) return true return (input.scope?.unverified ?? []).some(holdsBackApproval) } /** One `scope.unverified` entry keeps the run from approving: a file whose * review failed, or a model without compiled head SQL. Shared by the verdict * and the comment's banner, so the two cannot disagree. */ export function holdsBackApproval(u: { kind?: string; side?: string }): boolean { return u.kind === "failed" || (u.kind === "not_compiled" && u.side !== "base") } /** Assemble the verdict envelope (unsigned). Call signEnvelope to sign it. */ export function buildEnvelope(input: BuildEnvelopeInput): VerdictEnvelope { const rubric = input.rubric ?? DEFAULT_RUBRIC // An engine failure, a file whose review failed, or a model without compiled // head SQL means the run broke: "no findings" is then unknown, not clean, so // the verdict cannot be APPROVE. const instances = input.verdictFindings ?? input.findings const computed = computeIdealVerdict(instances, rubric) const ideal = computed === "APPROVE" && reviewIncomplete(input) ? "COMMENT" : computed const verdict = applyMode(ideal, input.mode) const degraded = input.degraded ?? input.findings.some((f) => f.degraded) return VerdictEnvelope.parse({ version: "1", verdict, idealVerdict: ideal, mode: input.mode, tier: input.tier, tierReasons: input.tierReasons, tierForced: input.tierForced, tierClassified: input.tierClassified, findings: input.findings.map((f) => ({ ...f, origin: findingOrigin(f) })), summary: summarize(instances, degraded), engine: EngineVersions.parse(input.engine ?? {}), manifestHash: input.manifestHash, staleManifest: input.staleManifest ? true : undefined, scope: input.scope, ai: input.ai, policy: input.policy, engineErrors: input.engineErrors, internalFailure: input.internalFailure ? true : undefined, withheld: input.withheld?.length ? input.withheld : undefined, withheldDecides: input.withheld?.length ? input.withheldDecides : undefined, generatedAt: input.generatedAt, }) } /** * Deterministic serialization with object keys sorted at EVERY depth and array * order preserved. Note: `JSON.stringify(obj, keysArray)` cannot be used here — * an array replacer is a recursive key-allowlist, so nested `findings[]` fields * (whose keys aren't top-level envelope keys) would be dropped and the signature * would not cover finding content. This walks the value instead. */ function stableStringify(value: unknown): string { if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null" if (Array.isArray(value)) return "[" + value.map(stableStringify).join(",") + "]" const obj = value as Record const keys = Object.keys(obj) .filter((k) => obj[k] !== undefined) .sort() return "{" + keys.map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k])).join(",") + "}" } /** Canonical, signature-independent serialization for hashing/signing. */ export function canonicalBody(env: VerdictEnvelope): string { const { signature: _sig, ...rest } = env return stableStringify(rest) } /** * Sign the envelope with HMAC-SHA256. The key comes from * ALTIMATE_REVIEW_SIGNING_KEY; when absent we fall back to an unkeyed digest * (still tamper-evident for replay, but not authenticated) and mark it so. */ export function signEnvelope(env: VerdictEnvelope, key?: string): VerdictEnvelope { const signingKey = key ?? process.env["ALTIMATE_REVIEW_SIGNING_KEY"] const body = canonicalBody(env) const signature = signingKey ? "hmac:" + createHmac("sha256", signingKey).update(body).digest("hex") : "sha256:" + createHash("sha256").update(body).digest("hex") return { ...env, signature } } /** Verify a signed envelope. Returns true when the signature matches. */ export function verifyEnvelope(env: VerdictEnvelope, key?: string): boolean { if (!env.signature) return false const recomputed = signEnvelope({ ...env, signature: undefined }, key).signature return recomputed === env.signature } /** Record a break-glass override on an envelope and re-sign it. */ export function applyOverride(env: VerdictEnvelope, by: string, reason: string, key?: string): VerdictEnvelope { const overridden: VerdictEnvelope = { ...env, verdict: "COMMENT", override: { by, reason, priorVerdict: env.verdict }, signature: undefined, } return signEnvelope(overridden, key) }