-
Notifications
You must be signed in to change notification settings - Fork 65
/
policy-generator-context.js
374 lines (339 loc) · 10.1 KB
/
policy-generator-context.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
/**
* Provides {@link PolicyGeneratorContext}
*
* @packageDocumentation
*/
import { isBuiltin as nodeIsBuiltin } from 'node:module'
import { fileURLToPath } from 'node:url'
import path from 'path'
import {
ENDO_PARSER_BYTES,
LAVAMOAT_PKG_POLICY_ROOT,
LMR_TYPE_BUILTIN,
LMR_TYPE_NATIVE,
LMR_TYPE_SOURCE,
} from '../constants.js'
import { defaultReadPower } from '../power.js'
const { entries, keys, fromEntries } = Object
/**
* Options for {@link PolicyGeneratorContext}
*
* @typedef PolicyGeneratorContextOptions
* @property {import('@endo/compartment-mapper').ReadFn} [readFn] - Read
* function
* @property {boolean} [isEntry] - If `true`, the `PolicyGeneratorContext`
* represents the entry compartment
*/
/**
* Handles creation of {@link LavamoatModuleRecord} objects for individual
* compartment descriptors.
*
* @internal
*/
export class PolicyGeneratorContext {
/**
* If `true`, this is the entry compartment
*
* @type {boolean}
*/
#isEntry
/**
* Internal cache for {@link LavamoatModuleRecord} objects
*
* @type {Readonly<import('./lmr-cache.js').LMRCache>}
*/
#lmrCache
/**
* Used for reading source files
*/
static #decoder = new TextDecoder()
/**
* Sets some properties
*
* @param {Readonly<
* import('@endo/compartment-mapper').CompartmentDescriptor
* >} compartment
* @param {Readonly<Record<string, string>>} renames
* @param {Readonly<import('./lmr-cache.js').LMRCache>} lmrCache
* @param {Readonly<PolicyGeneratorContextOptions>} opts
*/
constructor(
compartment,
renames,
lmrCache,
{ readFn: readPower = defaultReadPower, isEntry = false } = {}
) {
/**
* Compartment descriptor
*
* @type {Readonly<
* import('@endo/compartment-mapper').CompartmentDescriptor
* >}
*/
this.compartment = compartment
/**
* Read powers
*
* @type {NonNullable<PolicyGeneratorContextOptions['readFn']>}
*/
this.readPower = readPower
/**
* Mapping of renamed compartments
*
* @type {Readonly<Record<string, string>>}
*/
this.renames = renames
this.#isEntry = isEntry
this.#lmrCache = lmrCache
}
/**
* The package name which will appear in the source's `LavamoatModuleRecord`
* and eventual policy
*/
get packageName() {
return this.#isEntry ? LAVAMOAT_PKG_POLICY_ROOT : this.compartment.name
}
/**
* Ensures a specifier is not just a package with the same name as a builtin
*
* @param {string} specifier
*/
isBuiltin(specifier) {
return !(specifier in this.compartment.modules) && nodeIsBuiltin(specifier)
}
/**
* A `ModuleDescriptor` has a compartment and module, which can be joined to
* form an absolute path.
*
* @overload
* @param {Required<import('@endo/compartment-mapper').ModuleDescriptor>} descriptor
* @returns {string}
* @internal
* @todo Evaluate windows compat
*/
/**
* Converts a `string` `file://` URL to a path
*
* @overload
* @param {string} location
* @returns {string}
* @internal
*/
/**
* @remarks
* In Endo, the `compartment` is stored as a _string_ `file://` URL; hence the
* conversion.
* @param {string
* | Required<import('@endo/compartment-mapper').ModuleDescriptor>} descriptorOrLocation
* @returns {string}
* @internal
* @todo There may be a safer way to do this conversion
*/
toPath(descriptorOrLocation) {
if (typeof descriptorOrLocation === 'string') {
return fileURLToPath(new URL(descriptorOrLocation))
}
const location = this.renames[descriptorOrLocation.compartment]
if (!location) {
throw new TypeError(
`Rename map missing location for compartment "${descriptorOrLocation.compartment}" in compartment ${this.compartment.name}`
)
}
return fileURLToPath(
new URL(path.join(location, descriptorOrLocation.module))
)
}
/**
* Attempts to find the filepath of a specifier
*
* Strips trailing slashes from specifiers, since Endo does not store them
* with trailing slashes
*
* @param {string} specifier
* @returns {string | undefined}
* @internal
*/
getFilepath(specifier) {
specifier = specifier.replace(/\/$/, '')
const moduleDescriptor = this.compartment.modules[specifier]
if (PolicyGeneratorContext.isCompleteModuleDescriptor(moduleDescriptor)) {
return this.toPath(moduleDescriptor)
}
return undefined
}
/**
* Builds an import map for a {@link LavamoatModuleRecord} from a list of
* import specifiers.
*
* These specifiers can come from either `StaticModuleType` (as found in
* `Sources`) or `ModuleDescriptor` objects.
*
* Relative-path specifiers do not need an import map entry
*
* @param {string[]} imports
* @returns {Record<string, string>}
* @internal
*/
buildImportMap(imports = []) {
return fromEntries(
imports
.filter((specifier) => !specifier.startsWith('.'))
.map((specifier) => {
if (this.isBuiltin(specifier)) {
return [specifier, specifier]
}
/** @type {string | undefined} */
let file = this.getFilepath(specifier)
if (!file) {
throw new ReferenceError(
`Cannot find file for specifier "${specifier}" in compartment "${this.compartment.name}"`
)
}
return /** @type {[specifier: string, file: string]} */ ([
specifier,
file,
])
})
)
}
/**
* Type guard for a `Required<ModuleDescriptor>`.
*
* The `compartment` and `module` props are optional in the original type, but
* we need both.
*
* @param {unknown} descriptor
* @returns {descriptor is Required<import('@endo/compartment-mapper').ModuleDescriptor>}
* @this {void}
* @internal
*/
static isCompleteModuleDescriptor(descriptor) {
return Boolean(
descriptor &&
typeof descriptor === 'object' &&
'compartment' in descriptor &&
'module' in descriptor
)
}
/**
* Given an import map, creates an array of {@link LavamoatModuleRecord}s for
* each builtin found in there.
*
* @param {import('lavamoat-core').LavamoatModuleRecord['importMap']} importMap
* @returns {import('lavamoat-core').LavamoatModuleRecord[]} Zero or more LMRs
* @internal
*/
buildModuleRecordsFromImportMap(importMap) {
return keys(importMap)
.filter((specifier) => this.isBuiltin(specifier))
.map((specifier) =>
this.#lmrCache.get({
type: LMR_TYPE_BUILTIN,
file: specifier,
specifier,
packageName: specifier,
})
)
}
/**
* Creates one or more {@link LavamoatModuleRecord LavamoatModuleRecords} from
* a single `ModuleSource`.
*
* The resulting array will contain--at minimum--a LMR of the source itself.
* It will also contain zero (0) or more LMRs for any builtins the module
* references.
*
* @param {string} specifier
* @param {import('@endo/compartment-mapper').ModuleSource} source
* @returns {Promise<import('lavamoat-core').LavamoatModuleRecord[]>}
* @internal
*/
async buildModuleRecordsForSource(
specifier,
{ parser, record, sourceLocation }
) {
if (!sourceLocation) {
// XXX: why would we not have a sourceLocation?
throw new TypeError(
`Source descriptor "${specifier}" missing "sourceLocation" prop in compartment "${this.compartment.name}"`
)
}
if (!record) {
// XXX: under what circumstances does this occur?
throw new TypeError(
`Source descriptor "${specifier}" in compartment "${this.compartment.name}" missing prop: record`
)
}
// `record` can be several different types, but for our purposes,
// we can use `imports` as the discriminator
if (!('imports' in record)) {
// XXX: under what circumstances does this occur?
throw new TypeError(
`StaticModuleType for source descriptor "${specifier}" in compartment "${this.compartment.name} missing prop: imports`
)
}
/**
* The `ModuleSource.content` prop is already pre-processed by Endo, and we
* do not want that, since it befouls our AST crawling.
*
* This will not be run if the `parser` is `bytes`.
*
* @remarks
* Doing this first since it may be more likely to fail than the other
* operations below.
* @type {string | undefined}
* @todo Modify Endo to surface the original source
*
* @todo Add more exceptions to the parsers?
*/
let content
await Promise.resolve()
if (parser !== ENDO_PARSER_BYTES) {
content = await this.readPower(sourceLocation).then((buffer) =>
PolicyGeneratorContext.#decoder.decode(buffer)
)
}
/**
* The {@link LavamoatModuleRecord.file} prop
*
* @type {import('lavamoat-core').LavamoatModuleRecord['file']}
*/
const file = fileURLToPath(new URL(sourceLocation))
/**
* The {@link LavamoatModuleRecord.importMap} prop
*
* @type {import('lavamoat-core').LavamoatModuleRecord['importMap']}
*/
const importMap = this.buildImportMap(record.imports)
const lmrs = [
// because builtins do not have their own compartments, we need to
// look into the `importMap` and create LMRs for each builtin.
// we will add the source LMR to this array as the last step
...this.buildModuleRecordsFromImportMap(importMap),
// the LMR for the source module itself
this.#lmrCache.get({
specifier: file,
file,
packageName: this.packageName,
importMap,
content,
type: parser === ENDO_PARSER_BYTES ? LMR_TYPE_NATIVE : LMR_TYPE_SOURCE,
}),
]
return lmrs
}
/**
* Creates {@link LavamoatModuleRecord}s from CompartmentSources.
*
* @param {import('@endo/compartment-mapper').CompartmentSources} sources
* @returns {Promise<import('lavamoat-core').LavamoatModuleRecord[]>}
*/
async buildModuleRecords(sources) {
const lmrs = await Promise.all(
entries(sources).map((entry) =>
this.buildModuleRecordsForSource(...entry)
)
)
return lmrs.flat()
}
}