Debian Codegraph @

mock-registry/lib/index.js

raw
1 const Arborist = require('@npmcli/arborist')
2 const Nock = require('nock')
3 const npa = require('npm-package-arg')
4 const pacote = require('pacote')
5 const path = require('node:path')
6 const stringify = require('json-stringify-safe')
7
8 const { createReadStream } = require('node:fs')
9 const fs = require('node:fs/promises')
10
11 const corgiDoc = 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*'
12
13 const logReq = (req, ...keys) => {
14 const obj = JSON.parse(stringify(req))
15 const res = {}
16 for (const [k, v] of Object.entries(obj)) {
17 if (!keys.includes(k)) {
18 res[k] = v
19 }
20 }
21 return stringify(res, null, 2)
22 }
23
24 // helper to convert old audit results to new bulk results
25 // TODO eventually convert the fixture files themselves
26 const auditToBulk = audit => {
27 const bulk = {}
28 for (const advisory in audit.advisories) {
29 const {
30 id,
31 url,
32 title,
33 severity = 'high',
34 /* eslint-disable-next-line camelcase */
35 vulnerable_versions = '*',
36 module_name: name,
37 } = audit.advisories[advisory]
38 bulk[name] = bulk[name] || []
39 /* eslint-disable-next-line camelcase */
40 bulk[name].push({ id, url, title, severity, vulnerable_versions })
41 }
42 return bulk
43 }
44
45 class MockRegistry {
46 #tap
47 #nock
48 #registry
49 #authorization
50 #basic
51 #debug
52 #strict
53
54 constructor (opts) {
55 if (!opts.registry) {
56 throw new Error('mock registry requires a registry value')
57 }
58 this.#registry = new URL(opts.registry)
59 this.#authorization = opts.authorization
60 this.#basic = opts.basic
61 this.#debug = opts.debug
62 this.#strict = opts.strict
63 // Required for this.package
64 this.#tap = opts.tap
65 if (this.#tap) {
66 this.startNock()
67 }
68 }
69
70 static tnock (t, host, opts, { debug = false, strict = false } = {}) {
71 const noMatch = (req) => {
72 if (debug) {
73 /* eslint-disable-next-line no-console */
74 console.error('NO MATCH', t.name, req.options ? req.options : req.path)
75 }
76 if (strict) {
77 // There are network requests that get caught regardless of error code.
78 // Turning on strict mode requires that those requests get explicitly
79 // mocked with a 404, 500, etc.
80 // XXX: this is opt-in currently because it breaks some existing CLI
81 // tests. We should work towards making this the default for all tests.
82 t.comment(logReq(req, 'interceptors', 'socket', 'response', '_events'))
83 const protocol = req?.options?.protocol || 'http:'
84 const hostname = req?.options?.hostname || req?.hostname || 'localhost'
85 const p = req?.path || '/'
86 const url = new URL(p, `${protocol}//${hostname}`).toString()
87 t.fail(`Unmatched request: ${req.method} ${url}`)
88 }
89 }
90
91 Nock.emitter.on('no match', noMatch)
92 Nock.disableNetConnect()
93 const server = Nock(host, opts)
94
95 if (strict) {
96 // this requires that mocks not be shared between sub tests but it helps
97 // find mistakes quicker instead of waiting for the entire test to end
98 t.afterEach((t) => {
99 t.strictSame(server.pendingMocks(), [], 'no pending mocks after each')
100 })
101 }
102
103 t.teardown(() => {
104 Nock.enableNetConnect()
105 server.done()
106 Nock.emitter.off('no match', noMatch)
107 Nock.cleanAll()
108 })
109
110 return server
111 }
112
113 get origin () {
114 return this.#registry.origin
115 }
116
117 get pathname () {
118 if (this.#registry.pathname.endsWith('/')) {
119 return this.#registry.pathname.slice(0, -1)
120 }
121 return this.#registry.pathname
122 }
123
124 get nock () {
125 return this.#nock
126 }
127
128 set nock (nock) {
129 this.#nock = nock
130 }
131
132 startNock () {
133 if (this.nock) {
134 return
135 }
136
137 if (!this.#tap) {
138 throw new Error('cannot mock packages without a tap fixture')
139 }
140
141 const reqheaders = {}
142 if (this.#authorization) {
143 reqheaders.authorization = `Bearer ${this.#authorization}`
144 }
145 if (this.#basic) {
146 reqheaders.authorization = `Basic ${this.#basic}`
147 }
148
149 this.nock = MockRegistry.tnock(
150 this.#tap,
151 this.origin,
152 { reqheaders },
153 { debug: this.#debug, strict: this.#strict }
154 )
155 }
156
157 fullPath (uri) {
158 return `${this.pathname}${uri}`
159 }
160
161 search ({ responseCode = 200, results = [], error }) {
162 // the flags, score, and searchScore parts of the response are never used
163 // by npm, only package is used
164 const response = results.map(p => ({ package: p }))
165 this.nock = this.nock.get(this.fullPath(`/-/v1/search`)).query(true)
166 if (error) {
167 this.nock = this.nock.replyWithError(error)
168 } else {
169 this.nock = this.nock.reply(responseCode, { objects: response })
170 }
171 return this.nock
172 }
173
174 whoami ({ username, body, responseCode = 200, times = 1 }) {
175 if (username) {
176 this.nock = this.nock.get(this.fullPath('/-/whoami')).times(times)
177 .reply(responseCode, { username })
178 } else {
179 this.nock = this.nock.get(this.fullPath('/-/whoami')).times(times)
180 .reply(responseCode, body)
181 }
182 }
183
184 setAccess ({ spec, body = {} }) {
185 this.nock = this.nock.post(
186 this.fullPath(`/-/package/${npa(spec).escapedName}/access`),
187 body
188 ).reply(200)
189 }
190
191 getVisibility ({ spec, visibility, responseCode = 200 }) {
192 this.nock = this.nock.get(
193 this.fullPath(`/-/package/${npa(spec).escapedName}/visibility`))
194 .reply(responseCode, visibility)
195 }
196
197 setPermissions ({ spec, team, permissions }) {
198 if (team.startsWith('@')) {
199 team = team.slice(1)
200 }
201 const [scope, teamName] = team.split(':')
202 this.nock = this.nock.put(
203 this.fullPath(`/-/team/${encodeURIComponent(scope)}/${encodeURIComponent(teamName)}/package`),
204 { package: spec, permissions }
205 ).reply(200)
206 }
207
208 removePermissions ({ spec, team }) {
209 if (team.startsWith('@')) {
210 team = team.slice(1)
211 }
212 const [scope, teamName] = team.split(':')
213 this.nock = this.nock.delete(
214 this.fullPath(`/-/team/${encodeURIComponent(scope)}/${encodeURIComponent(teamName)}/package`),
215 { package: spec }
216 ).reply(200)
217 }
218
219 couchuser ({ username, body, responseCode = 200 }) {
220 if (body) {
221 this.nock = this.nock.get(
222 this.fullPath(`/-/user/org.couchdb.user:${encodeURIComponent(username)}`)
223 ).reply(responseCode, body)
224 } else {
225 this.nock = this.nock.get(
226 this.fullPath(`/-/user/org.couchdb.user:${encodeURIComponent(username)}`)
227 ).reply(responseCode, { _id: `org.couchdb.user:${username}`, email: '', name: username })
228 }
229 }
230
231 couchadduser ({ username, email, password, token = 'npm_default-test-token' }) {
232 this.nock = this.nock.put(this.fullPath(`/-/user/org.couchdb.user:${username}`), body => {
233 this.#tap.match(body, {
234 _id: `org.couchdb.user:${username}`,
235 name: username,
236 email, // Sole difference from couchlogin
237 password,
238 type: 'user',
239 roles: [],
240 })
241 if (!body.date) {
242 return false
243 }
244 return true
245 }).reply(201, {
246 id: 'org.couchdb.user:undefined',
247 rev: '_we_dont_use_revs_any_more',
248 token,
249 })
250 }
251
252 couchlogin ({ username, password, token = 'npm_default-test-token' }) {
253 this.nock = this.nock.put(this.fullPath(`/-/user/org.couchdb.user:${username}`), body => {
254 this.#tap.match(body, {
255 _id: `org.couchdb.user:${username}`,
256 name: username,
257 password,
258 type: 'user',
259 roles: [],
260 })
261 if (!body.date) {
262 return false
263 }
264 return true
265 }).reply(201, {
266 id: 'org.couchdb.user:undefined',
267 rev: '_we_dont_use_revs_any_more',
268 token,
269 })
270 }
271
272 webadduser ({ token = 'npm_default-test-token' }) {
273 const doneUrl = new URL('/npm-cli-test/done', this.origin).href
274 const loginUrl = new URL('/npm-cli-test/login', this.origin).href
275 this.nock = this.nock
276 .post(this.fullPath('/-/v1/login'), body => {
277 this.#tap.ok(body.create) // Sole difference from weblogin
278 return true
279 })
280 .reply(200, { doneUrl, loginUrl })
281 .get('/npm-cli-test/done')
282 .reply(200, { token })
283 }
284
285 weblogin ({ token = 'npm_default-test-token' }) {
286 const doneUrl = new URL('/npm-cli-test/done', this.origin).href
287 const loginUrl = new URL('/npm-cli-test/login/cli/00000000-0000-0000-0000-000000000000', this.origin).href
288 this.nock = this.nock
289 .post(this.fullPath('/-/v1/login'), () => {
290 return true
291 })
292 .reply(200, { doneUrl, loginUrl })
293 .get('/npm-cli-test/done')
294 .reply(200, { token })
295 }
296
297 logout (token) {
298 this.nock = this.nock.delete(this.fullPath(`/-/user/token/${encodeURIComponent(token)}`))
299 .reply(200, { ok: true })
300 }
301
302 // team can be a team or a username
303 getPackages ({ user, team, packages = {}, times = 1, responseCode = 200 }) {
304 let uri
305 if (user) {
306 uri = `/-/user/${user}/package`
307 } else {
308 if (team.startsWith('@')) {
309 team = team.slice(1)
310 }
311 const [scope, teamName] = team.split(':').map(encodeURIComponent)
312 if (teamName) {
313 uri = `/-/team/${scope}/${teamName}/package`
314 } else {
315 uri = `/-/org/${scope}/package`
316 }
317 }
318 this.nock = this.nock.get(this.fullPath(uri)).times(times).reply(responseCode, packages)
319 }
320
321 getCollaborators ({ spec, collaborators = {} }) {
322 this.nock = this.nock.get(this.fullPath(`/-/package/${npa(spec).escapedName}/collaborators`)
323 ).reply(200, collaborators)
324 }
325
326 advisory (advisory = {}) {
327 const id = advisory.id || parseInt(Math.random() * 1000000)
328 return {
329 id,
330 url: `https://github.com/advisories/GHSA-${id}`,
331 title: `Test advisory ${id}`,
332 severity: 'high',
333 vulnerable_versions: '*',
334 cwe: [
335 'cwe-0',
336 ],
337 cvss: {
338 score: 0,
339 },
340 ...advisory,
341 }
342 }
343
344 star (manifest, users) {
345 const spec = npa(manifest.name)
346 this.nock = this.nock.put(this.fullPath(`/${spec.escapedName}`), {
347 _id: manifest._id,
348 _rev: manifest._rev,
349 users,
350 }).reply(200, { ...manifest, users })
351 }
352
353 ping ({ body = {}, responseCode = 200 } = {}) {
354 this.nock = this.nock.get(this.fullPath('/-/ping')).reply(responseCode, body)
355 }
356
357 // full unpublish of an entire package
358 unpublish ({ manifest }) {
359 let nock = this.nock
360 const spec = npa(manifest.name)
361 nock = nock.delete(this.fullPath(`/${spec.escapedName}/-rev/${manifest._rev}`)).reply(201)
362 return nock
363 }
364
365 publish (name, {
366 packageJson, access, noGet, noPut, putCode, manifest, packuments, token,
367 } = {}) {
368 if (!noGet) {
369 // this getPackage call is used to get the latest semver version before publish
370 if (manifest) {
371 this.getPackage(name, { code: 200, resp: manifest })
372 } else if (packuments) {
373 this.getPackage(name, { code: 200, resp: this.manifest({ name, packuments }) })
374 } else {
375 // assumes the package does not exist yet and will 404 x2 from pacote.manifest
376 this.getPackage(name, { times: 2, code: 404 })
377 }
378 }
379 if (!noPut) {
380 this.putPackage(name, { code: putCode, packageJson, access, token })
381 }
382 }
383
384 getPackage (name, { times = 1, code = 200, query, resp = {} }) {
385 let nock = this.nock
386 nock = nock.get(`/${npa(name).escapedName}`).times(times)
387 if (query) {
388 nock = nock.query(query)
389 }
390 if (code === 404) {
391 nock = nock.reply(code, { error: 'Not found' })
392 } else {
393 nock = nock.reply(code, resp)
394 }
395 this.nock = nock
396 }
397
398 putPackage (name, { code = 200, resp = {}, token, ...putPackagePayload }) {
399 let n = this.nock.put(`/${npa(name).escapedName}`, body => {
400 return this.#tap.match(body, this.putPackagePayload({ name, ...putPackagePayload }))
401 })
402 if (token) {
403 n = n.matchHeader('authorization', `Bearer ${token}`)
404 }
405 n.reply(code, resp)
406 }
407
408 putPackagePayload (opts) {
409 const pkg = opts.packageJson
410 const name = opts.name || pkg?.name
411 const registry = opts.registry || pkg?.publishConfig?.registry || 'https://registry.npmjs.org'
412 const access = opts.access || null
413
414 const nameProperties = !name ? {} : {
415 _id: name,
416 name: name,
417 }
418
419 const packageProperties = !pkg ? {} : {
420 'dist-tags': { latest: pkg.version },
421 versions: {
422 [pkg.version]: {
423 _id: `${pkg.name}@${pkg.version}`,
424 dist: {
425 shasum: /\.*/,
426 tarball:
427 `http://${new URL(registry).host}/${pkg.name}/-/${pkg.name}-${pkg.version}.tgz`,
428 },
429 ...pkg,
430 },
431 },
432 _attachments: {
433 [`${pkg.name}-${pkg.version}.tgz`]: {},
434 },
435 }
436
437 return {
438 access,
439 ...nameProperties,
440 ...packageProperties,
441 }
442 }
443
444 getTokens (tokens) {
445 return this.nock.get(this.fullPath('/-/npm/v1/tokens'))
446 .reply(200, {
447 objects: tokens,
448 urls: {},
449 total: tokens.length,
450 userHasOldFormatToken: false,
451 })
452 }
453
454 // The server has rules for what resultData correlates with what tokenData but we don't need to be 100% in sync with that, we just need to be able to pass all of the possible tokenData attributes, and be able to accept all of the possible resultData attributes
455 createToken (tokenData, resultData = {}) {
456 return this.nock.post(this.fullPath('/-/npm/v1/tokens'), tokenData)
457 .reply(201, {
458 id: `0xdeadbeef`,
459 key: 'n3wk3y',
460 token: 'n3wt0k3n',
461 created: new Date(),
462 updated: new Date(),
463 access: 'read-only',
464 name: tokenData.name,
465 password: tokenData.password,
466 ...resultData,
467 })
468 }
469
470 revokeToken (token) {
471 return this.nock.delete(
472 this.fullPath(`/-/npm/v1/tokens/token/${token}`)
473 ).reply(200)
474 }
475
476 async package ({ manifest, times = 1, query, tarballs }) {
477 let nock = this.nock
478 const spec = npa(manifest.name)
479 nock = nock.get(this.fullPath(`/${spec.escapedName}`)).times(times)
480 if (query) {
481 nock = nock.query(query)
482 }
483 nock = nock.reply(200, manifest)
484 if (tarballs) {
485 for (const [version, tarball] of Object.entries(tarballs)) {
486 const m = manifest.versions[version]
487 nock = await this.tarball({ manifest: m, tarball })
488 }
489 }
490 this.nock = nock
491 }
492
493 async tarball ({ manifest, tarball }) {
494 const nock = this.nock
495 const dist = new URL(manifest.dist.tarball)
496 const tar = await pacote.tarball(tarball, { Arborist })
497 nock.get(this.fullPath(dist.pathname)).reply(200, tar)
498 return nock
499 }
500
501 // either pass in packuments if you need to set specific attributes besides version,
502 // or an array of versions
503 // the last packument in the packuments or versions array will be tagged latest
504 manifest ({ name = 'test-package', users, packuments, versions } = {}) {
505 packuments = this.packuments(versions || packuments, name)
506 const latest = packuments.slice(-1)[0]
507 const manifest = {
508 _id: `${name}@${latest.version}`,
509 _rev: '00-testdeadbeef',
510 name,
511 description: 'test package mock manifest',
512 dependencies: {},
513 versions: {},
514 time: {},
515 'dist-tags': { latest: latest.version },
516 ...latest,
517 }
518 if (users) {
519 manifest.users = users
520 }
521 for (const packument of packuments) {
522 const unscoped = name.includes('/') ? name.split('/')[1] : name
523 manifest.versions[packument.version] = {
524 _id: `${name}@${packument.version}`,
525 name,
526 description: 'test package mock manifest',
527 dependencies: {},
528 dist: {
529 /* eslint-disable-next-line max-len */
530 tarball: `${this.origin}${this.fullPath(`/${name}/-/${unscoped}-${packument.version}.tgz`)}`,
531 },
532 maintainers: [],
533 ...packument,
534 }
535 manifest.time[packument.version] = new Date()
536 }
537
538 return manifest
539 }
540
541 packuments (packuments = ['1.0.0'], name) {
542 return packuments.map(p => this.packument(p, name))
543 }
544
545 // Generate packument from shorthand
546 packument (packument, name = 'test-package') {
547 if (!packument.version) {
548 packument = { version: packument }
549 }
550 return {
551 name,
552 version: '1.0.0',
553 description: 'mocked test package',
554 dependencies: {},
555 ...packument,
556 }
557 }
558
559 // bulk advisory audit endpoint
560 audit ({ responseCode = 200, results = {}, convert = false, times = 1 } = {}) {
561 this.nock = this.nock
562 .post(this.fullPath('/-/npm/v1/security/advisories/bulk'))
563 .times(times)
564 .reply(
565 responseCode,
566 convert ? auditToBulk(results) : results
567 )
568 }
569
570 // Used in Arborist to mock the registry from fixture data on disk
571 // Will eat up all GET requests to the entire registry, so it probably doesn't work with the other GET routes very well.
572 mocks ({ dir }) {
573 const exists = (p) => fs.stat(p).then((s) => s).catch(() => false)
574 this.nock = this.nock.get(/.*/).reply(async function () {
575 const { headers, path: url } = this.req
576 const isCorgi = headers.accept.includes('application/vnd.npm.install-v1+json')
577 const encodedUrl = url.replace(/@/g, '').replace(/%2f/gi, '/')
578 const f = path.join(dir, 'registry-mocks', 'content', encodedUrl)
579 let file = f
580 let contentType = 'application/octet-stream'
581 if (isCorgi && await exists(`${f}.min.json`)) {
582 file = `${f}.min.json`
583 contentType = corgiDoc
584 } else if (await exists(`${f}.json`)) {
585 file = `${f}.json`
586 contentType = 'application/json'
587 } else if (await exists(`${f}/index.json`)) {
588 file = `${f}index.json`
589 contentType = 'application/json'
590 }
591 const stats = await exists(file)
592 if (stats) {
593 const body = createReadStream(file)
594 body.pause()
595 return [200, body, { 'content-type': contentType, 'content-length': stats.size }]
596 }
597 return [404, { error: 'not found' }]
598 }).persist()
599 }
600
601 /**
602 * this is a simpler convenience method for creating mockable registry with
603 * tarballs for specific versions
604 */
605 async setup (packages) {
606 const format = Object.keys(packages).map(v => {
607 const [name, version] = v.split('@')
608 return { name, version }
609 }).reduce((acc, inc) => {
610 const exists = acc.find(pkg => pkg.name === inc.name)
611 if (exists) {
612 exists.tarballs = {
613 ...exists.tarballs,
614 [inc.version]: packages[`${inc.name}@${inc.version}`],
615 }
616 } else {
617 acc.push({ name: inc.name,
618 tarballs: {
619 [inc.version]: packages[`${inc.name}@${inc.version}`],
620 },
621 })
622 }
623 return acc
624 }, [])
625 const registry = this
626 for (const pkg of format) {
627 const { name, tarballs } = pkg
628 const versions = Object.keys(tarballs)
629 const manifest = await registry.manifest({ name, versions })
630
631 for (const version of versions) {
632 const tarballPath = pkg.tarballs[version]
633 if (!tarballPath) {
634 throw new Error(`Tarball path not provided for version ${version}`)
635 }
636
637 await registry.tarball({
638 manifest: manifest.versions[version],
639 tarball: tarballPath,
640 })
641 }
642 }
643 }
644
645 mockOidcTokenExchange ({ packageName, idToken, statusCode = 200, body } = {}) {
646 const encodedPackageName = npa(packageName).escapedName
647 this.nock.post(this.fullPath(`/-/npm/v1/oidc/token/exchange/package/${encodedPackageName}`))
648 .matchHeader('authorization', `Bearer ${idToken}`)
649 .reply(statusCode, body || {})
650 }
651
652 // Trust API methods
653 trustList ({ packageName, responseCode = 200, body = [] }) {
654 const spec = npa(packageName)
655 this.nock = this.nock.get(this.fullPath(`/-/package/${spec.escapedName}/trust`))
656 .reply(responseCode, body)
657 }
658
659 trustCreate ({ packageName, responseCode = 200, body = { ok: true } }) {
660 const spec = npa(packageName)
661 this.nock = this.nock.post(this.fullPath(`/-/package/${spec.escapedName}/trust`))
662 .reply(responseCode, body)
663 }
664
665 trustRevoke ({ packageName, id, responseCode = 200, body = { ok: true } }) {
666 const spec = npa(packageName)
667 const encodedId = encodeURIComponent(id)
668 this.nock = this.nock.delete(this.fullPath(`/-/package/${spec.escapedName}/trust/${encodedId}`))
669 .reply(responseCode, body)
670 }
671 }
672
673 module.exports = MockRegistry