-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathapproval-artifacts.js
More file actions
178 lines (163 loc) · 7.26 KB
/
Copy pathapproval-artifacts.js
File metadata and controls
178 lines (163 loc) · 7.26 KB
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
'use strict'
const crypto = require('node:crypto')
const fs = require('node:fs')
const path = require('node:path')
const { getApprovalMaterial } = require('./approval')
const { parseBoundedJson } = require('./bounded-json')
const { ensureSafeDirectory, writeFileSafely } = require('./safe-files')
const APPROVAL_FILENAME = 'approval.json'
const APPROVAL_FILES_FILENAME = 'approval-files.sha256'
const APPROVAL_DIGEST_PATTERN = /^[a-f0-9]{64}$/
const MAX_APPROVAL_BYTES = 5 * 1024 * 1024
const MAX_APPROVAL_COLLECTION_ENTRIES = 100_000
const MAX_APPROVAL_NESTING_DEPTH = 64
const MAX_APPROVAL_STRING_BYTES = 256 * 1024
const REQUIRED_CAPABILITIES = new Set(['browser_process', 'localhost_socket'])
/**
* Writes inspectable approval material without running project code.
*
* The live validator verifies the exact approval JSON bytes first, reads only the bounded execution selection,
* then reconstructs the full material from current inputs before running project code.
*
* @param {object} input approval inputs
* @param {object} input.manifest loaded manifest
* @param {string} input.out validation output directory
* @param {Array<{path: string, sha256: string}>} [input.expectedProjectFiles] preflight project snapshot
* @returns {{approvalJsonPath: string, coveredFilesPath: string, digest: string}} written artifact details
*/
function writeApprovalArtifacts (input) {
const material = getApprovalMaterial(input)
assertExpectedProjectFiles(input.expectedProjectFiles, material.projectFiles)
const approvalJson = `${JSON.stringify(material, null, 2)}\n`
const digest = crypto.createHash('sha256').update(approvalJson).digest('hex')
const approvalJsonPath = path.join(input.out, APPROVAL_FILENAME)
const coveredFilesPath = path.join(input.out, APPROVAL_FILES_FILENAME)
ensureSafeDirectory(input.manifest.repository.root, input.out, 'validation approval artifact directory', {
allowRootSymlink: true,
})
writeFileSafely(input.out, approvalJsonPath, approvalJson, 'validation approval JSON')
writeFileSafely(
input.out,
coveredFilesPath,
getCoveredFilesManifest(material),
'validation approval file checksums'
)
return { approvalJsonPath, coveredFilesPath, digest }
}
/**
* Refuses to publish approval artifacts from static evidence read against a different project snapshot.
*
* @param {Array<{path: string, sha256: string}>|undefined} expected preflight project files
* @param {Array<{path: string, sha256: string}>} actual approval project files
* @returns {void}
*/
function assertExpectedProjectFiles (expected, actual) {
if (!expected) return
if (JSON.stringify(expected) !== JSON.stringify(actual)) {
throw new Error(
'Approval-bound project inputs changed during plan preflight. Render a fresh plan from the current checkout.'
)
}
}
/**
* Loads the reviewed approval file only after its exact bytes match the user-approved SHA-256.
*
* @param {string} approvalPath approval JSON path
* @param {string} expectedDigest user-approved SHA-256
* @returns {{material: object, path: string}} verified approval material
*/
function loadApprovedPlan (approvalPath, expectedDigest) {
if (!APPROVAL_DIGEST_PATTERN.test(String(expectedDigest || ''))) {
throw new Error('Invalid --sha256 value. Render a fresh plan with --print-plan.')
}
const resolvedPath = path.resolve(approvalPath)
const stat = fs.lstatSync(resolvedPath)
if (stat.isSymbolicLink() || !stat.isFile()) {
throw new Error(`Approved plan must be a regular file, not a symbolic link: ${resolvedPath}`)
}
if (stat.size > MAX_APPROVAL_BYTES) {
throw new Error(`Approved plan exceeds the ${MAX_APPROVAL_BYTES}-byte size limit: ${resolvedPath}`)
}
const raw = fs.readFileSync(resolvedPath)
const digest = crypto.createHash('sha256').update(raw).digest('hex')
if (digest !== expectedDigest) {
throw new Error('The approved plan file changed after approval. Render and approve a fresh execution plan.')
}
const material = parseBoundedJson(raw, {
label: 'Approved validation plan JSON',
maxCollectionEntries: MAX_APPROVAL_COLLECTION_ENTRIES,
maxNestingDepth: MAX_APPROVAL_NESTING_DEPTH,
maxStringBytes: MAX_APPROVAL_STRING_BYTES,
}).value
validateApprovedPlanShape(material, resolvedPath)
return { material, path: resolvedPath }
}
/**
* Validates the small set of approval fields used to reconstruct live CLI options.
*
* @param {object} material parsed approval material
* @param {string} approvalPath approved JSON path
* @returns {void}
*/
function validateApprovedPlanShape (material, approvalPath) {
const manifestPath = material?.manifest?.path
const outputDirectory = material?.validation?.outputDirectory
const frameworks = material?.selection?.frameworks
const scenario = material?.selection?.scenario
const requiredCapabilities = material?.validation?.requiredCapabilities
if (typeof manifestPath !== 'string' || !path.isAbsolute(manifestPath)) {
throw new Error('Approved plan manifest.path must be an absolute path.')
}
if (typeof outputDirectory !== 'string' || !path.isAbsolute(outputDirectory)) {
throw new Error('Approved plan validation.outputDirectory must be an absolute path.')
}
if (!Array.isArray(frameworks) || frameworks.some(framework => typeof framework !== 'string')) {
throw new Error('Approved plan selection.frameworks must be an array of framework identifiers.')
}
if (scenario !== null && typeof scenario !== 'string') {
throw new Error('Approved plan selection.scenario must be a string or null.')
}
if (!Array.isArray(requiredCapabilities) ||
requiredCapabilities.some(capability => !REQUIRED_CAPABILITIES.has(capability)) ||
new Set(requiredCapabilities).size !== requiredCapabilities.length) {
throw new Error(
'Approved plan validation.requiredCapabilities must contain unique browser_process or localhost_socket values.'
)
}
if (path.resolve(approvalPath) !== path.join(path.resolve(outputDirectory), APPROVAL_FILENAME)) {
throw new Error(`Approved plan must be ${APPROVAL_FILENAME} inside validation.outputDirectory.`)
}
}
/**
* Creates a standard SHA-256 checksum list for independently checking covered files.
*
* @param {object} material approval material
* @returns {string} checksum manifest
*/
function getCoveredFilesManifest (material) {
const files = new Map([[material.manifest.path, material.manifest.sha256]])
for (const file of material.validator.coveredFiles) {
files.set(path.join(material.validator.packageRoot, ...file.path.split('/')), file.sha256)
}
for (const executable of material.executables) {
if (executable.path && executable.sha256) files.set(executable.path, executable.sha256)
if (executable.delegated) {
for (const delegated of executable.delegated) files.set(delegated.path, delegated.sha256)
}
if (executable.entrypoints) {
for (const entrypoint of executable.entrypoints) files.set(entrypoint.path, entrypoint.sha256)
}
}
if (material.projectFiles) {
for (const projectFile of material.projectFiles) files.set(projectFile.path, projectFile.sha256)
}
return [...files]
.sort(([left], [right]) => left.localeCompare(right))
.map(([filename, sha256]) => `${sha256} ${filename}`)
.join('\n') + '\n'
}
module.exports = {
getCoveredFilesManifest,
loadApprovedPlan,
writeApprovalArtifacts,
}