diff --git a/test-companion/README.md b/test-companion/README.md index 37db10a..fbdc9cd 100644 --- a/test-companion/README.md +++ b/test-companion/README.md @@ -67,9 +67,22 @@ from the release you tested; a version without a checksum is refused. | `workflow` | no | Manual runs only; event-driven runs read the pipeline file | | `preview` | no | Report what would happen and change nothing | | `allow-unisolated` | no | `"true"` runs the agent as the job's own user when it cannot be locked down, where it can reach this job's tokens and secrets. Off by default | -| `app-id` / `app-private-key` | no | Post as the GitHub App. Keep the workflow's `permissions:` block: the workflow token is the fallback | +| `app-id` / `app-private-key` | no | Only for your own GitHub App: sign in with its key directly. Without them, the BrowserStack App is used through the token service (see below) | +| `token-broker-url` / `app-slug` | no | Point at a test token service and its App. Leave unset | | `github-token` | no | The token for the Action's own GitHub calls. Leave it as the default (the workflow token) or use the GitHub App's token, never a personal access token: Test Companion recognises its own comments by their bot account, and a person's token would make them look like that person's | +## Posting as BrowserStack + +Install the BrowserStack GitHub App on the repository and keep `id-token: write` +in the job's `permissions:` (the starter workflow has it). There is no key to +store: each run asks GitHub for a short-lived token that says which repository +it is, and BrowserStack's token service trades it for an App token limited to +that one repository, for at most an hour. If the App isn't installed, the job +has no `id-token: write`, or the service can't be reached, the run carries on +with the workflow token and posts as `github-actions[bot]`, with a notice +saying why. Keep the other `permissions:` lines either way: that token is the +fallback. + ## Approving a plan Before a job changes anything, Test Companion posts its plan and waits for diff --git a/test-companion/action.yml b/test-companion/action.yml index 498eb97..b6c8f2f 100644 --- a/test-companion/action.yml +++ b/test-companion/action.yml @@ -28,6 +28,21 @@ inputs: The App's private key. Store it as a repository or organisation secret, never inline. It is never passed to the agent's shell. required: false + token-broker-url: + description: >- + Without app-id and app-private-key, the Action signs in as the BrowserStack + GitHub App through BrowserStack's token service, which holds the App's key. + The job needs `permissions: id-token: write`. Leave this unset; it exists to + point at a test service. Must be https. + required: false + default: "https://test-companion.browserstack.com/api/github-app/token" + app-slug: + description: >- + The slug of the App the token service signs for, so commits and comments + are credited to [bot]. Leave this unset unless the token service is a + test one with its own App. + required: false + default: "browserstack" workflow: description: > @@ -212,6 +227,8 @@ runs: TC_ACTION_SELF_WORKFLOW: ${{ inputs.self-workflow-name }} TC_ACTION_APP_ID: ${{ inputs.app-id }} TC_ACTION_APP_PRIVATE_KEY: ${{ inputs.app-private-key }} + TC_ACTION_TOKEN_BROKER_URL: ${{ inputs.token-broker-url }} + TC_ACTION_APP_SLUG: ${{ inputs.app-slug }} TC_ACTION_ALLOW_UNISOLATED: ${{ inputs.allow-unisolated }} # The `tc --version` line, so a plan records which CLI made it. TC_ACTION_CLI_VERSION: ${{ steps.install.outputs.cli-version }} diff --git a/test-companion/src/main.mjs b/test-companion/src/main.mjs index 2138d8b..16a48b5 100644 --- a/test-companion/src/main.mjs +++ b/test-companion/src/main.mjs @@ -57,6 +57,7 @@ import { APP_SIGN_IN_BUDGET_MS, installationLookupMessage, } from "./app-auth.mjs" +import { appTokenFromBroker, brokerFallbackNotice, appSlugFrom } from "./token-broker.mjs" import { OUTCOMES, parseSummary, resolveOutcome, checkConclusion, stepShouldFail, approvalWasSpent, runDidNotWork } from "./outcome.mjs" import { renderJobSummary, @@ -135,7 +136,9 @@ import { const env = process.env // Taken before the App token replaces GH_TOKEN and the key is deleted, so both are still hidden. const STARTUP_SECRETS = secretsFrom(env) -const secretsNow = () => [...STARTUP_SECRETS, ...secretsFrom(env)] +// Credentials received at run time that never sit in env, such as the identity token sent to the token service. +const RECEIVED_SECRETS = [] +const secretsNow = () => [...STARTUP_SECRETS, ...RECEIVED_SECRETS, ...secretsFrom(env)] const REPO = env.GITHUB_REPOSITORY ?? "" const RUN_URL = `${env.GITHUB_SERVER_URL ?? "https://github.com"}/${REPO}/actions/runs/${env.GITHUB_RUN_ID ?? ""}` // RUNNER_TEMP is cleared per job; /tmp may hold an earlier job's files on a reused runner. @@ -308,10 +311,14 @@ function personTokenLogin() { return login } -/** A repo-scoped App installation token, or undefined to fall back to the workflow token. */ +/** + * A repo-scoped App installation token, or undefined to fall back to the workflow token. + * With the App's key as inputs (a self-managed App), sign in directly; otherwise ask + * BrowserStack's token service, which holds the key. + */ async function appInstallationToken() { const creds = appCredentials(env) - if (!creds) return undefined + if (!creds) return brokeredAppToken() // Remove the key from the environment so nothing started later, the agent included, inherits it. delete env.TC_ACTION_APP_PRIVATE_KEY @@ -382,6 +389,39 @@ async function appInstallationToken() { return token } +/** The App token from BrowserStack's token service, or undefined to fall back to the workflow token. */ +async function brokeredAppToken() { + const mask = (secret) => { + console.log(`::add-mask::${secret}`) + RECEIVED_SECRETS.push(secret) + } + let got + try { + got = await appTokenFromBroker({ env, mask }) + } catch (e) { + got = { notice: brokerFallbackNotice({ reason: e?.message ?? String(e) }) } + } finally { + // Spent: nothing started later, the agent included, can ask for another identity token. + delete env.ACTIONS_ID_TOKEN_REQUEST_TOKEN + delete env.ACTIONS_ID_TOKEN_REQUEST_URL + } + if (!got.token) { + if (got.notice) notice(got.notice) + return undefined + } + if (got.attempts > 1) notice(`Test Companion: reaching the token service took ${got.attempts} tries.`) + + // The service doesn't say which App it signed for; its bot account is [bot]. + const appSlug = appSlugFrom(env.TC_ACTION_APP_SLUG) + const appLogin = `${appSlug}[bot]` + botLogin = appLogin + // The bot account's id makes the noreply email GitHub links to the App. + const user = runGh(["api", `users/${encodeURIComponent(appLogin)}`, "--jq", ".id"], { token: got.token }) + if (user.status !== 0) warn(`Test Companion: could not look up ${appLogin}'s account, so commits use the plain Test Companion name.`) + identity = commitIdentity({ appSlug, appUserId: user.status === 0 ? String(user.stdout ?? "").trim() : "" }) + return got.token +} + /** * The settings file from the default branch, so a pull request cannot rewrite the rules for its own run. * Returns the local path, or undefined (treated as no settings). diff --git a/test-companion/src/token-broker.mjs b/test-companion/src/token-broker.mjs new file mode 100644 index 0000000..dca7d01 --- /dev/null +++ b/test-companion/src/token-broker.mjs @@ -0,0 +1,162 @@ +/** + * Signing in as the BrowserStack GitHub App without holding its key. + * + * The job asks GitHub for a short-lived identity token (OIDC) that says which + * repository and run it is, addressed to BrowserStack's token service. The + * service checks it and returns an App token limited to this one repository. + * The App's key never leaves the service. Any failure falls back to the + * workflow token, as a job without the App does today. + */ +import { retryDelayMs } from "./app-auth.mjs" + +export const DEFAULT_BROKER_URL = "https://test-companion.browserstack.com/api/github-app/token" +/** Who the identity token is addressed to; the service refuses any other. */ +export const OIDC_AUDIENCE = "test-companion.browserstack.com" +/** The App's slug, so its bot account is `[bot]`. */ +export const DEFAULT_APP_SLUG = "browserstack" +/** One call gives up after this long; a timeout counts as a network error, so it is retried. */ +export const BROKER_CALL_TIMEOUT_MS = 10_000 + +/** The service's address, or undefined with why: only an https URL with no credentials in it is used. */ +export function brokerUrlFrom(input) { + const raw = String(input ?? "").trim() || DEFAULT_BROKER_URL + let url + try { + url = new URL(raw) + } catch { + return { reason: "token-broker-url is not a valid URL" } + } + if (url.protocol !== "https:") return { reason: "token-broker-url must use https" } + if (url.username || url.password) return { reason: "token-broker-url must not contain credentials" } + return { url: url.toString() } +} + +/** The App's slug from the input, or the default. Only a GitHub-shaped slug is used. */ +export function appSlugFrom(input) { + const slug = String(input ?? "").trim().toLowerCase() + return /^[a-z0-9](?:[a-z0-9-]{0,98}[a-z0-9])?$/.test(slug) ? slug : DEFAULT_APP_SLUG +} + +/** + * Where to ask GitHub for the identity token, or undefined when this job can't: + * GitHub only sets these two when the job has `permissions: id-token: write`. + */ +export function oidcRequestFrom(env = {}) { + const requestUrl = String(env.ACTIONS_ID_TOKEN_REQUEST_URL ?? "").trim() + const requestToken = String(env.ACTIONS_ID_TOKEN_REQUEST_TOKEN ?? "").trim() + if (!requestUrl || !requestToken) return undefined + return { requestUrl, requestToken } +} + +/** The identity-token request URL with our audience; GitHub's URL already carries a query. */ +export function oidcUrlFor(requestUrl, audience = OIDC_AUDIENCE) { + const url = new URL(requestUrl) + url.searchParams.set("audience", audience) + return url.toString() +} + +/** A network failure, a 429 or a 5xx may pass on another try; 503 means "turned off" and won't. */ +export function isBrokerRetryable(status) { + const s = Number(status) + return s === 0 || s === 429 || (s >= 500 && s <= 599 && s !== 503) +} + +/** The one-line notice for falling back to the workflow token. Never contains a token. */ +export function brokerFallbackNotice(result) { + const status = Number(result?.status) + if (status === 404) return "Test Companion: the BrowserStack GitHub App isn't installed on this repository; using the workflow token." + if (status === 503) return "Test Companion: App sign-in is turned off; using the workflow token." + const why = result?.reason || (Number.isFinite(status) && status > 0 ? `HTTP ${status}` : "no reply") + return `Test Companion: could not sign in as the GitHub App (${why}); using the workflow token.` +} + +const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** One JSON call with a time limit and retries. Returns { ok, status, data, reason, attempts }; never throws. */ +async function callJson(url, init, { fetchImpl = fetch, attempts = 3, sleep = defaultSleep, timeoutMs = BROKER_CALL_TIMEOUT_MS } = {}) { + let result + for (let attempt = 1; attempt <= attempts; attempt++) { + result = await callOnce(url, init, { fetchImpl, timeoutMs }) + if (result.ok || !isBrokerRetryable(result.status) || attempt === attempts) return { ...result, attempts: attempt } + await sleep(retryDelayMs(result, attempt)) + } + return { ...result, attempts } +} + +async function callOnce(url, init, { fetchImpl, timeoutMs }) { + const controller = new AbortController() + const timer = setTimeout(() => controller.abort(new Error(`no reply within ${timeoutMs / 1000}s`)), timeoutMs) + try { + let response + try { + response = await fetchImpl(url, { ...init, signal: controller.signal }) + } catch (e) { + return { ok: false, status: 0, data: undefined, reason: `could not reach it: ${e?.message ?? e}` } + } + const data = await response.json().catch(() => undefined) + const retryAfter = response.headers?.get?.("retry-after") ?? undefined + return { + ok: response.ok, + status: response.status, + data, + reason: response.ok ? "" : `HTTP ${response.status}`, + ...(retryAfter ? { retryAfter } : {}), + } + } finally { + clearTimeout(timer) + } +} + +/** Ask GitHub for this job's identity token. Returns { ok, value } or { ok: false, status, reason }. */ +export async function requestOidcToken({ requestUrl, requestToken, audience = OIDC_AUDIENCE, ...opts }) { + const r = await callJson(oidcUrlFor(requestUrl, audience), { method: "GET", headers: { Authorization: `bearer ${requestToken}` } }, opts) + const value = r.ok ? r.data?.value : undefined + if (typeof value !== "string" || !value) { + return { ok: false, status: r.status, reason: r.ok ? "GitHub returned no identity token" : `identity token: ${r.reason}` } + } + return { ok: true, value } +} + +/** Trade the identity token for an App token. Returns the service's reply as { ok, status, data, reason }. */ +export async function requestBrokerToken({ url, oidcToken, ...opts }) { + return callJson( + url, + { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify({ oidc_token: oidcToken }) }, + opts, + ) +} + +/** + * The whole exchange. Returns { token, oidcToken } on success, or { notice } to fall back with. + * `mask` is called with each credential the moment it is received, before anything else uses it. + * The service's token must be for this job's repository; any other is refused. + */ +export async function appTokenFromBroker({ env = {}, mask = () => {}, ...opts } = {}) { + const request = oidcRequestFrom(env) + if (!request) { + return { + notice: + "Test Companion: posting as github-actions[bot]. To post as BrowserStack, install the BrowserStack GitHub App " + + "and add `id-token: write` to this job's permissions.", + } + } + const target = brokerUrlFrom(env.TC_ACTION_TOKEN_BROKER_URL) + if (!target.url) return { notice: `Test Companion: ${target.reason}; using the workflow token.` } + + const oidc = await requestOidcToken({ ...request, ...opts }) + if (!oidc.ok) return { notice: brokerFallbackNotice({ status: oidc.status, reason: oidc.reason }) } + mask(oidc.value) + + const got = await requestBrokerToken({ url: target.url, oidcToken: oidc.value, ...opts }) + const token = got.ok ? got.data?.token : undefined + if (token) mask(token) + if (!got.ok) return { notice: brokerFallbackNotice(got), attempts: got.attempts } + if (typeof token !== "string" || !token) return { notice: brokerFallbackNotice({ reason: "the reply had no token" }) } + + const repo = String(env.GITHUB_REPOSITORY ?? "").toLowerCase() + const issuedFor = String(got.data?.repository ?? "").toLowerCase() + if (!repo || issuedFor !== repo) { + return { notice: brokerFallbackNotice({ reason: "the token was issued for a different repository" }) } + } + return { token, oidcToken: oidc.value, attempts: got.attempts } +} diff --git a/test-companion/starter-workflow.yml b/test-companion/starter-workflow.yml index 37e534b..658a512 100644 --- a/test-companion/starter-workflow.yml +++ b/test-companion/starter-workflow.yml @@ -3,6 +3,10 @@ # Add two secrets under Settings → Secrets and variables → Actions: # BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY. # +# To have comments, checks and commits show as BrowserStack, install the BrowserStack +# GitHub App on the repository. There's no key to add: the job signs in through +# BrowserStack's token service, using `id-token: write` below. +# # What runs is set in testcompanion-pipeline.yml, so you can leave this file as it is. # Every trigger is listed up front; one that matches nothing costs a no-op job. name: Test Companion @@ -67,6 +71,7 @@ jobs: pull-requests: write # the one comment, and opening a pull request checks: write # the "Test Companion" check actions: write # reading the red run, and cancelling one when a PR closes + id-token: write # signing in as the BrowserStack GitHub App, with no key in this repository steps: # v4.4.0, pinned to a commit because a tag can be repointed. - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 @@ -85,7 +90,7 @@ jobs: # a version without a checksum is refused. # cli-version: "1.2.0" # cli-sha256: "" - # With the GitHub App installed, uncomment these. + # Only for your own GitHub App instead of BrowserStack's: uncomment these. # app-id: ${{ secrets.TEST_COMPANION_APP_ID }} # app-private-key: ${{ secrets.TEST_COMPANION_APP_PRIVATE_KEY }} # Manual runs only; event-driven runs read the pipeline file. diff --git a/test-companion/test/token-broker.test.mjs b/test-companion/test/token-broker.test.mjs new file mode 100644 index 0000000..5e67c73 --- /dev/null +++ b/test-companion/test/token-broker.test.mjs @@ -0,0 +1,262 @@ +import { test, describe } from "node:test" +import assert from "node:assert/strict" +import { readFileSync } from "node:fs" +import { + DEFAULT_BROKER_URL, + OIDC_AUDIENCE, + brokerUrlFrom, + appSlugFrom, + oidcRequestFrom, + oidcUrlFor, + isBrokerRetryable, + brokerFallbackNotice, + requestOidcToken, + appTokenFromBroker, +} from "../src/token-broker.mjs" +import { childEnvFor } from "../src/child-env.mjs" + +const REQUEST_URL = "https://pipelines.actions.githubusercontent.example/abc/idtoken?api-version=2.0" +const OIDC_ENV = { + ACTIONS_ID_TOKEN_REQUEST_URL: REQUEST_URL, + ACTIONS_ID_TOKEN_REQUEST_TOKEN: "request-token", + GITHUB_REPOSITORY: "acme/shop", +} + +const reply = (status, body, headers = {}) => ({ + ok: status >= 200 && status < 300, + status, + json: async () => body, + headers: { get: (k) => headers[k.toLowerCase()] }, +}) + +/** A fetch that records calls and answers the identity-token request and the service in turn. */ +function fakeFetch({ oidc = [reply(200, { value: "oidc-jwt" })], broker = [] } = {}) { + const calls = [] + const fetchImpl = async (url, init) => { + calls.push({ url, init }) + const queue = String(url).startsWith(REQUEST_URL.split("?")[0]) ? oidc : broker + const next = queue.shift() + if (next instanceof Error) throw next + return next ?? reply(500, {}) + } + return { calls, fetchImpl } +} + +const noSleep = async () => {} + +describe("the identity token request", () => { + test("is addressed to the token service, keeping GitHub's own query", () => { + const url = new URL(oidcUrlFor(REQUEST_URL)) + assert.equal(url.searchParams.get("audience"), OIDC_AUDIENCE) + assert.equal(url.searchParams.get("api-version"), "2.0") + assert.equal(OIDC_AUDIENCE, "test-companion.browserstack.com") + }) + + test("sends GitHub's request token as a bearer token and reads .value", async () => { + const { calls, fetchImpl } = fakeFetch() + const got = await requestOidcToken({ requestUrl: REQUEST_URL, requestToken: "request-token", fetchImpl, sleep: noSleep }) + assert.deepEqual(got, { ok: true, value: "oidc-jwt" }) + assert.equal(calls[0].init.method, "GET") + assert.equal(calls[0].init.headers.Authorization, "bearer request-token") + }) + + test("is only possible with both of GitHub's variables (id-token: write)", () => { + assert.ok(oidcRequestFrom(OIDC_ENV)) + assert.equal(oidcRequestFrom({ ACTIONS_ID_TOKEN_REQUEST_URL: REQUEST_URL }), undefined) + assert.equal(oidcRequestFrom({ ACTIONS_ID_TOKEN_REQUEST_TOKEN: "t" }), undefined) + }) +}) + +describe("the service's address", () => { + test("defaults to BrowserStack's token service", () => { + assert.equal(brokerUrlFrom("").url, DEFAULT_BROKER_URL) + assert.equal(brokerUrlFrom(undefined).url, DEFAULT_BROKER_URL) + }) + + test("must be https", () => { + assert.match(brokerUrlFrom("http://test-companion.browserstack.com/api/github-app/token").reason, /https/) + assert.ok(brokerUrlFrom("https://staging.example/api/github-app/token").url) + }) + + test("refuses nonsense and embedded credentials", () => { + assert.ok(brokerUrlFrom("not a url").reason) + assert.ok(brokerUrlFrom("https://user:pass@staging.example/x").reason) + }) +}) + +describe("the App's bot account", () => { + test("is browserstack[bot] unless a test App is named", () => { + assert.equal(appSlugFrom(""), "browserstack") + assert.equal(appSlugFrom("tc-staging-app"), "tc-staging-app") + }) + + test("an odd slug can't be used to name another account", () => { + assert.equal(appSlugFrom("evil[bot] x"), "browserstack") + assert.equal(appSlugFrom("../x"), "browserstack") + }) +}) + +describe("appTokenFromBroker", () => { + test("posts only the identity token, and uses the token it gets back", async () => { + const { calls, fetchImpl } = fakeFetch({ + broker: [reply(200, { token: "ghs_app", expires_at: "2026-11-16T10:00:00Z", repository: "acme/shop" })], + }) + const masked = [] + const got = await appTokenFromBroker({ env: OIDC_ENV, mask: (s) => masked.push(s), fetchImpl, sleep: noSleep }) + assert.equal(got.token, "ghs_app") + const post = calls[1] + assert.equal(post.url, DEFAULT_BROKER_URL) + assert.equal(post.init.method, "POST") + assert.deepEqual(JSON.parse(post.init.body), { oidc_token: "oidc-jwt" }) + }) + + test("masks the identity token and the App token as soon as each arrives", async () => { + const { fetchImpl } = fakeFetch({ broker: [reply(200, { token: "ghs_app", repository: "acme/shop" })] }) + const masked = [] + await appTokenFromBroker({ env: OIDC_ENV, mask: (s) => masked.push(s), fetchImpl, sleep: noSleep }) + assert.deepEqual(masked, ["oidc-jwt", "ghs_app"]) + }) + + test("a test service is used when named", async () => { + const { calls, fetchImpl } = fakeFetch({ broker: [reply(200, { token: "t", repository: "acme/shop" })] }) + const env = { ...OIDC_ENV, TC_ACTION_TOKEN_BROKER_URL: "https://staging.example/api/github-app/token" } + await appTokenFromBroker({ env, fetchImpl, sleep: noSleep }) + assert.equal(calls[1].url, "https://staging.example/api/github-app/token") + }) + + test("without id-token: write it falls back without calling anything", async () => { + const { calls, fetchImpl } = fakeFetch() + const got = await appTokenFromBroker({ env: { GITHUB_REPOSITORY: "acme/shop" }, fetchImpl, sleep: noSleep }) + assert.equal(got.token, undefined) + assert.match(got.notice, /id-token: write/) + assert.equal(calls.length, 0) + }) + + test("an http service address is refused before anything is sent", async () => { + const { calls, fetchImpl } = fakeFetch() + const env = { ...OIDC_ENV, TC_ACTION_TOKEN_BROKER_URL: "http://staging.example/x" } + const got = await appTokenFromBroker({ env, fetchImpl, sleep: noSleep }) + assert.equal(got.token, undefined) + assert.match(got.notice, /https/) + assert.equal(calls.length, 0) + }) + + for (const [status, body, expected] of [ + [404, { error: "app_not_installed" }, /isn't installed on this repository/], + [503, { error: "disabled" }, /App sign-in is turned off/], + [401, { error: "unauthorized" }, /could not sign in as the GitHub App \(HTTP 401\)/], + [502, { error: "upstream" }, /could not sign in as the GitHub App \(HTTP 502\)/], + [429, {}, /could not sign in as the GitHub App \(HTTP 429\)/], + ]) { + test(`a ${status} falls back with the right notice`, async () => { + const { fetchImpl } = fakeFetch({ broker: [reply(status, body), reply(status, body), reply(status, body)] }) + const got = await appTokenFromBroker({ env: OIDC_ENV, fetchImpl, sleep: noSleep }) + assert.equal(got.token, undefined) + assert.match(got.notice, expected) + }) + } + + test("no notice ever contains a token", async () => { + const { fetchImpl } = fakeFetch({ broker: [reply(401, { error: "unauthorized", token: "ghs_leak" })] }) + const got = await appTokenFromBroker({ env: OIDC_ENV, fetchImpl, sleep: noSleep }) + assert.doesNotMatch(got.notice, /ghs_leak|oidc-jwt|request-token/) + }) + + test("a token issued for another repository is not used", async () => { + const { fetchImpl } = fakeFetch({ broker: [reply(200, { token: "ghs_other", repository: "acme/other" })] }) + const masked = [] + const got = await appTokenFromBroker({ env: OIDC_ENV, mask: (s) => masked.push(s), fetchImpl, sleep: noSleep }) + assert.equal(got.token, undefined) + assert.match(got.notice, /different repository/) + // Still masked: it arrived in this job's memory. + assert.ok(masked.includes("ghs_other")) + }) + + test("GitHub refusing the identity token falls back", async () => { + const { fetchImpl } = fakeFetch({ oidc: [reply(403, { message: "no" })] }) + const got = await appTokenFromBroker({ env: OIDC_ENV, fetchImpl, sleep: noSleep }) + assert.equal(got.token, undefined) + assert.match(got.notice, /could not sign in as the GitHub App/) + }) + + test("a network failure is retried, then succeeds", async () => { + const { calls, fetchImpl } = fakeFetch({ + broker: [new Error("socket hang up"), reply(500, {}), reply(200, { token: "ghs_app", repository: "acme/shop" })], + }) + const got = await appTokenFromBroker({ env: OIDC_ENV, fetchImpl, sleep: noSleep }) + assert.equal(got.token, "ghs_app") + assert.equal(got.attempts, 3) + assert.equal(calls.length, 4) + }) + + test("gives up after three tries", async () => { + const { calls, fetchImpl } = fakeFetch({ broker: [reply(502, {}), reply(502, {}), reply(502, {}), reply(200, { token: "late" })] }) + const got = await appTokenFromBroker({ env: OIDC_ENV, fetchImpl, sleep: noSleep }) + assert.equal(got.token, undefined) + assert.equal(calls.length, 4) // one identity-token call, three to the service + }) + + for (const status of [401, 403, 404, 422, 503]) { + test(`a ${status} is not retried`, async () => { + const { calls, fetchImpl } = fakeFetch({ broker: [reply(status, {}), reply(200, { token: "t", repository: "acme/shop" })] }) + await appTokenFromBroker({ env: OIDC_ENV, fetchImpl, sleep: noSleep }) + assert.equal(calls.length, 2) + }) + } + + test("a stalled call is cut off by the time limit and retried", async () => { + let n = 0 + const fetchImpl = async (url, init) => { + if (String(url).startsWith(REQUEST_URL.split("?")[0])) return reply(200, { value: "oidc-jwt" }) + n++ + if (n === 1) { + return new Promise((_, reject) => init.signal.addEventListener("abort", () => reject(init.signal.reason))) + } + return reply(200, { token: "ghs_app", repository: "acme/shop" }) + } + const got = await appTokenFromBroker({ env: OIDC_ENV, fetchImpl, sleep: noSleep, timeoutMs: 20 }) + assert.equal(got.token, "ghs_app") + assert.equal(n, 2) + }) +}) + +describe("retry and notice rules", () => { + test("503 means turned off, so it isn't retried; other 5xx, 429 and network errors are", () => { + assert.equal(isBrokerRetryable(503), false) + for (const s of [0, 429, 500, 502, 504]) assert.equal(isBrokerRetryable(s), true, String(s)) + for (const s of [400, 401, 403, 404, 422]) assert.equal(isBrokerRetryable(s), false, String(s)) + }) + + test("a fallback with no reply says so", () => { + assert.match(brokerFallbackNotice({ status: 0 }), /no reply/) + }) +}) + +describe("main.mjs", () => { + const main = readFileSync(new URL("../src/main.mjs", import.meta.url), "utf8") + + test("with the App's key as inputs, the token service is never asked", () => { + assert.match(main, /const creds = appCredentials\(env\)\n\tif \(!creds\) return brokeredAppToken\(\)/) + assert.equal(main.match(/brokeredAppToken\(\)/g).length, 2, "defined once and called only from the no-key branch") + assert.equal(main.match(/appTokenFromBroker\(/g).length, 1) + }) + + test("the identity-token variables are removed once spent", () => { + assert.match(main, /delete env\.ACTIONS_ID_TOKEN_REQUEST_TOKEN/) + assert.match(main, /delete env\.ACTIONS_ID_TOKEN_REQUEST_URL/) + }) + + test("received credentials are masked and redacted from what is posted", () => { + assert.match(main, /::add-mask::\$\{secret\}/) + assert.match(main, /RECEIVED_SECRETS\.push\(secret\)/) + assert.match(main, /secretsNow = \(\) => \[\.\.\.STARTUP_SECRETS, \.\.\.RECEIVED_SECRETS/) + }) +}) + +describe("the agent's environment", () => { + test("never gets GitHub's identity-token variables", () => { + const out = childEnvFor({ ...OIDC_ENV, PATH: "/bin", TC_ACTION_TOKEN_BROKER_URL: DEFAULT_BROKER_URL }) + assert.equal(out.ACTIONS_ID_TOKEN_REQUEST_TOKEN, undefined) + assert.equal(out.ACTIONS_ID_TOKEN_REQUEST_URL, undefined) + }) +})