diff --git a/README.md b/README.md index b7d11dc..7fc22a7 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,22 @@ const repository = await client.resolveSourceRepository({ A provider object ID can replace `full_name` on the same host. For later requests, use the returned Proofline `repository_id`, which also resolves on its own within the organization. +## Pull request merge gates + +`readReviewMergeGate` reads and validates the server-recorded `PullRequestMergeGate` projection from a `Review` (`getReview`) or `ReviewOutcome` (`waitForReview`). + +```typescript +import { ProoflineClient, readReviewMergeGate } from "@proofline/sdk"; + +const outcome = await client.waitForReview(organizationId, reviewId); +const gate = readReviewMergeGate(outcome, { headSha: expectedHeadSha }); +if (gate.status === "BLOCKED") { + console.error(`Merge gate blocked (${gate.findingCount} blocking findings).`); +} +``` + +When `review` is unavailable (`TIMED_OUT` before a response) it returns `status: "UNAVAILABLE"`, and when the repository has not opted into merge gates (`merge_gate: null`) it returns `status: "NOT_CONFIGURED"`. Passing `headSha` pins the projection to an expected 40-character commit SHA and yields `status: "HEAD_MISMATCH"` with `decision: null` if the recorded gate belongs to another head. Malformed or contradictory gate fields raise `ProoflineError` with `urn:proofline:sdk:invalid-response`. + ## Errors and refusals A refused request throws `ProoflineError` with the server problem's `status`, `type`, `title` and `detail`. When a review request creates nothing, the error also carries `refusal`, whose `reason` names the setting to change, such as `NO_LINKED_ENVIRONMENT` or `ENVIRONMENT_NOT_READY`, and `repositoryName`. A refusal that does not match the public contract keeps its status, `title` and `detail` with the type `urn:proofline:sdk:invalid-response` and no `refusal`. Any other status, such as the 402 a review request answers when credits cannot pay, is a plain problem with no `refusal`. The token is redacted from every text field, and `String(error)`, `inspect(error)` and `JSON.stringify(error)` show only the status. diff --git a/src/index.ts b/src/index.ts index 0374a0e..9021bd9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,6 +14,17 @@ import { KnowledgeClient } from "./knowledge.js"; export type { KnowledgeResult, RepositoryKnowledge } from "./knowledge.js"; +export { + type MergeGateBypass, + type MergeGateDecision, + type MergeGateStatus, + type PullRequestMergeGate, + type ReadReviewMergeGateOptions, + type ReviewMergeGate, + type ReviewMergeGateStatus, + readReviewMergeGate, +} from "./merge-gate.js"; + import { decodeExport, type ExportPage, diff --git a/src/merge-gate.ts b/src/merge-gate.ts new file mode 100644 index 0000000..bcf2107 --- /dev/null +++ b/src/merge-gate.ts @@ -0,0 +1,268 @@ +import type { Review, ReviewOutcome } from "./index.js"; +import type { components } from "./schema.js"; +import { ProoflineError } from "./transport.js"; + +export type PullRequestMergeGate = + components["schemas"]["PullRequestMergeGate"]; +export type MergeGateStatus = components["schemas"]["GateStatus"]; +export type MergeGateDecision = components["schemas"]["Outcome"]; + +export type ReviewMergeGateStatus = + | MergeGateStatus + | "NOT_CONFIGURED" + | "UNAVAILABLE" + | "HEAD_MISMATCH"; + +export interface MergeGateBypass { + bypassedAt: string | null; + mergeCommitSha: string | null; + mergedPullRequestNumber: number | null; + mergedByGithubUserId: number | null; + mergedByLogin: string | null; + mergedByName: string | null; +} + +export interface ReadReviewMergeGateOptions { + /** Expected full 40-character commit SHA; mismatches yield `HEAD_MISMATCH`. */ + headSha?: string; +} + +export interface ReviewMergeGate { + status: ReviewMergeGateStatus; + decision: MergeGateDecision | null; + gateId: string | null; + reviewId: string | null; + pullRequestNumber: number | null; + headSha: string | null; + policyVersion: string | null; + blockingSeverity: string | null; + severityApplied: string | null; + findingCount: number | null; + assessmentCount: number | null; + coverageDigest: string | null; + reasonCode: string | null; + decidedAt: string | null; + bypass: MergeGateBypass | null; + raw: PullRequestMergeGate | null; +} + +const GATE_STATUSES = new Set([ + "REQUESTED", + "EVALUATING", + "ALLOWED", + "BLOCKED", + "BYPASSED", + "SUPERSEDED", +]); + +function invalidGate(detail: string): ProoflineError { + return new ProoflineError(0, "urn:proofline:sdk:invalid-response", detail); +} + +function isObject(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function optionalString( + record: Record, + field: string, +): string | null { + const value = record[field]; + if (value === undefined || value === null) return null; + if (typeof value !== "string") { + throw invalidGate(`merge_gate.${field} must be a string or null`); + } + return value; +} + +function optionalInteger( + record: Record, + field: string, + nonnegative = false, +): number | null { + const value = record[field]; + if (value === undefined || value === null) return null; + if ( + typeof value !== "number" || + !Number.isSafeInteger(value) || + (nonnegative && value < 0) + ) { + throw invalidGate( + `merge_gate.${field} must be a${nonnegative ? " nonnegative" : ""} integer or null`, + ); + } + return value; +} + +function requiredString( + record: Record, + field: string, +): string { + const value = record[field]; + if (typeof value !== "string" || value.length === 0) { + throw invalidGate(`merge_gate.${field} must be a nonempty string`); + } + return value; +} + +function emptyGate(status: "NOT_CONFIGURED" | "UNAVAILABLE"): ReviewMergeGate { + return { + status, + decision: null, + gateId: null, + reviewId: null, + pullRequestNumber: null, + headSha: null, + policyVersion: null, + blockingSeverity: null, + severityApplied: null, + findingCount: null, + assessmentCount: null, + coverageDigest: null, + reasonCode: null, + decidedAt: null, + bypass: null, + raw: null, + }; +} + +function extractReview(source: Review | ReviewOutcome): { + available: boolean; + review: Review | null; +} { + if (!isObject(source)) { + throw invalidGate("the review source is not an object"); + } + if ("reviewUrl" in source && "review" in source) { + if (source.review === null) return { available: false, review: null }; + if (!isObject(source.review)) { + throw invalidGate("the review outcome contains an invalid review"); + } + return { available: true, review: source.review as Review }; + } + return { available: true, review: source as Review }; +} + +function validateGate(rawGate: unknown): PullRequestMergeGate { + if (!isObject(rawGate)) { + throw invalidGate("the review merge_gate projection is malformed"); + } + const id = requiredString(rawGate, "id"); + const headSha = requiredString(rawGate, "head_sha"); + const policyVersion = requiredString(rawGate, "policy_version"); + const blockingSeverity = requiredString(rawGate, "blocking_severity"); + const status = requiredString(rawGate, "status"); + if (!GATE_STATUSES.has(status as MergeGateStatus)) { + throw invalidGate(`merge_gate.status ${JSON.stringify(status)} is unknown`); + } + const pullRequestNumber = rawGate.pull_request_number; + if ( + typeof pullRequestNumber !== "number" || + !Number.isSafeInteger(pullRequestNumber) || + pullRequestNumber <= 0 + ) { + throw invalidGate( + "merge_gate.pull_request_number must be a positive integer", + ); + } + const decision = rawGate.decision; + if ( + decision !== undefined && + decision !== null && + decision !== "ALLOW" && + decision !== "BLOCK" + ) { + throw invalidGate("merge_gate.decision must be ALLOW, BLOCK, or null"); + } + if (status === "ALLOWED" && decision !== "ALLOW") { + throw invalidGate("an ALLOWED merge gate must carry an ALLOW decision"); + } + if (status === "BLOCKED" && decision !== "BLOCK") { + throw invalidGate("a BLOCKED merge gate must carry a BLOCK decision"); + } + + optionalInteger(rawGate, "assessment_count", true); + optionalInteger(rawGate, "finding_count", true); + optionalInteger(rawGate, "merged_by_github_user_id"); + optionalInteger(rawGate, "merged_pull_request_number"); + for (const field of [ + "review_id", + "coverage_digest", + "reason_code", + "decided_at", + "bypassed_at", + "merge_commit_sha", + "merged_by_login", + "merged_by_name", + "severity_applied", + ]) { + optionalString(rawGate, field); + } + + return { + ...rawGate, + id, + head_sha: headSha, + policy_version: policyVersion, + blocking_severity: blockingSeverity, + status: status as MergeGateStatus, + pull_request_number: pullRequestNumber, + } as PullRequestMergeGate; +} + +/** + * Normalizes and validates the server-recorded `PullRequestMergeGate` projection + * from a `Review` or `ReviewOutcome`. + */ +export function readReviewMergeGate( + source: Review | ReviewOutcome, + options: ReadReviewMergeGateOptions = {}, +): ReviewMergeGate { + if ( + options.headSha !== undefined && + !/^[0-9a-f]{40}$/i.test(options.headSha) + ) { + throw new TypeError("headSha must be a full 40-character commit SHA"); + } + const { available, review } = extractReview(source); + if (!available || !review) return emptyGate("UNAVAILABLE"); + const rawMergeGate = (review as unknown as Record) + .merge_gate; + if (rawMergeGate === undefined || rawMergeGate === null) { + return emptyGate("NOT_CONFIGURED"); + } + const gate = validateGate(rawMergeGate); + const bypassFields: MergeGateBypass = { + bypassedAt: gate.bypassed_at ?? null, + mergeCommitSha: gate.merge_commit_sha ?? null, + mergedPullRequestNumber: gate.merged_pull_request_number ?? null, + mergedByGithubUserId: gate.merged_by_github_user_id ?? null, + mergedByLogin: gate.merged_by_login ?? null, + mergedByName: gate.merged_by_name ?? null, + }; + const hasBypass = + gate.status === "BYPASSED" || + Object.values(bypassFields).some((value) => value !== null); + const headMismatch = + options.headSha !== undefined && + gate.head_sha.toLowerCase() !== options.headSha.toLowerCase(); + + return { + status: headMismatch ? "HEAD_MISMATCH" : gate.status, + decision: headMismatch ? null : (gate.decision ?? null), + gateId: gate.id, + reviewId: gate.review_id ?? null, + pullRequestNumber: gate.pull_request_number, + headSha: gate.head_sha, + policyVersion: gate.policy_version, + blockingSeverity: gate.blocking_severity, + severityApplied: gate.severity_applied ?? null, + findingCount: gate.finding_count ?? null, + assessmentCount: gate.assessment_count ?? null, + coverageDigest: gate.coverage_digest ?? null, + reasonCode: gate.reason_code ?? null, + decidedAt: gate.decided_at ?? null, + bypass: hasBypass ? bypassFields : null, + raw: gate, + }; +} diff --git a/tests/merge-gate.test.mjs b/tests/merge-gate.test.mjs new file mode 100644 index 0000000..99eb271 --- /dev/null +++ b/tests/merge-gate.test.mjs @@ -0,0 +1,307 @@ +import assert from "node:assert/strict"; +import { once } from "node:events"; +import { createServer } from "node:http"; +import test from "node:test"; +import { + ProoflineClient, + ProoflineError, + readReviewMergeGate, +} from "../dist/index.js"; + +const orgId = "00000000-0000-7000-8000-000000000001"; +const reviewId = "00000000-0000-7000-8000-000000000002"; +const gateId = "00000000-0000-7000-8000-000000000009"; +const headSha = "a".repeat(40); +const otherSha = "b".repeat(40); +const token = "plp_customer_canary_3331"; + +async function server(t, handler) { + const http = createServer(handler); + http.listen(0, "127.0.0.1"); + await once(http, "listening"); + t.after( + () => + new Promise((resolve) => { + http.close(resolve); + http.closeAllConnections(); + }), + ); + return `http://127.0.0.1:${http.address().port}`; +} + +function makeReview(mergeGate) { + return { + id: reviewId, + public_key: "review-3331", + kind: "PULL_REQUEST", + status: "COMPLETED", + assessment_count: 1, + environment_display_names: ["production"], + finding_count: 0, + trigger_origin: "MANUAL", + publication: "WITHHELD", + created_at: "2026-10-01T12:00:00Z", + stoppable: false, + related_reviews: [], + subjects: [], + assessments: [ + { + id: "00000000-0000-7000-8000-000000000003", + environment_id: "00000000-0000-7000-8000-000000000004", + environment_display_name: "production", + status: "COMPLETED", + domains: [], + findings: [], + release_evidence_gap: null, + checks: { receipt_recorded: true, status: "READY", families: [] }, + }, + ], + actions: { + promote_findings: false, + rerun: false, + publish: false, + stop: false, + validate_findings: false, + }, + ...(mergeGate === undefined ? {} : { merge_gate: mergeGate }), + }; +} + +function makeGate(overrides = {}) { + return { + id: gateId, + pull_request_number: 42, + head_sha: headSha, + status: "ALLOWED", + decision: "ALLOW", + policy_version: "v1", + blocking_severity: "SERIOUS", + severity_applied: "SERIOUS", + assessment_count: 1, + finding_count: 0, + coverage_digest: "sha256:abc", + reason_code: "NO_BLOCKING_FINDINGS", + review_id: reviewId, + decided_at: "2026-10-01T12:05:00Z", + bypassed_at: null, + merge_commit_sha: null, + merged_pull_request_number: null, + merged_by_github_user_id: null, + merged_by_login: null, + merged_by_name: null, + ...overrides, + }; +} + +test("readReviewMergeGate handles unavailable outcomes and unconfigured reviews", () => { + const unavailable = readReviewMergeGate({ + status: "TIMED_OUT", + reviewUrl: `https://proofline.sh/orgs/by-id/${orgId}/reviews/${reviewId}`, + review: null, + gaps: [], + reason: "the review did not finish before timeoutMs", + }); + assert.equal(unavailable.status, "UNAVAILABLE"); + assert.equal(unavailable.decision, null); + assert.equal(unavailable.raw, null); + + for (const mergeGate of [undefined, null]) { + const unconfigured = readReviewMergeGate(makeReview(mergeGate)); + assert.equal(unconfigured.status, "NOT_CONFIGURED"); + assert.equal(unconfigured.decision, null); + assert.equal(unconfigured.gateId, null); + assert.equal(unconfigured.bypass, null); + } +}); + +test("readReviewMergeGate normalizes every documented GateStatus and Outcome", () => { + const cases = [ + { + name: "REQUESTED", + gate: makeGate({ + status: "REQUESTED", + decision: null, + assessment_count: null, + finding_count: null, + decided_at: null, + reason_code: null, + severity_applied: null, + coverage_digest: null, + }), + expectedDecision: null, + hasBypass: false, + }, + { + name: "EVALUATING", + gate: makeGate({ + status: "EVALUATING", + decision: null, + assessment_count: null, + finding_count: null, + decided_at: null, + }), + expectedDecision: null, + hasBypass: false, + }, + { + name: "ALLOWED", + gate: makeGate({ + status: "ALLOWED", + decision: "ALLOW", + finding_count: 0, + }), + expectedDecision: "ALLOW", + hasBypass: false, + }, + { + name: "BLOCKED", + gate: makeGate({ + status: "BLOCKED", + decision: "BLOCK", + blocking_severity: "SERIOUS", + severity_applied: "WARNING", + finding_count: 2, + reason_code: "BLOCKING_FINDINGS", + }), + expectedDecision: "BLOCK", + hasBypass: false, + }, + { + name: "BYPASSED", + gate: makeGate({ + status: "BYPASSED", + decision: "BLOCK", + finding_count: 1, + bypassed_at: "2026-10-01T12:10:00Z", + merge_commit_sha: "c".repeat(40), + merged_pull_request_number: 43, + merged_by_github_user_id: 98765, + merged_by_login: "octocat", + merged_by_name: "The Octocat", + }), + expectedDecision: "BLOCK", + hasBypass: true, + }, + { + name: "SUPERSEDED", + gate: makeGate({ + status: "SUPERSEDED", + decision: "ALLOW", + }), + expectedDecision: "ALLOW", + hasBypass: false, + }, + ]; + + for (const entry of cases) { + const result = readReviewMergeGate(makeReview(entry.gate)); + assert.equal(result.status, entry.name); + assert.equal(result.decision, entry.expectedDecision); + assert.equal(result.gateId, gateId); + assert.equal(result.pullRequestNumber, 42); + assert.equal(result.headSha, headSha); + assert.equal(result.policyVersion, "v1"); + assert.equal(result.blockingSeverity, entry.gate.blocking_severity); + assert.equal(result.severityApplied, entry.gate.severity_applied ?? null); + assert.equal(result.findingCount, entry.gate.finding_count ?? null); + assert.equal(result.assessmentCount, entry.gate.assessment_count ?? null); + if (entry.hasBypass) { + assert.deepEqual(result.bypass, { + bypassedAt: "2026-10-01T12:10:00Z", + mergeCommitSha: "c".repeat(40), + mergedPullRequestNumber: 43, + mergedByGithubUserId: 98765, + mergedByLogin: "octocat", + mergedByName: "The Octocat", + }); + } else { + assert.equal(result.bypass, null); + } + } +}); + +test("readReviewMergeGate enforces headSha pinning case-insensitively", () => { + const review = makeReview(makeGate({ status: "ALLOWED", decision: "ALLOW" })); + + const matched = readReviewMergeGate(review, { + headSha: headSha.toUpperCase(), + }); + assert.equal(matched.status, "ALLOWED"); + assert.equal(matched.decision, "ALLOW"); + + const mismatched = readReviewMergeGate(review, { headSha: otherSha }); + assert.equal(mismatched.status, "HEAD_MISMATCH"); + assert.equal(mismatched.decision, null); + assert.equal(mismatched.headSha, headSha); + assert.equal(mismatched.raw?.status, "ALLOWED"); + + for (const badSha of ["", "abc123", "g".repeat(40), "a".repeat(39)]) { + assert.throws( + () => readReviewMergeGate(review, { headSha: badSha }), + (err) => err instanceof TypeError, + ); + } +}); + +test("readReviewMergeGate rejects malformed or contradictory gate payloads", () => { + const malformedGates = [ + "not-an-object", + [], + makeGate({ id: "" }), + makeGate({ pull_request_number: 0 }), + makeGate({ pull_request_number: 1.5 }), + makeGate({ status: "UNKNOWN_GATE_STATUS" }), + makeGate({ decision: "MAYBE" }), + makeGate({ status: "ALLOWED", decision: "BLOCK" }), + makeGate({ status: "ALLOWED", decision: null }), + makeGate({ status: "BLOCKED", decision: "ALLOW" }), + makeGate({ status: "BLOCKED", decision: null }), + makeGate({ finding_count: -1 }), + makeGate({ assessment_count: "1" }), + makeGate({ severity_applied: 123 }), + ]; + + for (const gate of malformedGates) { + assert.throws( + () => readReviewMergeGate(makeReview(gate)), + (err) => + err instanceof ProoflineError && + err.type === "urn:proofline:sdk:invalid-response", + ); + } +}); + +test("readReviewMergeGate evaluates reviews returned by waitForReview and getReview", async (t) => { + const baseUrl = await server(t, (request, response) => { + assert.equal(request.headers.authorization, `Bearer ${token}`); + response.writeHead(200, { "Content-Type": "application/json" }); + response.end( + JSON.stringify( + makeReview( + makeGate({ + status: "BLOCKED", + decision: "BLOCK", + finding_count: 1, + reason_code: "BLOCKING_FINDINGS", + }), + ), + ), + ); + }); + + const client = new ProoflineClient({ baseUrl, token }); + const outcome = await client.waitForReview(orgId, reviewId, { + timeoutMs: 5_000, + }); + const fromOutcome = readReviewMergeGate(outcome, { headSha }); + assert.equal(fromOutcome.status, "BLOCKED"); + assert.equal(fromOutcome.decision, "BLOCK"); + assert.equal(fromOutcome.findingCount, 1); + + const fetched = await client.getReview({ + path: { org_id: orgId, review_id: reviewId }, + }); + const fromReview = readReviewMergeGate(fetched, { headSha }); + assert.equal(fromReview.status, "BLOCKED"); + assert.equal(fromReview.reasonCode, "BLOCKING_FINDINGS"); +});