-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathpolicy.js
505 lines (468 loc) · 14.6 KB
/
policy.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
/**
* @module Provides mechanisms for interacting with Compartment Map runtime policies.
*/
// @ts-check
/**
* @import {
* Policy,
* PackagePolicy,
* AttenuationDefinition,
* PackageNamingKit,
* DeferredAttenuatorsProvider,
* CompartmentDescriptor,
* Attenuator,
* SomePolicy,
* SomePackagePolicy,
* } from './types.js'
*/
import {
getAttenuatorFromDefinition,
isAllowingEverything,
isAttenuationDefinition,
policyLookupHelper,
} from './policy-format.js';
const { create, entries, values, assign, freeze, getOwnPropertyDescriptors } =
Object;
const { ownKeys } = Reflect;
const q = JSON.stringify;
/**
* Const string to identify the internal attenuators compartment
*/
export const ATTENUATORS_COMPARTMENT = '<ATTENUATORS>';
/**
* Copies properties (optionally limited to a specific list) from one object to another.
* @template {Record<PropertyKey, any>} T
* @template {Record<PropertyKey, any>} U
* @template {Array<Partial<keyof T>>} [K=Array<keyof T>]
* @param {T} from
* @param {U} to
* @param {K} [list]
* @returns {Omit<U, K[number]> & Pick<T, K[number]>}
*/
const selectiveCopy = (from, to, list) => {
/** @type {Array<Partial<keyof T>>} */
let props;
if (!list) {
const descs = getOwnPropertyDescriptors(from);
props = ownKeys(from).filter(key => descs[key].enumerable);
} else {
props = list;
}
for (let index = 0; index < props.length; index += 1) {
const key = props[index];
// If an endowment is missing, global value is undefined.
// This is an expected behavior if globals are used for platform feature detection
to[key] = from[key];
}
return to;
};
/**
* Parses an attenuation definition for attenuator names
*
* Note: this function is recursive
* @param {string[]} attenuators - List of attenuator names; may be mutated
* @param {AttenuationDefinition|Policy} policyFragment
*/
const collectAttenuators = (attenuators, policyFragment) => {
if ('attenuate' in policyFragment) {
attenuators.push(policyFragment.attenuate);
}
for (const value of values(policyFragment)) {
if (typeof value === 'object' && value !== null) {
collectAttenuators(attenuators, value);
}
}
};
const attenuatorsCache = new WeakMap();
/**
* Goes through policy and lists all attenuator specifiers used.
* Memoization keyed on policy object reference
*
* @param {Policy} [policy]
* @returns {Array<string>} attenuators
*/
export const detectAttenuators = policy => {
if (!policy) {
return [];
}
if (!attenuatorsCache.has(policy)) {
const attenuators = [];
if (policy.defaultAttenuator) {
attenuators.push(policy.defaultAttenuator);
}
collectAttenuators(attenuators, policy);
attenuatorsCache.set(policy, attenuators);
}
return attenuatorsCache.get(policy);
};
/**
* Generates a string identifying a package for policy lookup purposes.
*
* @param {PackageNamingKit} namingKit
* @returns {string}
*/
const generateCanonicalName = ({ isEntry = false, name, path }) => {
if (isEntry) {
throw Error('Entry module cannot be identified with a canonicalName');
}
if (name === ATTENUATORS_COMPARTMENT) {
return ATTENUATORS_COMPARTMENT;
}
return path.join('>');
};
/**
* Verifies if a module identified by `namingKit` can be a dependency of a package per `packagePolicy`.
* `packagePolicy` is required, when policy is not set, skipping needs to be handled by the caller.
*
* @param {PackageNamingKit} namingKit
* @param {PackagePolicy} packagePolicy
* @returns {boolean}
*/
export const dependencyAllowedByPolicy = (namingKit, packagePolicy) => {
if (namingKit.isEntry) {
// dependency on entry compartment should never be allowed
return false;
}
const canonicalName = generateCanonicalName(namingKit);
return !!policyLookupHelper(packagePolicy, 'packages', canonicalName);
};
/**
* Returns the policy applicable to the canonicalName of the package
*
* @overload
* @param {PackageNamingKit} namingKit - a key in the policy resources spec is derived from these
* @param {SomePolicy} policy - user supplied policy
* @returns {SomePackagePolicy} packagePolicy if policy was specified
*/
/**
* Returns `undefined`
*
* @overload
* @param {PackageNamingKit} namingKit - a key in the policy resources spec is derived from these
* @param {SomePolicy} [policy] - user supplied policy
* @returns {SomePackagePolicy|undefined} packagePolicy if policy was specified
*/
/**
* Returns the policy applicable to the canonicalName of the package
*
* @param {PackageNamingKit} namingKit - a key in the policy resources spec is derived from these
* @param {SomePolicy} [policy] - user supplied policy
*/
export const getPolicyForPackage = (namingKit, policy) => {
if (!policy) {
return undefined;
}
if (namingKit.isEntry) {
return policy.entry;
}
const canonicalName = generateCanonicalName(namingKit);
if (canonicalName === ATTENUATORS_COMPARTMENT) {
return {
defaultAttenuator: policy.defaultAttenuator,
packages: 'any',
};
}
if (policy.resources && policy.resources[canonicalName] !== undefined) {
return policy.resources[canonicalName];
} else {
// Allow skipping policy entries for packages with no powers.
return create(null);
}
};
/**
* Get list of globals from package policy
* @param {PackagePolicy} [packagePolicy]
* @returns {Array<string>}
*/
const getGlobalsList = packagePolicy => {
if (!packagePolicy || !packagePolicy.globals) {
return [];
}
return entries(packagePolicy.globals)
.filter(([_key, value]) => value)
.map(([key, _vvalue]) => key);
};
const GLOBAL_ATTENUATOR = 'attenuateGlobals';
const MODULE_ATTENUATOR = 'attenuateModule';
/**
* Imports attenuator per its definition and provider
* @param {AttenuationDefinition} attenuationDefinition
* @param {DeferredAttenuatorsProvider} attenuatorsProvider
* @param {string} attenuatorExportName
* @returns {Promise<Function>}
*/
const importAttenuatorForDefinition = async (
attenuationDefinition,
attenuatorsProvider,
attenuatorExportName,
) => {
if (!attenuatorsProvider) {
throw Error(`attenuatorsProvider is required to import attenuators`);
}
const { specifier, params, displayName } = getAttenuatorFromDefinition(
attenuationDefinition,
);
const attenuator = await attenuatorsProvider.import(specifier);
if (!attenuator[attenuatorExportName]) {
throw Error(
`Attenuator ${q(displayName)} does not export ${q(attenuatorExportName)}`,
);
}
// TODO: uncurry bind for security?
const attenuate = attenuator[attenuatorExportName].bind(attenuator, params);
return attenuate;
};
/**
* Makes an async provider for attenuators
* @param {Record<string, Compartment>} compartments
* @param {Record<string, CompartmentDescriptor>} compartmentDescriptors
* @returns {DeferredAttenuatorsProvider}
*/
export const makeDeferredAttenuatorsProvider = (
compartments,
compartmentDescriptors,
) => {
let importAttenuator;
let defaultAttenuator;
// Attenuators compartment is not created when there's no policy.
// Errors should be thrown when the provider is used.
if (!compartmentDescriptors[ATTENUATORS_COMPARTMENT]) {
importAttenuator = async () => {
throw Error(`No attenuators specified in policy`);
};
} else {
defaultAttenuator =
compartmentDescriptors[ATTENUATORS_COMPARTMENT].policy.defaultAttenuator;
// At the time of this function being called, attenuators compartment won't
// exist yet, we need to defer looking them up in the compartment to the
// time of the import function being called.
/**
*
* @param {string} attenuatorSpecifier
* @returns {Promise<Attenuator>}
*/
importAttenuator = async attenuatorSpecifier => {
if (!attenuatorSpecifier) {
if (!defaultAttenuator) {
throw Error(`No default attenuator specified in policy`);
}
attenuatorSpecifier = defaultAttenuator;
}
const { namespace } =
await compartments[ATTENUATORS_COMPARTMENT].import(attenuatorSpecifier);
return namespace;
};
}
return {
import: importAttenuator,
};
};
/**
* Attenuates the `globalThis` object
*
* @param {object} options
* @param {DeferredAttenuatorsProvider} options.attenuators
* @param {AttenuationDefinition} options.attenuationDefinition
* @param {object} options.globalThis
* @param {object} options.globals
*/
async function attenuateGlobalThis({
attenuators,
attenuationDefinition,
globalThis,
globals,
}) {
const attenuate = await importAttenuatorForDefinition(
attenuationDefinition,
attenuators,
GLOBAL_ATTENUATOR,
);
// attenuate can either define properties on globalThis on its own,
// or return an object with properties to transfer onto globalThis.
// The latter is consistent with how module attenuators work so that
// one attenuator implementation can be used for both if use of
// defineProperty is not needed for attenuating globals.
// Globals attenuator could be made async by adding a single `await`
// here, but module attenuation must be synchronous, so we make it
// synchronous too for consistency.
// For async attenuators see PR https://github.com/endojs/endo/pull/1535
const result = /* await */ attenuate(globals, globalThis);
if (typeof result === 'object' && result !== null) {
assign(globalThis, result);
}
}
/**
* Filters available globals and returns a copy according to the policy
*
* @param {object} globalThis
* @param {object} globals
* @param {PackagePolicy} packagePolicy
* @param {DeferredAttenuatorsProvider} attenuators
* @param {Array<Promise>} pendingJobs
* @param {string} name
* @returns {void}
*/
export const attenuateGlobals = (
globalThis,
globals,
packagePolicy,
attenuators,
pendingJobs,
name = '<unknown>',
) => {
let freezeGlobalThisUnlessOptedOut = () => {
freeze(globalThis);
};
if (packagePolicy && packagePolicy.noGlobalFreeze) {
freezeGlobalThisUnlessOptedOut = () => {};
}
if (!packagePolicy || isAllowingEverything(packagePolicy.globals)) {
selectiveCopy(globals, globalThis);
freezeGlobalThisUnlessOptedOut();
return;
}
if (isAttenuationDefinition(packagePolicy.globals)) {
const attenuationDefinition = packagePolicy.globals;
const { displayName } = getAttenuatorFromDefinition(attenuationDefinition);
const attenuationPromise = Promise.resolve() // delay to next tick while linking is synchronously finalized
.then(() =>
attenuateGlobalThis({
attenuators,
attenuationDefinition,
globalThis,
globals,
}),
)
.then(freezeGlobalThisUnlessOptedOut, error => {
freezeGlobalThisUnlessOptedOut();
throw Error(
`Error while attenuating globals for ${q(name)} with ${q(
displayName,
)}: ${q(error.message)}`, // TODO: consider an option to expose stacktrace for ease of debugging
);
});
pendingJobs.push(attenuationPromise);
return;
}
const list = getGlobalsList(packagePolicy);
selectiveCopy(globals, globalThis, list);
freezeGlobalThisUnlessOptedOut();
};
/**
* @param {string} [errorHint]
* @returns {string}
*/
const diagnoseModulePolicy = errorHint => {
if (!errorHint) {
return '';
}
return ` (info: ${errorHint})`;
};
/**
* Options for {@link enforceModulePolicy}
* @typedef EnforceModulePolicyOptions
* @property {boolean} [exit] - Whether it is an exit module
* @property {string} [errorHint] - Error hint message
*/
/**
* Throws if importing of the specifier is not allowed by the policy
*
* @param {string} specifier
* @param {CompartmentDescriptor} compartmentDescriptor
* @param {EnforceModulePolicyOptions} [options]
*/
export const enforceModulePolicy = (
specifier,
compartmentDescriptor,
{ exit, errorHint } = {},
) => {
const { policy, modules, label } = compartmentDescriptor;
if (!policy) {
return;
}
if (!exit) {
if (!modules[specifier]) {
throw Error(
`Importing ${q(specifier)} in ${q(
label,
)} was not allowed by packages policy ${q(
policy.packages,
)}${diagnoseModulePolicy(errorHint)}`,
);
}
return;
}
if (!policyLookupHelper(policy, 'builtins', specifier)) {
throw Error(
`Importing ${q(specifier)} was not allowed by policy builtins:${q(
policy.builtins,
)}${diagnoseModulePolicy(errorHint)}`,
);
}
};
/**
* Attenuates a module
* @param {object} options
* @param {DeferredAttenuatorsProvider} options.attenuators
* @param {AttenuationDefinition} options.attenuationDefinition
* @param {import('ses').ThirdPartyStaticModuleInterface} options.originalModuleRecord
* @returns {Promise<import('ses').ThirdPartyStaticModuleInterface>}
*/
async function attenuateModule({
attenuators,
attenuationDefinition,
originalModuleRecord,
}) {
const attenuate = await importAttenuatorForDefinition(
attenuationDefinition,
attenuators,
MODULE_ATTENUATOR,
);
// An async attenuator maker could be introduced here to return a synchronous attenuator.
// For async attenuators see PR https://github.com/endojs/endo/pull/1535
return freeze({
imports: originalModuleRecord.imports,
// It seems ok to declare the exports but then let the attenuator trim the values.
// Seems ok for attenuation to leave them undefined - accessing them is malicious behavior.
exports: originalModuleRecord.exports,
execute: (moduleExports, compartment, resolvedImports) => {
const ns = {};
originalModuleRecord.execute(ns, compartment, resolvedImports);
const attenuated = attenuate(ns);
moduleExports.default = attenuated;
assign(moduleExports, attenuated);
},
});
}
/**
* Throws if importing of the specifier is not allowed by the policy
*
* @param {string} specifier - exit module name
* @param {import('ses').ThirdPartyStaticModuleInterface} originalModuleRecord - reference to the exit module
* @param {PackagePolicy} policy - local compartment policy
* @param {DeferredAttenuatorsProvider} attenuators - a key-value where attenuations can be found
* @returns {Promise<import('ses').ThirdPartyStaticModuleInterface>} - the attenuated module
*/
export const attenuateModuleHook = async (
specifier,
originalModuleRecord,
policy,
attenuators,
) => {
const policyValue = policyLookupHelper(policy, 'builtins', specifier);
if (!policy || policyValue === true) {
return originalModuleRecord;
}
if (!policyValue) {
throw Error(
`Attenuation failed '${specifier}' was not in policy builtins:${q(
policy.builtins,
)}`,
);
}
return attenuateModule({
attenuators,
attenuationDefinition: policyValue,
originalModuleRecord,
});
};