From 08f3e6a0e93d100309776c19cddca71a81bf9645 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Wed, 18 Nov 2026 18:12:20 +0800 Subject: [PATCH] feat(publish): trusted publishing from GitHub Actions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `flb publish` can publish without a stored secret: in a job with `id-token: write` it requests the GitHub OIDC token (audience: the registry's host name, FLB_OIDC_AUDIENCE overrides), exchanges it with POST /v1/auth/oidc/github for a short-lived flbt_ token scoped to the extension (named by its npm package, else composer), and uses that token for the listing lookup, upload and checks. - Token order for publish: FLB_TOKEN, then the exchange when ACTIONS_ID_TOKEN_REQUEST_URL/TOKEN are set (or --oidc), then the stored login; --no-oidc skips it. Other commands are unchanged. - The exchange runs after the build and again when the token is within two minutes of expiry (RegistryClient gains a tokenProvider), so long check runs outlive the ~15 minute token. - Actionable errors: missing OIDC variables or a refused GitHub request point at `permissions: id-token: write`; 401 names the audience; 403 names the repository, workflow file and ref to configure in Studio → Access. A GitHub Actions job with no token at all gets the same hint. - Trusted publishing never creates a listing or adds a package to one. - flbt_ tokens are service tokens (not legacy) and are redacted in output, as are JWTs. Neither token is printed or written to disk. action/: a composite action (fleetbase/fleetbase-cli/action@v2) that sets up Node, installs @fleetbase/cli (or builds it from the action's checkout with cli-version: source), runs `flb publish --json` and exposes release-id, version, status, channel and extension, with a job summary. action/examples/publish-on-tag.yml publishes on tag push. README documents the setup. --- README.md | 47 +++++- RELEASE.md | 1 + action/README.md | 105 ++++++++++++ action/action.yml | 179 ++++++++++++++++++++ action/examples/publish-on-tag.yml | 43 +++++ src/commands/publish.ts | 87 ++++++++-- src/config.ts | 11 +- src/context.ts | 7 +- src/http.ts | 8 +- src/oidc.ts | 200 +++++++++++++++++++++++ src/output.ts | 10 +- test/unit/oidc.test.ts | 251 +++++++++++++++++++++++++++++ vitest.config.ts | 3 +- 13 files changed, 929 insertions(+), 23 deletions(-) create mode 100644 action/README.md create mode 100644 action/action.yml create mode 100644 action/examples/publish-on-tag.yml create mode 100644 src/oidc.ts create mode 100644 test/unit/oidc.test.ts diff --git a/README.md b/README.md index 621b335..c15fd3b 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ price and permissions are published as soon as their checks pass. | `flb init [dir]` | Scaffolds from [fleetbase/starter-extension](https://github.com/fleetbase/starter-extension): package names under your organization, PHP namespace, engine route, and an `extension.json` with `compat` ranges | | `flb build [--prebuilt --console ]` | Engine tarball (`npm pack`), api archive (Composer layout), optional prebuilt engine dist, and `.fleetbase/release.json` | | `flb bump ` | One version in extension.json, package.json and composer.json | -| `flb publish [--channel beta] [--submit]` | Creates the draft listing if needed, uploads the release, streams the check results | +| `flb publish [--channel beta] [--submit]` | Creates the draft listing if needed, uploads the release, streams the check results. In GitHub Actions it can use trusted publishing (`--oidc`, see below) | | `flb release list\|status\|submit\|withdraw\|yank` | Release lifecycle, by `rel_` id or by version inside the extension | | `flb listing list\|show\|update\|categories` | The catalog listing: subtitle, description, category, tags, URLs, icon (`--file listing.json` for several at once); shows what is still needed before a first release can be submitted | | `flb search [query]` / `flb info ` | The public catalog | @@ -86,7 +86,50 @@ Service token: commands that need one ask you to `flb login` again. - No command prints a token unless you pass `--show-token`. - Tokens are never written anywhere but this file: no `.npmrc`, no `auth.json`, no `.fleetbase/` files in your extension. -- In CI, set `FLB_TOKEN` instead of logging in; it is never written to disk. +- In CI, set `FLB_TOKEN` instead of logging in; it is never written to disk. From GitHub + Actions, `flb publish` can use trusted publishing instead (next section). + +## Publishing from GitHub Actions + +With trusted publishing a workflow publishes releases without any stored secret: `flb +publish` requests the job's GitHub OIDC token and exchanges it (`POST /v1/auth/oidc/github`) +for a short-lived `flbt_` token that can publish releases of that one extension, when the +token's claims match a trusted publisher configured on the listing. + +1. Publish the first release from your machine (`flb login`, `flb publish`) or create the + listing in Studio: trusted publishing does not create listings or add packages to them. +2. In Studio → Access, add a trusted publisher to the listing: the repository (`owner/repo`), + the workflow file name (`release.yml`), optionally an environment (`release`), and the + refs it may publish from (`refs/tags/v*`). +3. Add the workflow, with `permissions: id-token: write`: + +```yaml +on: + push: + tags: ['v*'] +permissions: + contents: read + id-token: write +jobs: + publish: + runs-on: ubuntu-latest + environment: release + steps: + - uses: actions/checkout@v4 + - uses: fleetbase/fleetbase-cli/action@v2 +``` + +The action ([action/README.md](action/README.md), example in +[action/examples/publish-on-tag.yml](action/examples/publish-on-tag.yml)) installs the CLI, +runs `flb publish --json --submit` and exposes the release id, version and status as outputs. + +Without the action, run `flb publish` in a job with `id-token: write`. It picks its token in +this order: `FLB_TOKEN`; a trusted publishing exchange when the job can request an OIDC token +(`ACTIONS_ID_TOKEN_REQUEST_URL` is set), or with `--oidc`; the stored login. `--no-oidc` skips +the exchange. The OIDC token's audience is the registry's host name (`registry.fleetbase.io`); +`FLB_OIDC_AUDIENCE` overrides it. Only `flb publish` does the exchange. Neither token is +printed or written to disk, and the exchanged token is renewed if it is about to expire while +the checks run. ## Building diff --git a/RELEASE.md b/RELEASE.md index 0ef174f..eea2057 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -7,6 +7,7 @@ - `flb init` scaffolds from fleetbase/starter-extension with your organization's package names, PHP namespace and an `extension.json` with `compat` ranges. - `flb build` writes the engine tarball, the Composer api archive and, with `--prebuilt --console `, the prebuilt engine dist from ember-core's `build-engine-release`; `flb bump` keeps the three manifests on one version. - `flb publish [--channel beta] [--submit]` creates the listing, uploads the release and streams the registry checks; `flb release status|submit|withdraw|yank|list` follow it through review. +- Trusted publishing from GitHub Actions: `flb publish` exchanges the job's OIDC token for a short-lived, publish-only token when a trusted publisher is configured on the listing. The composite action `fleetbase/fleetbase-cli/action@v2` installs the CLI, publishes and exposes the release id, version and status. - `flb search`, `flb info`: the public catalog. - `flb listing list|show|update|categories`: complete the catalog listing from the terminal. - `flb instance code|register|status|updates`: instance registration from a server shell; `register --path|--docker` hands the code to the instance (`registry:register`) so its token never leaves it. diff --git a/action/README.md b/action/README.md new file mode 100644 index 0000000..3d14ab4 --- /dev/null +++ b/action/README.md @@ -0,0 +1,105 @@ +# Publish a Fleetbase extension (GitHub Action) + +`fleetbase/fleetbase-cli/action` builds an extension and publishes it to the Fleetbase +Extensions Registry with `flb publish`. With **trusted publishing** it needs no secret: the job +asks GitHub for an OIDC token, and the registry trades it for a short-lived token that can +publish releases of that one extension, provided the token's repository, workflow, ref and +environment match a trusted publisher configured on the listing. + +```yaml +on: + push: + tags: ['v*'] + +permissions: + contents: read + id-token: write + +jobs: + publish: + runs-on: ubuntu-latest + environment: release # optional, if the trusted publisher requires it + steps: + - uses: actions/checkout@v4 + - uses: fleetbase/fleetbase-cli/action@v2 +``` + +A complete workflow is in [examples/publish-on-tag.yml](examples/publish-on-tag.yml). + +## Setting up trusted publishing + +1. The listing must exist. Trusted publishing tokens can publish releases but cannot create + listings or change their packages, so publish the first release from your machine + (`flb login`, then `flb publish`), or create the listing in Studio. +2. In Studio → Access, add a trusted publisher to the listing: + - **Repository**: `owner/repo` + - **Workflow**: the workflow file name, e.g. `release.yml` + - **Environment** (optional): e.g. `release`. The job must then declare `environment: release`. + - **Allowed refs**: e.g. `refs/tags/v*` +3. Add the workflow with `permissions: id-token: write`. + +The CLI looks up the listing by the extension's npm package name (the composer name when the +extension has no engine). The OIDC token is requested for the audience the registry expects +by default, its host name (`registry.fleetbase.io`); set `oidc-audience` only if the registry +was configured with another one. + +Neither the OIDC token nor the exchanged token is printed or written to disk. The exchanged +token lasts about 15 minutes; `flb` exchanges again when it is about to expire during a long +check run. + +## With a token instead + +Pass a personal token with the `publish` scope (`flb token create --name ci --scopes publish`) +as `token`. It takes precedence over trusted publishing, and is the only way to publish a +listing's first release from CI. A job-level `FLB_TOKEN` environment variable does the same. + +```yaml + - uses: fleetbase/fleetbase-cli/action@v2 + with: + token: ${{ secrets.FLEETBASE_TOKEN }} +``` + +## Inputs + +| Input | Default | Description | +| --- | --- | --- | +| `path` | `.` | Extension directory (with `extension.json`) | +| `registry` | `https://registry.fleetbase.io` | Registry Service URL | +| `channel` | extension.json, else `stable` | `stable` or `beta` | +| `submit` | `true` | Submit for review as soon as the checks pass | +| `wait` | `true` | Follow the checks until the release settles; `false` returns after the upload | +| `timeout` | `15m` | How long to follow the checks | +| `notes` | | Release notes | +| `notes-file` | | File with the release notes | +| `token` | | Personal token instead of trusted publishing | +| `oidc-audience` | registry host name | Audience of the GitHub OIDC token (`FLB_OIDC_AUDIENCE`) | +| `install-command` | | Run in `path` before publishing, e.g. `pnpm install --frozen-lockfile` | +| `args` | | Extra `flb publish` arguments, split on whitespace, e.g. `--ignore-scripts` | +| `cli-version` | `^2.0.0-0` | `@fleetbase/cli` version, range or dist-tag from npm; `source` builds the CLI from this action's checkout | +| `node-version` | `22` | Node.js for `actions/setup-node`; empty to use the runner's Node (20.10 or later) | + +## Outputs + +| Output | Description | +| --- | --- | +| `release-id` | The release id (`rel_…`) | +| `version` | The released version | +| `status` | The release status when the step finished: `published`, `submitted`, `in_review`, `uploaded`, `failed_checks`, … | +| `channel` | The release channel | +| `extension` | The listing slug | + +The step also writes the release and its check results to the job summary. It fails when +the checks fail, when a requested submit was refused (the listing is not ready), or when +anything before the upload fails; the outputs are set whenever the upload happened. + +## What the build needs + +`flb publish` builds the release first (see `flb build`): the engine with `npm pack` and the +api archive from the files `composer.json` autoloads. Neither needs the extension's +dependencies installed, unless `package.json` has `prepare`/`prepack` scripts that do; then +set `install-command` (and set up pnpm or yarn first if you use them), or pass +`args: --ignore-scripts`. Composer and PHP are not needed. Prebuilt engine dists +(`--prebuilt --console `) need a console checkout in the job and are not set up by the +action. + +The action runs on Linux and macOS runners. diff --git a/action/action.yml b/action/action.yml new file mode 100644 index 0000000..f45c113 --- /dev/null +++ b/action/action.yml @@ -0,0 +1,179 @@ +name: Publish a Fleetbase extension +description: Build and publish a Fleetbase extension to the Fleetbase Extensions Registry with `flb publish`, using trusted publishing (GitHub OIDC) or a token. +author: Fleetbase +branding: + icon: upload-cloud + color: blue + +inputs: + path: + description: Extension directory (the one with extension.json), relative to the workspace. + required: false + default: '.' + registry: + description: Registry Service URL. + required: false + default: 'https://registry.fleetbase.io' + channel: + description: Release channel, stable or beta. Default is the channel in extension.json, else stable. + required: false + default: '' + submit: + description: Submit the release for review as soon as its checks pass. + required: false + default: 'true' + wait: + description: Follow the registry checks (and the submit) until the release settles. With false the step returns after the upload. + required: false + default: 'true' + timeout: + description: How long to follow the checks (90s, 15m, 1h). + required: false + default: '15m' + notes: + description: Release notes. + required: false + default: '' + notes-file: + description: File with the release notes, relative to the workspace. + required: false + default: '' + token: + description: 'A personal token (flbp_, publish scope) to use instead of trusted publishing. Leave empty to exchange the job''s GitHub OIDC token, which needs `permissions: id-token: write`.' + required: false + default: '' + oidc-audience: + description: Audience for the GitHub OIDC token. Default is the registry's host name, which is what the registry expects unless it was configured otherwise. + required: false + default: '' + install-command: + description: Command run in `path` before publishing, e.g. `pnpm install --frozen-lockfile`. Needed only when `npm pack` runs prepare/prepack scripts that need the extension's dependencies. + required: false + default: '' + args: + description: Extra arguments for `flb publish`, e.g. `--ignore-scripts` or `--rebuild`. + required: false + default: '' + cli-version: + description: Version (or range or dist-tag) of @fleetbase/cli to install from npm, or `source` to build the CLI from this action's own checkout. + required: false + default: '^2.0.0-0' + node-version: + description: Node.js version for actions/setup-node. Set to an empty string to use the Node already on the runner (20.10 or later). + required: false + default: '22' + +outputs: + release-id: + description: The release id (rel_…). + value: ${{ steps.publish.outputs.release-id }} + version: + description: The released version. + value: ${{ steps.publish.outputs.version }} + status: + description: The release status when the step finished (uploaded, checking, failed_checks, submitted, in_review, published, …). + value: ${{ steps.publish.outputs.status }} + channel: + description: The release channel. + value: ${{ steps.publish.outputs.channel }} + extension: + description: The listing slug. + value: ${{ steps.publish.outputs.extension }} + +runs: + using: composite + steps: + - name: Set up Node.js + if: inputs.node-version != '' + uses: actions/setup-node@v4 + with: + node-version: ${{ inputs.node-version }} + + - name: Install the Fleetbase CLI + id: cli + shell: bash + env: + CLI_VERSION: ${{ inputs.cli-version }} + ACTION_PATH: ${{ github.action_path }} + run: | + set -euo pipefail + if [ "$CLI_VERSION" = "source" ]; then + cli_root="$(cd "$ACTION_PATH/.." && pwd)" + (cd "$cli_root" && npm ci --no-audit --no-fund && npm run build) + bin="$cli_root/dist/bin/flb.js" + else + npm install --global --no-audit --no-fund "@fleetbase/cli@${CLI_VERSION:-latest}" + bin="$(npm root --global)/@fleetbase/cli/dist/bin/flb.js" + fi + echo "flb $(node "$bin" --version)" + echo "bin=$bin" >> "$GITHUB_OUTPUT" + + - name: Install the extension's dependencies + if: inputs.install-command != '' + shell: bash + working-directory: ${{ inputs.path }} + env: + INSTALL_COMMAND: ${{ inputs.install-command }} + run: bash -euo pipefail -c "$INSTALL_COMMAND" + + - name: Publish + id: publish + shell: bash + env: + FLB_BIN: ${{ steps.cli.outputs.bin }} + INPUT_PATH: ${{ inputs.path }} + INPUT_REGISTRY: ${{ inputs.registry }} + INPUT_CHANNEL: ${{ inputs.channel }} + INPUT_SUBMIT: ${{ inputs.submit }} + INPUT_WAIT: ${{ inputs.wait }} + INPUT_TIMEOUT: ${{ inputs.timeout }} + INPUT_NOTES: ${{ inputs.notes }} + INPUT_NOTES_FILE: ${{ inputs.notes-file }} + INPUT_ARGS: ${{ inputs.args }} + INPUT_TOKEN: ${{ inputs.token }} + INPUT_OIDC_AUDIENCE: ${{ inputs.oidc-audience }} + run: | + set -euo pipefail + # a token input overrides FLB_TOKEN; without one, FLB_TOKEN from the job (if any) is kept + if [ -n "$INPUT_TOKEN" ]; then + echo "::add-mask::$INPUT_TOKEN" + export FLB_TOKEN="$INPUT_TOKEN" + fi + if [ -n "$INPUT_OIDC_AUDIENCE" ]; then + export FLB_OIDC_AUDIENCE="$INPUT_OIDC_AUDIENCE" + fi + unset INPUT_TOKEN + + args=(publish "$INPUT_PATH" --json --timeout "$INPUT_TIMEOUT") + [ -n "$INPUT_REGISTRY" ] && args+=(--registry "$INPUT_REGISTRY") + [ -n "$INPUT_CHANNEL" ] && args+=(--channel "$INPUT_CHANNEL") + [ "$INPUT_SUBMIT" = "true" ] && args+=(--submit) + [ "$INPUT_WAIT" = "false" ] && args+=(--no-wait) + [ -n "$INPUT_NOTES" ] && args+=(--notes "$INPUT_NOTES") + [ -n "$INPUT_NOTES_FILE" ] && args+=(--notes-file "$INPUT_NOTES_FILE") + if [ -n "$INPUT_ARGS" ]; then + read -r -a extra <<< "$INPUT_ARGS" + args+=("${extra[@]}") + fi + + result="$RUNNER_TEMP/flb-publish-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT.json" + set +e + node "$FLB_BIN" "${args[@]}" > "$result" + code=$? + set -e + + # the release JSON is on stdout whenever the upload happened, even when checks failed + node -e ' + const fs = require("fs"); + let release; + try { release = JSON.parse(fs.readFileSync(process.argv[1], "utf8")); } catch { process.exit(0); } + if (!release || !release.id) process.exit(0); + const outputs = { "release-id": release.id, version: release.version, status: release.status, channel: release.channel, extension: release.extension && release.extension.slug }; + fs.appendFileSync(process.env.GITHUB_OUTPUT, Object.entries(outputs).map(([k, v]) => `${k}=${v ?? ""}\n`).join("")); + const checks = (release.checks || []).map((c) => `| ${c.skipped ? "–" : c.passed ? "✓" : "✗"} | ${c.check} | ${(c.summary || "").replace(/\|/g, "\\|")} |`); + const summary = [`### ${outputs.extension}@${release.version}: ${String(release.status).replace(/_/g, " ")}`, "", `Release \`${release.id}\` on the ${release.channel} channel.`]; + if (checks.length) summary.push("", "| | Check | Summary |", "| --- | --- | --- |", ...checks); + if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary.join("\n") + "\n"); + ' "$result" + rm -f "$result" + exit "$code" diff --git a/action/examples/publish-on-tag.yml b/action/examples/publish-on-tag.yml new file mode 100644 index 0000000..8b092f1 --- /dev/null +++ b/action/examples/publish-on-tag.yml @@ -0,0 +1,43 @@ +# Publishes the extension to the Fleetbase Extensions Registry when a version tag is pushed. +# +# Copy to .github/workflows/release.yml in the extension's repository. Trusted publishing needs +# no secret: in Studio → Access, add a trusted publisher for this repository with +# repository owner/repo +# workflow release.yml (this file's name) +# environment release (optional; remove `environment:` below if you do not use one) +# refs refs/tags/v* +# The listing must exist first (publish the first release with `flb publish` after `flb login`). +# +# Bump the version in extension.json, package.json and composer.json (`flb bump patch`), commit, +# then `git tag v1.2.3 && git push --tags`. + +name: Publish to the Fleetbase Registry + +on: + push: + tags: ['v*'] + +permissions: + contents: read + id-token: write # lets the job request the GitHub OIDC token flb exchanges + +jobs: + publish: + runs-on: ubuntu-latest + environment: release + steps: + - uses: actions/checkout@v4 + + # Only needed when package.json has prepare/prepack scripts that need dependencies; + # then also set `install-command` below (e.g. `pnpm install --frozen-lockfile`). + # - uses: pnpm/action-setup@v4 + + - name: Publish + id: publish + uses: fleetbase/fleetbase-cli/action@v2 + with: + submit: true + notes: Release ${{ github.ref_name }} + + - name: Result + run: echo "Release ${{ steps.publish.outputs.release-id }} (${{ steps.publish.outputs.version }}) is ${{ steps.publish.outputs.status }}" diff --git a/src/commands/publish.ts b/src/commands/publish.ts index 54b4bb4..96bca99 100644 --- a/src/commands/publish.ts +++ b/src/commands/publish.ts @@ -2,9 +2,10 @@ import fs from 'node:fs'; import path from 'node:path'; import type { Command } from 'commander'; import { readRelease, type ReleaseFile } from '../build.js'; -import { type Context, context } from '../context.js'; -import { ApiError } from '../http.js'; +import { type Context, context, currentFetch } from '../context.js'; +import { ApiError, type RegistryClient } from '../http.js'; import { type LoadedExtension, loadExtension } from '../manifest.js'; +import { assertGithubOidcAvailable, githubOidcEnv, inGithubActions, PERMISSION_HINT, TrustedPublishing } from '../oidc.js'; import { colors, formatBytes, log } from '../output.js'; import { isSettled, listingFor, printCheck, reviewReasons, statusLabel, watchRelease } from '../releases.js'; import type { PublisherExtension, ReleaseDetail } from '../types.js'; @@ -25,7 +26,9 @@ export function register(program: Command): void { .option('--no-build', 'fail instead of building when .fleetbase/release.json is missing or stale') .option('--rebuild', 'build again even when the last build is current') .option('--no-wait', 'return after the upload without following the checks') - .option('--timeout ', 'how long to follow the checks', '15m'), + .option('--timeout ', 'how long to follow the checks', '15m') + .option('--oidc', 'authenticate with a GitHub Actions OIDC token (trusted publishing); the default in a job with id-token: write unless FLB_TOKEN is set') + .option('--no-oidc', 'do not use trusted publishing, even in GitHub Actions'), ) .option('--json', 'print the release as JSON') .action(async (dir: string, opts, command: Command) => { @@ -43,12 +46,54 @@ interface PublishOptions { rebuild?: boolean; wait: boolean; timeout: string; + /** undefined: trusted publishing when GitHub Actions offers an OIDC token and FLB_TOKEN is not set */ + oidc?: boolean; [key: string]: unknown; } +interface PublishAuth { + client: RegistryClient; + /** set in trusted publishing mode: the token is exchanged after the build, refreshed as it nears expiry */ + trusted?: TrustedPublishing; +} + +/** + * The token for a publish: FLB_TOKEN, else a trusted publishing exchange when the job can + * request a GitHub OIDC token (or with --oidc), else the stored login. Only publish does the + * exchange; every other command stays on the stored token or FLB_TOKEN. + */ +export function publishAuth(ctx: Context, ext: LoadedExtension, oidc?: boolean): PublishAuth { + const envToken = process.env.FLB_TOKEN?.trim(); + const github = githubOidcEnv(); + const useOidc = oidc ?? (!envToken && Boolean(github.url || github.token)); + + if (!useOidc) { + try { + return { client: ctx.authed() }; + } catch (error) { + if (error instanceof CliError && inGithubActions() && oidc === undefined && !envToken) { + throw new CliError(error.message, error.exitCode, [ + ...error.hints, + `For trusted publishing instead of a token: ${PERMISSION_HINT.charAt(0).toLowerCase()}${PERMISSION_HINT.slice(1)}`, + ]); + } + throw error; + } + } + + assertGithubOidcAvailable(); + const extension = ext.engine?.name || ext.api?.name; + if (!extension) { + throw new CliError('Trusted publishing needs the extension\'s npm or composer package name.'); + } + const trusted = new TrustedPublishing(ctx.registry, extension, currentFetch()); + return { client: trusted.client(), trusted }; +} + export async function publish(ctx: Context, dir: string, opts: PublishOptions): Promise { - const client = ctx.authed(); const ext = loadExtension(dir); + const auth = publishAuth(ctx, ext, opts.oidc); + const client = auth.client; const channel = opts.channel || ext.manifest.channel || 'stable'; if (!['stable', 'beta'].includes(channel)) { throw new CliError(`Unknown channel "${channel}": use stable or beta.`); @@ -74,10 +119,18 @@ export async function publish(ctx: Context, dir: string, opts: PublishOptions): release = await runBuild(ext, opts, ctx.json); } - // 2. the listing - const listing = await ensureListing(ctx, ext, opts.organization); + // 2. the token, for trusted publishing: exchanged after the build so its lifetime goes to the upload and checks + if (auth.trusted) { + await auth.trusted.token(); + const exchanged = auth.trusted.exchanged!; + const publisher = exchanged.trusted_publisher; + log.step(`Trusted publishing to ${exchanged.extension?.slug || auth.trusted.extension}${publisher?.repository ? ` as ${publisher.repository}${publisher.workflow ? ` (${publisher.workflow})` : ''}` : ''}`); + } + + // 3. the listing + const listing = await ensureListing(ctx, client, ext, opts.organization, Boolean(auth.trusted)); - // 3. the upload + // 4. the upload const form = new FormData(); form.append('manifest', await fs.openAsBlob(ext.manifestPath, { type: 'application/json' }), 'extension.json'); for (const kind of ['engine', 'api', 'dist'] as const) { @@ -107,7 +160,7 @@ export async function publish(ctx: Context, dir: string, opts: PublishOptions): } log.success(`Uploaded ${uploaded.id}`); - // 4. the checks + // 5. the checks let final = uploaded; if (opts.wait) { if (!ctx.json) { @@ -131,15 +184,27 @@ export async function publish(ctx: Context, dir: string, opts: PublishOptions): return final; } -async function ensureListing(ctx: Context, ext: LoadedExtension, organizationFlag?: string): Promise { - const client = ctx.authed(); +async function ensureListing(ctx: Context, client: RegistryClient, ext: LoadedExtension, organizationFlag: string | undefined, trusted: boolean): Promise { const packages = { npm: ext.engine?.name, composer: ext.api?.name }; const existing = await listingFor(client, packages); - const missingKind = existing && ((packages.npm && !existing.packages.some((p) => p.kind === 'npm')) || (packages.composer && !existing.packages.some((p) => p.kind === 'composer'))); + const missingKind = existing ? (['npm', 'composer'] as const).find((kind) => packages[kind] && !existing.packages.some((p) => p.kind === kind)) : undefined; if (existing && !missingKind) { return existing; } + // a trusted publishing token can publish releases of its extension, never create or change listings + if (trusted) { + const names = Object.values(packages).filter(Boolean).join(' or '); + if (!existing) { + throw new CliError(`No listing on ${ctx.host} owns ${names}, and trusted publishing cannot create one.`, 1, [ + 'Create the listing first (`flb publish` with a personal token, or in Studio), then add a trusted publisher for this workflow in Studio → Access.', + ]); + } + throw new CliError(`The listing ${existing.slug} has no ${missingKind} package yet, and trusted publishing cannot add one.`, 1, [ + 'Publish this release once with a personal token (`flb publish` after `flb login`), which adds the package to the listing.', + ]); + } + const organization = ctx.organization(organizationFlag); const body = { name: ext.manifest.name, diff --git a/src/config.ts b/src/config.ts index f1b31b5..4b4096d 100644 --- a/src/config.ts +++ b/src/config.ts @@ -231,6 +231,13 @@ export function resolveRegistry(flag: string | undefined, config: Config): strin export const PERSONAL_TOKEN = /^flbp_[A-Za-z0-9]{20,}$/; export const INSTANCE_TOKEN = /^flbi_[A-Za-z0-9]{20,}$/; +/** short-lived, publish-only token from trusted publishing (`POST /v1/auth/oidc/github`) */ +export const TRUSTED_PUBLISHING_TOKEN = /^flbt_[A-Za-z0-9]{20,}$/; + +/** Tokens the Registry Service accepts from a publisher. */ +export function isServiceToken(token: string): boolean { + return PERSONAL_TOKEN.test(token) || TRUSTED_PUBLISHING_TOKEN.test(token); +} export interface StoredToken { token: string; @@ -243,12 +250,12 @@ export interface StoredToken { export function getToken(config: Config, registry: string): StoredToken | null { const env = process.env.FLB_TOKEN?.trim(); if (env) { - return { token: env, source: 'env', legacy: !PERSONAL_TOKEN.test(env) }; + return { token: env, source: 'env', legacy: !isServiceToken(env) }; } const token = config.tokens?.[hostKey(registry)]; if (typeof token === 'string' && token !== '') { - return { token, source: 'config', legacy: !PERSONAL_TOKEN.test(token) }; + return { token, source: 'config', legacy: !isServiceToken(token) }; } return null; diff --git a/src/context.ts b/src/context.ts index 715fb1e..c50781f 100644 --- a/src/context.ts +++ b/src/context.ts @@ -29,6 +29,11 @@ export function setFetch(impl: FetchLike | undefined): void { fetchOverride = impl; } +/** The fetch requests go through: the test override, else the global one. */ +export function currentFetch(): FetchLike { + return fetchOverride || globalThis.fetch; +} + export function context(command: Command): Context { const opts = command.optsWithGlobals(); const config = readConfig(); @@ -55,7 +60,7 @@ export function requireToken(config: Config, registry: string): string { } if (stored.legacy) { const where = stored.source === 'env' ? 'FLB_TOKEN' : `the token stored for ${host} in ${configDisplayPath()}`; - throw new CliError(`${where} is not a Registry Service token (they start with flbp_).`, 1, [ + throw new CliError(`${where} is not a Registry Service token (they start with flbp_, or flbt_ for trusted publishing).`, 1, [ `It is probably a v1 registry token. Run \`flb login${registryFlag(registry)}\` to replace it.`, ]); } diff --git a/src/http.ts b/src/http.ts index fa5449f..6e254b6 100644 --- a/src/http.ts +++ b/src/http.ts @@ -39,6 +39,8 @@ export interface RequestOptions { export interface ClientOptions { token?: string; + /** resolves the token for each request instead of a fixed `token` (short-lived tokens that refresh) */ + tokenProvider?: () => Promise; fetch?: typeof fetch; timeoutMs?: number; } @@ -46,18 +48,20 @@ export interface ClientOptions { export class RegistryClient { readonly baseUrl: string; private readonly token?: string; + private readonly tokenProvider?: () => Promise; private readonly fetchImpl: typeof fetch; private readonly timeoutMs: number; constructor(baseUrl: string, options: ClientOptions = {}) { this.baseUrl = baseUrl.replace(/\/+$/, ''); this.token = options.token; + this.tokenProvider = options.tokenProvider; this.fetchImpl = options.fetch || globalThis.fetch; this.timeoutMs = options.timeoutMs ?? 60_000; } get hasToken(): boolean { - return Boolean(this.token); + return Boolean(this.token || this.tokenProvider); } withToken(token: string | undefined): RegistryClient { @@ -79,7 +83,7 @@ export class RegistryClient { Accept: 'application/json', 'User-Agent': `flb/${VERSION} node/${process.versions.node}`, }; - const token = options.token ?? (options.auth === false ? undefined : this.token); + const token = options.token ?? (options.auth === false ? undefined : this.tokenProvider ? await this.tokenProvider() : this.token); if (token) { headers.Authorization = `Bearer ${token}`; } diff --git a/src/oidc.ts b/src/oidc.ts new file mode 100644 index 0000000..5b11e6e --- /dev/null +++ b/src/oidc.ts @@ -0,0 +1,200 @@ +import { hostKey } from './config.js'; +import type { FetchLike } from './context.js'; +import { ApiError, NetworkError, RegistryClient } from './http.js'; +import { log } from './output.js'; +import { CliError } from './util.js'; +import { VERSION } from './version.js'; + +/** + * Trusted publishing from GitHub Actions: the job asks GitHub for an OIDC token (a JWT whose + * claims name the repository, workflow, ref and environment), and `POST /v1/auth/oidc/github` + * trades it for a short-lived `flbt_` token that can publish releases of one extension. + * + * Neither the JWT nor the exchanged token is printed or written anywhere; both live in memory + * for the one command. + */ + +export const PERMISSION_HINT = 'Give the job `permissions: id-token: write` (and `contents: read` for checkout) so it can request a GitHub OIDC token.'; + +/** Refresh the exchanged token when it has less than this left. */ +const REFRESH_MARGIN_MS = 2 * 60_000; + +export interface TrustedPublishingToken { + token: string; + token_type?: string; + expires_at?: string; + scopes?: string[]; + extension?: { id: string; slug: string }; + trusted_publisher?: { id: string; repository?: string; workflow?: string }; +} + +/** The GitHub Actions OIDC request variables, set only when the job has `id-token: write`. */ +export function githubOidcEnv(): { url?: string; token?: string } { + return { + url: process.env.ACTIONS_ID_TOKEN_REQUEST_URL?.trim() || undefined, + token: process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN?.trim() || undefined, + }; +} + +export function inGithubActions(): boolean { + return process.env.GITHUB_ACTIONS === 'true'; +} + +/** The audience the registry expects: its host name without the port, unless FLB_OIDC_AUDIENCE says otherwise. */ +export function oidcAudience(registry: string): string { + const override = process.env.FLB_OIDC_AUDIENCE?.trim(); + if (override) { + return override; + } + return new URL(registry).hostname.replace(/^\[(.*)\]$/, '$1'); +} + +/** `release.yml` from GITHUB_WORKFLOW_REF (`owner/repo/.github/workflows/release.yml@refs/tags/v1`). */ +function workflowFile(): string | undefined { + const ref = process.env.GITHUB_WORKFLOW_REF; + return ref?.split('@')[0].split('/').pop() || undefined; +} + +/** Fails with the permission hint when the OIDC request variables are missing or only half set. */ +export function assertGithubOidcAvailable(): void { + const env = githubOidcEnv(); + if (env.url && env.token) { + return; + } + const missing = [!env.url && 'ACTIONS_ID_TOKEN_REQUEST_URL', !env.token && 'ACTIONS_ID_TOKEN_REQUEST_TOKEN'].filter(Boolean).join(' and '); + const where = inGithubActions() ? 'This GitHub Actions job' : 'This environment'; + throw new CliError(`${where} cannot request a GitHub OIDC token (${missing} not set).`, 1, [ + PERMISSION_HINT, + ...(inGithubActions() ? [] : ['Trusted publishing works only inside GitHub Actions; elsewhere log in with `flb login` or set FLB_TOKEN.']), + ]); +} + +/** GET the job's OIDC token for `audience` from the Actions runtime. */ +export async function requestGithubIdToken(audience: string, fetchImpl: FetchLike = globalThis.fetch): Promise { + assertGithubOidcAvailable(); + const env = githubOidcEnv(); + const url = `${env.url}${env.url!.includes('?') ? '&' : '?'}audience=${encodeURIComponent(audience)}`; + + let response: Response; + try { + response = await fetchImpl(url, { + method: 'GET', + headers: { Accept: 'application/json', Authorization: `Bearer ${env.token}`, 'User-Agent': `flb/${VERSION}` }, + signal: AbortSignal.timeout(30_000), + }); + } catch (error) { + const cause = (error as { cause?: { code?: string } }).cause; + throw new CliError(`Could not reach the GitHub OIDC token endpoint (${cause?.code || (error as Error).message}).`, 1, [PERMISSION_HINT]); + } + + let value: unknown; + try { + value = ((await response.json()) as { value?: unknown })?.value; + } catch { + value = undefined; + } + if (!response.ok || typeof value !== 'string' || value === '') { + throw new CliError(`GitHub did not issue an OIDC token (HTTP ${response.status}).`, 1, [PERMISSION_HINT]); + } + return value; +} + +/** + * Exchanges GitHub OIDC tokens for `flbt_` tokens, and exchanges again shortly before one + * expires so long check runs do not outlive it. + */ +export class TrustedPublishing { + private current?: TrustedPublishingToken; + private pending?: Promise; + + constructor( + readonly registry: string, + /** the listing's npm or composer package name */ + readonly extension: string, + private readonly fetchImpl: FetchLike = globalThis.fetch, + ) {} + + get audience(): string { + return oidcAudience(this.registry); + } + + get exchanged(): TrustedPublishingToken | undefined { + return this.current; + } + + /** A client that authenticates every request with the current exchanged token. */ + client(): RegistryClient { + return new RegistryClient(this.registry, { fetch: this.fetchImpl, tokenProvider: () => this.token() }); + } + + async token(): Promise { + if (this.current && !expiresSoon(this.current.expires_at)) { + return this.current.token; + } + if (!this.pending) { + const refreshing = Boolean(this.current); + this.pending = this.exchange() + .then((result) => { + this.current = result; + if (refreshing) { + log.info(' refreshed the trusted publishing token'); + } + return result; + }) + .finally(() => { + this.pending = undefined; + }); + } + return (await this.pending).token; + } + + private async exchange(): Promise { + const audience = this.audience; + const jwt = await requestGithubIdToken(audience, this.fetchImpl); + const host = hostKey(this.registry); + const anonymous = new RegistryClient(this.registry, { fetch: this.fetchImpl }); + + let result: TrustedPublishingToken; + try { + result = await anonymous.post('v1/auth/oidc/github', { token: jwt, extension: this.extension }, { auth: false }); + } catch (error) { + throw describeExchangeError(error, { host, audience, extension: this.extension }); + } + if (!result || typeof result.token !== 'string' || result.token === '') { + throw new CliError(`${host} answered the trusted publishing exchange without a token.`); + } + return result; + } +} + +function expiresSoon(expiresAt: string | undefined): boolean { + const at = expiresAt ? Date.parse(expiresAt) : NaN; + return Number.isFinite(at) && at - Date.now() < REFRESH_MARGIN_MS; +} + +function describeExchangeError(error: unknown, { host, audience, extension }: { host: string; audience: string; extension: string }): unknown { + if (error instanceof NetworkError || !(error instanceof ApiError)) { + return error; + } + const repository = process.env.GITHUB_REPOSITORY; + const workflow = workflowFile(); + const ref = process.env.GITHUB_REF; + switch (error.status) { + case 401: + return new CliError(`${host} rejected the GitHub OIDC token: ${error.message}`, 1, [ + `The token was requested for the audience "${audience}"; set FLB_OIDC_AUDIENCE if the registry expects another.`, + ]); + case 403: + return new CliError(`No trusted publisher of ${extension} on ${host} matches this workflow: ${error.message}`, 1, [ + `In Studio → Access, add a trusted publisher for repository ${repository || 'owner/repo'}, workflow ${workflow || '.yml'}${ref ? `, with allowed refs that include ${ref}` : ''}, and the job's environment if you require one.`, + ]); + case 404: + return new CliError(`${host} has no listing for ${extension} that accepts trusted publishing: ${error.message}`, 1, [ + 'Trusted publishing does not create listings: publish the first release with a personal token (`flb publish` after `flb login`), then add a trusted publisher in Studio → Access.', + ]); + case 422: + return new CliError(`${host} refused the trusted publishing exchange: ${error.message}`); + default: + return error; + } +} diff --git a/src/output.ts b/src/output.ts index 8d893e8..3ca9b35 100644 --- a/src/output.ts +++ b/src/output.ts @@ -2,14 +2,16 @@ import pc from 'picocolors'; /** * Terminal output. Everything a command prints goes through here so tokens can be - * redacted in one place: personal (flbp_), instance (flbi_) and session (flbs_) tokens - * are masked in every message unless a command prints one on purpose with `secret()`. + * redacted in one place: personal (flbp_), instance (flbi_), session (flbs_) and trusted + * publishing (flbt_) tokens are masked in every message unless a command prints one on + * purpose with `secret()`, and JWTs (GitHub OIDC tokens) are masked whole. */ -const TOKEN_PATTERN = /\b(flb[pis]_)[A-Za-z0-9]{8,}/g; +const TOKEN_PATTERN = /\b(flb[pist]_)[A-Za-z0-9]{8,}/g; +const JWT_PATTERN = /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]+/g; export function redact(text: string): string { - return text.replace(TOKEN_PATTERN, (match, prefix: string) => `${prefix}…${match.slice(-4)}`); + return text.replace(TOKEN_PATTERN, (match, prefix: string) => `${prefix}…${match.slice(-4)}`).replace(JWT_PATTERN, ''); } export interface Writer { diff --git a/test/unit/oidc.test.ts b/test/unit/oidc.test.ts new file mode 100644 index 0000000..29ced91 --- /dev/null +++ b/test/unit/oidc.test.ts @@ -0,0 +1,251 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { getToken } from '../../src/config.js'; +import { oidcAudience } from '../../src/oidc.js'; +import { redact } from '../../src/output.js'; +import type { ReleaseDetail } from '../../src/types.js'; +import { REGISTRY, TOKEN, capture, copyFixture, fakeRegistry, flb, reset, tempDir, useTempHome, writeConfig } from './helpers.js'; + +const REQUEST_URL = 'http://actions.test/_apis/token?api-version=2.0'; +const REQUEST_TOKEN = 'ghs_' + 'r'.repeat(40); +const JWT = 'eyJhbGciOiJSUzI1NiJ9.' + 'eyJyZXBvc2l0b3J5IjoiYWNtZS9pbnNpZ2h0cyJ9' + '.c2lnbmF0dXJlLXNpZ25hdHVyZS1zaWduYXR1cmU'; +const TRUSTED = 'flbt_' + 't'.repeat(36) + 'Tp01'; +const OIDC_ENV = ['ACTIONS_ID_TOKEN_REQUEST_URL', 'ACTIONS_ID_TOKEN_REQUEST_TOKEN', 'FLB_OIDC_AUDIENCE', 'GITHUB_ACTIONS', 'GITHUB_REPOSITORY', 'GITHUB_WORKFLOW_REF', 'GITHUB_REF']; + +const listing = { id: 'ext_1', slug: 'acme-insights', name: 'Acme Insights', status: 'draft', organization: { id: 'org_1', slug: 'acme', name: 'Acme' }, packages: [{ kind: 'npm', name: '@acme/insights-engine' }, { kind: 'composer', name: 'acme/insights-api' }] }; + +function release(overrides: Partial = {}): ReleaseDetail { + return { + id: 'rel_1', + extension: { id: 'ext_1', slug: 'acme-insights', name: 'Acme Insights', status: 'published' }, + version: '1.2.0', + channel: 'stable', + status: 'uploaded', + compat: null, + notes: null, + size_bytes: 1, + checks: [], + submission: { requested: false, submitted_at: null, errors: [] }, + review: { required: null, reasons: {} }, + reviews: [], + published_at: null, + yanked_at: null, + created_at: '2026-10-22T00:00:00Z', + ...overrides, + }; +} + +function exchanged(overrides: Record = {}) { + return { + token: TRUSTED, + token_type: 'Bearer', + expires_at: new Date(Date.now() + 15 * 60_000).toISOString(), + scopes: ['publish'], + extension: { id: 'ext_1', slug: 'acme-insights' }, + trusted_publisher: { id: 'tp_1', repository: 'acme/insights', workflow: 'release.yml' }, + ...overrides, + }; +} + +function inActions(): void { + process.env.GITHUB_ACTIONS = 'true'; + process.env.ACTIONS_ID_TOKEN_REQUEST_URL = REQUEST_URL; + process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN = REQUEST_TOKEN; + process.env.GITHUB_REPOSITORY = 'acme/insights'; + process.env.GITHUB_WORKFLOW_REF = 'acme/insights/.github/workflows/release.yml@refs/tags/v1.2.0'; + process.env.GITHUB_REF = 'refs/tags/v1.2.0'; +} + +const routes = (extra: Record = {}) => ({ + 'GET /_apis/token': { value: JWT }, + 'POST /v1/auth/oidc/github': exchanged(), + 'GET /v1/publisher/extensions': [listing], + 'POST /v1/publisher/extensions/acme-insights/releases': { status: 201, body: release({ status: 'checking' }) }, + 'GET /v1/publisher/releases/rel_1': release(), + ...extra, +}); + +describe('trusted publishing', () => { + // build once: the build is current as long as the archives and extension.json are unchanged + let built: string; + let root: string; + beforeAll(async () => { + useTempHome(); + built = copyFixture('extension'); + capture(); + expect(await flb('build', built)).toBe(0); + reset(); + }, 180_000); + beforeEach(() => { + useTempHome(); + writeConfig({}); + root = path.join(tempDir('flb-fixture-'), 'extension'); + fs.cpSync(built, root, { recursive: true }); + vi.useFakeTimers({ shouldAdvanceTime: true, advanceTimeDelta: 500 }); + }); + afterEach(() => { + vi.useRealTimers(); + for (const name of OIDC_ENV) { + delete process.env[name]; + } + delete process.env.FLB_TOKEN; + reset(); + }); + + it('exchanges the GitHub OIDC token and publishes with the exchanged token', async () => { + inActions(); + const { requests } = fakeRegistry(routes({ 'GET /v1/publisher/releases/rel_1': release({ status: 'submitted', submission: { requested: true, submitted_at: 'now', errors: [] } }) })); + const out = capture(); + + expect(await flb('publish', root, '--submit', '--json')).toBe(0); + + const oidc = requests.find((r) => r.path === '/_apis/token')!; + expect(oidc.method).toBe('GET'); + expect(oidc.query.get('api-version')).toBe('2.0'); + expect(oidc.query.get('audience')).toBe('registry.test'); + expect(oidc.headers.authorization).toBe(`Bearer ${REQUEST_TOKEN}`); + + const exchange = requests.find((r) => r.path === '/v1/auth/oidc/github')!; + expect(exchange.body).toEqual({ token: JWT, extension: '@acme/insights-engine' }); + expect(exchange.headers.authorization).toBeUndefined(); + + const registryCalls = requests.filter((r) => r.path.startsWith('/v1/publisher')); + expect(registryCalls.length).toBeGreaterThan(0); + for (const call of registryCalls) { + expect(call.headers.authorization).toBe(`Bearer ${TRUSTED}`); + } + const upload = requests.find((r) => r.method === 'POST' && r.path.endsWith('/releases'))!; + expect(upload.form!.get('submit')).toBe('1'); + expect(requests.some((r) => r.method === 'POST' && r.path === '/v1/publisher/extensions')).toBe(false); + + expect(JSON.parse(out.stdout).id).toBe('rel_1'); + expect(out.stderr).toMatch(/Trusted publishing to acme-insights as acme\/insights \(release\.yml\)/); + for (const secret of [JWT, TRUSTED, REQUEST_TOKEN]) { + expect(out.all).not.toContain(secret); + } + }); + + it('requests the registry host as the audience unless FLB_OIDC_AUDIENCE overrides it', async () => { + inActions(); + process.env.FLB_OIDC_AUDIENCE = 'registry.fleetbase.io'; + const { requests } = fakeRegistry(routes()); + capture(); + expect(await flb('publish', root, '--no-wait')).toBe(0); + expect(requests.find((r) => r.path === '/_apis/token')!.query.get('audience')).toBe('registry.fleetbase.io'); + delete process.env.FLB_OIDC_AUDIENCE; + expect(oidcAudience('http://localhost:8000')).toBe('localhost'); + expect(oidcAudience('https://registry.fleetbase.io')).toBe('registry.fleetbase.io'); + }); + + it('lets FLB_TOKEN win over the OIDC exchange, and --no-oidc keep the stored token', async () => { + inActions(); + process.env.FLB_TOKEN = TOKEN; + let fake = fakeRegistry(routes()); + capture(); + expect(await flb('publish', root, '--no-wait')).toBe(0); + expect(fake.requests.some((r) => r.path === '/_apis/token' || r.path === '/v1/auth/oidc/github')).toBe(false); + expect(fake.requests.find((r) => r.path.endsWith('/releases'))!.headers.authorization).toBe(`Bearer ${TOKEN}`); + + delete process.env.FLB_TOKEN; + writeConfig({ tokens: { 'registry.test:8000': TOKEN } }); + fake = fakeRegistry({ ...routes(), 'POST /v1/publisher/extensions/acme-insights/releases': { status: 201, body: release({ version: '1.2.0' }) } }); + capture(); + expect(await flb('publish', root, '--no-wait', '--no-oidc')).toBe(0); + expect(fake.requests.some((r) => r.path === '/_apis/token')).toBe(false); + expect(fake.requests.find((r) => r.path.endsWith('/releases'))!.headers.authorization).toBe(`Bearer ${TOKEN}`); + }); + + it('asks for id-token: write when the request token is missing or GitHub refuses', async () => { + inActions(); + delete process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN; + let fake = fakeRegistry(routes()); + let out = capture(); + expect(await flb('publish', root)).toBe(1); + expect(out.stderr).toMatch(/cannot request a GitHub OIDC token \(ACTIONS_ID_TOKEN_REQUEST_TOKEN not set\)/); + expect(out.stderr).toMatch(/permissions: id-token: write/); + expect(fake.requests).toEqual([]); + + process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN = REQUEST_TOKEN; + fake = fakeRegistry(routes({ 'GET /_apis/token': { status: 403, body: { message: 'Forbidden' } } })); + out = capture(); + expect(await flb('publish', root)).toBe(1); + expect(out.stderr).toMatch(/GitHub did not issue an OIDC token \(HTTP 403\)/); + expect(out.stderr).toMatch(/permissions: id-token: write/); + expect(fake.requests.some((r) => r.path.startsWith('/v1/'))).toBe(false); + }); + + it('points at id-token: write when a GitHub Actions job has no token at all, and --oidc outside Actions', async () => { + process.env.GITHUB_ACTIONS = 'true'; + fakeRegistry({}); + let out = capture(); + expect(await flb('publish', root)).toBe(1); + expect(out.stderr).toMatch(/Not logged in to registry.test:8000/); + expect(out.stderr).toMatch(/trusted publishing instead of a token: give the job `permissions: id-token: write`/); + + delete process.env.GITHUB_ACTIONS; + out = capture(); + expect(await flb('publish', root, '--oidc')).toBe(1); + expect(out.stderr).toMatch(/cannot request a GitHub OIDC token/); + expect(out.stderr).toMatch(/works only inside GitHub Actions/); + }); + + it('surfaces 401 and 403 from the exchange as clear errors', async () => { + inActions(); + let fake = fakeRegistry(routes({ 'POST /v1/auth/oidc/github': { status: 401, body: { errors: ['The OIDC token audience is not registry.test.'] } } })); + let out = capture(); + expect(await flb('publish', root)).toBe(1); + expect(out.stderr).toMatch(/registry.test:8000 rejected the GitHub OIDC token: The OIDC token audience is not registry.test./); + expect(out.stderr).toMatch(/audience "registry.test"; set FLB_OIDC_AUDIENCE/); + expect(out.stderr).not.toMatch(/flb login/); + expect(fake.requests.some((r) => r.path.startsWith('/v1/publisher'))).toBe(false); + + fake = fakeRegistry(routes({ 'POST /v1/auth/oidc/github': { status: 403, body: { errors: ['No trusted publisher matches acme/insights release.yml.'] } } })); + out = capture(); + expect(await flb('publish', root)).toBe(1); + expect(out.stderr).toMatch(/No trusted publisher of @acme\/insights-engine on registry.test:8000 matches this workflow: No trusted publisher matches/); + expect(out.stderr).toMatch(/Studio → Access, add a trusted publisher for repository acme\/insights, workflow release.yml, with allowed refs that include refs\/tags\/v1.2.0/); + expect(fake.requests.some((r) => r.path.startsWith('/v1/publisher'))).toBe(false); + expect(out.all).not.toContain(JWT); + }); + + it('never creates a listing in trusted publishing mode', async () => { + inActions(); + const { requests } = fakeRegistry(routes({ 'GET /v1/publisher/extensions': [], 'POST /v1/publisher/extensions': { status: 403, body: { errors: ['Forbidden.'] } } })); + let out = capture(); + expect(await flb('publish', root)).toBe(1); + expect(out.stderr).toMatch(/No listing on registry.test:8000 owns @acme\/insights-engine or acme\/insights-api, and trusted publishing cannot create one/); + expect(out.stderr).toMatch(/Studio → Access/); + expect(requests.some((r) => r.method === 'POST' && r.path === '/v1/publisher/extensions')).toBe(false); + + const partial = { ...listing, packages: [{ kind: 'npm', name: '@acme/insights-engine' }] }; + const fake = fakeRegistry(routes({ 'GET /v1/publisher/extensions': [partial] })); + out = capture(); + expect(await flb('publish', root)).toBe(1); + expect(out.stderr).toMatch(/The listing acme-insights has no composer package yet, and trusted publishing cannot add one/); + expect(fake.requests.some((r) => r.method === 'POST' && r.path === '/v1/publisher/extensions')).toBe(false); + }); + + it('exchanges again when the token is about to expire', async () => { + inActions(); + const tokens = [TRUSTED, 'flbt_' + 'u'.repeat(36) + 'Tp02']; + let exchanges = 0; + const { requests } = fakeRegistry( + routes({ + 'POST /v1/auth/oidc/github': () => exchanged({ token: tokens[Math.min(exchanges++, 1)], expires_at: new Date(Date.now() + (exchanges === 1 ? 30_000 : 15 * 60_000)).toISOString() }), + }), + ); + const out = capture(); + expect(await flb('publish', root)).toBe(0); + expect(exchanges).toBe(2); + expect(requests.filter((r) => r.path === '/_apis/token')).toHaveLength(2); + expect(requests.find((r) => r.path.endsWith('/releases'))!.headers.authorization).toBe(`Bearer ${tokens[1]}`); + expect(out.stderr).toMatch(/refreshed the trusted publishing token/); + }); + + it('treats flbt_ tokens as Registry Service tokens and redacts them and JWTs', () => { + process.env.FLB_TOKEN = TRUSTED; + expect(getToken({}, REGISTRY)).toEqual({ token: TRUSTED, source: 'env', legacy: false }); + expect(redact(`token ${TRUSTED} jwt ${JWT}`)).toBe('token flbt_…Tp01 jwt '); + }); +}); diff --git a/vitest.config.ts b/vitest.config.ts index b51ccc2..2f61d74 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -6,6 +6,7 @@ export default defineConfig({ environment: 'node', testTimeout: 30000, // Tests point FLEETBASE_HOME at a temp directory; never touch the real ~/.fleetbase - env: { FLEETBASE_HOME: '', FLB_TOKEN: '', FLB_REGISTRY: '', NO_COLOR: '1' }, + // and never pick up a GitHub Actions job's OIDC variables + env: { FLEETBASE_HOME: '', FLB_TOKEN: '', FLB_REGISTRY: '', NO_COLOR: '1', ACTIONS_ID_TOKEN_REQUEST_URL: '', ACTIONS_ID_TOKEN_REQUEST_TOKEN: '', FLB_OIDC_AUDIENCE: '', GITHUB_ACTIONS: '' }, }, });