diff --git a/docs/src/content/docs/targets/nuget.md b/docs/src/content/docs/targets/nuget.md index 7519622a..92fd2c01 100644 --- a/docs/src/content/docs/targets/nuget.md +++ b/docs/src/content/docs/targets/nuget.md @@ -14,6 +14,7 @@ Uploads packages to [NuGet](https://www.nuget.org/) via .NET Core. | `includeWorkspaces` | `string` | Regex pattern to filter which packages to include. Example: `'/^Sentry\./'` | | `excludeWorkspaces` | `string` | Regex pattern to filter which packages to exclude. Example: `'/\.Tests$/'` | | `serverUrl` | `string` | NuGet server URL. Default: `https://api.nuget.org/v3/index.json` | +| `trustedPublishingUser` | `string` | nuget.org user who created the [trusted publishing](#trusted-publishing) policy. When set, Craft doesn't use `NUGET_API_TOKEN` | ## Workspace Support @@ -86,9 +87,32 @@ NuGet.org validates new packages before serving them, which usually takes a few | Name | Description | |------|-------------| -| `NUGET_API_TOKEN` | NuGet [API token](https://www.nuget.org/account/apikeys) | +| `NUGET_USER` | nuget.org user for [trusted publishing](#trusted-publishing), used when `trustedPublishingUser` isn't set in the config | +| `NUGET_API_TOKEN` | NuGet [API token](https://www.nuget.org/account/apikeys). Required unless trusted publishing is enabled | | `NUGET_DOTNET_BIN` | Path to .NET Core. Default: `dotnet` | +## Trusted Publishing + +With [trusted publishing](https://learn.microsoft.com/nuget/nuget-org/trusted-publishing), Craft publishes to nuget.org from GitHub Actions without a long-lived API key, so there is no key to rotate or let expire. + +When `trustedPublishingUser` (or the `NUGET_USER` environment variable) is set, Craft requests a GitHub Actions OIDC token for each `nuget` target and exchanges it at nuget.org for a temporary API key, which it then pushes with. Temporary keys are valid for 1 hour, so Craft gets a new one after 45 minutes. + +To set it up: + +1. On nuget.org, open **Trusted Publishing** from your account menu and add a policy for the repository and workflow that run `craft publish`. Enter the workflow file name only (for example `publish.yml`), and the GitHub Actions environment if the job uses one. Pick the user or organization that owns the packages as the policy owner: the policy covers all of its packages. +2. Give the publishing job the `id-token: write` permission. +3. Set `trustedPublishingUser` to the nuget.org user who **created** the policy (their profile name, not their email address). For a policy owned by an organization, this is still the member who created it, not the organization. If that member leaves the organization, the policy stops working. + +```yaml +targets: + - name: nuget + trustedPublishingUser: sentry-bot +``` + +Alternatively, set the `NUGET_USER` environment variable in the publishing workflow; `trustedPublishingUser` takes precedence over it. + +Trusted publishing only works with nuget.org: Craft fails if it's enabled with a custom `serverUrl`. + ## Examples ### Basic Usage diff --git a/src/targets/__tests__/nuget.test.ts b/src/targets/__tests__/nuget.test.ts index fdeddaad..460002d7 100644 --- a/src/targets/__tests__/nuget.test.ts +++ b/src/targets/__tests__/nuget.test.ts @@ -1,6 +1,6 @@ import { vi, type MockInstance } from 'vitest'; import { resolve } from 'path'; -import { NugetTarget } from '../nuget'; +import { NugetTarget, NUGET_TOKEN_SERVICE_URL } from '../nuget'; import * as dotnetWorkspaces from '../../utils/dotnetWorkspaces'; import { NoneArtifactProvider } from '../../artifact_providers/none'; import { RemoteArtifact } from '../../artifact_providers/base'; @@ -169,7 +169,7 @@ describe('NugetTarget.expand', () => { expect(result[0].id).toBe('Sentry.Core'); }); - it('propagates serverUrl to expanded targets', async () => { + it('propagates serverUrl and trustedPublishingUser to expanded targets', async () => { discoverDotnetPackagesMock = vi .spyOn(dotnetWorkspaces, 'discoverDotnetPackages') .mockResolvedValue({ @@ -188,6 +188,7 @@ describe('NugetTarget.expand', () => { name: 'nuget', workspaces: true, serverUrl: 'https://custom.nuget.server/v3/index.json', + trustedPublishingUser: 'sentry-bot', }; const result = await NugetTarget.expand(config, '/root'); @@ -195,6 +196,7 @@ describe('NugetTarget.expand', () => { expect(result[0].serverUrl).toBe( 'https://custom.nuget.server/v3/index.json', ); + expect(result[0].trustedPublishingUser).toBe('sentry-bot'); }); it('sorts packages topologically by dependencies', async () => { @@ -498,3 +500,223 @@ describe('NugetTarget.publish', () => { await expect(target.publish('1.0.0', 'abc123')).rejects.toBe(error); }); }); + +describe('NugetTarget authentication', () => { + const oldEnv = process.env; + const OIDC_REQUEST_URL = + 'https://token.actions.example/token?api-version=2.0'; + let fetchMock: MockInstance; + + beforeEach(() => { + process.env = { ...oldEnv }; + delete process.env.NUGET_API_TOKEN; + delete process.env.NUGET_USER; + delete process.env.ACTIONS_ID_TOKEN_REQUEST_URL; + delete process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN; + delete process.env.GITHUB_ACTIONS; + vi.mocked(spawnProcess).mockReset(); + vi.mocked(getRemotePackageState) + .mockReset() + .mockResolvedValue({ status: 'missing' }); + fetchMock = vi.fn(async (url: string | URL) => + String(url).startsWith('https://token.actions.example/') + ? Response.json({ value: 'github-oidc-token' }) + : Response.json({ apiKey: 'temporary-api-key' }), + ); + vi.stubGlobal('fetch', fetchMock); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.useRealTimers(); + }); + + afterAll(() => { + process.env = oldEnv; + }); + + function enableTrustedPublishing(): void { + process.env.NUGET_USER = 'sentry-bot'; + process.env.ACTIONS_ID_TOKEN_REQUEST_URL = OIDC_REQUEST_URL; + process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN = 'actions-request-token'; + } + + function createTarget( + filenames = ['Sentry.1.0.0.nupkg'], + config: Record = {}, + ): NugetTarget { + const artifactProvider = new NoneArtifactProvider(); + const target = new NugetTarget( + { name: 'nuget', ...config }, + artifactProvider, + ); + const artifacts = filenames.map(filename => ({ + filename, + })) as RemoteArtifact[]; + vi.spyOn(artifactProvider, 'filterArtifactsForRevision').mockImplementation( + async (_revision, filterOptions) => + artifacts.filter(a => filterOptions?.includeNames?.test(a.filename)), + ); + vi.spyOn(artifactProvider, 'downloadArtifact').mockImplementation( + async (a: RemoteArtifact) => `/tmp/${a.filename}`, + ); + return target; + } + + function pushes(): { args: string[]; apiKey: unknown }[] { + return vi + .mocked(spawnProcess) + .mock.calls.filter(([, args]) => args?.[1] === 'push') + .map(([, args, options]) => ({ + args: args ?? [], + apiKey: options?.env?.NUGET_API_KEY, + })); + } + + function exchanges(): Request[] { + return fetchMock.mock.calls + .filter(([url]) => String(url) === NUGET_TOKEN_SERVICE_URL) + .map(([url, init]) => new Request(url, init)); + } + + it('fails without any credentials', () => { + expect(() => createTarget()).toThrow(/NUGET_USER .* or NUGET_API_TOKEN/); + }); + + it('pushes with NUGET_API_TOKEN without putting it on the logged command line', async () => { + process.env.NUGET_API_TOKEN = 'long-lived-token'; + const target = createTarget(); + + await target.publish('1.0.0', 'abc123'); + + expect(pushes()).toEqual([ + { + args: expect.arrayContaining(['--api-key', '${NUGET_API_KEY}']), + apiKey: 'long-lived-token', + }, + ]); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('requires GitHub Actions OIDC when NUGET_USER is set', () => { + process.env.NUGET_USER = 'sentry-bot'; + process.env.NUGET_API_TOKEN = 'long-lived-token'; + + expect(() => createTarget()).toThrow(/OIDC is not available/); + }); + + it('refuses trusted publishing to a feed other than nuget.org', () => { + enableTrustedPublishing(); + + expect(() => + createTarget(undefined, { + serverUrl: 'https://nuget.example/v3/index.json', + }), + ).toThrow(/only works with https:\/\/api\.nuget\.org/); + }); + + it('pushes with a temporary key from trusted publishing, even if NUGET_API_TOKEN is set', async () => { + enableTrustedPublishing(); + process.env.NUGET_API_TOKEN = 'long-lived-token'; + const target = createTarget(); + + await target.publish('1.0.0', 'abc123'); + + const [oidcUrl, oidcInit] = fetchMock.mock.calls[0]; + expect(new URL(oidcUrl).searchParams.get('audience')).toBe( + 'https://www.nuget.org', + ); + expect(oidcInit.headers).toMatchObject({ + Authorization: 'Bearer actions-request-token', + }); + + const [exchange] = exchanges(); + expect(exchange.method).toBe('POST'); + expect(exchange.headers.get('Authorization')).toBe( + 'Bearer github-oidc-token', + ); + expect(await exchange.json()).toEqual({ + username: 'sentry-bot', + tokenType: 'ApiKey', + }); + + expect(pushes().map(p => p.apiKey)).toEqual(['temporary-api-key']); + }); + + it('enables trusted publishing from the target config', async () => { + process.env.ACTIONS_ID_TOKEN_REQUEST_URL = OIDC_REQUEST_URL; + process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN = 'actions-request-token'; + process.env.NUGET_USER = 'env-user'; + const target = createTarget(undefined, { + trustedPublishingUser: 'config-user', + }); + + await target.publish('1.0.0', 'abc123'); + + const [exchange] = exchanges(); + expect(await exchange.json()).toMatchObject({ username: 'config-user' }); + expect(pushes().map(p => p.apiKey)).toEqual(['temporary-api-key']); + }); + + it('shares one temporary key between the packages of a target', async () => { + enableTrustedPublishing(); + const target = createTarget([ + 'Sentry.1.0.0.nupkg', + 'Sentry.Maui.1.0.0.nupkg', + ]); + + await target.publish('1.0.0', 'abc123'); + + expect(pushes()).toHaveLength(2); + expect(exchanges()).toHaveLength(1); + }); + + it('gets a new temporary key before the old one expires', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + enableTrustedPublishing(); + const target = createTarget(); + + await target.publish('1.0.0', 'abc123'); + vi.setSystemTime(Date.now() + 30 * 60 * 1000); + await target.publish('1.0.0', 'abc123'); + expect(exchanges()).toHaveLength(1); + + vi.setSystemTime(Date.now() + 16 * 60 * 1000); + await target.publish('1.0.0', 'abc123'); + expect(exchanges()).toHaveLength(2); + }); + + it('masks the temporary key in GitHub Actions logs', async () => { + enableTrustedPublishing(); + process.env.GITHUB_ACTIONS = 'true'; + const write = vi + .spyOn(process.stdout, 'write') + .mockImplementation(() => true); + const target = createTarget(); + + let writes: unknown[][]; + try { + await target.publish('1.0.0', 'abc123'); + } finally { + writes = [...write.mock.calls]; + write.mockRestore(); + } + + expect(writes).toContainEqual(['::add-mask::temporary-api-key\n']); + }); + + it('explains a rejected token exchange', async () => { + enableTrustedPublishing(); + fetchMock.mockImplementation(async (url: string | URL) => + String(url).startsWith('https://token.actions.example/') + ? Response.json({ value: 'github-oidc-token' }) + : Response.json({ error: 'No matching trust policy' }, { status: 401 }), + ); + const target = createTarget(); + + await expect(target.publish('1.0.0', 'abc123')).rejects.toThrow( + /HTTP 401: \{"error":"No matching trust policy"\}[\s\S]*user who created the policy/, + ); + expect(pushes()).toEqual([]); + }); +}); diff --git a/src/targets/mcpRegistry.ts b/src/targets/mcpRegistry.ts index 43a1f7f5..27f94886 100644 --- a/src/targets/mcpRegistry.ts +++ b/src/targets/mcpRegistry.ts @@ -11,6 +11,7 @@ import { import { sleep } from '../utils/async'; import { logDryRun } from '../utils/dryRun'; import { ConfigurationError } from '../utils/errors'; +import { getGitHubOidcRequest, getGitHubOidcToken } from '../utils/githubOidc'; import { isDryRun } from '../utils/helpers'; import { BaseTarget } from './base'; import { BaseArtifactProvider } from '../artifact_providers/base'; @@ -365,11 +366,15 @@ export class McpRegistryTarget extends BaseTarget { * `id-token: write`, otherwise exchanges `MCP_GITHUB_TOKEN`. */ private async getRegistryToken(): Promise { - const requestUrl = process.env.ACTIONS_ID_TOKEN_REQUEST_URL; - const requestToken = process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN; - if (requestUrl && requestToken) { + const oidcRequest = getGitHubOidcRequest(); + if (oidcRequest) { this.logger.debug('Authenticating with GitHub Actions OIDC'); - const oidcToken = await this.getGitHubOidcToken(requestUrl, requestToken); + // The registry checks that the audience is its origin (same as + // `mcp-publisher login github-oidc`). + const oidcToken = await getGitHubOidcToken( + oidcRequest, + new URL(this.mcpRegistryConfig.registryUrl).origin, + ); return this.exchangeToken('github-oidc', { oidc_token: oidcToken }); } @@ -385,38 +390,6 @@ export class McpRegistryTarget extends BaseTarget { ); } - /** - * Requests a GitHub Actions OIDC token. Its audience is the registry origin, - * which the registry checks (same as `mcp-publisher login github-oidc`). - */ - private async getGitHubOidcToken( - requestUrl: string, - requestToken: string, - ): Promise { - const url = new URL(requestUrl); - url.searchParams.set( - 'audience', - new URL(this.mcpRegistryConfig.registryUrl).origin, - ); - const response = await fetch(url, { - headers: { - Accept: 'application/json', - Authorization: `Bearer ${requestToken}`, - }, - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), - }); - if (!response.ok) { - throw new Error( - `GitHub OIDC token request failed: HTTP ${response.status}`, - ); - } - const { value } = (await response.json()) as { value?: string }; - if (!value) { - throw new Error('GitHub OIDC token response has no token'); - } - return value; - } - /** Exchanges a GitHub credential for a short-lived registry token */ private async exchangeToken( method: 'github-oidc' | 'github-at', diff --git a/src/targets/nuget.ts b/src/targets/nuget.ts index 41c33314..3114c0c2 100644 --- a/src/targets/nuget.ts +++ b/src/targets/nuget.ts @@ -27,6 +27,7 @@ import { packageIdToNugetArtifactPattern, } from '../utils/dotnetWorkspaces'; import { filterWorkspacePackages } from '../utils/workspaces'; +import { getGitHubOidcRequest, getGitHubOidcToken } from '../utils/githubOidc'; import { getRemotePackageState, isSymbolPackagePublished, @@ -40,6 +41,26 @@ export const NUGET_DOTNET_BIN = process.env.NUGET_DOTNET_BIN || 'dotnet'; /** Default Nuget registry URL */ export const DEFAULT_NUGET_SERVER_URL = 'https://api.nuget.org/v3/index.json'; +/** + * nuget.org user for trusted publishing. When set, Craft exchanges a GitHub + * Actions OIDC token for a temporary API key instead of using NUGET_API_TOKEN. + */ +const NUGET_USER_ENV_VAR = 'NUGET_USER'; + +/** nuget.org endpoint that exchanges an OIDC token for a temporary API key */ +export const NUGET_TOKEN_SERVICE_URL = 'https://www.nuget.org/api/v2/token'; + +/** OIDC audience that nuget.org accepts */ +const NUGET_OIDC_AUDIENCE = 'https://www.nuget.org'; + +/** + * nuget.org's temporary API keys are valid for 1 hour. Get a new one well + * before that, so a key never expires in the middle of a push. + */ +const TEMPORARY_API_KEY_MAX_AGE_MS = 45 * 60 * 1000; + +const REQUEST_TIMEOUT_MS = 30_000; + /** A regular expression used to find the package tarball */ const DEFAULT_NUGET_REGEX = /^.*\d\.\d.*\.nupkg$/; const SYMBOLS_NUGET_REGEX = /^.*\d\.\d.*\.snupkg$/; @@ -76,12 +97,20 @@ export interface NugetTargetConfig extends TargetConfig { excludeWorkspaces?: string; /** NuGet server URL */ serverUrl?: string; + /** + * nuget.org user who created the trusted publishing policy. When set (here + * or via NUGET_USER), Craft publishes with trusted publishing instead of + * NUGET_API_TOKEN. + */ + trustedPublishingUser?: string; } /** Nuget target configuration options */ export interface NugetTargetOptions { - /** Nuget API token */ - apiToken: string; + /** Long-lived Nuget API token, used when trusted publishing is off */ + apiToken?: string; + /** nuget.org user to get temporary API keys for, with trusted publishing */ + trustedPublishingUser?: string; /** Nuget server URL */ serverUrl: string; } @@ -89,6 +118,7 @@ export interface NugetTargetOptions { /** Config fields for nuget target from .craft.yml */ interface NugetYamlConfig extends Record { serverUrl?: string; + trustedPublishingUser?: string; } /** Returns the trimmed text of the first `...` in an XML file */ @@ -102,6 +132,8 @@ function readXmlTag(content: string, tag: string): string | undefined { export class NugetTarget extends BaseTarget { public readonly name: string = 'nuget'; public readonly nugetConfig: NugetTargetOptions; + /** Temporary API key from trusted publishing, shared by parallel pushes */ + private temporaryApiKey?: { value: Promise; expiresAt: number }; /** * Expand a nuget target config into multiple targets if workspaces is enabled. @@ -209,6 +241,9 @@ export class NugetTarget extends BaseTarget { if (config.serverUrl) { expandedTarget.serverUrl = config.serverUrl; } + if (config.trustedPublishingUser) { + expandedTarget.trustedPublishingUser = config.trustedPublishingUser; + } return expandedTarget; }); @@ -369,43 +404,137 @@ export class NugetTarget extends BaseTarget { * Extracts Nuget target options from the raw configuration */ protected getNugetConfig(): NugetTargetOptions { + const config = this.config as TypedTargetConfig; + const serverUrl = config.serverUrl || DEFAULT_NUGET_SERVER_URL; + + const trustedPublishingUser = + config.trustedPublishingUser || process.env[NUGET_USER_ENV_VAR]; + if (trustedPublishingUser) { + if (!getGitHubOidcRequest()) { + throw new ConfigurationError( + 'Cannot perform Nuget release: trusted publishing is enabled ' + + `("trustedPublishingUser" or ${NUGET_USER_ENV_VAR}), but GitHub Actions OIDC is not ` + + 'available. Run in GitHub Actions with the "id-token: write" permission.', + ); + } + // The temporary key is for nuget.org only; never send it to another feed. + if (serverUrl !== DEFAULT_NUGET_SERVER_URL) { + throw new ConfigurationError( + `Cannot perform Nuget release: trusted publishing only works with ` + + `${DEFAULT_NUGET_SERVER_URL}, but serverUrl is ${serverUrl}.`, + ); + } + return { trustedPublishingUser, serverUrl }; + } + if (!process.env.NUGET_API_TOKEN) { throw new ConfigurationError( `Cannot perform Nuget release: missing credentials. - Please use NUGET_API_TOKEN environment variable.`, + Please set "trustedPublishingUser" or ${NUGET_USER_ENV_VAR} (trusted publishing), or NUGET_API_TOKEN.`, ); } - const config = this.config as TypedTargetConfig; - return { - apiToken: process.env.NUGET_API_TOKEN, - serverUrl: config.serverUrl || DEFAULT_NUGET_SERVER_URL, - }; + return { apiToken: process.env.NUGET_API_TOKEN, serverUrl }; + } + + /** + * Returns the API key to push with: NUGET_API_TOKEN, or with trusted + * publishing, a temporary key that is renewed before it expires. + */ + private getApiKey(): Promise { + const { apiToken, trustedPublishingUser } = this.nugetConfig; + if (!trustedPublishingUser) { + return Promise.resolve(apiToken ?? ''); + } + if (!this.temporaryApiKey || Date.now() >= this.temporaryApiKey.expiresAt) { + this.temporaryApiKey = { + value: this.requestTemporaryApiKey(trustedPublishingUser), + expiresAt: Date.now() + TEMPORARY_API_KEY_MAX_AGE_MS, + }; + } + return this.temporaryApiKey.value; + } + + /** + * Exchanges a GitHub Actions OIDC token for a temporary nuget.org API key, + * as described in https://learn.microsoft.com/nuget/nuget-org/trusted-publishing + */ + private async requestTemporaryApiKey(user: string): Promise { + const oidcRequest = getGitHubOidcRequest(); + if (!oidcRequest) { + throw new Error('GitHub Actions OIDC is no longer available'); + } + const oidcToken = await getGitHubOidcToken( + oidcRequest, + NUGET_OIDC_AUDIENCE, + ); + + this.logger.info( + `Requesting a temporary NuGet API key for "${user}" with trusted publishing`, + ); + const response = await fetch(NUGET_TOKEN_SERVICE_URL, { + method: 'POST', + headers: { + Authorization: `Bearer ${oidcToken}`, + 'Content-Type': 'application/json', + 'User-Agent': 'getsentry/craft', + }, + body: JSON.stringify({ username: user, tokenType: 'ApiKey' }), + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + if (!response.ok) { + const details = (await response.text().catch(() => '')).slice(0, 500); + throw new Error( + `NuGet trusted publishing token exchange failed: HTTP ${response.status}` + + (details ? `: ${details}` : '') + + '\n\nCheck that a trusted publishing policy on nuget.org matches this repository, ' + + `workflow file and environment, and that "${user}" is the nuget.org user ` + + 'who created the policy, not the organization that owns it.', + ); + } + const { apiKey } = (await response.json()) as { apiKey?: string }; + if (!apiKey) { + throw new Error( + 'NuGet trusted publishing token exchange returned no API key', + ); + } + if (process.env.GITHUB_ACTIONS === 'true') { + // Keep the key out of the workflow logs, like NuGet/login does. + process.stdout.write(`::add-mask::${apiKey}\n`); + } + return apiKey; } /** * Uploads an archive to Nuget using "dotnet nuget" + * + * The key is passed as a `${...}` placeholder that spawnProcess fills in, + * so it never shows up in the logged command line. */ - public async uploadAsset(path: string): Promise { + public async uploadAsset(path: string, apiKey: string): Promise { const args = [ 'nuget', 'push', path, '--api-key', - '${NUGET_API_TOKEN}', + '${NUGET_API_KEY}', '--source', this.nugetConfig.serverUrl, '--timeout', '1800', ]; - return spawnProcess(NUGET_DOTNET_BIN, args, DOTNET_SPAWN_OPTIONS); + return spawnProcess(NUGET_DOTNET_BIN, args, { + ...DOTNET_SPAWN_OPTIONS, + env: { ...process.env, NUGET_API_KEY: apiKey }, + }); } /** * Pushes a file, adding a hint when NuGet rejects it as a duplicate. */ private async push(path: string): Promise { + const apiKey = await this.getApiKey(); try { - await this.uploadAsset(path); + await this.uploadAsset(path, apiKey); } catch (error) { const message = error instanceof Error ? error.message : String(error); if (/\b409\b|already (contains|exists)/i.test(message)) { diff --git a/src/utils/githubOidc.ts b/src/utils/githubOidc.ts new file mode 100644 index 00000000..6a06def5 --- /dev/null +++ b/src/utils/githubOidc.ts @@ -0,0 +1,48 @@ +const REQUEST_TIMEOUT_MS = 30_000; + +/** Credentials GitHub Actions exposes when the job has `id-token: write` */ +interface GitHubOidcRequest { + url: string; + token: string; +} + +/** + * Returns the GitHub Actions OIDC request credentials, or undefined when the + * job does not have the `id-token: write` permission (or isn't on Actions). + */ +export function getGitHubOidcRequest(): GitHubOidcRequest | undefined { + const url = process.env.ACTIONS_ID_TOKEN_REQUEST_URL; + const token = process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN; + return url && token ? { url, token } : undefined; +} + +/** + * Requests a GitHub Actions OIDC token for the given audience. + * + * @param request Credentials from {@link getGitHubOidcRequest} + * @param audience The `aud` claim the receiving service checks + */ +export async function getGitHubOidcToken( + request: GitHubOidcRequest, + audience: string, +): Promise { + const url = new URL(request.url); + url.searchParams.set('audience', audience); + const response = await fetch(url, { + headers: { + Accept: 'application/json', + Authorization: `Bearer ${request.token}`, + }, + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + if (!response.ok) { + throw new Error( + `GitHub OIDC token request failed: HTTP ${response.status}`, + ); + } + const { value } = (await response.json()) as { value?: string }; + if (!value) { + throw new Error('GitHub OIDC token response has no token'); + } + return value; +}