Skip to content

Commit 9741b64

Browse files
reggiCopilot
andauthored
feat(dist-tag): support OIDC authentication (#10038)
## Summary - Add OIDC authentication to dist-tag add, remove, and list operations, including scoped registries and workspace listing. - Keep exchanged tokens in the non-persistable CLI config layer and clear the previous token before each subsequent OIDC attempt, preventing failed exchanges from reusing another package's token. - Keep automatic provenance configuration specific to publishing, and invalidate cached flat options when deleting configuration values. - Add coverage for provider exchanges, fallback credentials, workspace token isolation, provenance exclusion, and config cache invalidation. ## Notable bug fix: workspace OIDC token reuse During a single `npm publish --workspaces` invocation, a successful OIDC exchange for workspace A could leave its package-specific token in shared configuration. If workspace B's exchange failed, npm could incorrectly fall back to A's token instead of the original credentials or reporting `ENEEDAUTH` when no credentials were available. This PR clears the previous exchanged token before every subsequent OIDC attempt, including attempts that fail or are skipped. Exchanged tokens now use the `cli` config namespace instead of `user`. The `cli` layer is non-persistable, so temporary tokens do not overwrite user credentials (in memory) and cannot be included when saving user configuration. Token deletion also invalidates cached flat options so a stale copy cannot remain available to subsequent operations. ## Validation All 1,439 assertions passed: 422 across the affected OIDC and command tests, plus 1,017 in the config workspace. ```sh node node_modules/tap/bin/run.js --no-coverage --reporter=classic test/lib/utils/oidc.js test/lib/commands/dist-tag.js test/lib/commands/publish.js test/lib/commands/stage/index.js (cd workspaces/config && node ../../node_modules/tap/bin/run.js --no-coverage --reporter=classic test) ``` The workspace token-reuse and config cache regression tests were also verified to fail against the existing implementation with the fixes stashed. --------- Co-authored-by: Copilot <[email protected]> Copilot-Session: 15207d1d-40b3-4973-9371-b7aba1e286fb Copilot-Session: 18971883-024d-4f5a-b531-4eeaa0af80b3
1 parent 0c3b82a commit 9741b64

11 files changed

Lines changed: 893 additions & 9 deletions

File tree

‎lib/commands/dist-tag.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ const npmFetch = require('npm-registry-fetch')
33
const semver = require('semver')
44
const { log, output } = require('proc-log')
55
const { otplease } = require('../utils/auth.js')
6+
const { oidc } = require('../utils/oidc.js')
67
const pkgJson = require('@npmcli/package-json')
78
const BaseCommand = require('../base-cmd.js')
89

@@ -101,6 +102,7 @@ class DistTag extends BaseCommand {
101102
throw new Error('Tag name must not be a valid SemVer range: ' + t)
102103
}
103104

105+
await this.#oidc(spec, opts)
104106
const tags = await this.fetchTags(spec, opts)
105107
if (tags[t] === version) {
106108
log.warn('dist-tag add', t, 'is already set to version', version)
@@ -130,6 +132,7 @@ class DistTag extends BaseCommand {
130132
throw this.usageError()
131133
}
132134

135+
await this.#oidc(spec, opts)
133136
const tags = await this.fetchTags(spec, opts)
134137
if (!tags[tag]) {
135138
log.info('dist-tag del', tag, 'is not a dist-tag on', spec.name)
@@ -163,6 +166,7 @@ class DistTag extends BaseCommand {
163166
spec = npa(spec)
164167

165168
try {
169+
await this.#oidc(spec, opts)
166170
const tags = await this.fetchTags(spec, opts)
167171
const msg =
168172
Object.keys(tags).map(k => `${k}: ${tags[k]}`).sort().join('\n')
@@ -202,6 +206,16 @@ class DistTag extends BaseCommand {
202206

203207
return data
204208
}
209+
210+
async #oidc (spec, opts) {
211+
const registry = npmFetch.pickRegistry(spec, opts)
212+
await oidc({
213+
packageName: spec.name,
214+
registry,
215+
opts,
216+
config: this.npm.config,
217+
})
218+
}
205219
}
206220

207221
module.exports = DistTag

‎lib/commands/publish.js‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,13 @@ class Publish extends BaseCommand {
149149

150150
const registry = npmFetch.pickRegistry(resolved, opts)
151151

152-
await oidc({ packageName: manifest.name, registry, opts, config: this.npm.config })
152+
await oidc({
153+
packageName: manifest.name,
154+
registry,
155+
opts,
156+
config: this.npm.config,
157+
enableProvenanceAutoConfiguration: true,
158+
})
153159

154160
const creds = this.npm.config.getCredentialsByURI(registry)
155161
const noCreds = !(creds.token || creds.username || creds.certfile && creds.keyfile)

‎lib/utils/oidc.js‎

Lines changed: 84 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,62 @@ const fetch = require('make-fetch-happen')
55
const npa = require('npm-package-arg')
66
const libaccess = require('libnpmaccess')
77

8+
/**
9+
* Caches the runtime state of the active OIDC token exchange
10+
* so it can be cleared on subsequent OIDC attempts in workflows
11+
* that run OIDC multiple times within one runtime execution,
12+
* preventing the previous exchange token from being reused.
13+
*/
14+
let activeExchangeRecord
15+
16+
const setOidcToken = ({ config, opts, authTokenKey, token }) => {
17+
activeExchangeRecord = {
18+
config,
19+
authTokenKey,
20+
token,
21+
previousCliToken: config.get(authTokenKey, 'cli'),
22+
opts,
23+
previousOptsToken: opts[authTokenKey],
24+
}
25+
opts[authTokenKey] = token
26+
config.set(authTokenKey, token, 'cli')
27+
log.verbose('oidc', 'Successfully retrieved and set token')
28+
}
29+
30+
const clearOidcToken = ({ config, opts }) => {
31+
if (!activeExchangeRecord) {
32+
return
33+
}
34+
35+
const {
36+
config: previousConfig,
37+
authTokenKey,
38+
token,
39+
previousCliToken,
40+
opts: previousOpts,
41+
previousOptsToken,
42+
} = activeExchangeRecord
43+
if (previousConfig.get(authTokenKey, 'cli') === token) {
44+
if (previousCliToken === undefined) {
45+
previousConfig.delete(authTokenKey, 'cli')
46+
} else {
47+
previousConfig.set(authTokenKey, previousCliToken, 'cli')
48+
}
49+
}
50+
for (const requestOpts of new Set([previousOpts, opts])) {
51+
if (requestOpts[authTokenKey] === token) {
52+
const fallback = requestOpts === previousOpts ? previousOptsToken : config.get(authTokenKey)
53+
if (fallback === undefined) {
54+
delete requestOpts[authTokenKey]
55+
} else {
56+
requestOpts[authTokenKey] = fallback
57+
}
58+
}
59+
}
60+
activeExchangeRecord = undefined
61+
log.verbose('oidc', 'Cleared previous exchange token')
62+
}
63+
864
/**
965
* Handles OpenID Connect (OIDC) token retrieval and exchange for CI environments.
1066
*
@@ -13,18 +69,35 @@ const libaccess = require('libnpmaccess')
1369
*
1470
* This function is intended to never throw, as it mutates the state of the `opts` and `config` objects on success.
1571
* OIDC is always an optional feature, and the function should not throw if OIDC is not configured by the registry.
72+
* Before each attempt, it restores credentials replaced by the previous exchange so package-specific tokens are never used as fallback credentials.
1673
*
1774
* @see https://github.com/watson/ci-info for CI environment detection.
1875
* @see https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect for GitHub Actions OIDC.
1976
* @see https://circleci.com/docs/openid-connect-tokens/ for CircleCI OIDC.
2077
*/
21-
async function oidc ({ packageName, registry, opts, config }) {
78+
async function oidc ({
79+
// Selects the package-specific npm token exchange endpoint.
80+
packageName,
81+
// Determines the OIDC audience, exchange host, and registry-scoped auth key.
82+
registry,
83+
// Mutable request options for the current command, often called flatOptions.
84+
// The exchanged token is added here so subsequent registry requests use it immediately.
85+
opts,
86+
// npm's live configuration state. This is also updated so credential lookups see the token.
87+
config,
88+
// Publish and stage publish can infer provenance from trusted-publishing claims and package
89+
// visibility so users do not need to set --provenance. Other commands that use OIDC, such as
90+
// npm dist-tag, only need token exchange and must not enable unrelated publish provenance.
91+
enableProvenanceAutoConfiguration = false,
92+
}) {
2293
/*
2394
* This code should never run when people try to publish locally on their machines.
2495
* It is designed to execute only in Continuous Integration (CI) environments.
2596
*/
2697

2798
try {
99+
clearOidcToken({ config, opts })
100+
28101
if (!(
29102
/** @see https://github.com/watson/ci-info/blob/v4.2.0/vendors.json#L152 */
30103
ciInfo.GITHUB_ACTIONS ||
@@ -133,13 +206,17 @@ async function oidc ({ packageName, registry, opts, config }) {
133206
}
134207

135208
/*
136-
* The "opts" object is a clone of npm.flatOptions and is passed through the `publish` command, eventually reaching `otplease`.
137-
* To ensure the token is accessible during the publishing process, it must be directly attached to the `opts` object.
138-
* Additionally, the token is required by the "live" configuration or getters within `config`.
209+
* `opts` is derived from npm.flatOptions and carried through the current command.
210+
* Publish and dist-tag pass it to later registry requests, including mutations wrapped by
211+
* `otplease`, so the exchanged token must be attached directly to this object.
212+
* The non-persistable cli layer also makes the token available to credential lookups without
213+
* modifying any file-backed configuration.
139214
*/
140-
opts[authTokenKey] = response.token
141-
config.set(authTokenKey, response.token, 'user')
142-
log.verbose('oidc', `Successfully retrieved and set token`)
215+
setOidcToken({ config, opts, authTokenKey, token: response.token })
216+
217+
if (!enableProvenanceAutoConfiguration) {
218+
return undefined
219+
}
143220

144221
try {
145222
const isDefaultProvenance = config.isDefault('provenance')

‎test/fixtures/mock-oidc.js‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ const mockOidc = async (t, {
5454
mockGithubOidcOptions = false,
5555
mockOidcTokenExchangeOptions = false,
5656
publishOptions = {},
57+
publish = true,
5758
provenance = false,
5859
oidcVisibilityOptions = false,
5960
}) => {
@@ -139,7 +140,9 @@ const mockOidc = async (t, {
139140
registry.getVisibility({ spec: packageName, visibility: oidcVisibilityOptions })
140141
}
141142

142-
registry.publish(packageName, publishOptions)
143+
if (publish) {
144+
registry.publish(packageName, publishOptions)
145+
}
143146

144147
/**
145148
* this will nock / mock all the successful requirements for provenance and

0 commit comments

Comments
 (0)