Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
280 changes: 280 additions & 0 deletions src/github-actions.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> {
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<SecretToken> {
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<Exchanged> {
const transport = new Transport({
baseUrl: origin,
token: await identity(issuer, origin, timeout),
requestTimeoutMs: timeout,
});
const reply = await transport.request<unknown>(
"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<Exchanged>;
#lease: Lease;
#renewal: Promise<SecretToken> | undefined;

private constructor(
origin: string,
first: Exchanged,
again: () => Promise<Exchanged>,
) {
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<GitHubActionsCredentials> {
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<SecretToken> {
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<SecretToken> {
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;
}
}
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading