Skip to content

Commit

Permalink
fix: validate username at get-identity (#5884)
Browse files Browse the repository at this point in the history
Fix for #5867 (prevent undefined username)

Co-authored-by: nlf <nlf@github.com>
  • Loading branch information
sosoba and nlf committed Nov 30, 2022
1 parent 80c6c4a commit c26d708
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/utils/get-identity.js
Expand Up @@ -12,7 +12,9 @@ module.exports = async (npm, opts) => {
// No username, but we have other credentials; fetch the username from registry
if (creds.token || creds.certfile && creds.keyfile) {
const registryData = await npmFetch.json('/-/whoami', { ...opts })
return registryData.username
if (typeof registryData?.username === 'string') {
return registryData.username
}
}

// At this point, even if they have a credentials object, it doesn't have a
Expand Down
25 changes: 25 additions & 0 deletions test/lib/commands/whoami.js
@@ -1,6 +1,7 @@
const t = require('tap')
const { load: loadMockNpm } = require('../../fixtures/mock-npm')
const MockRegistry = require('@npmcli/mock-registry')
const nock = require('nock')

const username = 'foo'
const auth = { '//registry.npmjs.org/:_authToken': 'test-auth-token' }
Expand Down Expand Up @@ -67,3 +68,27 @@ t.test('not logged in', async t => {
})
await t.rejects(npm.exec('whoami', []), { code: 'ENEEDAUTH' })
})

t.test('non-string username in response', async t => {
nock.disableNetConnect()
t.teardown(() => {
nock.enableNetConnect()
})

const server = nock('https://registry.npmjs.org', {
reqheaders: {
authorization: 'Bearer abcd1234',
},
})
.get('/-/whoami')
.reply(200, { username: null })

const { npm } = await loadMockNpm(t, {
config: {
'//registry.npmjs.org/:_authToken': 'abcd1234',
},
})

await t.rejects(npm.exec('whoami', []), { code: 'ENEEDAUTH' })
t.ok(server.isDone())
})

0 comments on commit c26d708

Please sign in to comment.