Skip to content

fix: Validate username at get-identity #5884

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 30, 2022
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
4 changes: 3 additions & 1 deletion lib/utils/get-identity.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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())
})