Skip to content

Commit c26d708

Browse files
sosobanlf
andauthored
fix: validate username at get-identity (#5884)
Fix for #5867 (prevent undefined username) Co-authored-by: nlf <nlf@github.com>
1 parent 80c6c4a commit c26d708

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

lib/utils/get-identity.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ module.exports = async (npm, opts) => {
1212
// No username, but we have other credentials; fetch the username from registry
1313
if (creds.token || creds.certfile && creds.keyfile) {
1414
const registryData = await npmFetch.json('/-/whoami', { ...opts })
15-
return registryData.username
15+
if (typeof registryData?.username === 'string') {
16+
return registryData.username
17+
}
1618
}
1719

1820
// At this point, even if they have a credentials object, it doesn't have a

test/lib/commands/whoami.js

+25
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const t = require('tap')
22
const { load: loadMockNpm } = require('../../fixtures/mock-npm')
33
const MockRegistry = require('@npmcli/mock-registry')
4+
const nock = require('nock')
45

56
const username = 'foo'
67
const auth = { '//registry.npmjs.org/:_authToken': 'test-auth-token' }
@@ -67,3 +68,27 @@ t.test('not logged in', async t => {
6768
})
6869
await t.rejects(npm.exec('whoami', []), { code: 'ENEEDAUTH' })
6970
})
71+
72+
t.test('non-string username in response', async t => {
73+
nock.disableNetConnect()
74+
t.teardown(() => {
75+
nock.enableNetConnect()
76+
})
77+
78+
const server = nock('https://registry.npmjs.org', {
79+
reqheaders: {
80+
authorization: 'Bearer abcd1234',
81+
},
82+
})
83+
.get('/-/whoami')
84+
.reply(200, { username: null })
85+
86+
const { npm } = await loadMockNpm(t, {
87+
config: {
88+
'//registry.npmjs.org/:_authToken': 'abcd1234',
89+
},
90+
})
91+
92+
await t.rejects(npm.exec('whoami', []), { code: 'ENEEDAUTH' })
93+
t.ok(server.isDone())
94+
})

0 commit comments

Comments
 (0)