diff --git a/README.md b/README.md index b7d11dc..e732144 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,47 @@ try { } ``` +## GitHub Actions without a stored token + +A GitHub Actions job granted `id-token: write` can read its repository's reviews with no `PROOFLINE_TOKEN` secret, as `proofline ci review` does. `GitHubActionsCredentials.exchange()` asks the runner for the job's OIDC token and exchanges it with Proofline for a token that reads only that repository's reviews and expires after one hour. The credentials name the repository's organization, so the job needs no organization ID. The [CI review check](https://proofline.sh/docs/ci/#github-actions) guide lists when Proofline issues the token. + +```yaml +permissions: + contents: read + id-token: write +``` + +```typescript +import { readFileSync } from "node:fs"; +import { GitHubActionsCredentials, ProoflineClient } from "@proofline/sdk"; + +// On a pull_request event GITHUB_SHA is GitHub's merge commit, never a commit +// Proofline reviewed. The runner's event payload names the head. +const event = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH!, "utf8")); +const head: string = event.pull_request.head.sha; + +const credentials = await GitHubActionsCredentials.exchange({ pullRequestHead: head }); +const client = new ProoflineClient({ token: credentials }); +const organizationId = credentials.organizationId; + +const page = await client.listReviews({ + path: { org_id: organizationId }, + query: { search: head }, +}); +const review = page.items.find( + (item) => item.kind === "PULL_REQUEST" && item.head_commit_sha === head, +); +if (!review) throw new Error(`Proofline has no pull-request review of ${head} yet.`); +const outcome = await client.waitForReview(organizationId, review.id); +console.log(outcome.status, outcome.reviewUrl); +``` + +With `pullRequestHead`, the exchange is refused unless that commit is still the pull request's live head; rerun the job when the head has moved. Pass it on `pull_request`, `pull_request_review` and `pull_request_review_comment` events, and omit it on every other event, `pull_request_target` included, because the job's signed ref is not the pull request's merge ref there. The SDK reads no event payload and chooses no commit. + +The client asks the credentials for a token before every request attempt. Five minutes before a token expires, or at half its lifetime when that is shorter, the next request asks the runner for a new identity and exchanges it again with the same head, so a wait can outlast one token. Concurrent requests share one renewal. A refused renewal, or one that names another organization, fails the request that needed it; the SDK does not go on sending the earlier token. The credentials are sent only to the origin that issued them: a client with another `baseUrl` throws a `TypeError`. Nothing is stored, and the runner's bearer, the OIDC token and the exchanged token are absent from errors and from `inspect` and `JSON.stringify` output. + +A job without `id-token: write` throws a `TypeError` that names the permission before any request; a `permissions` block on the job replaces the workflow's, so the job's own block needs it too. A runner that issues no token throws `ProoflineError` with type `urn:proofline:sdk:github-actions`. A refused exchange throws the server's problem, which does not say which condition failed; [Restore GitHub Actions access to pull request reviews](https://proofline.sh/help/ci-actions-oidc-exchange/) walks through them. The runner request and the exchange are each sent once, and `requestTimeoutMs` bounds each. `exchange()` is explicit, so a job that should prefer a stored token, as the CLI does, checks `process.env.PROOFLINE_TOKEN` and constructs `new ProoflineClient()` instead. The exchanged token is limited to reading, so requesting a review or uploading coverage still needs a stored token with those scopes. + ## Coverage uploads Upload CI coverage reports with a repository-restricted token that holds `coverage:write`. The token holder must have current GitHub write access to that repository. Set `PROOFLINE_TOKEN` to that token and pass the full lowercase 40-character SHA of the commit the tests ran on. diff --git a/src/github-actions.ts b/src/github-actions.ts new file mode 100644 index 0000000..35ffdb6 --- /dev/null +++ b/src/github-actions.ts @@ -0,0 +1,280 @@ +import { + confidential, + configuredOrigin, + ProoflineError, + positive, + SecretToken, + Transport, +} from "./transport.js"; + +export interface GitHubActionsOptions { + /** Defaults to `PROOFLINE_BASE_URL`, then to `https://proofline.sh`. */ + baseUrl?: string; + /** + * The pull request head the job tests, as a full lowercase 40-character SHA. + * The exchange, and every renewal, is then refused unless that commit is + * still the pull request's live head. Name it only on a `pull_request`, + * `pull_request_review` or `pull_request_review_comment` event; on any other + * event the job's signed ref is not the pull request's merge ref. + */ + pullRequestHead?: string; + /** Bounds the request to the runner and the exchange separately. Defaults to 30 seconds. */ + requestTimeoutMs?: number; +} + +const MAX_IDENTITY_BYTES = 64 * 1024; +// How long before its expiry a token is renewed, or half its lifetime when that is shorter. +const RENEW_BEFORE_MS = 5 * 60_000; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const UTC_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/; + +/** Where the runner issues OIDC tokens, and the bearer for asking. */ +interface Runner { + url: URL; + token: SecretToken; +} + +interface Lease { + token: SecretToken; + /** On the clock of `performance.now()`. */ + renewAt: number; +} + +interface Exchanged { + organizationId: string; + lease: Lease; +} + +function object(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +// The runner's fault, never Proofline's: its own type tells the two apart. +function unissued(detail: string): ProoflineError { + return new ProoflineError(0, "urn:proofline:sdk:github-actions", detail); +} + +function malformedExchange(): ProoflineError { + return new ProoflineError( + 0, + "urn:proofline:sdk:invalid-response", + "the credential exchange response is malformed", + ); +} + +// GitHub sets both variables only in a job granted `id-token: write`. +function runner(): Runner { + const environment = typeof process === "undefined" ? {} : process.env; + const address = environment.ACTIONS_ID_TOKEN_REQUEST_URL; + const bearer = environment.ACTIONS_ID_TOKEN_REQUEST_TOKEN; + if (!address || !bearer) + throw new TypeError( + "GitHub Actions offers this job no OIDC token; grant the job `permissions: id-token: write`", + ); + let url: URL | undefined; + try { + url = new URL(address); + } catch { + // Reported below, without the value. + } + if (!url || !confidential(url) || url.username || url.password || url.hash) + throw new TypeError( + "ACTIONS_ID_TOKEN_REQUEST_URL must be an HTTPS URL without credentials", + ); + try { + return { url, token: new SecretToken(bearer) }; + } catch { + throw new TypeError( + "ACTIONS_ID_TOKEN_REQUEST_TOKEN must be a bearer token without whitespace", + ); + } +} + +/** A newly issued OIDC token whose audience is this origin's CI routes. */ +async function identity( + { url, token }: Runner, + origin: string, + timeout: number, +): Promise { + const request = new URL(url); + // Appended as text, so the runner's own query reaches it unchanged. + request.search = `${request.search ? `${request.search}&` : "?"}audience=${encodeURIComponent(`${origin}/ci`)}`; + const headers = new Headers({ Accept: "application/json" }); + token.apply(headers); + const malformed = "GitHub Actions sent a malformed OIDC token response"; + const chunks: Uint8Array[] = []; + try { + const response = await fetch(request, { + headers, + // A redirect would carry the runner's bearer to another origin. + redirect: "manual", + credentials: "omit", + signal: AbortSignal.timeout(Math.ceil(timeout)), + }); + if (!response.ok) { + await response.body?.cancel(); + throw unissued( + `GitHub Actions refused to issue the job's OIDC token with HTTP ${response.status}`, + ); + } + const reader = response.body?.getReader(); + let size = 0; + while (reader) { + const { value, done } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > MAX_IDENTITY_BYTES) { + await reader.cancel(); + throw unissued(malformed); + } + chunks.push(value); + } + } catch (error) { + if (error instanceof ProoflineError) throw error; + throw unissued( + "GitHub Actions did not issue the job's OIDC token within its timeout", + ); + } + try { + const decoder = new TextDecoder("utf-8", { fatal: true }); + const text = chunks + .map((chunk) => decoder.decode(chunk, { stream: true })) + .concat(decoder.decode()) + .join(""); + const issued: unknown = JSON.parse(text); + if (object(issued) && typeof issued.value === "string") + return new SecretToken(issued.value); + } catch { + // Neither the response nor the reason it could not be read is repeated. + } + throw unissued(malformed); +} + +/** + * Exchanges a newly issued runner identity for a token that reads the + * repository's reviews. The transport sends a POST once, refuses a redirect, + * and redacts the identity from the problem of a refusal. + */ +async function exchange( + issuer: Runner, + origin: string, + head: string | undefined, + timeout: number, +): Promise { + const transport = new Transport({ + baseUrl: origin, + token: await identity(issuer, origin, timeout), + requestTimeoutMs: timeout, + }); + const reply = await transport.request( + "POST", + "/api/v1/ci/github-actions/credentials", + { query: { pull_request_head: head } }, + ); + if ( + !object(reply) || + typeof reply.organization_id !== "string" || + !UUID.test(reply.organization_id) || + typeof reply.token !== "string" || + typeof reply.expires_at !== "string" || + !UTC_TIME.test(reply.expires_at) + ) + throw malformedExchange(); + const lifetime = Math.max(0, Date.parse(reply.expires_at) - Date.now()); + if (!Number.isFinite(lifetime)) throw malformedExchange(); + let token: SecretToken; + try { + token = new SecretToken(reply.token); + } catch { + throw malformedExchange(); + } + return { + organizationId: reply.organization_id.toLowerCase(), + lease: { + token, + renewAt: + performance.now() + lifetime - Math.min(RENEW_BEFORE_MS, lifetime / 2), + }, + }; +} + +/** + * A GitHub Actions job's read access to its repository's reviews, with no + * stored secret. The runner signs an OIDC token for the job, and Proofline + * exchanges it for a token that reads only that repository's reviews and + * expires after one hour. Pass the credentials as a client's `token`; a wait + * that outlasts the token renews it with a new runner identity. Nothing is + * stored, and no request is sent for a review. + */ +export class GitHubActionsCredentials { + /** The organization the job's repository belongs to. */ + readonly organizationId: string; + /** The Proofline origin that issued the credentials, the only one they are sent to. */ + readonly origin: string; + readonly #exchange: () => Promise; + #lease: Lease; + #renewal: Promise | undefined; + + private constructor( + origin: string, + first: Exchanged, + again: () => Promise, + ) { + this.origin = origin; + this.organizationId = first.organizationId; + this.#lease = first.lease; + this.#exchange = again; + } + + /** + * Asks the runner for the job's OIDC token and exchanges it, once. A job + * without `id-token: write` throws a `TypeError` before any request, a + * runner that issues no token throws `urn:proofline:sdk:github-actions`, + * and a refused exchange throws the server's problem. + */ + static async exchange( + options: GitHubActionsOptions = {}, + ): Promise { + const origin = configuredOrigin(options.baseUrl).origin; + const timeout = positive( + options.requestTimeoutMs ?? 30_000, + "requestTimeoutMs", + ); + const head = options.pullRequestHead; + if (head !== undefined && !/^[0-9a-f]{40}$/.test(head)) + throw new TypeError( + "pullRequestHead must be a full 40-character lowercase commit SHA", + ); + const issuer = runner(); + // A renewal repeats the first exchange: a new identity and the same head. + const again = () => exchange(issuer, origin, head, timeout); + return new GitHubActionsCredentials(origin, await again(), again); + } + + /** + * The current token, exchanged again once it is due for renewal. Concurrent + * requests share one renewal. A refused renewal, or one that names another + * organization, fails the request that needed it. + */ + token(): Promise { + if (performance.now() < this.#lease.renewAt) + return Promise.resolve(this.#lease.token); + this.#renewal ??= this.#renew().finally(() => { + this.#renewal = undefined; + }); + return this.#renewal; + } + + async #renew(): Promise { + const { organizationId, lease } = await this.#exchange(); + // The client's requests name the first organization; a token for another reads nothing of it. + if (organizationId !== this.organizationId) + throw new ProoflineError( + 0, + "urn:proofline:sdk:invalid-response", + "the renewed credentials name another organization", + ); + this.#lease = lease; + return lease.token; + } +} diff --git a/src/index.ts b/src/index.ts index 0374a0e..78812af 100644 --- a/src/index.ts +++ b/src/index.ts @@ -21,6 +21,8 @@ import { } from "./exports.js"; export type { ExportPage, ExportParameters } from "./exports.js"; +export type { GitHubActionsOptions } from "./github-actions.js"; +export { GitHubActionsCredentials } from "./github-actions.js"; import { type ListReviewsParameters, diff --git a/src/transport.ts b/src/transport.ts index 3f4d25a..e5cd25d 100644 --- a/src/transport.ts +++ b/src/transport.ts @@ -1,3 +1,4 @@ +import type { GitHubActionsCredentials } from "./github-actions.js"; import type { components } from "./schema.js"; const VERSION = "10.8.0"; @@ -106,7 +107,11 @@ export class ProoflineError extends Error { export interface ClientOptions { /** Defaults to `PROOFLINE_BASE_URL`, then to `https://proofline.sh`. */ baseUrl?: string; - token?: string | SecretToken; + /** + * Defaults to `PROOFLINE_TOKEN`. A GitHub Actions job's credentials supply + * each request's token and renew it before it expires. + */ + token?: string | SecretToken | GitHubActionsCredentials; requestTimeoutMs?: number; } @@ -134,6 +139,15 @@ function environmentBaseUrl(): string | undefined { return process.env.PROOFLINE_BASE_URL || undefined; } +/** HTTPS, or HTTP to this machine: a bearer token never crosses a network in the clear. */ +export function confidential(url: URL): boolean { + const loopback = + url.hostname === "localhost" || + url.hostname === "[::1]" || + /^127\.\d+\.\d+\.\d+$/.test(url.hostname); + return url.protocol === "https:" || (url.protocol === "http:" && loopback); +} + function origin(value: string, name: string): URL { let url: URL; try { @@ -143,12 +157,8 @@ function origin(value: string, name: string): URL { `${name} must be an absolute HTTPS URL or loopback HTTP URL`, ); } - const loopback = - url.hostname === "localhost" || - url.hostname === "[::1]" || - /^127\.\d+\.\d+\.\d+$/.test(url.hostname); if ( - (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) || + !confidential(url) || url.username || url.password || url.search || @@ -162,7 +172,7 @@ function origin(value: string, name: string): URL { return url; } -function configuredOrigin(baseUrl: string | undefined): URL { +export function configuredOrigin(baseUrl: string | undefined): URL { if (baseUrl !== undefined) return origin(baseUrl, "baseUrl"); const fromEnvironment = environmentBaseUrl(); return fromEnvironment === undefined @@ -170,7 +180,7 @@ function configuredOrigin(baseUrl: string | undefined): URL { : origin(fromEnvironment, "PROOFLINE_BASE_URL"); } -function positive(value: number, name: string): number { +export function positive(value: number, name: string): number { if (!Number.isFinite(value) || value <= 0) { throw new TypeError(`${name} must be a finite positive number`); } @@ -406,14 +416,23 @@ export function sleep(milliseconds: number): Promise { export class Transport { readonly #base: URL; - readonly #token: SecretToken; + readonly #token: SecretToken | GitHubActionsCredentials; readonly #timeout: number; constructor(options: ClientOptions) { this.#base = configuredOrigin(options.baseUrl); const token = options.token ?? environmentToken(); - this.#token = - token instanceof SecretToken ? token : new SecretToken(token ?? ""); + if (typeof token === "object" && !(token instanceof SecretToken)) { + // A job's token is for the origin that issued it and for no other. + if (token.origin !== this.#base.origin) + throw new TypeError( + "baseUrl must be the origin that issued the GitHub Actions credentials", + ); + this.#token = token; + } else { + this.#token = + token instanceof SecretToken ? token : new SecretToken(token ?? ""); + } this.#timeout = positive( options.requestTimeoutMs ?? 30_000, "requestTimeoutMs", @@ -454,6 +473,11 @@ export class Transport { if (mcpPhase && new TextEncoder().encode(requestBody).length > 8192) throw new TypeError("MCP request exceeds 8192 bytes"); for (let attempt = 0; ; attempt += 1) { + // A job's credentials renew here, so a retry never sends an expired token. + const token = + this.#token instanceof SecretToken + ? this.#token + : await this.#token.token(); const headers = new Headers({ Accept: accept, "User-Agent": `proofline-typescript/${VERSION}`, @@ -465,7 +489,7 @@ export class Transport { if (mcpPhase !== "initialize") headers.set("MCP-Protocol-Version", "2025-11-25"); } - this.#token.apply(headers); + token.apply(headers); const now = performance.now(); const waitRemaining = deadline === undefined ? this.#timeout : deadline - now; @@ -529,7 +553,7 @@ export class Transport { decode, ); if (response.ok) return value as T; - const error = problem(response.status, value, this.#token); + const error = problem(response.status, value, token); const delay = retryDelay(response.headers.get("Retry-After"), attempt); if ( method !== "GET" || diff --git a/tests/github-actions.test.mjs b/tests/github-actions.test.mjs new file mode 100644 index 0000000..ae1a494 --- /dev/null +++ b/tests/github-actions.test.mjs @@ -0,0 +1,631 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { once } from "node:events"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { inspect } from "node:util"; +import { + GitHubActionsCredentials, + ProoflineClient, + ProoflineError, +} from "../dist/index.js"; + +const orgId = "00000000-0000-7000-8000-000000000001"; +const foreignOrgId = "00000000-0000-7000-8000-00000000000f"; +const reviewId = "00000000-0000-7000-8000-000000000002"; +const head = "a".repeat(40); +const runnerBearer = "runner-bearer-canary-7719"; +const responseCanary = "private-response-canary-7719"; +const exchangePath = "/api/v1/ci/github-actions/credentials"; +const reviewPath = `/api/v1/organizations/${orgId}/reviews/${reviewId}`; +const HOUR = 60 * 60_000; + +async function server(t, handler) { + const calls = []; + const http = createServer(async (request, response) => { + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + calls.push({ + method: request.method, + url: request.url, + authorization: request.headers.authorization, + body: Buffer.concat(chunks).toString("utf8"), + }); + handler(request, response, calls); + }); + http.listen(0, "127.0.0.1"); + await once(http, "listening"); + t.after( + () => + new Promise((resolve) => { + http.close(resolve); + http.closeAllConnections(); + }), + ); + return { baseUrl: `http://127.0.0.1:${http.address().port}`, calls }; +} + +function json(response, status, body, headers = {}) { + response.writeHead(status, { + "Content-Type": "application/json", + ...headers, + }); + response.end(JSON.stringify(body)); +} + +function withEnvironment(t, name, value) { + const previous = process.env[name]; + t.after(() => { + if (previous === undefined) delete process.env[name]; + else process.env[name] = previous; + }); + const set = (next) => { + if (next === undefined) delete process.env[name]; + else process.env[name] = next; + }; + set(value); + return set; +} + +/** + * A runner that issues numbered identities, as GitHub issues a new OIDC token + * for each request, and the job environment that points at it. + */ +async function runner(t, handler) { + const fixture = await server( + t, + handler ?? + ((_, response, calls) => + json(response, 200, { value: `identity-${calls.length}` })), + ); + const requestUrl = `${fixture.baseUrl}/_apis/idtoken?api-version=2.0`; + withEnvironment(t, "ACTIONS_ID_TOKEN_REQUEST_URL", requestUrl); + withEnvironment(t, "ACTIONS_ID_TOKEN_REQUEST_TOKEN", runnerBearer); + withEnvironment(t, "PROOFLINE_BASE_URL", undefined); + withEnvironment(t, "PROOFLINE_TOKEN", undefined); + return fixture; +} + +/** + * Proofline's exchange and one review. Each exchange grants a numbered token + * for `lifetimes`' next entry, or for an hour once they run out. + */ +async function proofline(t, lifetimes = [], refuse = () => false) { + let granted = 0; + const fixture = await server(t, (request, response) => { + if (refuse(request, response)) return; + if (!request.url.startsWith(exchangePath)) + return json(response, 200, { id: reviewId }); + granted += 1; + json(response, 200, { + organization_id: orgId, + token: `plp_ci_${granted}`, + expires_at: new Date( + Date.now() + (lifetimes[granted - 1] ?? HOUR), + ).toISOString(), + }); + }); + const exchanges = () => + fixture.calls.filter(({ url }) => url.startsWith(exchangePath)); + const reads = () => fixture.calls.filter(({ url }) => url === reviewPath); + return { ...fixture, exchanges, reads }; +} + +const read = (client) => + client.getReview({ path: { org_id: orgId, review_id: reviewId } }); + +test("a job signs in with its runner identity and reads with the exchanged token", async (t) => { + const issuer = await runner(t); + const service = await proofline(t); + const credentials = await GitHubActionsCredentials.exchange({ + baseUrl: service.baseUrl, + pullRequestHead: head, + }); + assert.equal(credentials.organizationId, orgId); + assert.equal(credentials.origin, service.baseUrl); + // The runner's own query is kept, and the audience is this origin's CI routes. + assert.deepEqual(issuer.calls, [ + { + method: "GET", + url: `/_apis/idtoken?api-version=2.0&audience=${encodeURIComponent(`${service.baseUrl}/ci`)}`, + authorization: `Bearer ${runnerBearer}`, + body: "", + }, + ]); + assert.deepEqual(service.calls, [ + { + method: "POST", + url: `${exchangePath}?pull_request_head=${head}`, + authorization: "Bearer identity-1", + body: "", + }, + ]); + + const client = new ProoflineClient({ + baseUrl: service.baseUrl, + token: credentials, + }); + assert.equal((await read(client)).id, reviewId); + assert.equal((await read(client)).id, reviewId); + assert.deepEqual( + service.reads().map(({ authorization }) => authorization), + ["Bearer plp_ci_1", "Bearer plp_ci_1"], + ); + assert.equal(issuer.calls.length, 1); + + // Nothing printable holds the runner's bearer, the identity or the token. + const printed = `${inspect(credentials, { depth: 8, showHidden: true })}${JSON.stringify(credentials)}${String(credentials)}`; + for (const secret of [runnerBearer, "identity-1", "plp_ci_1"]) + assert(!printed.includes(secret)); + + // Without a head the exchange verifies none, and the origin follows the environment. + withEnvironment(t, "PROOFLINE_BASE_URL", service.baseUrl); + const unpinned = await GitHubActionsCredentials.exchange(); + assert.equal(unpinned.origin, service.baseUrl); + assert.equal(service.exchanges().at(-1).url, exchangePath); + await read(new ProoflineClient({ token: unpinned })); + assert.equal(service.reads().at(-1).authorization, "Bearer plp_ci_2"); +}); + +test("a token is renewed five minutes before it expires, once for concurrent requests", async (t) => { + const issuer = await runner(t); + let onRead = () => false; + const service = await proofline( + t, + [HOUR, HOUR, 60_000], + (request, response) => + request.url === reviewPath ? onRead(response) : false, + ); + // Move the client's clock without waiting. Timers still run in real time. + const real = performance.now.bind(performance); + let elapsed = 0; + t.mock.method(performance, "now", () => real() + elapsed); + + const client = new ProoflineClient({ + baseUrl: service.baseUrl, + token: await GitHubActionsCredentials.exchange({ + baseUrl: service.baseUrl, + pullRequestHead: head, + }), + }); + elapsed = 55 * 60_000 - 5_000; + await read(client); + assert.equal(service.exchanges().length, 1); + assert.equal(service.reads().at(-1).authorization, "Bearer plp_ci_1"); + + elapsed = 55 * 60_000 + 5_000; + await Promise.all(Array.from({ length: 5 }, () => read(client))); + // One new identity and the same head, shared by all five requests. + assert.deepEqual( + service.exchanges().map(({ url, authorization }) => [url, authorization]), + [ + [`${exchangePath}?pull_request_head=${head}`, "Bearer identity-1"], + [`${exchangePath}?pull_request_head=${head}`, "Bearer identity-2"], + ], + ); + assert.deepEqual( + service + .reads() + .slice(-5) + .map(({ authorization }) => authorization), + Array.from({ length: 5 }, () => "Bearer plp_ci_2"), + ); + await read(client); + assert.equal(issuer.calls.length, 2); + + // A token that comes due while a read waits out a 503 is renewed for the retry. + onRead = (response) => { + onRead = () => false; + elapsed += 55 * 60_000; + json(response, 503, {}, { "Retry-After": "0" }); + return true; + }; + await read(client); + assert.deepEqual( + service + .reads() + .slice(-2) + .map(({ authorization }) => authorization), + ["Bearer plp_ci_2", "Bearer plp_ci_3"], + ); + assert.equal(service.exchanges().length, 3); + + // The third token lasts a minute, so it is renewed at half its lifetime. + elapsed += 25_000; + await read(client); + assert.equal(service.exchanges().length, 3); + elapsed += 10_000; + await read(client); + assert.equal(service.exchanges().length, 4); + assert.equal(service.reads().at(-1).authorization, "Bearer plp_ci_4"); +}); + +test("a refused or foreign renewal fails the request without sending the old token", async (t) => { + await runner(t); + let mode = "granted"; + const service = await proofline(t, [0], (request, response) => { + if (!request.url.startsWith(exchangePath) || mode === "granted") + return false; + if (mode === "refused") + json(response, 403, { + type: "https://proofline.test/problems/forbidden", + title: "forbidden", + status: 403, + detail: `the pull request's head is now ${"b".repeat(40)}; rerun the job`, + }); + else + json(response, 200, { + organization_id: foreignOrgId, + token: "plp_ci_foreign", + expires_at: new Date(Date.now() + HOUR).toISOString(), + }); + return true; + }); + // The first token has already expired, so the next request must renew it. + const credentials = await GitHubActionsCredentials.exchange({ + baseUrl: service.baseUrl, + pullRequestHead: head, + }); + const client = new ProoflineClient({ + baseUrl: service.baseUrl, + token: credentials, + }); + + mode = "refused"; + await assert.rejects( + read(client), + (error) => + error instanceof ProoflineError && + error.status === 403 && + error.type === "https://proofline.test/problems/forbidden" && + error.detail.includes("rerun the job"), + ); + // A wait reports a refused renewal as it reports any other refusal. + await assert.rejects( + client.waitForReview(orgId, reviewId, { timeoutMs: 1_000 }), + (error) => error instanceof ProoflineError && error.status === 403, + ); + mode = "foreign"; + await assert.rejects( + read(client), + (error) => + error instanceof ProoflineError && + error.status === 0 && + error.type === "urn:proofline:sdk:invalid-response" && + error.detail === "the renewed credentials name another organization", + ); + assert.equal(service.reads().length, 0); + assert.equal(credentials.organizationId, orgId); + + // A failed renewal leaves the credentials able to renew. + mode = "granted"; + await read(client); + assert.deepEqual( + service.reads().map(({ authorization }) => authorization), + ["Bearer plp_ci_2"], + ); +}); + +test("a job without id-token: write is told so before any request", async (t) => { + const issuer = await runner(t); + const service = await proofline(t); + const options = { baseUrl: service.baseUrl }; + const setUrl = withEnvironment(t, "ACTIONS_ID_TOKEN_REQUEST_URL", undefined); + const setBearer = withEnvironment( + t, + "ACTIONS_ID_TOKEN_REQUEST_TOKEN", + runnerBearer, + ); + const requestUrl = `${issuer.baseUrl}/_apis/idtoken`; + for (const [url, bearer] of [ + [undefined, runnerBearer], + [requestUrl, undefined], + [requestUrl, ""], + ["", ""], + ]) { + setUrl(url); + setBearer(bearer); + await assert.rejects( + GitHubActionsCredentials.exchange(options), + (error) => + error instanceof TypeError && + error.message.includes("permissions: id-token: write"), + ); + } + + // An address that could leak the runner's bearer is refused without echoing it. + setBearer(runnerBearer); + for (const url of [ + "http://runner.example/idtoken?sig=url-canary", + "https://user:url-canary@runner.example/idtoken", + "https://runner.example/idtoken#url-canary", + "not a url-canary", + ]) { + setUrl(url); + await assert.rejects( + GitHubActionsCredentials.exchange(options), + (error) => + error instanceof TypeError && + error.message.startsWith("ACTIONS_ID_TOKEN_REQUEST_URL must be") && + !error.message.includes("url-canary"), + ); + } + setUrl(requestUrl); + setBearer(`${runnerBearer}\nX-Injected: 1`); + await assert.rejects( + GitHubActionsCredentials.exchange(options), + (error) => + error instanceof TypeError && + error.message.startsWith("ACTIONS_ID_TOKEN_REQUEST_TOKEN must be") && + !error.message.includes(runnerBearer), + ); + + setBearer(runnerBearer); + for (const pullRequestHead of [ + "main", + head.slice(1), + "A".repeat(40), + `${head}\n`, + "", + ]) { + await assert.rejects( + GitHubActionsCredentials.exchange({ ...options, pullRequestHead }), + (error) => + error instanceof TypeError && + error.message.startsWith("pullRequestHead must be"), + ); + } + await assert.rejects( + GitHubActionsCredentials.exchange({ ...options, requestTimeoutMs: 0 }), + TypeError, + ); + await assert.rejects( + GitHubActionsCredentials.exchange({ baseUrl: "http://customer.example" }), + (error) => error.message.startsWith("baseUrl must be"), + ); + assert.equal(issuer.calls.length, 0); + assert.equal(service.calls.length, 0); +}); + +test("a runner that issues no token is told apart from Proofline, without its response", async (t) => { + const elsewhere = await server(t, (_, response) => + json(response, 200, { value: "identity-from-elsewhere" }), + ); + let mode; + const issuer = await runner(t, (_, response) => { + if (mode === "refused") return json(response, 500, { responseCanary }); + if (mode === "redirect") + return json(response, 302, {}, { Location: elsewhere.baseUrl }); + if (mode === "silent") return; + response.writeHead(200, { "Content-Type": "application/json" }); + if (mode === "text") return response.end(responseCanary); + if (mode === "no-value") + return response.end(JSON.stringify({ token: responseCanary })); + if (mode === "spaced") + return response.end(JSON.stringify({ value: `${responseCanary} 1` })); + if (mode === "invalid-utf8") return response.end(Buffer.from([0xff])); + response.end(JSON.stringify({ value: "x".repeat(64 * 1024) })); + }); + const service = await proofline(t); + const details = { + refused: + "GitHub Actions refused to issue the job's OIDC token with HTTP 500", + redirect: + "GitHub Actions refused to issue the job's OIDC token with HTTP 302", + silent: + "GitHub Actions did not issue the job's OIDC token within its timeout", + }; + for (mode of [ + "refused", + "redirect", + "silent", + "text", + "no-value", + "spaced", + "invalid-utf8", + "oversize", + ]) { + const before = issuer.calls.length; + const started = performance.now(); + await assert.rejects( + GitHubActionsCredentials.exchange({ + baseUrl: service.baseUrl, + requestTimeoutMs: 100, + }), + (error) => + error instanceof ProoflineError && + error.status === 0 && + error.type === "urn:proofline:sdk:github-actions" && + error.detail === + (details[mode] ?? + "GitHub Actions sent a malformed OIDC token response") && + !inspect(error).includes(responseCanary) && + !error.detail.includes(responseCanary), + mode, + ); + assert(performance.now() - started < 2_000, mode); + assert.equal(issuer.calls.length, before + 1, mode); + } + // The runner's bearer followed no redirect, and Proofline was never asked. + assert.equal(elsewhere.calls.length, 0); + assert.equal(service.calls.length, 0); +}); + +test("a refused exchange keeps the server's problem and is sent once", async (t) => { + await runner(t); + const elsewhere = await server(t, (_, response) => + json(response, 200, { id: reviewId }), + ); + let mode; + const service = await proofline(t, [], (request, response) => { + if (mode === "forbidden") + json(response, 403, { + type: "https://proofline.test/problems/forbidden", + title: "forbidden", + status: 403, + // A refusal that repeats the runner identity has it redacted. + detail: `refused ${request.headers.authorization}`, + }); + else if (mode === "unavailable") + json(response, 503, {}, { "Retry-After": "0" }); + else if (mode === "redirect") + json(response, 307, {}, { Location: `${elsewhere.baseUrl}/x` }); + else if (mode === "silent") return true; + else { + const granted = { + organization_id: orgId, + token: responseCanary, + expires_at: "2099-01-01T00:00:00Z", + }; + json( + response, + 200, + { + array: [granted], + "no-organization": { ...granted, organization_id: "acme" }, + "no-token": { ...granted, token: undefined }, + "spaced-token": { ...granted, token: `${responseCanary} 1` }, + "no-expiry": { ...granted, expires_at: undefined }, + "local-time": { ...granted, expires_at: "2099-01-01T00:00:00+01:00" }, + "not-a-time": { ...granted, expires_at: "9999-99-99T99:99:99Z" }, + }[mode], + ); + } + return true; + }); + const exchange = (requestTimeoutMs = 30_000) => + GitHubActionsCredentials.exchange({ + baseUrl: service.baseUrl, + requestTimeoutMs, + }); + + mode = "forbidden"; + const refusal = await exchange().catch((error) => error); + assert(refusal instanceof ProoflineError); + assert.equal(refusal.status, 403); + assert.equal(refusal.type, "https://proofline.test/problems/forbidden"); + assert.equal(refusal.title, "forbidden"); + assert.equal(service.calls.at(-1).authorization, "Bearer identity-1"); + assert.equal(refusal.detail, "refused Bearer [redacted]"); + assert(!inspect(refusal).includes("identity-1")); + + for (const [next, status] of [ + ["unavailable", 503], + ["redirect", 307], + ]) { + mode = next; + const before = service.calls.length; + await assert.rejects( + exchange(), + (error) => error instanceof ProoflineError && error.status === status, + ); + assert.equal(service.calls.length, before + 1, mode); + } + assert.equal(elsewhere.calls.length, 0); + + mode = "silent"; + await assert.rejects( + exchange(100), + (error) => + error instanceof ProoflineError && + error.status === 0 && + error.type === "urn:proofline:sdk:transport", + ); + + for (mode of [ + "array", + "no-organization", + "no-token", + "spaced-token", + "no-expiry", + "local-time", + "not-a-time", + ]) { + await assert.rejects( + exchange(), + (error) => + error instanceof ProoflineError && + error.status === 0 && + error.type === "urn:proofline:sdk:invalid-response" && + error.detail === "the credential exchange response is malformed" && + !inspect(error).includes(responseCanary), + mode, + ); + } +}); + +test("credentials stay on the origin that issued them", async (t) => { + await runner(t); + const service = await proofline(t); + const other = await proofline(t); + const credentials = await GitHubActionsCredentials.exchange({ + baseUrl: service.baseUrl, + }); + const refused = (error) => + error instanceof TypeError && + error.message === + "baseUrl must be the origin that issued the GitHub Actions credentials"; + assert.throws( + () => new ProoflineClient({ baseUrl: other.baseUrl, token: credentials }), + refused, + ); + // PROOFLINE_BASE_URL may have changed since the exchange read it. + withEnvironment(t, "PROOFLINE_BASE_URL", other.baseUrl); + assert.throws(() => new ProoflineClient({ token: credentials }), refused); + assert.equal(other.calls.length, 0); + // A stored token in the environment does not replace explicit credentials. + withEnvironment(t, "PROOFLINE_TOKEN", "plp_stored_token"); + await read( + new ProoflineClient({ baseUrl: service.baseUrl, token: credentials }), + ); + assert.equal(service.reads().at(-1).authorization, "Bearer plp_ci_1"); +}); + +test("the README's job compiles against the public declarations", async (t) => { + const work = await mkdtemp(join(tmpdir(), "sdk-github-actions-types-")); + t.after(() => rm(work, { recursive: true, force: true })); + const entry = fileURLToPath(new URL("../dist/index.js", import.meta.url)); + const readme = await readFile( + new URL("../README.md", import.meta.url), + "utf8", + ); + const documented = readme + .split("```typescript\n") + .map((block) => block.split("\n```")[0]) + .filter((block) => block.includes("GitHubActionsCredentials.exchange(")); + assert.equal(documented.length, 1); + const fixture = join(work, "consumer.mts"); + await writeFile( + fixture, + `${documented[0].replace('"@proofline/sdk"', JSON.stringify(entry))} +import type { ClientOptions, GitHubActionsOptions, ReviewOutcome } from ${JSON.stringify(entry)}; +const options: GitHubActionsOptions = { baseUrl: "https://proofline.sh", requestTimeoutMs: 5_000 }; +const clientOptions: ClientOptions = { token: await GitHubActionsCredentials.exchange(options) }; +const typed: ReviewOutcome = outcome; +console.log(clientOptions, typed); +// @ts-expect-error Credentials come only from an exchange. +new GitHubActionsCredentials(); +// @ts-expect-error Only a job's credentials renew a token; a look-alike is refused. +new ProoflineClient({ token: { origin: "https://proofline.sh", organizationId: "", token: async () => "" } }); +`, + ); + execFileSync(process.execPath, [ + fileURLToPath( + new URL("../node_modules/typescript/lib/tsc.js", import.meta.url), + ), + "--noEmit", + "--strict", + "--exactOptionalPropertyTypes", + "--target", + "ES2022", + "--module", + "NodeNext", + "--moduleResolution", + "NodeNext", + fixture, + ]); +});