Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion docs/src/content/docs/targets/nuget.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
226 changes: 224 additions & 2 deletions src/targets/__tests__/nuget.test.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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({
Expand All @@ -188,13 +188,15 @@ 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');

expect(result).toHaveLength(1);
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 () => {
Expand Down Expand Up @@ -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<string, unknown> = {},
): 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([]);
});
});
45 changes: 9 additions & 36 deletions src/targets/mcpRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -365,11 +366,15 @@ export class McpRegistryTarget extends BaseTarget {
* `id-token: write`, otherwise exchanges `MCP_GITHUB_TOKEN`.
*/
private async getRegistryToken(): Promise<string> {
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 });
}

Expand All @@ -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<string> {
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',
Expand Down
Loading
Loading