@mago-foundation/mago-ski 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +54 -9
- package/action.yml +2 -2
- package/dist/hosts/github/run.d.ts +9 -1
- package/dist/hosts/github/run.js +64 -11
- package/dist/hosts/pi/index.d.ts +5 -3
- package/dist/hosts/pi/index.js +219 -14
- package/dist/src/admin.d.ts +140 -1
- package/dist/src/admin.js +328 -63
- package/dist/src/canonical-json.js +73 -28
- package/dist/src/certificate.js +23 -15
- package/dist/src/cli.js +590 -89
- package/dist/src/diff.d.ts +0 -4
- package/dist/src/diff.js +326 -70
- package/dist/src/dsse.d.ts +6 -4
- package/dist/src/dsse.js +22 -6
- package/dist/src/fs-safe.d.ts +32 -3
- package/dist/src/fs-safe.js +193 -31
- package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
- package/dist/src/gate/adapters/claude-code-hook.js +4 -0
- package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
- package/dist/src/gate/adapters/claude-code-settings.js +49 -0
- package/dist/src/gate/adapters/claude-code.d.ts +33 -0
- package/dist/src/gate/adapters/claude-code.js +193 -0
- package/dist/src/gate/adapters/client.d.ts +13 -0
- package/dist/src/gate/adapters/client.js +57 -0
- package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
- package/dist/src/gate/adapters/codex-hook.js +5 -0
- package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
- package/dist/src/gate/adapters/codex-requirements.js +56 -0
- package/dist/src/gate/adapters/codex.d.ts +16 -0
- package/dist/src/gate/adapters/codex.js +574 -0
- package/dist/src/gate/adapters/hook-main.d.ts +7 -0
- package/dist/src/gate/adapters/hook-main.js +35 -0
- package/dist/src/gate/adapters/host-pid.d.ts +1 -0
- package/dist/src/gate/adapters/host-pid.js +20 -0
- package/dist/src/gate/admission.d.ts +54 -0
- package/dist/src/gate/admission.js +490 -0
- package/dist/src/gate/contract.d.ts +51 -0
- package/dist/src/gate/contract.js +94 -0
- package/dist/src/gate/decision-log.d.ts +38 -0
- package/dist/src/gate/decision-log.js +251 -0
- package/dist/src/gate/generations.d.ts +67 -0
- package/dist/src/gate/generations.js +518 -0
- package/dist/src/gate/proc.d.ts +31 -0
- package/dist/src/gate/proc.js +79 -0
- package/dist/src/gate/refresh.d.ts +11 -0
- package/dist/src/gate/refresh.js +30 -0
- package/dist/src/gate/run-verifier.d.ts +23 -0
- package/dist/src/gate/run-verifier.js +89 -0
- package/dist/src/gate/service.d.ts +80 -0
- package/dist/src/gate/service.js +722 -0
- package/dist/src/gate/strict-json.d.ts +11 -0
- package/dist/src/gate/strict-json.js +190 -0
- package/dist/src/gate/trust-store.d.ts +36 -0
- package/dist/src/gate/trust-store.js +251 -0
- package/dist/src/gate/verifier-worker.d.ts +8 -0
- package/dist/src/gate/verifier-worker.js +66 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +2 -0
- package/dist/src/keys.d.ts +4 -0
- package/dist/src/keys.js +85 -30
- package/dist/src/main-module.js +1 -1
- package/dist/src/names.js +2 -4
- package/dist/src/policy.d.ts +173 -6
- package/dist/src/policy.js +685 -54
- package/dist/src/recovery-admin.d.ts +173 -0
- package/dist/src/recovery-admin.js +400 -0
- package/dist/src/revocations.js +3 -1
- package/dist/src/root-events.d.ts +107 -0
- package/dist/src/root-events.js +376 -0
- package/dist/src/time.d.ts +19 -3
- package/dist/src/time.js +50 -8
- package/dist/src/timestamp.d.ts +61 -0
- package/dist/src/timestamp.js +107 -0
- package/dist/src/tree-digest.d.ts +4 -0
- package/dist/src/tree-digest.js +41 -16
- package/dist/src/trust-root.d.ts +5 -0
- package/dist/src/trust-root.js +34 -13
- package/dist/src/verify.d.ts +69 -13
- package/dist/src/verify.js +309 -61
- package/docs/hosts/adapter-interface.md +8 -2
- package/docs/hosts/github-action.md +3 -3
- package/docs/hosts/pi.md +10 -3
- package/docs/spec/gui-admin-rack-v1.md +289 -0
- package/docs/spec/root-recovery-v1.md +451 -0
- package/docs/spec/skill-certificate-v1.md +1 -1
- package/docs/spec/skill-tree-v2.md +2 -2
- package/docs/spec/trust-documents-v1.md +12 -6
- package/docs/spec/verification.md +20 -3
- package/docs/threat-model.md +9 -6
- package/package.json +49 -44
package/dist/src/policy.js
CHANGED
|
@@ -1,17 +1,44 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { hostname } from 'node:os';
|
|
1
|
+
import { lstat, opendir, stat } from 'node:fs/promises';
|
|
2
|
+
import { homedir, hostname } from 'node:os';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
+
import { StaleDocumentError } from "./admin.js";
|
|
4
5
|
import { canonicalBytes, exactKeys, isRecord, parseCanonicalJsonBytes, requireArray, requireString } from "./canonical-json.js";
|
|
5
|
-
import { readRegularFile, writeFileAtomic } from "./fs-safe.js";
|
|
6
|
+
import { FileChangedError, appendToRegularFile, isInside, readRegularFile, realpathAllowingMissing, resolveInsideDirectory, writeFileAtomic } from "./fs-safe.js";
|
|
6
7
|
import { validateKeyId } from "./keys.js";
|
|
7
|
-
import {
|
|
8
|
+
import { readRevocationsForUpdate } from "./revocations.js";
|
|
9
|
+
import { readTrustRootForUpdate } from "./trust-root.js";
|
|
10
|
+
import { MAX_ROOT_EVENTS_BYTES, parseRecoverySet, walkRootEventsCached, } from "./root-events.js";
|
|
11
|
+
import { formatTimestamp, parseDuration } from "./time.js";
|
|
12
|
+
import { DEFAULT_MAX_TIMESTAMP_LIFETIME, MAX_TIMESTAMP_BYTES, MAX_TIMESTAMP_LIFETIME_MS, TimestampBindingError, TimestampRollbackError, verifyTimestamp } from "./timestamp.js";
|
|
13
|
+
import { CERTIFICATE_FILENAME, sha256Hex } from "./tree-digest.js";
|
|
8
14
|
import { loadTrustContext, unverifiable, verifySkill, } from "./verify.js";
|
|
9
15
|
export const POLICY_VERSION = 'mago.policy/v1';
|
|
16
|
+
/** Adds root recovery and freshness; a v2 host reads v1 policies unchanged. */
|
|
17
|
+
export const POLICY_VERSION_V2 = 'mago.policy/v2';
|
|
10
18
|
export const STATE_TYPE = 'mago.host-state/v1';
|
|
11
|
-
export const
|
|
19
|
+
export const STATE_TYPE_V2 = 'mago.host-state/v2';
|
|
12
20
|
const MAX_CERTIFICATE_BYTES = 8 * 1024 * 1024;
|
|
21
|
+
/** Per-Skill budget across all certificate candidates (explicit file, policy directories, in-Skill file). */
|
|
22
|
+
export const MAX_CERTIFICATE_CANDIDATES = 64;
|
|
23
|
+
export const MAX_CERTIFICATE_TOTAL_BYTES = 32 * 1024 * 1024;
|
|
13
24
|
const POLICY_KEYS = ['policy_version', 'mode', 'root_fingerprint', 'trust_root', 'revocations', 'certificate_dirs', 'skill_dirs', 'state_file', 'decision_log'];
|
|
25
|
+
const POLICY_V2_KEYS = ['recovery', 'root_events', 'root_events_after', 'freshness'];
|
|
14
26
|
const REQUIRED_POLICY_KEYS = ['policy_version', 'mode', 'root_fingerprint', 'trust_root', 'revocations'];
|
|
27
|
+
const FRESHNESS_KEYS = ['timestamp', 'key_id', 'max_lifetime'];
|
|
28
|
+
/*
|
|
29
|
+
* Where hosts and the CLI read policy when none is given: $MAGO_SKI_POLICY (absolute, or "~/..."), else ~/.mago-ski/policy.json.
|
|
30
|
+
* Never a path in the current directory, because the project being checked may be controlled by the code under review.
|
|
31
|
+
*/
|
|
32
|
+
export function defaultPolicyPath(env = process.env, home = homedir()) {
|
|
33
|
+
const configured = env.MAGO_SKI_POLICY;
|
|
34
|
+
if (!configured)
|
|
35
|
+
return path.join(home, '.mago-ski', 'policy.json');
|
|
36
|
+
if (configured === '~' || configured.startsWith('~/'))
|
|
37
|
+
return path.join(home, configured.slice(2));
|
|
38
|
+
if (!path.isAbsolute(configured))
|
|
39
|
+
throw new Error(`MAGO_SKI_POLICY must be an absolute path (or start with "~/"); got "${configured}"`);
|
|
40
|
+
return configured;
|
|
41
|
+
}
|
|
15
42
|
/** Policy files are hand-edited JSON; paths are relative to the policy file's directory. */
|
|
16
43
|
export async function loadPolicy(policyPath) {
|
|
17
44
|
const absolute = path.resolve(policyPath);
|
|
@@ -25,30 +52,123 @@ export async function loadPolicy(policyPath) {
|
|
|
25
52
|
}
|
|
26
53
|
if (!isRecord(value))
|
|
27
54
|
throw new Error('Policy file must contain a JSON object');
|
|
55
|
+
if (value.policy_version !== POLICY_VERSION && value.policy_version !== POLICY_VERSION_V2)
|
|
56
|
+
throw new Error(`Policy file must declare policy_version "${POLICY_VERSION}" or "${POLICY_VERSION_V2}"`);
|
|
57
|
+
const v2 = value.policy_version === POLICY_VERSION_V2;
|
|
28
58
|
for (const key of Object.keys(value))
|
|
29
|
-
if (!POLICY_KEYS.includes(key))
|
|
30
|
-
throw new Error(`Policy file has unsupported field "${key}"`);
|
|
59
|
+
if (!POLICY_KEYS.includes(key) && !(v2 && POLICY_V2_KEYS.includes(key)))
|
|
60
|
+
throw new Error(`Policy file has unsupported field "${key}"${POLICY_V2_KEYS.includes(key) ? ` (it needs policy_version "${POLICY_VERSION_V2}")` : ''}`);
|
|
31
61
|
for (const key of REQUIRED_POLICY_KEYS)
|
|
32
62
|
if (!(key in value))
|
|
33
63
|
throw new Error(`Policy file is missing "${key}"`);
|
|
34
|
-
if (value.policy_version !== POLICY_VERSION)
|
|
35
|
-
throw new Error(`Policy file must declare policy_version "${POLICY_VERSION}"`);
|
|
36
64
|
if (value.mode !== 'shadow' && value.mode !== 'enforce')
|
|
37
65
|
throw new Error('Policy mode must be "shadow" or "enforce"');
|
|
38
66
|
const base = path.dirname(absolute);
|
|
39
67
|
const resolvePath = (item, label) => path.resolve(base, requireString(item, `Policy ${label}`, 4096));
|
|
68
|
+
// decision_log and state_file are files this tool writes, so the policy may only place them in its own directory.
|
|
69
|
+
const writablePath = async (item, label) => item === undefined || item === null ? null : await resolveInsideDirectory(base, requireString(item, `Policy ${label}`, 4096), `Policy ${label}`);
|
|
40
70
|
const optionalList = (item, label) => item === undefined ? [] : requireArray(item, `Policy ${label}`, 256).map((entry, index) => resolvePath(entry, `${label}[${index}]`));
|
|
41
|
-
|
|
71
|
+
const rootKeyId = validateKeyId(value.root_fingerprint, 'Policy root_fingerprint');
|
|
72
|
+
const policy = {
|
|
42
73
|
path: absolute,
|
|
43
74
|
mode: value.mode,
|
|
44
|
-
rootKeyId
|
|
75
|
+
rootKeyId,
|
|
45
76
|
trustRootPath: resolvePath(value.trust_root, 'trust_root'),
|
|
46
77
|
revocationsPath: resolvePath(value.revocations, 'revocations'),
|
|
47
78
|
certificateDirs: optionalList(value.certificate_dirs, 'certificate_dirs'),
|
|
48
79
|
skillDirs: optionalList(value.skill_dirs, 'skill_dirs'),
|
|
49
|
-
statePath:
|
|
50
|
-
decisionLogPath:
|
|
80
|
+
statePath: await writablePath(value.state_file, 'state_file'),
|
|
81
|
+
decisionLogPath: await writablePath(value.decision_log, 'decision_log'),
|
|
82
|
+
recovery: parseRecoveryPolicy(value, rootKeyId, resolvePath),
|
|
51
83
|
};
|
|
84
|
+
await rejectWriteTargetsThatOverlapInputs(policy);
|
|
85
|
+
return policy;
|
|
86
|
+
}
|
|
87
|
+
/** The v2 fields. A policy without "recovery" must not use the other recovery fields: it behaves as v1. */
|
|
88
|
+
function parseRecoveryPolicy(value, rootKeyId, resolvePath) {
|
|
89
|
+
if (value.recovery === undefined) {
|
|
90
|
+
for (const key of ['root_events', 'root_events_after', 'freshness'])
|
|
91
|
+
if (value[key] !== undefined)
|
|
92
|
+
throw new Error(`Policy "${key}" requires "recovery"`);
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
const set = parseRecoverySet(value.recovery, 'Policy recovery');
|
|
96
|
+
if (set.keyIds.includes(rootKeyId))
|
|
97
|
+
throw new Error('Policy recovery key_ids must not include root_fingerprint');
|
|
98
|
+
if (value.root_events === undefined)
|
|
99
|
+
throw new Error('Policy "recovery" requires "root_events" (publish an empty log with "mago-ski root-events init")');
|
|
100
|
+
const eventsAfter = value.root_events_after === undefined ? 0 : value.root_events_after;
|
|
101
|
+
if (typeof eventsAfter !== 'number' || !Number.isSafeInteger(eventsAfter) || eventsAfter < 0)
|
|
102
|
+
throw new Error('Policy root_events_after must be a non-negative integer');
|
|
103
|
+
let freshness = null;
|
|
104
|
+
if (value.freshness !== undefined) {
|
|
105
|
+
if (!isRecord(value.freshness))
|
|
106
|
+
throw new Error('Policy freshness must be a JSON object');
|
|
107
|
+
for (const key of Object.keys(value.freshness))
|
|
108
|
+
if (!FRESHNESS_KEYS.includes(key))
|
|
109
|
+
throw new Error(`Policy freshness has unsupported field "${key}"`);
|
|
110
|
+
const keyId = validateKeyId(value.freshness.key_id, 'Policy freshness key_id');
|
|
111
|
+
if (keyId === rootKeyId || set.keyIds.includes(keyId))
|
|
112
|
+
throw new Error('Policy freshness key_id must not be root_fingerprint or a recovery key');
|
|
113
|
+
const lifetime = value.freshness.max_lifetime === undefined ? DEFAULT_MAX_TIMESTAMP_LIFETIME : requireString(value.freshness.max_lifetime, 'Policy freshness max_lifetime', 16);
|
|
114
|
+
const maxLifetimeMs = parseDuration(lifetime, 'Policy freshness max_lifetime');
|
|
115
|
+
if (maxLifetimeMs > MAX_TIMESTAMP_LIFETIME_MS)
|
|
116
|
+
throw new Error('Policy freshness max_lifetime must be at most 7d');
|
|
117
|
+
freshness = { timestampPath: resolvePath(value.freshness.timestamp, 'freshness timestamp'), keyId, maxLifetimeMs };
|
|
118
|
+
}
|
|
119
|
+
return { set, rootEventsPath: resolvePath(value.root_events, 'root_events'), eventsAfter, freshness };
|
|
120
|
+
}
|
|
121
|
+
/** A path with symlinks resolved where possible; falls back to the lexical path (the read itself will fail later). */
|
|
122
|
+
async function canonicalOrLexical(target) {
|
|
123
|
+
try {
|
|
124
|
+
return await realpathAllowingMissing(target);
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return path.resolve(target);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
/** decision_log and state_file are overwritten or appended to, so they must not be a file the policy reads. */
|
|
131
|
+
async function rejectWriteTargetsThatOverlapInputs(policy) {
|
|
132
|
+
const inputs = [
|
|
133
|
+
['the policy file', policy.path], ['trust_root', policy.trustRootPath], ['revocations', policy.revocationsPath],
|
|
134
|
+
...(policy.recovery ? [['root_events', policy.recovery.rootEventsPath]] : []),
|
|
135
|
+
...(policy.recovery?.freshness ? [['freshness timestamp', policy.recovery.freshness.timestampPath]] : []),
|
|
136
|
+
];
|
|
137
|
+
const directories = await Promise.all(policy.certificateDirs.map(canonicalOrLexical));
|
|
138
|
+
const targets = [['state_file', policy.statePath], ['decision_log', policy.decisionLogPath]];
|
|
139
|
+
const seen = [];
|
|
140
|
+
for (const [label, target] of targets) {
|
|
141
|
+
if (!target)
|
|
142
|
+
continue;
|
|
143
|
+
const canonical = await canonicalOrLexical(target);
|
|
144
|
+
for (const [name, input] of inputs) {
|
|
145
|
+
if (canonical === await canonicalOrLexical(input))
|
|
146
|
+
throw new Error(`Policy ${label} must not be ${name}`);
|
|
147
|
+
}
|
|
148
|
+
if (directories.some((directory) => isInside(directory, canonical)))
|
|
149
|
+
throw new Error(`Policy ${label} must not be inside a certificate_dirs directory`);
|
|
150
|
+
for (const [other, otherPath] of seen)
|
|
151
|
+
if (canonical === otherPath)
|
|
152
|
+
throw new Error(`Policy ${label} must not be the same file as ${other}`);
|
|
153
|
+
seen.push([label, canonical]);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function stateCount(value, label) {
|
|
157
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1)
|
|
158
|
+
throw new Error(`${label} must be a positive integer`);
|
|
159
|
+
return value;
|
|
160
|
+
}
|
|
161
|
+
/** The host state file exists and was read, but its content or kind is wrong. Every other read error is not this. */
|
|
162
|
+
export class HostStateFormatError extends Error {
|
|
163
|
+
constructor(message) {
|
|
164
|
+
super(message);
|
|
165
|
+
this.name = 'HostStateFormatError';
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const FORMAT_READ_ERROR = /(must be a regular, non-symlink file|exceeds the \d+-byte limit)$/;
|
|
169
|
+
/** The host state file as it is now (a missing file is an empty state). The GUI memory uses this format too. */
|
|
170
|
+
export async function readHostState(statePath) {
|
|
171
|
+
return await readState(statePath);
|
|
52
172
|
}
|
|
53
173
|
async function readState(statePath) {
|
|
54
174
|
let bytes;
|
|
@@ -57,52 +177,482 @@ async function readState(statePath) {
|
|
|
57
177
|
}
|
|
58
178
|
catch (error) {
|
|
59
179
|
if (error?.code === 'ENOENT')
|
|
60
|
-
return {};
|
|
180
|
+
return { roots: {}, rootEvents: {}, timestamps: {}, v2: false };
|
|
181
|
+
if (error instanceof Error && FORMAT_READ_ERROR.test(error.message))
|
|
182
|
+
throw new HostStateFormatError(error.message);
|
|
61
183
|
throw error;
|
|
62
184
|
}
|
|
63
|
-
|
|
64
|
-
|
|
185
|
+
try {
|
|
186
|
+
return parseState(bytes);
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
throw new HostStateFormatError(error.message);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
function parseState(bytes) {
|
|
193
|
+
const parsed = parseCanonicalJsonBytes(bytes, 'host state');
|
|
194
|
+
const v2 = isRecord(parsed) && parsed.type === STATE_TYPE_V2;
|
|
195
|
+
const value = exactKeys(parsed, v2 ? ['type', 'roots', 'root_events', 'timestamps'] : ['type', 'roots'], 'host state');
|
|
196
|
+
if ((value.type !== STATE_TYPE && !v2) || !isRecord(value.roots))
|
|
65
197
|
throw new Error('host state file has an unsupported format');
|
|
66
|
-
const
|
|
198
|
+
const state = { roots: {}, rootEvents: {}, timestamps: {}, v2 };
|
|
67
199
|
for (const [rootKeyId, entry] of Object.entries(value.roots)) {
|
|
68
200
|
const fields = exactKeys(entry, ['trust_root_version', 'revocations_version'], 'host state root');
|
|
69
|
-
roots[validateKeyId(rootKeyId, 'host state root key')] = {
|
|
70
|
-
trust_root_version:
|
|
201
|
+
state.roots[validateKeyId(rootKeyId, 'host state root key')] = {
|
|
202
|
+
trust_root_version: stateCount(fields.trust_root_version, 'host state trust_root_version'),
|
|
203
|
+
revocations_version: stateCount(fields.revocations_version, 'host state revocations_version'),
|
|
71
204
|
};
|
|
72
205
|
}
|
|
73
|
-
|
|
206
|
+
if (v2) {
|
|
207
|
+
if (!isRecord(value.root_events) || !isRecord(value.timestamps))
|
|
208
|
+
throw new Error('host state file has an unsupported format');
|
|
209
|
+
for (const [rootKeyId, entry] of Object.entries(value.root_events)) {
|
|
210
|
+
const withRevoked = isRecord(entry) && 'revoked' in entry;
|
|
211
|
+
const fields = exactKeys(entry, withRevoked ? ['sequence', 'event_digest', 'revoked'] : ['sequence', 'event_digest'], 'host state root_events');
|
|
212
|
+
if (withRevoked && fields.revoked !== true)
|
|
213
|
+
throw new Error('host state root_events revoked must be true when present');
|
|
214
|
+
state.rootEvents[validateKeyId(rootKeyId, 'host state root_events key')] = {
|
|
215
|
+
sequence: stateCount(fields.sequence, 'host state root_events sequence'),
|
|
216
|
+
event_digest: validateKeyId(fields.event_digest, 'host state root_events event_digest'),
|
|
217
|
+
...(withRevoked ? { revoked: true } : {}),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
for (const [keyId, entry] of Object.entries(value.timestamps)) {
|
|
221
|
+
const fields = exactKeys(entry, ['version'], 'host state timestamps');
|
|
222
|
+
state.timestamps[validateKeyId(keyId, 'host state timestamps key')] = { version: stateCount(fields.version, 'host state timestamp version') };
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return state;
|
|
74
226
|
}
|
|
75
|
-
/**
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
227
|
+
/**
|
|
228
|
+
* Combines this load's state with the state file as it is now, so two hosts sharing one state file (two Pi sessions,
|
|
229
|
+
* Pi and the CLI) cannot erase each other's progress: every counter keeps its highest value, the root event entry
|
|
230
|
+
* with the higher sequence wins (on a tie with different digests, the one already on disk stays, so the fork is
|
|
231
|
+
* reported on the next load), and v2 is never written back as v1.
|
|
232
|
+
*/
|
|
233
|
+
export function mergeHostState(ours, disk) {
|
|
234
|
+
const merged = { roots: { ...disk.roots }, rootEvents: { ...disk.rootEvents }, timestamps: { ...disk.timestamps }, v2: ours.v2 || disk.v2 };
|
|
235
|
+
for (const [keyId, entry] of Object.entries(ours.roots)) {
|
|
236
|
+
const other = merged.roots[keyId];
|
|
237
|
+
merged.roots[keyId] = other ? {
|
|
238
|
+
trust_root_version: Math.max(entry.trust_root_version, other.trust_root_version),
|
|
239
|
+
revocations_version: Math.max(entry.revocations_version, other.revocations_version),
|
|
240
|
+
} : entry;
|
|
241
|
+
}
|
|
242
|
+
for (const [keyId, entry] of Object.entries(ours.rootEvents)) {
|
|
243
|
+
const other = merged.rootEvents[keyId];
|
|
244
|
+
if (!other || entry.sequence > other.sequence)
|
|
245
|
+
merged.rootEvents[keyId] = entry;
|
|
246
|
+
}
|
|
247
|
+
for (const [keyId, entry] of Object.entries(ours.timestamps)) {
|
|
248
|
+
const other = merged.timestamps[keyId];
|
|
249
|
+
if (!other || entry.version > other.version)
|
|
250
|
+
merged.timestamps[keyId] = entry;
|
|
251
|
+
}
|
|
252
|
+
return merged;
|
|
253
|
+
}
|
|
254
|
+
function stateBytes(state) {
|
|
255
|
+
if (!state.v2)
|
|
256
|
+
return canonicalBytes({ type: STATE_TYPE, roots: state.roots });
|
|
257
|
+
return canonicalBytes({ type: STATE_TYPE_V2, roots: state.roots, root_events: state.rootEvents, timestamps: state.timestamps });
|
|
258
|
+
}
|
|
259
|
+
/** Reads a file once, so the bytes that are hashed for freshness are the bytes that are parsed. */
|
|
260
|
+
async function readTrustFile(filePath, label, maxBytes) {
|
|
80
261
|
try {
|
|
81
|
-
|
|
82
|
-
revocationsBytes = await readRegularFile(policy.revocationsPath, 'Revocation list', 8 * 1024 * 1024);
|
|
83
|
-
if (policy.statePath)
|
|
84
|
-
roots = await readState(policy.statePath);
|
|
262
|
+
return await readRegularFile(filePath, label, maxBytes);
|
|
85
263
|
}
|
|
86
264
|
catch (error) {
|
|
87
|
-
|
|
265
|
+
if (error?.code === 'ENOENT' && (label === 'Root event log' || label === 'Timestamp'))
|
|
266
|
+
throw new Error(`${label} not found: ${filePath}`);
|
|
267
|
+
throw error;
|
|
88
268
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
269
|
+
}
|
|
270
|
+
/*
|
|
271
|
+
* A revoke this host has applied stays in force while the log cannot be checked: making the log missing, malformed,
|
|
272
|
+
* shorter or forked must not turn root-revoked into trust-unavailable, which shadow mode would let through.
|
|
273
|
+
*/
|
|
274
|
+
function rootBlocked(problem, entry) {
|
|
275
|
+
return entry?.revoked
|
|
276
|
+
? { reason: `root key was revoked by root event ${entry.sequence}, and the root event log cannot be checked now (${problem}); waiting for a valid log with a rotation`, rootRevoked: true }
|
|
277
|
+
: { reason: problem, rootRevoked: false };
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* The root-event part of a load, without I/O: walks the log, compares it with what this host has applied (rollback,
|
|
281
|
+
* fork), and says which progress to record. `loadPolicyTrust` and `loadPolicyRoot` both apply `progress` to their state.
|
|
282
|
+
* Only a revoke result carries a walk on failure; a log that is old, forked or unreadable yields no walk and so no roles.
|
|
283
|
+
*/
|
|
284
|
+
function checkRootEvents(policy, state, log, now) {
|
|
285
|
+
const recovery = policy.recovery;
|
|
286
|
+
const pinned = policy.rootKeyId;
|
|
287
|
+
if (!recovery || log === null)
|
|
288
|
+
return { ok: true, walk: null, activeRootKeyId: pinned, progress: null };
|
|
289
|
+
const seen = state.rootEvents[pinned];
|
|
290
|
+
const stop = (problem, rollback) => ({ ok: false, ...rootBlocked(problem, seen), ...(rollback ? { rollback } : {}), walk: null, progress: null });
|
|
291
|
+
if ('error' in log)
|
|
292
|
+
return stop(`root event log: ${log.error}`);
|
|
293
|
+
let walk;
|
|
294
|
+
try {
|
|
295
|
+
walk = walkRootEventsCached(log.bytes, {
|
|
296
|
+
rootKeyId: pinned, recovery: recovery.set, timestampKeyId: recovery.freshness?.keyId ?? null, eventsAfter: recovery.eventsAfter,
|
|
297
|
+
}, now);
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
return stop(`root event log: ${error.message}`);
|
|
301
|
+
}
|
|
302
|
+
if (seen) {
|
|
303
|
+
if (walk.count < seen.sequence)
|
|
304
|
+
return stop(`root event log has ${walk.count} event(s), but this host has already applied ${seen.sequence} (rollback)`, true);
|
|
305
|
+
if (walk.eventDigests[seen.sequence - 1] !== seen.event_digest)
|
|
306
|
+
return stop(`root event ${seen.sequence} differs from the one this host already applied (fork); the organization must resolve it`);
|
|
307
|
+
}
|
|
308
|
+
// Only events this host checked are recorded: those before root_events_after were never verified here.
|
|
309
|
+
const progress = walk.count > recovery.eventsAfter && (!seen || walk.count > seen.sequence)
|
|
310
|
+
? { sequence: walk.count, event_digest: walk.eventDigests[walk.count - 1], ...(walk.revoked ? { revoked: true } : {}) }
|
|
311
|
+
: null;
|
|
312
|
+
if (walk.revoked) {
|
|
313
|
+
return {
|
|
314
|
+
ok: false, rootRevoked: true, walk, progress,
|
|
315
|
+
reason: `root key ${walk.activeRootKeyId} was revoked by root event ${walk.revoked.sequence} (${walk.revoked.reason}); waiting for a rotation`,
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
return { ok: true, walk, activeRootKeyId: walk.activeRootKeyId, progress };
|
|
319
|
+
}
|
|
320
|
+
async function readRootEventLog(policy) {
|
|
321
|
+
if (!policy.recovery)
|
|
322
|
+
return null;
|
|
323
|
+
try {
|
|
324
|
+
return { bytes: await readTrustFile(policy.recovery.rootEventsPath, 'Root event log', MAX_ROOT_EVENTS_BYTES) };
|
|
325
|
+
}
|
|
326
|
+
catch (error) {
|
|
327
|
+
return { error: error.message };
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
/** Applies a progress entry to a state, as the loads record it. */
|
|
331
|
+
function applyProgress(state, pinned, progress) {
|
|
332
|
+
state.v2 = true;
|
|
333
|
+
state.rootEvents[pinned] = progress;
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Merges `state` with the state file as it is now and writes the result, as a compare-and-swap: the raw bytes are read
|
|
337
|
+
* once, the merge is written only if the file still has those bytes, and a change in between (another process) means
|
|
338
|
+
* re-read, merge and retry, up to 5 times with 10 to 80 ms jittered waits. A counter is never lowered within that
|
|
339
|
+
* budget; when it runs out the write fails closed. A file that cannot be read or parsed fails the write.
|
|
340
|
+
* Returns the merged state, or the reason the write failed.
|
|
341
|
+
*/
|
|
342
|
+
const persistChains = new Map();
|
|
343
|
+
async function persistState(statePath, state) {
|
|
344
|
+
const key = await canonicalOrLexical(statePath);
|
|
345
|
+
const previous = persistChains.get(key) ?? Promise.resolve();
|
|
346
|
+
const run = previous.then(() => persistStateNow(statePath, state));
|
|
347
|
+
const tail = run.catch(() => undefined);
|
|
348
|
+
persistChains.set(key, tail);
|
|
349
|
+
try {
|
|
350
|
+
return await run;
|
|
351
|
+
}
|
|
352
|
+
finally {
|
|
353
|
+
if (persistChains.get(key) === tail)
|
|
354
|
+
persistChains.delete(key);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
const PERSIST_ATTEMPTS = 5;
|
|
358
|
+
async function persistStateNow(statePath, state) {
|
|
359
|
+
try {
|
|
360
|
+
for (let attempt = 0; attempt < PERSIST_ATTEMPTS; attempt += 1) {
|
|
361
|
+
let raw = null;
|
|
362
|
+
try {
|
|
363
|
+
raw = await readRegularFile(statePath, 'Host state file', 1024 * 1024);
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
if (error?.code !== 'ENOENT')
|
|
367
|
+
throw error;
|
|
368
|
+
}
|
|
369
|
+
const disk = raw === null ? null : parseState(raw);
|
|
370
|
+
const merged = disk ? mergeHostState(state, disk) : state;
|
|
99
371
|
try {
|
|
100
|
-
await writeFileAtomic(
|
|
372
|
+
await writeFileAtomic(statePath, stateBytes(merged), 0o600, { expectSha256: raw === null ? null : `sha256:${sha256Hex(raw)}` });
|
|
373
|
+
return { state: merged };
|
|
101
374
|
}
|
|
102
375
|
catch (error) {
|
|
103
|
-
|
|
376
|
+
if (!(error instanceof FileChangedError))
|
|
377
|
+
throw error;
|
|
104
378
|
}
|
|
379
|
+
if (attempt < PERSIST_ATTEMPTS - 1)
|
|
380
|
+
await new Promise((resolve) => setTimeout(resolve, 10 + Math.random() * 70));
|
|
105
381
|
}
|
|
382
|
+
throw new Error('the file kept changing');
|
|
383
|
+
}
|
|
384
|
+
catch (error) {
|
|
385
|
+
return { error: `cannot record trust versions in ${statePath}: ${error.message}` };
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Records document versions in a host state file (the GUI memory), merging with what is on disk: every counter keeps
|
|
390
|
+
* its highest value, so this never lowers anything within the retry budget of `persistState` (it fails closed otherwise). A root entry takes each given half and `1` (the lowest valid
|
|
391
|
+
* value) for a missing one. Throws when the file cannot be read or written.
|
|
392
|
+
*/
|
|
393
|
+
export async function recordDocumentVersions(statePath, v) {
|
|
394
|
+
if ((v.trustRoot !== undefined || v.revocations !== undefined) && v.rootKeyId === undefined)
|
|
395
|
+
throw new Error('rootKeyId is required to record a trust root or revocation list version');
|
|
396
|
+
await readState(statePath);
|
|
397
|
+
const ours = { roots: {}, rootEvents: {}, timestamps: {}, v2: false };
|
|
398
|
+
if (v.rootKeyId !== undefined && (v.trustRoot !== undefined || v.revocations !== undefined))
|
|
399
|
+
ours.roots[v.rootKeyId] = { trust_root_version: v.trustRoot ?? 1, revocations_version: v.revocations ?? 1 };
|
|
400
|
+
if (v.timestamp) {
|
|
401
|
+
ours.timestamps[v.timestamp.keyId] = { version: v.timestamp.version };
|
|
402
|
+
ours.v2 = true;
|
|
403
|
+
}
|
|
404
|
+
const saved = await persistState(statePath, ours);
|
|
405
|
+
if ('error' in saved)
|
|
406
|
+
throw new Error(saved.error);
|
|
407
|
+
}
|
|
408
|
+
/** The lowest versions this computer's memory allows for each document; 0 where nothing is recorded. */
|
|
409
|
+
export function memoryMinimums(state, rootKeyId, timestampKeyId) {
|
|
410
|
+
const root = state.roots[rootKeyId];
|
|
411
|
+
return {
|
|
412
|
+
trustRoot: root?.trust_root_version ?? 0,
|
|
413
|
+
revocations: root?.revocations_version ?? 0,
|
|
414
|
+
timestamp: timestampKeyId === null ? 0 : (state.timestamps[timestampKeyId]?.version ?? 0),
|
|
415
|
+
};
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Keys that must not be approvers in this organisation: the root, the recovery set, the timestamp key, keys that left
|
|
419
|
+
* the root or timestamp role, keys that left a recovery set, and every revoked key. Neither reads nor writes host state.
|
|
420
|
+
* Throws when the root event log or the revocation list cannot be checked, and `StaleDocumentError` when the revocation
|
|
421
|
+
* list is older than `minimumRevocations` (the caller's memory; the CLI passes none).
|
|
422
|
+
*/
|
|
423
|
+
export async function forbiddenApproverKeys(policy, now, o = {}) {
|
|
424
|
+
const rootResult = await loadPolicyRoot(policy, now, { recordVersions: false });
|
|
425
|
+
if (!rootResult.ok)
|
|
426
|
+
throw new Error(`Cannot check the root event log, so no approver is added: ${rootResult.reason}`);
|
|
427
|
+
const found = new Map();
|
|
428
|
+
const add = (keyId, why) => {
|
|
429
|
+
if (keyId && !found.has(keyId))
|
|
430
|
+
found.set(keyId, why);
|
|
431
|
+
};
|
|
432
|
+
const { walk, activeRootKeyId } = rootResult;
|
|
433
|
+
add(activeRootKeyId, 'root');
|
|
434
|
+
add(policy.rootKeyId, 'retired');
|
|
435
|
+
if (walk) {
|
|
436
|
+
for (const keyId of walk.recovery.keyIds)
|
|
437
|
+
add(keyId, 'recovery');
|
|
438
|
+
add(walk.timestampKeyId, 'timestamp');
|
|
439
|
+
for (const keyId of walk.retired)
|
|
440
|
+
add(keyId, 'retired');
|
|
441
|
+
for (const keyId of walk.formerRecovery)
|
|
442
|
+
add(keyId, 'formerRecovery');
|
|
443
|
+
}
|
|
444
|
+
else if (policy.recovery) {
|
|
445
|
+
for (const keyId of policy.recovery.set.keyIds)
|
|
446
|
+
add(keyId, 'recovery');
|
|
447
|
+
add(policy.recovery.freshness?.keyId, 'timestamp');
|
|
448
|
+
}
|
|
449
|
+
let stale = null;
|
|
450
|
+
try {
|
|
451
|
+
const trust = readTrustRootForUpdate(await readRegularFile(policy.trustRootPath, 'Trust root', 4 * 1024 * 1024), activeRootKeyId);
|
|
452
|
+
const list = readRevocationsForUpdate(await readRegularFile(policy.revocationsPath, 'Revocation list', 8 * 1024 * 1024), activeRootKeyId, trust.root.publicKey);
|
|
453
|
+
if (o.minimumRevocations !== undefined && list.version < o.minimumRevocations)
|
|
454
|
+
stale = new StaleDocumentError('Revocation list', list.version, o.minimumRevocations);
|
|
455
|
+
for (const entry of list.keys)
|
|
456
|
+
add(entry.keyId, 'revoked');
|
|
457
|
+
}
|
|
458
|
+
catch (error) {
|
|
459
|
+
throw new Error(`Cannot read the revocation list, so no approver is added: ${error.message}`);
|
|
460
|
+
}
|
|
461
|
+
if (stale)
|
|
462
|
+
throw stale;
|
|
463
|
+
return [...found].map(([keyId, why]) => ({ keyId, why }));
|
|
464
|
+
}
|
|
465
|
+
const stateErrorKind = (error) => error instanceof HostStateFormatError ? 'corrupt' : 'unreadable';
|
|
466
|
+
const failure = (reason, extra = {}) => ({ ok: false, verdict: 'UNVERIFIABLE', reason, ...extra });
|
|
467
|
+
/**
|
|
468
|
+
* Only the root-event part of `loadPolicyTrust`: which root key is active, whether it is revoked, and the walk. It
|
|
469
|
+
* reads the state and the log, checks rollback and forks the same way, and with `recordVersions` (the default) and a
|
|
470
|
+
* state file records the progress with the same merge-before-write. A policy without `recovery` reads nothing.
|
|
471
|
+
*/
|
|
472
|
+
export async function loadPolicyRoot(policy, now, options = {}) {
|
|
473
|
+
if (!policy.recovery)
|
|
474
|
+
return { ok: true, walk: null, activeRootKeyId: policy.rootKeyId };
|
|
475
|
+
const pinned = policy.rootKeyId;
|
|
476
|
+
let state = { roots: {}, rootEvents: {}, timestamps: {}, v2: false };
|
|
477
|
+
try {
|
|
478
|
+
if (policy.statePath)
|
|
479
|
+
state = await readState(policy.statePath);
|
|
480
|
+
}
|
|
481
|
+
catch (error) {
|
|
482
|
+
return { ok: false, reason: error.message, rootRevoked: false, walk: null, stateError: stateErrorKind(error) };
|
|
483
|
+
}
|
|
484
|
+
const checked = checkRootEvents(policy, state, await readRootEventLog(policy), now);
|
|
485
|
+
if (checked.progress)
|
|
486
|
+
applyProgress(state, pinned, checked.progress);
|
|
487
|
+
if (checked.progress && options.recordVersions !== false && policy.statePath !== null) {
|
|
488
|
+
const saved = await persistState(policy.statePath, state);
|
|
489
|
+
if ('error' in saved) {
|
|
490
|
+
// A revoke stays reported as a revoke even when it could not be recorded.
|
|
491
|
+
if (!checked.ok)
|
|
492
|
+
return { ok: false, reason: checked.reason, rootRevoked: checked.rootRevoked, walk: checked.walk, ...(checked.rollback ? { rollback: true } : {}) };
|
|
493
|
+
return { ok: false, reason: saved.error, rootRevoked: false, walk: null, stateError: 'write' };
|
|
494
|
+
}
|
|
495
|
+
const merged = saved.state.rootEvents[pinned];
|
|
496
|
+
if (checked.ok && checked.walk && merged && merged.sequence > checked.walk.count)
|
|
497
|
+
return { ok: false, ...rootBlocked(`root event log has ${checked.walk.count} event(s), but this host has already applied ${merged.sequence} (rollback)`, merged), walk: null, rollback: true };
|
|
498
|
+
}
|
|
499
|
+
if (!checked.ok)
|
|
500
|
+
return { ok: false, reason: checked.reason, rootRevoked: checked.rootRevoked, walk: checked.walk, ...(checked.rollback ? { rollback: true } : {}) };
|
|
501
|
+
return { ok: true, walk: checked.walk, activeRootKeyId: checked.activeRootKeyId };
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Loads trust documents for a policy, enforcing rollback protection through the state file.
|
|
505
|
+
* With `recordVersions: false` the state file is still read (the same rollback minimums apply) but never written:
|
|
506
|
+
* for observers such as the GUI, which must not move a host's rollback memory.
|
|
507
|
+
*
|
|
508
|
+
* With root recovery (policy v2), the order is: walk the root event log, check rollback and forks, stop if the active
|
|
509
|
+
* root is revoked (`rootRevoked`, which blocks in every mode), check the timestamp, then the trust root and revocation
|
|
510
|
+
* list against the active root, then record the new state.
|
|
511
|
+
*/
|
|
512
|
+
export async function loadPolicyTrust(policy, now, options = {}) {
|
|
513
|
+
return await loadTrustBody(policy, now, { record: options.recordVersions !== false });
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* The host's own trust load, for a preview: never records versions, may replace the documents read from disk with
|
|
517
|
+
* in-memory bytes (`override`, subject to the same size limits), and with `skipFreshness` skips reading and checking
|
|
518
|
+
* the timestamp and its binding to the documents (`context.root.timestamp` is then null). Only the GUI service uses it.
|
|
519
|
+
*/
|
|
520
|
+
export async function loadTrustForPreview(policy, now, o = {}) {
|
|
521
|
+
return await loadTrustBody(policy, now, { record: false, ...(o.override ? { override: o.override } : {}), ...(o.skipFreshness ? { skipFreshness: true } : {}) });
|
|
522
|
+
}
|
|
523
|
+
function overridden(bytes, label, maxBytes) {
|
|
524
|
+
if (bytes.byteLength > maxBytes)
|
|
525
|
+
throw new Error(`${label} exceeds the ${maxBytes}-byte limit`);
|
|
526
|
+
return bytes;
|
|
527
|
+
}
|
|
528
|
+
async function loadTrustBody(policy, now, o) {
|
|
529
|
+
const record = o.record && policy.statePath !== null;
|
|
530
|
+
const freshness = o.skipFreshness ? undefined : policy.recovery?.freshness;
|
|
531
|
+
let state = { roots: {}, rootEvents: {}, timestamps: {}, v2: false };
|
|
532
|
+
try {
|
|
533
|
+
if (policy.statePath)
|
|
534
|
+
state = await readState(policy.statePath);
|
|
535
|
+
}
|
|
536
|
+
catch (error) {
|
|
537
|
+
return failure(error.message, { stateError: stateErrorKind(error) });
|
|
538
|
+
}
|
|
539
|
+
const recovery = policy.recovery;
|
|
540
|
+
const pinned = policy.rootKeyId;
|
|
541
|
+
let activeRootKeyId = pinned;
|
|
542
|
+
let walk = null;
|
|
543
|
+
let logBytes = null;
|
|
544
|
+
// Root event progress is recorded as soon as the log is accepted, even if a later step fails: the events are signed
|
|
545
|
+
// by recovery keys, and remembering them is what stops a host being moved back to a log without a revoke.
|
|
546
|
+
let stateChanged = false;
|
|
547
|
+
const saveState = async () => {
|
|
548
|
+
if (!record || !stateChanged)
|
|
549
|
+
return null;
|
|
550
|
+
const saved = await persistState(policy.statePath, state);
|
|
551
|
+
if ('error' in saved)
|
|
552
|
+
return failure(saved.error, { stateError: 'write' });
|
|
553
|
+
state = saved.state;
|
|
554
|
+
stateChanged = false;
|
|
555
|
+
// Another load on this host may have applied later root events meanwhile; this load's log is then a rollback.
|
|
556
|
+
const merged = state.rootEvents[pinned];
|
|
557
|
+
if (walk && merged && merged.sequence > walk.count) {
|
|
558
|
+
const { reason, rootRevoked } = rootBlocked(`root event log has ${walk.count} event(s), but this host has already applied ${merged.sequence} (rollback)`, merged);
|
|
559
|
+
return failure(reason, { ...(rootRevoked ? { rootRevoked } : {}), rollback: true });
|
|
560
|
+
}
|
|
561
|
+
return null;
|
|
562
|
+
};
|
|
563
|
+
if (recovery) {
|
|
564
|
+
const log = await readRootEventLog(policy);
|
|
565
|
+
const checked = checkRootEvents(policy, state, log, now);
|
|
566
|
+
if (checked.progress) {
|
|
567
|
+
applyProgress(state, pinned, checked.progress);
|
|
568
|
+
stateChanged = true;
|
|
569
|
+
}
|
|
570
|
+
walk = checked.walk;
|
|
571
|
+
if (!checked.ok) {
|
|
572
|
+
if (checked.progress)
|
|
573
|
+
await saveState();
|
|
574
|
+
return failure(checked.reason, { ...(checked.rootRevoked ? { rootRevoked: true } : {}), ...(checked.rollback ? { rollback: true } : {}) });
|
|
575
|
+
}
|
|
576
|
+
logBytes = log !== null && 'bytes' in log ? log.bytes : null;
|
|
577
|
+
activeRootKeyId = checked.activeRootKeyId;
|
|
578
|
+
}
|
|
579
|
+
let trustRootBytes;
|
|
580
|
+
let revocationsBytes;
|
|
581
|
+
let timestampBytes = null;
|
|
582
|
+
try {
|
|
583
|
+
trustRootBytes = o.override?.trustRoot ? overridden(o.override.trustRoot, 'Trust root', 4 * 1024 * 1024) : await readTrustFile(policy.trustRootPath, 'Trust root', 4 * 1024 * 1024);
|
|
584
|
+
revocationsBytes = o.override?.revocations ? overridden(o.override.revocations, 'Revocation list', 8 * 1024 * 1024) : await readTrustFile(policy.revocationsPath, 'Revocation list', 8 * 1024 * 1024);
|
|
585
|
+
if (freshness)
|
|
586
|
+
timestampBytes = o.override?.timestamp ? overridden(o.override.timestamp, 'Timestamp', MAX_TIMESTAMP_BYTES) : await readTrustFile(freshness.timestampPath, 'Timestamp', MAX_TIMESTAMP_BYTES);
|
|
587
|
+
}
|
|
588
|
+
catch (error) {
|
|
589
|
+
return await saveState() ?? failure(error.message);
|
|
590
|
+
}
|
|
591
|
+
let timestamp = null;
|
|
592
|
+
if (freshness) {
|
|
593
|
+
// Freshness is configured, so a missing input fails closed instead of skipping the check.
|
|
594
|
+
if (!walk || !logBytes || !timestampBytes || walk.timestampKeyId === null)
|
|
595
|
+
return await saveState() ?? failure('freshness: the timestamp could not be checked');
|
|
596
|
+
const timestampKeyId = walk.timestampKeyId;
|
|
597
|
+
try {
|
|
598
|
+
timestamp = verifyTimestamp(timestampBytes, {
|
|
599
|
+
keyId: timestampKeyId, now, maxLifetimeMs: freshness.maxLifetimeMs,
|
|
600
|
+
minimumVersion: state.timestamps[timestampKeyId]?.version,
|
|
601
|
+
inputs: {
|
|
602
|
+
rootEvents: { sha256: walk.logSha256, count: walk.count },
|
|
603
|
+
trustRoot: { sha256: sha256Hex(trustRootBytes) },
|
|
604
|
+
revocations: { sha256: sha256Hex(revocationsBytes) },
|
|
605
|
+
},
|
|
606
|
+
});
|
|
607
|
+
}
|
|
608
|
+
catch (error) {
|
|
609
|
+
return await saveState() ?? failure(`freshness: ${error.message}`, error instanceof TimestampRollbackError ? { rollback: true } : error instanceof TimestampBindingError ? { bindingMismatch: true } : {});
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
const seen = state.roots[activeRootKeyId];
|
|
613
|
+
const minimum = seen ? { trustRootVersion: seen.trust_root_version, revocationsVersion: seen.revocations_version } : undefined;
|
|
614
|
+
const result = loadTrustContext({ trustRootBytes, revocationsBytes, rootKeyId: activeRootKeyId, now, minimum });
|
|
615
|
+
if (!result.ok)
|
|
616
|
+
return await saveState() ?? result;
|
|
617
|
+
const { trustRoot, revocations } = result.context;
|
|
618
|
+
if (walk) {
|
|
619
|
+
const collision = trustRoot.approvers.find((approver) => walk.recovery.keyIds.includes(approver.keyId) || approver.keyId === walk.timestampKeyId);
|
|
620
|
+
if (collision)
|
|
621
|
+
return await saveState() ?? failure(`trust root lists approver ${collision.keyId}, which is a recovery or timestamp key; no key may hold two roles`);
|
|
622
|
+
const retiredApprover = trustRoot.approvers.find((approver) => walk.retired.includes(approver.keyId));
|
|
623
|
+
if (retiredApprover)
|
|
624
|
+
return await saveState() ?? failure(`trust root lists approver ${retiredApprover.keyId}, which has held the root or timestamp role; a key that left those roles never takes another`);
|
|
625
|
+
}
|
|
626
|
+
if (timestamp && (timestamp.trustRoot.version !== trustRoot.version || timestamp.revocations.version !== revocations.version))
|
|
627
|
+
return await saveState() ?? failure('freshness: the trust root or revocation list version does not match the timestamp', { bindingMismatch: true });
|
|
628
|
+
const next = { trust_root_version: trustRoot.version, revocations_version: revocations.version };
|
|
629
|
+
if (!seen || next.trust_root_version > seen.trust_root_version || next.revocations_version > seen.revocations_version) {
|
|
630
|
+
state.roots[activeRootKeyId] = {
|
|
631
|
+
trust_root_version: Math.max(next.trust_root_version, seen?.trust_root_version ?? 0),
|
|
632
|
+
revocations_version: Math.max(next.revocations_version, seen?.revocations_version ?? 0),
|
|
633
|
+
};
|
|
634
|
+
stateChanged = true;
|
|
635
|
+
}
|
|
636
|
+
if (timestamp && walk?.timestampKeyId) {
|
|
637
|
+
const previous = state.timestamps[walk.timestampKeyId]?.version ?? 0;
|
|
638
|
+
if (timestamp.version > previous) {
|
|
639
|
+
state.v2 = true;
|
|
640
|
+
state.timestamps[walk.timestampKeyId] = { version: timestamp.version };
|
|
641
|
+
stateChanged = true;
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
const problem = await saveState();
|
|
645
|
+
if (problem)
|
|
646
|
+
return problem;
|
|
647
|
+
if (walk) {
|
|
648
|
+
result.context.root = {
|
|
649
|
+
pinnedRootKeyId: policy.rootKeyId,
|
|
650
|
+
activeRootKeyId,
|
|
651
|
+
sequence: walk.count,
|
|
652
|
+
recovery: walk.recovery,
|
|
653
|
+
timestampKeyId: walk.timestampKeyId,
|
|
654
|
+
timestamp: timestamp ? { version: timestamp.version, expiresAt: timestamp.expiresAt } : null,
|
|
655
|
+
};
|
|
106
656
|
}
|
|
107
657
|
return result;
|
|
108
658
|
}
|
|
@@ -116,23 +666,51 @@ async function readOptional(filePath, label) {
|
|
|
116
666
|
throw error;
|
|
117
667
|
}
|
|
118
668
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
669
|
+
/*
|
|
670
|
+
* Certificate lookup order: explicit file, policy certificate directories (<name>.cert.json), then the in-Skill certificate.
|
|
671
|
+
* Candidates are read lazily, one at a time, so a caller that stops early never reads the rest and none are retained here.
|
|
672
|
+
* Candidates come from the checkout under review, so a Skill may have at most MAX_CERTIFICATE_CANDIDATES candidate files
|
|
673
|
+
* totalling MAX_CERTIFICATE_TOTAL_BYTES; going over throws (the Skill is UNVERIFIABLE) instead of reading further.
|
|
674
|
+
*/
|
|
675
|
+
export async function* iterateCertificates(skillName, skillRoot, certificateDirs, explicit) {
|
|
676
|
+
let count = 0;
|
|
677
|
+
let totalBytes = 0;
|
|
678
|
+
const seen = new Set();
|
|
679
|
+
const account = (source, bytes) => {
|
|
680
|
+
count += 1;
|
|
681
|
+
totalBytes += bytes.length;
|
|
682
|
+
if (count > MAX_CERTIFICATE_CANDIDATES)
|
|
683
|
+
throw new Error(`more than ${MAX_CERTIFICATE_CANDIDATES} certificate candidates for this Skill; reduce certificate_dirs or remove stray certificates`);
|
|
684
|
+
if (totalBytes > MAX_CERTIFICATE_TOTAL_BYTES)
|
|
685
|
+
throw new Error(`certificate candidates for this Skill exceed ${MAX_CERTIFICATE_TOTAL_BYTES} bytes in total`);
|
|
686
|
+
return { source, bytes };
|
|
687
|
+
};
|
|
122
688
|
if (explicit) {
|
|
123
|
-
const
|
|
124
|
-
|
|
689
|
+
const candidate = path.resolve(explicit);
|
|
690
|
+
seen.add(candidate);
|
|
691
|
+
yield account(candidate, await readRegularFile(candidate, 'Certificate', MAX_CERTIFICATE_BYTES));
|
|
125
692
|
}
|
|
126
693
|
for (const directory of certificateDirs) {
|
|
127
694
|
const candidate = path.join(directory, `${skillName}.cert.json`);
|
|
695
|
+
if (seen.has(candidate))
|
|
696
|
+
continue;
|
|
697
|
+
seen.add(candidate);
|
|
128
698
|
const bytes = await readOptional(candidate, 'Certificate');
|
|
129
699
|
if (bytes)
|
|
130
|
-
|
|
700
|
+
yield account(candidate, bytes);
|
|
131
701
|
}
|
|
132
702
|
const inSkill = path.join(skillRoot, CERTIFICATE_FILENAME);
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
703
|
+
if (!seen.has(inSkill)) {
|
|
704
|
+
const bytes = await readOptional(inSkill, 'Certificate');
|
|
705
|
+
if (bytes)
|
|
706
|
+
yield account(inSkill, bytes);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
/** Collects every candidate (within the same budget). Prefer `iterateCertificates`, which retains nothing. */
|
|
710
|
+
export async function discoverCertificates(skillName, skillRoot, certificateDirs, explicit) {
|
|
711
|
+
const sources = [];
|
|
712
|
+
for await (const source of iterateCertificates(skillName, skillRoot, certificateDirs, explicit))
|
|
713
|
+
sources.push(source);
|
|
136
714
|
return sources;
|
|
137
715
|
}
|
|
138
716
|
/**
|
|
@@ -141,13 +719,31 @@ export async function discoverCertificates(skillName, skillRoot, certificateDirs
|
|
|
141
719
|
* directory or a linked SKILL.md is returned as a Skill, and verification then rejects it.
|
|
142
720
|
*/
|
|
143
721
|
export const MAX_DISCOVERY_DEPTH = 16;
|
|
144
|
-
|
|
722
|
+
/** Work budget for one discovery run over untrusted trees; exceeding either throws DiscoveryBudgetError. */
|
|
723
|
+
export const MAX_DISCOVERED_SKILLS = 1_000;
|
|
724
|
+
export const MAX_DISCOVERY_ENTRIES = 50_000;
|
|
725
|
+
/** Discovery stopped because the tree is larger than the budget. It never returns a partial list: callers must fail closed. */
|
|
726
|
+
export class DiscoveryBudgetError extends Error {
|
|
727
|
+
constructor(message) {
|
|
728
|
+
super(message);
|
|
729
|
+
this.name = 'DiscoveryBudgetError';
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH, limits = {}) {
|
|
733
|
+
const maxSkills = limits.maxSkills ?? MAX_DISCOVERED_SKILLS;
|
|
734
|
+
const maxEntries = limits.maxEntries ?? MAX_DISCOVERY_ENTRIES;
|
|
145
735
|
const found = new Set();
|
|
146
736
|
const tooDeep = new Set();
|
|
737
|
+
let entries = 0;
|
|
738
|
+
const checkSkills = () => {
|
|
739
|
+
if (found.size + tooDeep.size > maxSkills)
|
|
740
|
+
throw new DiscoveryBudgetError(`more than ${maxSkills} Skills found under skill_dirs; narrow skill_dirs or split the repository`);
|
|
741
|
+
};
|
|
147
742
|
async function walk(directory, depth) {
|
|
148
743
|
try {
|
|
149
744
|
await lstat(path.join(directory, 'SKILL.md'));
|
|
150
745
|
found.add(directory);
|
|
746
|
+
checkSkills();
|
|
151
747
|
return;
|
|
152
748
|
}
|
|
153
749
|
catch (error) {
|
|
@@ -164,6 +760,9 @@ export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH) {
|
|
|
164
760
|
throw error;
|
|
165
761
|
}
|
|
166
762
|
for await (const child of dir) {
|
|
763
|
+
entries += 1;
|
|
764
|
+
if (entries > maxEntries)
|
|
765
|
+
throw new DiscoveryBudgetError(`more than ${maxEntries} directory entries under skill_dirs; narrow skill_dirs or split the repository`);
|
|
167
766
|
const childPath = path.join(directory, child.name);
|
|
168
767
|
if (child.isSymbolicLink()) {
|
|
169
768
|
try {
|
|
@@ -173,6 +772,7 @@ export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH) {
|
|
|
173
772
|
catch {
|
|
174
773
|
// A dangling link has nothing a host could load.
|
|
175
774
|
}
|
|
775
|
+
checkSkills();
|
|
176
776
|
continue;
|
|
177
777
|
}
|
|
178
778
|
if (!child.isDirectory() || child.name === '.git' || child.name === 'node_modules')
|
|
@@ -180,6 +780,7 @@ export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH) {
|
|
|
180
780
|
// Hosts such as Pi search without a depth limit, so never skip deeper directories silently.
|
|
181
781
|
if (depth + 1 > maxDepth) {
|
|
182
782
|
tooDeep.add(childPath);
|
|
783
|
+
checkSkills();
|
|
183
784
|
continue;
|
|
184
785
|
}
|
|
185
786
|
await walk(childPath, depth + 1);
|
|
@@ -193,6 +794,32 @@ export async function findSkillDirs(roots, maxDepth = MAX_DISCOVERY_DEPTH) {
|
|
|
193
794
|
export function tooDeepResult(directory, now) {
|
|
194
795
|
return unverifiable(directory, path.basename(directory), `directory is deeper than the discovery limit (${MAX_DISCOVERY_DEPTH} levels below skill_dirs); Skills below it were not checked. Point skill_dirs closer to the Skills`, now);
|
|
195
796
|
}
|
|
797
|
+
export function trustFailureEvent(failure) {
|
|
798
|
+
return failure.rootRevoked ? 'root-revoked' : 'trust-unavailable';
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* The mode a host acts in for this trust state. A revoked root is a signed statement that the trust anchor is not
|
|
802
|
+
* sound, so it blocks in shadow mode too; no policy setting changes that. Every other failure follows the policy.
|
|
803
|
+
*/
|
|
804
|
+
export function effectiveMode(mode, trust) {
|
|
805
|
+
return trust && !trust.ok && trust.rootRevoked ? 'enforce' : mode;
|
|
806
|
+
}
|
|
807
|
+
/** The single decision-log record for a trust failure: empty skill and skill_dir, null digest and certificate_id. */
|
|
808
|
+
export function trustFailureRecord(failure, mode, now, host = `${hostname()}`) {
|
|
809
|
+
return {
|
|
810
|
+
timestamp: formatTimestamp(now),
|
|
811
|
+
host,
|
|
812
|
+
mode,
|
|
813
|
+
action: failure.rootRevoked ? 'block' : actionFor(mode, false),
|
|
814
|
+
event: trustFailureEvent(failure),
|
|
815
|
+
skill: '',
|
|
816
|
+
skill_dir: '',
|
|
817
|
+
digest: null,
|
|
818
|
+
certificate_id: null,
|
|
819
|
+
verdict: 'UNVERIFIABLE',
|
|
820
|
+
reason: failure.reason,
|
|
821
|
+
};
|
|
822
|
+
}
|
|
196
823
|
export function actionFor(mode, verified) {
|
|
197
824
|
if (verified)
|
|
198
825
|
return 'allow';
|
|
@@ -201,8 +828,12 @@ export function actionFor(mode, verified) {
|
|
|
201
828
|
export async function appendDecision(logPath, record) {
|
|
202
829
|
if (!logPath)
|
|
203
830
|
return;
|
|
204
|
-
|
|
831
|
+
// One JSON object per line. JSON.stringify escapes newlines and control characters; also escape the Unicode
|
|
832
|
+
// line separators some JSON Lines readers split on, plus C1 controls, DEL and bidi controls. The text is data, not shell syntax: never source a log.
|
|
833
|
+
const line = JSON.stringify(record).replace(/[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/gu, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
|
|
834
|
+
await appendToRegularFile(logPath, `${line}\n`, 'Decision log');
|
|
205
835
|
}
|
|
836
|
+
/* */
|
|
206
837
|
export function decisionRecord(result, mode, event, host = `${hostname()}`) {
|
|
207
838
|
return {
|
|
208
839
|
timestamp: result.checkedAt,
|
|
@@ -232,6 +863,6 @@ export async function verifyWithPolicy(policy, skillDir, options) {
|
|
|
232
863
|
skillName: options.skillName,
|
|
233
864
|
context,
|
|
234
865
|
now: options.now,
|
|
235
|
-
certificates: (name, root) =>
|
|
866
|
+
certificates: (name, root) => iterateCertificates(name, root, policy.certificateDirs, options.certificate),
|
|
236
867
|
});
|
|
237
868
|
}
|