diff --git a/AGENTS.md b/AGENTS.md index e1d5ec1..0caa9ef 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,8 +26,12 @@ dependency-light and customer-neutral. write permission. A Workspace whose policy declares `permission_ceiling: "contents"` (since `0.16.0`) mints exactly `contents: write` for the write tier and exactly `contents: read` for the - read tier, never an opt-in, so its tokens carry no Actions, Checks, issue, - membership, pull request or workflow permission. A mint without an explicit + read tier, never an installation opt-in, so its tokens carry no Actions, + issue, membership, pull request or workflow permission. Its only opt-in, + `checks_read: true` (since `0.17.0`, accepted only on a contents-ceiling + Workspace), adds exactly `checks: read` to its read tier outside the + policy's `conglomerate_hosts` repository; its write tier and every other + Workspace never gain it. A mint without an explicit tier or a Workspace of the policy fails, and so does any set that asks for a permission or level the installation has not accepted. A token of a GitHub Actions OIDC purpose is limited to the purpose's one repository and its exact reviewed permission diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 0041322..2e6271f 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -62,7 +62,9 @@ its tier, and refuses a response with any other scope or any other repository: becomes `issues: read`; - a Workspace with `permission_ceiling: "contents"`: exactly `contents: write` for the write tier and exactly `contents: read` for the - read tier, never an opt-in. + read tier, never an installation opt-in. With `checks_read: true` (since + `0.17.0`) its read tier is `contents: read` and `checks: read`, except on + the policy's `conglomerate_hosts` repository. Before asking GitHub, the runtime refuses any set that asks for a permission or level the installation has not accepted, any write tier for a Workspace @@ -140,9 +142,13 @@ production applications host that pushes its applications' data, declares tier of each grant, with one exception below, and each tier asks for repository contents only: `contents: write` or `contents: read`, plus GitHub's `metadata: read`, with no -opt-in whatever the installation accepted. Its tokens therefore carry no -permission for pull requests, issues, check runs, workflow runs, workflow -files or Organization membership (opening an issue in a public repository, +installation opt-in whatever the installation accepted. Its tokens therefore +carry no permission for pull requests, issues, workflow runs, workflow files +or Organization membership, and none for check runs unless the Workspace +declares `checks_read: true` (since `0.17.0`): then its read tier also reads +check runs, so an application host can verify a commit's checks before it +deploys it, while its write tier and the `conglomerate_hosts` repository stay +contents-only (opening an issue in a public repository, above, is GitHub's exception for every token). `contents: write` stays GitHub's whole contents permission: it pushes, force-pushes and deletes every unprotected branch and creates tags, releases and `repository_dispatch` events, and a diff --git a/README.md b/README.md index f2534b6..4c2fce8 100644 --- a/README.md +++ b/README.md @@ -25,9 +25,13 @@ Since `0.16.0` a Workspace whose policy entry declares repository contents only: `contents: write` for a `push`, `maintain` or `admin` grant, `contents: read` for a `pull` or `triage` grant, and only `contents: read` on the policy's `conglomerate_hosts` repository. Its tokens -never carry an Actions, Checks, issue, membership, pull request or workflow -permission. See -[Contents-only Workspaces](#contents-only-workspaces-permission_ceiling-contents). +never carry an Actions, issue, membership, pull request or workflow +permission, and no Checks permission unless it opts in: since `0.17.0` such a +Workspace can declare `checks_read: true`, and then its `pull` and `triage` +grants also ask for `checks: read`, so an application host can verify a +commit's check runs before it deploys it. See +[Contents-only Workspaces](#contents-only-workspaces-permission_ceiling-contents) +and [Reading check runs](#reading-check-runs-checks_read). Since `0.13.0` the Cloudflare Worker adapter also serves short-lived GitHub Actions runners: a job of an allowlisted Deployment Repo exchanges its GitHub @@ -135,7 +139,11 @@ Workspace id + Workspace credential + repository (name or id) `pull` or `triage`, and only `contents: read` on the policy's `conglomerate_hosts` repository. It carries no permission for pull requests, issues, check runs, GitHub Actions, workflow files or - Organization membership: in the live check GitHub refused it opening and + Organization membership, except that a Workspace with `checks_read: true` + (since `0.17.0`) adds `checks: read` to its `pull` and `triage` grants + outside that repository (see + [Reading check runs](#reading-check-runs-checks_read)). In the live check of + `0.16.0` GitHub refused a contents-ceiling token opening and listing pull requests, opening an issue in a private repository, rerunning and dispatching workflows, creating a check run and pushing a change to `.github/workflows/`. @@ -257,6 +265,10 @@ Schema v3 binds each Workspace to its GitHub Team and names no repositories: `"contents"` every token carries repository contents only; see [Contents-only Workspaces](#contents-only-workspaces-permission_ceiling-contents). Any other value, including `null`, is rejected. +- `workspaces[].checks_read` is optional (since `0.17.0`). Its only value is + `true`, and only a Workspace with `permission_ceiling: "contents"` may + declare it; any other value or Workspace is rejected. See + [Reading check runs](#reading-check-runs-checks_read). - `oidc` is optional (since `0.13.0`). It declares the purposes for which GitHub Actions jobs of listed Deployment Repos may obtain a token; see [The `oidc` purpose table](#the-oidc-purpose-table). Absent, the broker has @@ -498,6 +510,51 @@ For such a Workspace: there, and the mint refuses the write set for that repository before GitHub is asked, should a gate ever select it. +#### Reading check runs (`checks_read`) + +Since `0.17.0` a contents-ceiling Workspace can opt in to reading check runs. +An application host needs it to deploy a Module's commit only once that +commit's checks have passed: it reads +`GET /repos/{owner}/{repo}/commits/{sha}/check-runs` for the Module +repository, which a `contents: read` token cannot. The policy entry adds: + +```json +{ + "id": "example-apps-host", + "github_team_id": 4005, + "github_team_slug": "apps-host", + "credential_file": "/run/secrets/workspace-example-apps-host", + "permission_ceiling": "contents", + "checks_read": true +} +``` + +For such a Workspace: + +- a `pull` or `triage` grant mints exactly `contents: read` and + `checks: read` (plus `metadata: read`); +- a `push`, `maintain` or `admin` grant still mints exactly + `contents: write`, so the repositories the host writes, such as its + applications' data repositories, gain nothing; +- on the policy's `conglomerate_hosts` repository every grant still mints + exactly `contents: read`, so a `push` grant lowered to the read tier there + gains nothing either; +- no write permission is added anywhere, and other Workspaces of the policy + mint exactly as before. + +`checks: read` reveals check runs (names, status, conclusions and output +summaries) of repositories the Workspace can already read. It cannot create, +rerun or change a check run. The installation already holds `checks: read` +(the policy requires it), so an Organization accepts no new installation +permission; what it accepts is this wider read for that one Workspace, by +merging the opt-in into its reviewed policy. + +`checks_read` is only `true` and only on a contents-ceiling Workspace; any +other value, or the key on another Workspace, is rejected and the broker +fails closed. A broker before `0.17.0` ignores the key, keeps minting +`contents: read` and the host's read of check runs is refused, so nothing is +deployed. Deploy `0.17.0` before relying on the opt-in. + `contents: write` is GitHub's whole permission for repository contents, and the ceiling cannot narrow it further: GitHub has no installation permission for one branch or for fast-forward pushes only. Such a token pushes, diff --git a/package-lock.json b/package-lock.json index 178fb57..259c4fd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@lazurio/github-app-broker", - "version": "0.16.0", + "version": "0.17.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@lazurio/github-app-broker", - "version": "0.16.0", + "version": "0.17.0", "license": "Apache-2.0", "dependencies": { "jose": "6.2.12" diff --git a/package.json b/package.json index a80811a..7b59d79 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@lazurio/github-app-broker", - "version": "0.16.0", + "version": "0.17.0", "private": true, "license": "Apache-2.0", "repository": { diff --git a/src/broker.mjs b/src/broker.mjs index 7bcd639..a23113c 100644 --- a/src/broker.mjs +++ b/src/broker.mjs @@ -204,20 +204,29 @@ function formatHostsSummary(hosts) { * Offline summary of the parsed Team binding and of the exact permission set each access tier * mints under this policy; no GitHub traffic and no secret. A policy whose Workspaces declare no * permission ceiling prints exactly the two tier lines; a read ceiling adds the one set every - * grant of such a Workspace mints, a contents ceiling the two sets its write and read grants mint, - * and either adds a CEILING column. OIDC purposes, when declared, follow. + * grant of such a Workspace mints, a contents ceiling the two sets its write and read grants mint + * (the read set of a Workspace with `checks_read` on its own line, `contents+checks_read` in the + * column), and either adds a CEILING column. OIDC purposes, when declared, follow. */ export function formatPolicySummary(policy) { const uncapped = policy.workspaces.find((workspace) => workspace.permission_ceiling === undefined); const capped = policy.workspaces.find((workspace) => workspace.permission_ceiling === READ_CEILING); const contentsOnly = policy.workspaces.find((workspace) => workspace.permission_ceiling === CONTENTS_CEILING); + const contentsChecks = policy.workspaces.find( + (workspace) => workspace.permission_ceiling === CONTENTS_CEILING && workspace.checks_read === true, + ); + const contentsPlain = policy.workspaces.find( + (workspace) => workspace.permission_ceiling === CONTENTS_CEILING && workspace.checks_read !== true, + ); const ceilingColumn = capped !== undefined || contentsOnly !== undefined; const header = ["WORKSPACE", "TEAM_ID", "TEAM_SLUG", ...(ceilingColumn ? ["CEILING"] : [])]; const rows = policy.workspaces.map((workspace) => [ workspace.id, String(workspace.github_team_id), workspace.github_team_slug ?? "-", - ...(ceilingColumn ? [workspace.permission_ceiling ?? "-"] : []), + ...(ceilingColumn + ? [workspace.checks_read === true ? `${workspace.permission_ceiling}+checks_read` : (workspace.permission_ceiling ?? "-")] + : []), ]); const widths = header.map((title, column) => Math.max(title.length, ...rows.map((row) => row[column].length))); const line = (values) => values.map((value, column) => value.padEnd(widths[column])).join(" ").trimEnd(); @@ -235,7 +244,16 @@ export function formatPolicySummary(policy) { ...(contentsOnly ? [ `contents ceiling (push/maintain/admin grant of a CEILING contents Workspace) asks for: ${formatPermissions(tokenPermissions(policy, WRITE_ACCESS, contentsOnly))}`, - `contents ceiling (pull/triage grant of a CEILING contents Workspace) asks for: ${formatPermissions(tokenPermissions(policy, READ_ACCESS, contentsOnly))}`, + ] + : []), + ...(contentsPlain + ? [ + `contents ceiling (pull/triage grant of a CEILING contents Workspace) asks for: ${formatPermissions(tokenPermissions(policy, READ_ACCESS, contentsPlain))}`, + ] + : []), + ...(contentsChecks + ? [ + `contents ceiling with checks_read (pull/triage grant, not on the conglomerate_hosts repository) asks for: ${formatPermissions(tokenPermissions(policy, READ_ACCESS, contentsChecks))}`, ] : []), ...(rows.length > 0 ? [line(header), ...rows.map(line)] : ["no Workspaces"]), diff --git a/src/core.mjs b/src/core.mjs index 535c51f..618a13f 100644 --- a/src/core.mjs +++ b/src/core.mjs @@ -25,7 +25,7 @@ const RETIRED_POLICY_SCHEMA_V2 = "lazurio.github_app_broker.policy.v2"; const V3_MIGRATION = "migrate to lazurio.github_app_broker.policy.v3 by deleting `repositories` and every `workspaces[].repository_ids`; the live Team grant is the scope"; const GITHUB_API_VERSION = "2026-03-10"; -const USER_AGENT = "lazurio-github-app-broker/0.16.0"; +const USER_AGENT = "lazurio-github-app-broker/0.17.0"; /** Upper bound for `policy check --live` Team repository pages (100 repositories per page). */ const MAX_TEAM_REPOSITORY_PAGES = 100; const MAX_HOST_ADMISSION_PAGES = 10; @@ -81,11 +81,13 @@ const PERMISSION_CEILINGS = Object.freeze([READ_CEILING, CONTENTS_CEILING]); /** * The two exact sets of a contents-ceiling Workspace (plus GitHub's automatic `metadata: read`). - * No opt-in reaches them, so such a token never carries an Actions, Checks, issue, membership, - * pull request or workflow permission. + * Neither installation opt-in reaches them, so such a token never carries an Actions, issue, + * membership, pull request or workflow permission. Its one Workspace opt-in, `checks_read: true` + * (since 0.17.0), adds `checks: read` to the read set only (see tokenPermissions). */ const CONTENTS_WRITE_TOKEN_PERMISSIONS = Object.freeze({ contents: "write" }); const CONTENTS_READ_TOKEN_PERMISSIONS = Object.freeze({ contents: "read" }); +const CONTENTS_CHECKS_READ_TOKEN_PERMISSIONS = Object.freeze({ checks: "read", contents: "read" }); const PERMISSION_LEVELS = Object.freeze({ read: 1, write: 2 }); @@ -106,18 +108,24 @@ const PERMISSION_LEVELS = Object.freeze({ read: 1, write: 2 }); * * A Workspace with `permission_ceiling: "contents"` keeps the tier the Team gate selects for its * grant (see grantAccess) and asks for repository contents only, at that level: `contents: write` - * for the write tier and `contents: read` for the read tier. Neither opt-in reaches it, whatever - * the installation accepted. + * for the write tier and `contents: read` for the read tier. Neither installation opt-in reaches + * it, whatever the installation accepted. With `checks_read: true` (since 0.17.0) its read tier + * asks for `contents: read` and `checks: read`, so an application host can verify a commit's check + * runs before it deploys it. The write tier never gains it, and neither does the read tier on the + * policy's host key repository (`repositoryId`), where the Team gate lowers every grant of such a + * Workspace to the read tier, so a push grant there gains nothing either. */ -export function tokenPermissions(policy, access, workspace) { +export function tokenPermissions(policy, access, workspace, repositoryId) { if (!policy.workspaces.includes(workspace)) fail("token permissions need a Workspace of the policy"); const accepted = policy.installation_permissions; const issues = accepted.issues === "write" ? { issues: "write" } : {}; let permissions; if (workspace.permission_ceiling === CONTENTS_CEILING) { if (access === WRITE_ACCESS) permissions = { ...CONTENTS_WRITE_TOKEN_PERMISSIONS }; - else if (access === READ_ACCESS) permissions = { ...CONTENTS_READ_TOKEN_PERMISSIONS }; - else fail("token access tier must be read or write"); + else if (access === READ_ACCESS) { + const checks = workspace.checks_read === true && !isHostKeyRepository(policy, repositoryId); + permissions = { ...(checks ? CONTENTS_CHECKS_READ_TOKEN_PERMISSIONS : CONTENTS_READ_TOKEN_PERMISSIONS) }; + } else fail("token access tier must be read or write"); } else if (access === WRITE_ACCESS) { if (workspace.permission_ceiling === READ_CEILING) { fail(`Workspace ${workspace.id} permission ceiling is read; it never mints the write tier`); @@ -683,12 +691,19 @@ export function parsePolicy(raw) { if (ceiling !== undefined && !PERMISSION_CEILINGS.includes(ceiling)) { fail(`workspaces[${index}].permission_ceiling must be "${READ_CEILING}" or "${CONTENTS_CEILING}" when present`); } + // Optional and absent by default (since 0.17.0): only a contents-ceiling Workspace takes it, and + // only as `true`, so a misspelled or misplaced opt-in fails closed instead of widening anything. + const checksRead = workspace?.checks_read; + if (checksRead !== undefined && (checksRead !== true || ceiling !== CONTENTS_CEILING)) { + fail(`workspaces[${index}].checks_read must be true and needs permission_ceiling "${CONTENTS_CEILING}" when present`); + } return Object.freeze({ id, github_team_id: teamId, ...(teamSlug === undefined ? {} : { github_team_slug: teamSlug }), credential_file: credentialFile, ...(ceiling === undefined ? {} : { permission_ceiling: ceiling }), + ...(checksRead === undefined ? {} : { checks_read: true }), }); }); if (new Set(workspaces.map(({ id }) => id)).size !== workspaces.length) { @@ -1174,7 +1189,7 @@ export function createGithubClient({ appId, signJwt, fetchImpl = fetch, now = () } async function mintToken(policy, workspace, repositoryId, access) { - const requested = tokenPermissions(policy, access, workspace); + const requested = tokenPermissions(policy, access, workspace, repositoryId); // The Team gate already selects the read tier there for a contents-ceiling Workspace; a gate // that lost that rule fails closed here instead of minting such a write (see grantAccess). if ( diff --git a/test/broker.test.mjs b/test/broker.test.mjs index 893b7ba..5f1b12e 100644 --- a/test/broker.test.mjs +++ b/test/broker.test.mjs @@ -2436,3 +2436,166 @@ test("a contents-ceiling Workspace mints only the read tier on the host key repo }).readWorkspaceTeamGrants(onKeys, onKeys.workspaces[0]); assert.deepEqual(rows.map(({ repository_id, role, access }) => [repository_id, role, access]), [[3001, "write", "read"], [3004, "write", "write"]]); }); + +/** contentsPolicyFixture whose contents-ceiling Workspace also declares `checks_read: true` (0.17.0). */ +function checksReadPolicyFixture(options = {}) { + const fixture = contentsPolicyFixture(options); + fixture.workspaces[options.contentsWorkspace ?? 0].checks_read = true; + return fixture; +} + +const CONTENTS_CHECKS_READ_SET = { checks: "read", contents: "read" }; + +test("policy accepts checks_read only as true on a contents-ceiling Workspace", () => { + const parsed = parsePolicy(checksReadPolicyFixture()); + assert.equal(parsed.workspaces[0].checks_read, true); + assert.equal(Object.hasOwn(parsed.workspaces[1], "checks_read"), false); + assert.equal(Object.hasOwn(parsePolicy(contentsPolicyFixture()).workspaces[0], "checks_read"), false); + // Any other value, or the opt-in on a Workspace without the contents ceiling, fails closed. + for (const value of [false, "true", 1, null, ["checks"], { checks: "read" }]) { + const fixture = checksReadPolicyFixture(); + fixture.workspaces[0].checks_read = value; + assert.throws( + () => parsePolicy(fixture), + /workspaces\[0\]\.checks_read must be true and needs permission_ceiling "contents" when present/, + JSON.stringify(value), + ); + } + for (const ceiling of [undefined, "read"]) { + const fixture = policyFixture(); + if (ceiling !== undefined) fixture.workspaces[0].permission_ceiling = ceiling; + fixture.workspaces[0].checks_read = true; + assert.throws( + () => parsePolicy(fixture), + /workspaces\[0\]\.checks_read must be true and needs permission_ceiling "contents" when present/, + String(ceiling), + ); + } +}); + +test("checks_read adds checks: read to the contents read tier only, never to the write tier or the host key repository", () => { + const policy = parsePolicy(checksReadPolicyFixture()); + const [alpha, beta] = policy.workspaces; + assert.deepEqual(tokenPermissions(policy, "read", alpha), CONTENTS_CHECKS_READ_SET); + assert.deepEqual(tokenPermissions(policy, "read", alpha, 3001), CONTENTS_CHECKS_READ_SET); + assert.deepEqual(tokenPermissions(policy, "write", alpha), CONTENTS_WRITE_SET); + assert.deepEqual(tokenPermissions(policy, "write", alpha, 3001), CONTENTS_WRITE_SET); + // The other Workspace of the policy is unchanged. + assert.deepEqual(tokenPermissions(policy, "write", beta), { ...WRITE_SET, issues: "write", workflows: "write" }); + assert.deepEqual(tokenPermissions(policy, "read", beta), { ...READ_SET, issues: "write" }); + // Without the opt-in the contents read tier is exactly as before. + const plain = parsePolicy(contentsPolicyFixture()); + assert.deepEqual(tokenPermissions(plain, "read", plain.workspaces[0]), CONTENTS_READ_SET); + // On the host key repository, where the Team gate lowers every grant to the read tier, nothing is added. + const onKeys = parsePolicy({ ...contentsHostsPolicyFixture(), workspaces: checksReadPolicyFixture().workspaces }); + assert.deepEqual(tokenPermissions(onKeys, "read", onKeys.workspaces[0], 3001), CONTENTS_READ_SET); + assert.deepEqual(tokenPermissions(onKeys, "read", onKeys.workspaces[0], 3002), CONTENTS_CHECKS_READ_SET); +}); + +test("checks_read refuses a policy whose installation has not accepted checks: read", () => { + // The installation permissions must include checks: read anyway; the opt-in never asks beyond them. + const fixture = checksReadPolicyFixture(); + delete fixture.installation_permissions.checks; + assert.throws(() => parsePolicy(fixture), /installation_permissions must be exact/); +}); + +test("end to end: a checks_read Workspace mints contents and checks read for a pull grant and contents write only for a push grant; others mint nothing", async () => { + const grantOn = (permissions) => teamGrantFetch({ + grant: { id: 3001, full_name: "example-org/alpha", owner: { id: 1001, login: "example-org" }, permissions }, + }); + for (const [permissions, access, set] of [ + [{ admin: false, maintain: false, pull: true, push: false, triage: false }, "read", CONTENTS_CHECKS_READ_SET], + [{ admin: false, maintain: false, pull: true, push: false, triage: true }, "read", CONTENTS_CHECKS_READ_SET], + [{ admin: false, maintain: false, pull: true, push: true, triage: true }, "write", CONTENTS_WRITE_SET], + ]) { + const scopedMints = []; + await withLiveCoreServer(mintingFetch([], grantOn(permissions), scopedMints), async (origin) => { + const response = await request(origin, { body: { repository: "example-org/alpha" } }); + assert.equal(response.status, 200, access); + assert.equal((await response.json()).access, access); + assert.deepEqual(scopedMints, [set]); + const crossWorkspace = await request(origin, { workspace: "beta-team", secret: secretByPath.get("/run/secrets/workspace-beta") }); + assert.equal(crossWorkspace.status, 403); + assert.deepEqual(await crossWorkspace.json(), { error: "team_grant_missing" }); + const crossRepository = await request(origin, { body: { repository: "example-org/beta" } }); + assert.equal(crossRepository.status, 403); + assert.deepEqual(await crossRepository.json(), { error: "team_grant_missing" }); + const foreign = await request(origin, { body: { repository: "other-org/alpha" } }); + assert.equal(foreign.status, 403); + assert.deepEqual(await foreign.json(), { error: "repository_denied" }); + assert.equal(scopedMints.length, 1); + }, parsePolicy(checksReadPolicyFixture())); + } + + // A push grant on the host key repository is lowered to the read tier and gains no checks. + const keyMints = []; + const onKeys = parsePolicy({ ...contentsHostsPolicyFixture(), workspaces: checksReadPolicyFixture().workspaces }); + await withLiveCoreServer(mintingFetch([], teamGrantFetch(), keyMints), async (origin) => { + const response = await request(origin); + assert.equal(response.status, 200); + assert.equal((await response.json()).access, "read"); + assert.deepEqual(keyMints, [CONTENTS_READ_SET]); + }, onKeys); +}); + +test("a checks_read mint refuses and revokes an answer with any other permission", async () => { + const now = 1_700_000_000_000; + const requests = []; + const revocations = []; + let responsePermissions; + const github = createGithubClient({ + appId: "42", + privateKey: testPrivateKey(), + fetchImpl: async (url, init) => { + if (new URL(url).pathname === "/installation/token" && init.method === "DELETE") { + revocations.push(init.headers.Authorization); + return jsonResponse(null, 204); + } + requests.push(JSON.parse(init.body)); + return jsonResponse({ + token: `ghs_checks_synthetic_${requests.length}`, + expires_at: new Date(now + 60 * 60 * 1000).toISOString(), + repositories: [{ id: 3001 }], + permissions: responsePermissions, + }); + }, + now: () => now, + }); + const policy = parsePolicy(checksReadPolicyFixture()); + responsePermissions = { ...CONTENTS_CHECKS_READ_SET, metadata: "read" }; + assert.equal((await github.mintToken(policy, policy.workspaces[0], 3001, "read")).access, "read"); + assert.deepEqual(requests.at(-1), { repository_ids: [3001], permissions: CONTENTS_CHECKS_READ_SET }); + for (const permissions of [ + { contents: "read", metadata: "read" }, + { checks: "write", contents: "read", metadata: "read" }, + { checks: "read", contents: "write", metadata: "read" }, + { checks: "read", contents: "read", metadata: "read", actions: "read" }, + { checks: "read", contents: "read", metadata: "read", pull_requests: "read" }, + ]) { + responsePermissions = permissions; + await assert.rejects( + () => github.mintToken(policy, policy.workspaces[0], 3001, "read"), + /outside the requested repository or permission scope/, + JSON.stringify(permissions), + ); + assert.equal(revocations.at(-1), `Bearer ghs_checks_synthetic_${requests.length}`); + } + assert.equal(revocations.length, 5); +}); + +test("policy check prints the checks_read set on its own line and marks the Workspace in the CEILING column", () => { + assert.equal( + formatPolicySummary(parsePolicy(checksReadPolicyFixture())), + [ + "lazurio.github_app_broker.policy.v3 owner=example-org installation=2001", + "write tier (push/maintain/admin grant) asks for: actions=write checks=read contents=write issues=write members=read pull_requests=write workflows=write", + "read tier (pull/triage grant) asks for: actions=read checks=read contents=read issues=write members=read pull_requests=read", + "contents ceiling (push/maintain/admin grant of a CEILING contents Workspace) asks for: contents=write", + "contents ceiling with checks_read (pull/triage grant, not on the conglomerate_hosts repository) asks for: checks=read contents=read", + "WORKSPACE TEAM_ID TEAM_SLUG CEILING", + "alpha-team 4001 alpha-team contents+checks_read", + "beta-team 4002 - -", + "", + ].join("\n"), + ); +}); diff --git a/test/worker.test.mjs b/test/worker.test.mjs index 94e47a3..339e299 100644 --- a/test/worker.test.mjs +++ b/test/worker.test.mjs @@ -602,3 +602,90 @@ test("Worker with the real core: a contents-ceiling Workspace mints contents onl assert.equal(invalid.status, 503); assert.deepEqual(await invalid.json(), { error: "configuration_unavailable" }); }); + +test("Worker with the real core: a checks_read Workspace adds checks: read to its pull grants only; the other Workspace keeps its tiers", async () => { + const fixture = policyFixture(); + fixture.installation_permissions = { + ...fixture.installation_permissions, + administration: "read", + issues: "write", + organization_plan: "read", + workflows: "write", + }; + fixture.workspaces[0].permission_ceiling = "contents"; + fixture.workspaces[0].checks_read = true; + // alpha's Team holds push on alpha and pull on handbook; beta's Team holds push on alpha. + const grants = { + "4001/alpha": { id: 3001, full_name: "example-org/alpha", permissions: { pull: true, push: true } }, + "4001/handbook": { id: 3004, full_name: "example-org/handbook", permissions: { pull: true } }, + "4002/alpha": { id: 3001, full_name: "example-org/alpha", permissions: { pull: true, push: true } }, + }; + const scopedMints = []; + const github = async (url, init) => { + const path = new URL(url).pathname; + const body = init.body ? JSON.parse(init.body) : undefined; + if (path === "/app/installations/2001" && init.method === "GET") { + return Response.json({ + app_id: 42, + app_slug: "example-app", + account: { id: 1001, login: "example-org" }, + target_type: "Organization", + repository_selection: "selected", + permissions: fixture.installation_permissions, + }); + } + if (path === "/app/installations/2001/access_tokens" && !body.repository_ids) return Response.json({ token: "ghs_probe" }); + if (path === "/app/installations/2001/access_tokens") { + scopedMints.push(body.permissions); + return Response.json({ + token: "ghs_scoped_synthetic", + expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(), + repositories: [{ id: body.repository_ids[0] }], + permissions: { ...body.permissions, metadata: "read" }, + }); + } + const team = path.match(/^\/organizations\/1001\/team\/(4001|4002)$/); + if (team) return Response.json({ id: Number(team[1]), slug: `team-${team[1]}`, organization: { id: 1001, login: "example-org" } }); + const grant = path.match(/^\/organizations\/1001\/team\/(400[12])\/repos\/example-org\/([a-z]+)$/); + if (grant) { + const entry = grants[`${grant[1]}/${grant[2]}`]; + return entry + ? Response.json({ ...entry, owner: { id: 1001, login: "example-org" } }) + : Response.json({ message: "Not Found" }, { status: 404 }); + } + if (path === "/installation/token" && init.method === "DELETE") return new Response(null, { status: 204 }); + throw new Error(`unexpected request ${init.method} ${path}`); + }; + const worker = createWorkerEntrypoint({ + createGithub: ({ appId }) => createGithubClient({ appId, signJwt: async () => "c2lnbmF0dXJl", fetchImpl: github }), + }); + const env = environment({ BROKER_POLICY_JSON: JSON.stringify(fixture) }); + + const pushGrant = await worker.fetch(tokenRequest(), env); + assert.equal(pushGrant.status, 200); + assert.equal((await pushGrant.json()).access, "write"); + const readGrant = await worker.fetch(tokenRequest({ body: { repository: "example-org/handbook" } }), env); + assert.equal(readGrant.status, 200); + assert.equal((await readGrant.json()).access, "read"); + const uncapped = await worker.fetch(tokenRequest({ workspace: "beta-team", credential: BETA_CREDENTIAL }), env); + assert.equal(uncapped.status, 200); + assert.equal((await uncapped.json()).access, "write"); + assert.deepEqual(scopedMints, [ + { contents: "write" }, + { checks: "read", contents: "read" }, + { actions: "write", checks: "read", contents: "write", issues: "write", members: "read", pull_requests: "write", workflows: "write" }, + ]); + + // Cross-repository: no grant of alpha's Team, no mint. + const noGrant = await worker.fetch(tokenRequest({ body: { repository: "example-org/gamma" } }), env); + assert.equal(noGrant.status, 403); + assert.deepEqual(await noGrant.json(), { error: "team_grant_missing" }); + assert.equal(scopedMints.length, 3); + + // checks_read on a Workspace without the contents ceiling is a configuration error, never an ignored key. + fixture.workspaces[0].checks_read = true; + delete fixture.workspaces[0].permission_ceiling; + const invalid = await worker.fetch(tokenRequest(), environment({ BROKER_POLICY_JSON: JSON.stringify(fixture) })); + assert.equal(invalid.status, 503); + assert.deepEqual(await invalid.json(), { error: "configuration_unavailable" }); +});