-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
523 lines (477 loc) · 16.2 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
'use strict'
/**
* @fileoverview
* See notes on mintable types in ../README.md
*/
/* eslint no-warning-comments: "off" */
// Our security relies on some of these behaving as expected.
// In the README, we insist on loading early, and take that as given
// below.
const { Boolean } = global
const { isArray } = Array
const {
create, defineProperties, defineProperty,
getPrototypeOf, freeze, hasOwnProperty
} = Object
const { Error, TypeError, WeakSet } = global
const { apply } = Reflect
const {
indexOf: arrayIndexOf,
join: arrayJoin,
map: arrayMap,
slice: arraySlice,
push: arrayPush
} = Array.prototype
const mapGet = Map.prototype.get
const mapSet = Map.prototype.set
const weakSetAdd = WeakSet.prototype.add
const weakSetHas = WeakSet.prototype.has
const { indexOf, lastIndexOf, split, substring } = String.prototype
const { dedot, dirname } = require('module-keys/lib/relpath.js')
const { isAbsolute, sep } = require('path')
// Module keys polyfill as per module-keys/babel
require('module-keys/cjs').polyfill(module, require)
const { isPublicKey, publicKeySymbol } = require('module-keys')
/**
* The path to the directory containing the first loading module
* which should be the main file that loads us early using the
* idiom above.
*/
let configRoot = module.parent && module.parent &&
module.parent.filename
? dirname(module.parent.filename)
: __dirname
/** Maps contract keys to allowed minters. */
let whitelist = null
/**
* What to do when a violation is detected.
* One of ('enforce', 'report-only', 'permissive').
*/
let failureMode = 'permissive'
/**
* True to dump information about grant checks to console.info.
*/
let debugGrants = false
/**
* Takes a configuration object with "mintableGrants" &| "mintableMode"
*/
function authorize (options, root) {
if (whitelist) {
throw new Error('Cannot re-initialize mintable')
}
if (root) {
configRoot = root
}
const {
mintable: {
grants = {},
second,
mode,
debug
} = {}
} = options
function modeFromConfig () {
switch (mode) {
case 'enforce': case 'report-only': case 'permissive':
return mode
case undefined: // eslint-disable-line no-undefined
// If no configuration is present, we default to permissive
// and rely on package.json linters to warn about the absence
// of configuration when there is a non-dev dependency on
// this module.
return 'mintable' in options ? 'enforce' : 'permissive'
default:
}
throw new Error(`invalid mintable mode ${mode}`)
}
/**
* Updates whitelist to add the target package to package whitelists
* for the given contract keys.
*/
function incorporateSelfNominationsFor (targetPackage, contractKeys) {
if (isArray(contractKeys)) {
for (let i = 0, nNoms = contractKeys.length; i < nNoms; ++i) {
if (apply(hasOwnProperty, contractKeys, [ i ])) {
const selfNomination = contractKeys[i]
whitelist[selfNomination] = whitelist[selfNomination] || []
apply(arrayPush, whitelist[selfNomination], [ targetPackage ])
}
}
}
}
function computeResolvePaths () {
const resolvePaths = []
const configRootParts = apply(split, configRoot, [ sep ])
for (let i = configRootParts.length; --i >= 0;) {
const rootPrefix = apply(
arrayJoin,
apply(arraySlice, configRootParts, [ 0, i + 1 ]),
[ sep ])
resolvePaths[resolvePaths.length] = `${rootPrefix}${sep}node_modules`
}
return resolvePaths
}
/**
* Loads configuration files for packages whose self nominations have
* been seconded and modifies whitelist in place to incorporate them.
*/
function incorporateSelfNominations (seconds) {
const resolvePaths = computeResolvePaths()
for (let i = 0, nSeconds = seconds.length; i < nSeconds; ++i) {
if (apply(hasOwnProperty, seconds, [ i ])) {
let targetConfigPath = `${seconds[i]}`
if (!targetConfigPath) {
continue
}
// eslint-disable-next-line no-magic-numbers
if (apply(substring, targetConfigPath, [ targetConfigPath.length - 5 ]) !== '.json') {
targetConfigPath += '/package.json'
}
// Infer the target package name from the configuration path file
// "path/to/config.json" => "/abs/node_modules/path/to/config.json"
const resolvedTargetConfigPath = require.resolve(targetConfigPath, { paths: resolvePaths })
let targetPackage = resolvedTargetConfigPath
// "/abs/node_modules/path/to/config.json"
// => [ "", "abs", "node_modules", "path", "to", "config.json" ]
targetPackage = apply(split, targetPackage, [ '/' ])
// [ "", "abs", "node_modules", "path", "to", "config.json" ]
// => [ "path", "to", "config.json" ]
targetPackage = apply(
arraySlice, targetPackage,
[ apply(arrayIndexOf, targetPackage, [ 'node_modules' ]) + 1 ])
// [ "path", "to", "config.json" ] => [ "path" ]
// OR [ "@namespace", "path", "to", "..." ] => [ "@namespace", "path" ]
targetPackage = apply(
arraySlice, targetPackage,
[ 0, targetPackage[0][0] === '@' ? 2 : 1 ])
// [ "@namespace", "path" ] => "@namespace/path"
targetPackage = apply(arrayJoin, targetPackage, [ '/' ])
// Fetch the target configuration
// eslint-disable-next-line global-require
const targetConfig = require(resolvedTargetConfigPath)
const contractKeys = ((targetConfig && targetConfig.mintable) || {}).selfNominate
if (debug) {
// eslint-disable-next-line no-console
console.info(`seconding ${targetPackage}
targetConfigPath=${targetConfigPath}
resolvedTargetConfigPath=${resolvedTargetConfigPath}
contractKeys=${JSON.stringify(contractKeys)}`)
}
incorporateSelfNominationsFor(targetPackage, contractKeys)
}
}
}
whitelist = create(null)
debugGrants = Boolean(debug)
if (debug) {
// eslint-disable-next-line no-console
console.group(`node-sec-patterns authorize`)
}
try {
failureMode = modeFromConfig()
// Defensively copy grants over
for (const key in grants) {
if (typeof key === 'string' && apply(hasOwnProperty, grants, [ key ])) {
const val = grants[key]
if (isArray(val)) {
whitelist[key] = apply(arrayMap, val, [ (ele) => `${ele}` ])
}
}
}
if (isArray(second)) {
incorporateSelfNominations(second, whitelist)
}
} finally {
for (const key in whitelist) {
freeze(whitelist[key])
}
freeze(whitelist)
if (debug) {
// eslint-disable-next-line no-console
console.info(`consolidated whitelist\n${JSON.stringify(whitelist)}`)
// eslint-disable-next-line no-console
console.groupEnd()
}
}
}
/**
* Base type for a type that can be created by a mint and verified by
* a corresponding verifier.
*
* We can't prevent forgery via Object.create, but we can ensure that
* only outputs of mint pass the corresponding verifier.
*/
class Mintable {
constructor () {
// Fail fast when creating an instance that will not pass
// the verifier.
// Our security does not rely on this check.
// We try to catch common cases where an object is created
// via `new` instead of the mint early so we can guide developers
// to the mint.
// Freezing the prototype would be nice, but is not required.
// If the constructor property has been meddled with we will fail to find
// the privates since the minter closes over the constructor to call.
const concreteType = getPrototypeOf(this).constructor
const privates = privatesPerMintableType.get(concreteType)
if (!(privates && privates.mayConstruct())) {
const { name } = concreteType
throw new Error(
`Construct instances using Mintable.minterFor(${name}), not via new ${name}`)
}
}
}
// Given
// class SubType extends Mintable {}
// make sure that
// Mintable.minterFor(SubType)
// Mintable.verifierFor(SubType)
// evaluate to the minter and verifier for the given SubType.
//
// We could enable
// const o = SubType.mint(...constructorArguments)
// SubType.verify(o) // -> true
// by defining the below as getters and using `this` as the concreteType
// but this would not provide a trusted path to the minter or verifier.
defineProperties(
Mintable,
{
minterFor: {
configurable: false,
enumerable: true,
// eslint-disable-next-line func-name-matching
value: function getMinterFor (concreteType) {
const allowedAccess = mayAccessMint(concreteType)
const { mint } = privatesFor(concreteType)
return require.moduleKeys.box(mint, allowedAccess)
}
},
verifierFor: {
configurable: false,
enumerable: true,
// eslint-disable-next-line func-name-matching
value: function getVerifierFor (concreteType) {
const { verify } = privatesFor(concreteType)
return verify
}
}
})
freeze(Mintable)
/** Privates per concrete type. */
const privatesPerMintableType = new WeakMap()
/** Stateful functions related to a particular contract type. */
function privatesFor (concreteType) {
let privates = privatesPerMintableType.get(concreteType)
if (!privates) {
privatesPerMintableType.set(
concreteType,
privates = makePrivates(concreteType))
}
return privates
}
let hasWarnedAboutUninitializedUse = false
/**
* Returns a public key predicate that allows access to the minter is disallowed in the current context.
*/
function mayAccessMint (concreteType) {
if (failureMode === 'permissive') {
if (!whitelist) {
// Let users of minters who have not opted into whitelisting
// know that that is a thing they could do.
if (!hasWarnedAboutUninitializedUse) {
// eslint-disable-next-line no-console
console.warn('mintable: minter accessed before authorization')
}
hasWarnedAboutUninitializedUse = true
}
return () => true
}
const { contractKey } = concreteType
const grantRecord = keysGranted(contractKey)
function toFullModuleId (moduleId) {
if (moduleId[0] !== '/' && !isAbsolute(moduleId)) {
return `${configRoot}${sep}${moduleId}`
}
return moduleId
}
function mayMint (pubKey) {
const moduleId = dedot(pubKey.moduleIdentifier)
if (grantRecord && isPublicKey(pubKey) && pubKey()) {
const { grants, pubKeys } = grantRecord
if (apply(weakSetHas, pubKeys, [ pubKey ])) {
// We've seen it before, great!
return true
}
// Otherwise, see if its on the set of grants for which we have
// yet to resolve keys.
if (findGrantMatch(grants, moduleId)) {
let publicKey = null
// Treat the exported publicKey as the source of truth.
try {
// eslint-disable-next-line global-require
publicKey = require(toFullModuleId(moduleId))[publicKeySymbol]
} catch (failedToRequire) {
// deny
}
if (publicKey) {
apply(weakSetAdd, pubKeys, [ publicKey ])
if (publicKey === pubKey) {
return true
}
}
}
}
const message = `mintable: ${relModuleId(moduleId)} not allowed to mint ${contractKey}`
console.warn(message) // eslint-disable-line no-console
return failureMode === 'report-only'
}
return mayMint
}
// True iff arr has an element === elt and if so, removes that element.
// Does not preserve order when removing.
function arrayHad (arr, elt) {
for (let i = 0, len = arr.length; i < len; ++i) {
if (arr[i] === elt) {
arr[i] = arr[len - 1]
--arr.length
return true
}
}
return false
}
// Converts a module identifier to one relative to the config root so that it
// can be compared to whitelist entries.
function relModuleId (moduleIdentifier) {
// "/path/to/root/foo/bar" -> "foo/bar"
if (moduleIdentifier[configRoot.length] === '/' &&
apply(lastIndexOf, moduleIdentifier, [ configRoot, configRoot.length ]) === 0) {
moduleIdentifier = apply(substring, moduleIdentifier, [ configRoot.length + 1 ])
}
{
const prefix = 'node_modules/'
const i = apply(lastIndexOf, moduleIdentifier, [ prefix, 0 ])
if (i === 0) {
// node_modules/foo/bar/baz -> "foo/bar/baz"
return apply(substring, moduleIdentifier, [ i + prefix.length ])
}
}
{
const infix = '/node_modules/'
const i = apply(indexOf, moduleIdentifier, [ infix ])
if (i >= 0) {
// "/path/to/node_modules/foo/bar/baz" -> "foo/bar/baz"
return apply(substring, moduleIdentifier, [ i + infix.length ])
}
}
if (moduleIdentifier[0] === '/') {
return moduleIdentifier
}
// "foo/bar" -> "./foo/bar"
return `./${moduleIdentifier}`
}
function findGrantMatch (grants, moduleId) {
let relModule = relModuleId(moduleId)
if (debugGrants) {
// eslint-disable-next-line no-console
console.info(`node-sec-patterns: looking for grant ${JSON.stringify(moduleId)} in ${JSON.stringify(grants)}`)
}
do {
if (arrayHad(grants, relModule)) {
return true
}
const lastSlash = apply(lastIndexOf, relModule, [ '/' ])
if (lastSlash) {
relModule = apply(substring, relModule, [ 0, lastSlash ])
} else {
break
}
} while (relModule)
return false
}
// Maps contract keys to { pubKeys: WeakSet<PublicKey>, grants: Array<string> }
// As a public key needs to be looked up, it is moved from grants to pubKeys.
const memoizedGrants = new Map()
const emptyGrants = freeze(Object.assign(
create(null), { pubKeys: freeze(new WeakSet()), grants: freeze([]) }))
function keysGranted (contractKey) {
if (whitelist && typeof contractKey === 'string') {
let granted = apply(mapGet, memoizedGrants, [ contractKey ])
if (granted) {
return granted
}
if (apply(hasOwnProperty, whitelist, [ contractKey ])) {
const grants = []
const grantList = whitelist[contractKey]
if (isArray(grantList)) {
for (let i = 0, len = grantList.length; i < len; ++i) {
if (apply(hasOwnProperty, grantList, [ i ])) {
grants[grants.length] = `${grantList[i]}`
}
}
}
granted = { pubKeys: new WeakSet(), grants }
apply(mapSet, memoizedGrants, [ contractKey, granted ])
return granted
}
}
return emptyGrants
}
/** Allocate a mint/verifier pair for a concrete type. */
function makePrivates (SubType) {
const minted = new WeakSet()
/** True iff o was created by mint. */
const verify = freeze(
(val) =>
// eslint-disable-next-line no-implicit-coercion
!!(val && typeof val === 'object' && apply(weakSetHas, minted, [ val ])))
let mintingDepth = 0
/** Called to create an instance that will pass the verifier. */
const mint = freeze((...args) => {
// This allows us to fail fast in the Mintable
// constructor. See comments there.
const mintingDepthBefore = mintingDepth
// Constructors can be reentrant
mintingDepth += 1
if (mintingDepth - mintingDepthBefore !== 1) {
throw new TypeError('ulp > 1')
}
try {
const newInstance = new SubType(...args)
if (!(newInstance instanceof SubType)) {
throw new TypeError(
`Expected to mint a ${SubType.name} but constructed ${newInstance}`)
}
// This is what causes the verifier to pass.
apply(weakSetAdd, minted, [ newInstance ])
return newInstance
} finally {
mintingDepth = mintingDepthBefore
}
})
const mayConstruct = freeze(() => mintingDepth !== 0)
return freeze({ mint, verify, minted, mayConstruct })
}
module.exports = freeze({
Mintable,
authorize
})
// Pin this module in place, so that require('node-sec-patterns').Mintable is
// a reliable path to the module that was just initialized. This
// prevents an attacker from deleting the module, re-requiring it, and
// re-authorizing with their own configuration.
// We wait until the end so that if any other module initialization
// step fails, the module loader can remove it from the module cache.
void ((() => {
const cacheEntry = require.cache[module.id]
if (cacheEntry !== module) {
throw new Error()
}
delete require.cache[module.id]
defineProperty(
require.cache,
module.id,
{
enumerable: true,
value: cacheEntry
})
})())