axstack 0.67.0 → 0.69.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 +2 -2
- package/docs/host-operations.md +3 -6
- package/docs/installation.md +10 -10
- package/docs/workflows.md +7 -11
- package/package.json +2 -2
- package/profiles/presets/claude-only.json +2 -2
- package/profiles/presets/codex-only.json +2 -2
- package/profiles/presets/mixed.json +2 -2
- package/skills/axstack/references/automations.md +18 -33
- package/skills/axstack/references/autopilot.md +1 -0
- package/skills/axstack/references/capture-receipts.md +22 -0
- package/skills/axstack/references/contracts.md +1 -1
- package/skills/axstack/references/lifecycle.md +1 -1
- package/skills/axstack/references/live-run.md +59 -0
- package/skills/axstack/references/local-artifacts.md +1 -1
- package/skills/axstack/references/pr-shape.md +13 -16
- package/skills/axstack/references/review-manager-prompt.md +38 -42
- package/skills/axstack/references/role-roster.md +1 -1
- package/skills/axstack/references/run-record.md +7 -5
- package/skills/axstack/references/test-audit-weekly.md +1 -2
- package/skills/axstack/references/ui-verification.md +5 -3
- package/skills/axstack/references/workspace-hygiene.md +3 -0
- package/skills/axstack/sandbox/Dockerfile +28 -0
- package/skills/axstack/sandbox/host-execution.md +14 -0
- package/skills/axstack/sandbox/inventory.json +503 -0
- package/skills/axstack/sandbox/launcher-capture.js +63 -0
- package/skills/axstack/sandbox/launcher-contract.schema.json +341 -0
- package/skills/axstack/sandbox/launcher-contracts.js +35 -0
- package/skills/axstack/sandbox/launcher-docker.js +75 -0
- package/skills/axstack/sandbox/launcher-host-budget.json +10 -0
- package/skills/axstack/sandbox/launcher-host.js +165 -0
- package/skills/axstack/sandbox/launcher-host.json +5 -0
- package/skills/axstack/sandbox/launcher-image.json +4 -0
- package/skills/axstack/sandbox/launcher-interface.md +7 -0
- package/skills/axstack/sandbox/launcher-policy.js +135 -0
- package/skills/axstack/sandbox/launcher-policy.json +121 -0
- package/skills/axstack/sandbox/launcher-runtime.js +157 -0
- package/skills/axstack/sandbox/launcher-source.js +72 -0
- package/skills/axstack/sandbox/launcher.js +106 -0
- package/skills/axstack/sandbox/network-address.js +39 -0
- package/skills/axstack/sandbox/network-firewall.js +81 -0
- package/skills/axstack/sandbox/network-rules.js +86 -0
- package/skills/axstack/sandbox/network-runtime.js +109 -0
- package/skills/axstack/sandbox/network.js +49 -0
- package/skills/axstack/sandbox/probes-android-platform.xml +17 -0
- package/skills/axstack/sandbox/probes-check.js +185 -0
- package/skills/axstack/sandbox/probes-exec.js +20 -0
- package/skills/axstack/sandbox/probes-image-build.js +129 -0
- package/skills/axstack/sandbox/probes-image-pins.json +370 -0
- package/skills/axstack/sandbox/probes-link-local.js +25 -0
- package/skills/axstack/sandbox/probes-storage.js +33 -0
- package/skills/axstack/sandbox/probes-udp.js +44 -0
- package/skills/axstack/sandbox/probes.js +239 -0
- package/skills/axstack/sandbox/proxy-command.js +6 -0
- package/skills/axstack/sandbox/proxy-config.json +9 -0
- package/skills/axstack/sandbox/proxy-dns.js +114 -0
- package/skills/axstack/sandbox/proxy-policy.js +22 -0
- package/skills/axstack/sandbox/proxy.js +119 -0
- package/skills/axstack/sandbox/reap.md +7 -0
- package/skills/axstack/sandbox/sidecars.json +153 -0
- package/skills/axstack/sandbox/storage-checks.js +39 -0
- package/skills/axstack/sandbox/storage-cleanup.js +49 -0
- package/skills/axstack/sandbox/storage-execution.js +110 -0
- package/skills/axstack/sandbox/storage-plan.js +78 -0
- package/skills/axstack/sandbox/storage-support.js +91 -0
- package/skills/axstack/sandbox/storage.js +75 -0
- package/skills/axstack/scripts/archive-evidence.js +2 -2
- package/skills/axstack/scripts/capture-identity.js +122 -0
- package/skills/axstack/scripts/check-run.js +248 -0
- package/skills/axstack/scripts/check-staged-file-tokens.js +6 -3
- package/skills/axstack/scripts/command-capture.js +81 -0
- package/skills/axstack/scripts/evidence-inspector.js +182 -0
- package/skills/axstack/scripts/git-argv.js +6 -0
- package/skills/axstack/scripts/image-evidence.js +183 -0
- package/skills/axstack/scripts/lane-owner.js +183 -0
- package/skills/axstack/scripts/pr-digest.js +17 -1
- package/skills/axstack/scripts/pr-fresh.js +139 -0
- package/skills/axstack/scripts/pr-shape.js +54 -29
- package/skills/axstack/scripts/readiness-run.js +3 -75
- package/skills/axstack/scripts/readiness.js +2 -2
- package/skills/axstack/scripts/run-init.js +13 -11
- package/skills/axstack/scripts/schedule-drift.js +221 -4
- package/skills/axstack-audit/references/record.md +1 -1
- package/skills/axstack-brainstorm/references/arena.md +5 -5
- package/skills/axstack-explain/references/inline-pages.md +8 -4
- package/skills/axstack-implement/SKILL.md +6 -5
- package/skills/axstack-review/SKILL.md +2 -3
- package/skills/axstack-review/references/candidate-brief.md +12 -21
- package/skills/axstack-review/references/codebase-brief.md +1 -0
- package/skills/axstack-review/references/codebase-mode.md +4 -1
- package/skills/axstack-review/references/codebase-report.md +2 -1
- package/skills/axstack-review/references/peer-mode.md +11 -12
- package/skills/axstack-review/references/review-candidate.md +2 -2
- package/skills/axstack-review/references/review-receipt.md +8 -3
- package/skills/axstack-verify/SKILL.md +10 -4
- package/skills/axstack-watch/references/proven-verification.md +3 -2
- package/skills/axstack-watch/references/readiness.md +56 -61
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statfsSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { sha256 } from '../scripts/capture-identity.js';
|
|
3
|
+
import { fact, hold, safePath, validate } from './launcher-policy.js';
|
|
4
|
+
|
|
5
|
+
export const ownedDirectory = '/var/lib/axstack/sandbox';
|
|
6
|
+
const moduleDir = import.meta.dir;
|
|
7
|
+
const env = { PATH: '/usr/sbin:/usr/bin:/sbin:/bin', LANG: 'C', HOME: '/nonexistent', DOCKER_HOST: 'unix:///var/run/docker.sock', DOCKER_CONFIG: '/nonexistent' };
|
|
8
|
+
export async function execute(argv, { maxBytes = 1048576, binary = false, timeoutMs = 10000 } = {}) {
|
|
9
|
+
let p;
|
|
10
|
+
try { p = Bun.spawn(argv, { env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' }); }
|
|
11
|
+
catch { hold(`host prerequisite unavailable: ${argv[0]}`); }
|
|
12
|
+
let timer, used = 0;
|
|
13
|
+
const read = async stream => {
|
|
14
|
+
const chunks = [];
|
|
15
|
+
for await (const data of stream) {
|
|
16
|
+
used += data.length;
|
|
17
|
+
if (used > maxBytes) { p.kill('SIGKILL'); hold('host command output cap exceeded'); }
|
|
18
|
+
chunks.push(data);
|
|
19
|
+
}
|
|
20
|
+
const bytes = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
|
|
21
|
+
let offset = 0; for (const c of chunks) { bytes.set(c, offset); offset += c.length; }
|
|
22
|
+
return bytes;
|
|
23
|
+
};
|
|
24
|
+
try {
|
|
25
|
+
timer = setTimeout(() => p.kill('SIGKILL'), timeoutMs);
|
|
26
|
+
const [stdout, stderr, exitCode] = await Promise.all([read(p.stdout), read(p.stderr), p.exited]);
|
|
27
|
+
return { exitCode, stdout: binary ? stdout : new TextDecoder().decode(stdout), stderr: new TextDecoder().decode(stderr) };
|
|
28
|
+
} finally { clearTimeout(timer); }
|
|
29
|
+
}
|
|
30
|
+
function jsonFile(name) { return JSON.parse(readFileSync(`${moduleDir}/${name}`, 'utf8')); }
|
|
31
|
+
export async function loadAssets() {
|
|
32
|
+
const optional = name => { try { return jsonFile(name); } catch (e) { if (e.code !== 'ENOENT') throw e; return null; } };
|
|
33
|
+
return { hostBinding: optional('launcher-host.json'), hostBudget: optional('launcher-host-budget.json'), policy: optional('launcher-policy.json'),
|
|
34
|
+
proxy: optional('proxy-config.json'), sidecars: optional('sidecars.json'), workloadImage: optional('launcher-image.json')?.image ?? null,
|
|
35
|
+
registryAllowlist: optional('inventory.json')?.registryAllowlist, ownedDir: ownedDirectory };
|
|
36
|
+
}
|
|
37
|
+
export function processState(owner, read = path => readFileSync(path, 'utf8')) {
|
|
38
|
+
let boot;
|
|
39
|
+
try { boot = read('/proc/sys/kernel/random/boot_id').trim(); } catch { return 'unknown'; }
|
|
40
|
+
if (!owner?.bootId || !/^\d+$/.test(owner.startTimeTicks) || !Number.isSafeInteger(owner.pid) || owner.pid < 1) return 'unknown';
|
|
41
|
+
if (boot !== owner.bootId) return 'dead';
|
|
42
|
+
try {
|
|
43
|
+
const text = read(`/proc/${owner.pid}/stat`);
|
|
44
|
+
const rest = text.slice(text.lastIndexOf(')') + 2).trim().split(/\s+/);
|
|
45
|
+
if (!text.startsWith(`${owner.pid} (`) || !/^\d+$/.test(rest[19])) return 'unknown';
|
|
46
|
+
return rest[19] === owner.startTimeTicks ? 'live' : 'dead';
|
|
47
|
+
} catch (e) { return e.code === 'ENOENT' || e.code === 'ESRCH' ? 'dead' : 'unknown'; }
|
|
48
|
+
}
|
|
49
|
+
export async function currentOwner(runId) {
|
|
50
|
+
const text = readFileSync(`/proc/${process.pid}/stat`, 'utf8');
|
|
51
|
+
const startTimeTicks = text.slice(text.lastIndexOf(')') + 2).trim().split(/\s+/)[19];
|
|
52
|
+
const owner = { label: 'axstack.sandbox', runId, pid: process.pid, startTimeTicks, bootId: readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim() };
|
|
53
|
+
if (processState(owner) !== 'live') hold('cannot establish launcher PID/start time');
|
|
54
|
+
return owner;
|
|
55
|
+
}
|
|
56
|
+
export async function observeHost(a) {
|
|
57
|
+
const hostname = readFileSync('/proc/sys/kernel/hostname', 'utf8').trim();
|
|
58
|
+
const machineIdSha256 = sha256(readFileSync('/etc/machine-id', 'utf8').trim());
|
|
59
|
+
const memory = /^MemAvailable:\s+(\d+) kB$/m.exec(readFileSync('/proc/meminfo', 'utf8'));
|
|
60
|
+
let path = a.ownedDir;
|
|
61
|
+
while (true) {
|
|
62
|
+
try { lstatSync(path); break; } catch (e) { if (e.code !== 'ENOENT') throw e; path = path.slice(0, path.lastIndexOf('/')) || '/'; }
|
|
63
|
+
}
|
|
64
|
+
const fs = statfsSync(path);
|
|
65
|
+
const r = await execute(['ip', '-j', 'address', 'show']);
|
|
66
|
+
let addresses = [];
|
|
67
|
+
try { if (r.exitCode === 0 && typeof r.stdout === 'string') addresses = JSON.parse(r.stdout).flatMap(n => n.addr_info.map(x => x.local)); } catch { /* Unknown facts hold. */ }
|
|
68
|
+
return { hostname, machineIdSha256, freeMemoryBytes: memory ? Number(memory[1]) * 1024 : NaN, freeDiskBytes: Number(fs.bavail) * Number(fs.bsize), addresses,
|
|
69
|
+
terms: [fact('host-addresses', addresses.length ? 'pass' : 'unknown', 'ip -j address show'), fact('host-memory', memory ? 'pass' : 'unknown', '/proc/meminfo MemAvailable'),
|
|
70
|
+
fact('host-process-visibility', readFileSync('/proc/1/comm', 'utf8').trim() === 'systemd' ? 'pass' : 'unknown', 'approved host requires visible systemd PID 1; hidden host processes hold reaping')] };
|
|
71
|
+
}
|
|
72
|
+
function privateDirectory(path, create = false, allowGitMetadata = false) {
|
|
73
|
+
safePath(path, { allowGitMetadata });
|
|
74
|
+
if (create) mkdirSync(path, { mode: 0o700, recursive: true });
|
|
75
|
+
const s = lstatSync(path);
|
|
76
|
+
if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== process.getuid() || (s.mode & 0o777) !== 0o700 || realpathSync(path) !== path) hold(`require owned 0700 real directory: ${path}`);
|
|
77
|
+
}
|
|
78
|
+
export async function withAdmission(fn, directory = ownedDirectory, wait = false) {
|
|
79
|
+
privateDirectory(directory, true);
|
|
80
|
+
const lockPath = `${directory}/admission.lock`;
|
|
81
|
+
try { writeFileSync(lockPath, '', { flag: 'wx', mode: 0o600 }); }
|
|
82
|
+
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
83
|
+
const lockStat = lstatSync(lockPath);
|
|
84
|
+
if (!lockStat.isFile() || lockStat.uid !== process.getuid() || lockStat.nlink !== 1 || lockStat.mode & 0o077) hold('unsafe admission lock');
|
|
85
|
+
// The kernel drops flock when this helper exits, even after launcher SIGKILL.
|
|
86
|
+
const p = Bun.spawn(['flock', '--exclusive', ...(wait ? ['--wait', '30'] : ['--nonblock']), `${directory}/admission.lock`, process.execPath, '-e', 'process.stdout.write("locked\\n"); await Bun.stdin.text();'], { env, stdin: 'pipe', stdout: 'pipe', stderr: 'ignore' });
|
|
87
|
+
const reader = p.stdout.getReader();
|
|
88
|
+
let timer;
|
|
89
|
+
try {
|
|
90
|
+
const first = await Promise.race([reader.read(), new Promise((_, reject) => { timer = setTimeout(() => reject(Error('admission lock timeout')), wait ? 35000 : 5000); })]);
|
|
91
|
+
if (first.done || new TextDecoder().decode(first.value) !== 'locked\n') hold('host admission busy; retry in a later run');
|
|
92
|
+
return await fn();
|
|
93
|
+
} finally {
|
|
94
|
+
// Wait for flock AND its child to release the inherited lock fd. Killing only
|
|
95
|
+
// flock can return while its still-exiting child briefly retains admission.
|
|
96
|
+
clearTimeout(timer); reader.releaseLock(); p.stdin.end(); await p.exited;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
export async function records(a, observe = execute) {
|
|
100
|
+
const runs = [];
|
|
101
|
+
for (const entry of readdirSync(a.ownedDir, { withFileTypes: true })) {
|
|
102
|
+
if (['admission.lock', '.axstack-storage.lock'].includes(entry.name)) {
|
|
103
|
+
const s = lstatSync(`${a.ownedDir}/${entry.name}`);
|
|
104
|
+
if (!s.isFile() || s.uid !== process.getuid() || s.nlink !== 1 || s.mode & 0o077) hold('unsafe owned lock file');
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (entry.isFile() && entry.name.endsWith('.img')) continue; // Checked against records below.
|
|
108
|
+
if (entry.isFile() && entry.name.endsWith('.img.owner.json')) continue;
|
|
109
|
+
if (!entry.isDirectory() || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(entry.name)) hold(`unknown owned state: ${entry.name}; driver must resolve`);
|
|
110
|
+
try {
|
|
111
|
+
privateDirectory(`${a.ownedDir}/${entry.name}`);
|
|
112
|
+
const p = JSON.parse(readFileSync(`${a.ownedDir}/${entry.name}/plan.json`, 'utf8'));
|
|
113
|
+
validate('plan', p);
|
|
114
|
+
const image = safePath(p.storage.imageFile);
|
|
115
|
+
if (p.runId !== entry.name || p.sourceExport.path !== `${a.ownedDir}/${p.runId}/source` || !image.startsWith(`${a.ownedDir}/`) || image.slice(a.ownedDir.length + 1).includes('/')) hold('record paths do not match owned run');
|
|
116
|
+
runs.push(p);
|
|
117
|
+
} catch (e) { hold(`unreadable run record ${entry.name}: ${e.message}; owning driver must resolve`); }
|
|
118
|
+
}
|
|
119
|
+
for (const file of readdirSync(a.ownedDir).filter(n => n.endsWith('.img'))) if (!runs.some(p => p.storage.imageFile === `${a.ownedDir}/${file}`)) hold(`orphan image file ${file}; owning driver must resolve`);
|
|
120
|
+
for (const file of readdirSync(a.ownedDir).filter(n => n.endsWith('.img.owner.json'))) {
|
|
121
|
+
const path = `${a.ownedDir}/${file}`, stat = lstatSync(path);
|
|
122
|
+
if (!stat.isFile() || stat.uid !== process.getuid() || stat.nlink !== 1 || stat.mode & 0o077) hold('unsafe storage ownership record');
|
|
123
|
+
const record = JSON.parse(readFileSync(path, 'utf8'));
|
|
124
|
+
if (!runs.some(p => `${p.storage.imageFile}.owner.json` === path && record.imageFile === p.storage.imageFile && record.volumeName === p.storage.volumeName && JSON.stringify(record.owner) === JSON.stringify(p.owner) && record.bytes === p.storage.bytes && record.inodes === p.storage.inodes)) hold(`orphan/changed storage record ${file}; owning driver must resolve`);
|
|
125
|
+
}
|
|
126
|
+
const r = await observe(['docker', 'ps', '-a', '--filter', 'label=axstack.sandbox=true', '--format', '{{.Names}}']);
|
|
127
|
+
if (r.exitCode !== 0 || typeof r.stdout !== 'string') hold('cannot enumerate labelled containers');
|
|
128
|
+
for (const name of r.stdout.trim().split('\n').filter(Boolean)) if (!runs.some(p => p.containers.some(c => c.id === name))) hold(`labelled container lacks liveness record: ${name}`);
|
|
129
|
+
return runs;
|
|
130
|
+
}
|
|
131
|
+
export async function savePlan(p, evidenceDir, directory = ownedDirectory) {
|
|
132
|
+
privateDirectory(evidenceDir, false, true);
|
|
133
|
+
const sourceRoot = realpathSync(p.request.repo);
|
|
134
|
+
if (evidenceDir === sourceRoot || evidenceDir.startsWith(`${sourceRoot}/`) || evidenceDir === directory || evidenceDir.startsWith(`${directory}/`)) hold('evidence must be outside source and owned writable roots');
|
|
135
|
+
const dir = `${directory}/${p.runId}`;
|
|
136
|
+
let existing = false;
|
|
137
|
+
try { lstatSync(dir); existing = true; } catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
138
|
+
if (!existing && readdirSync(evidenceDir).length) hold('a new run requires an empty evidence directory');
|
|
139
|
+
if (lstatSync(evidenceDir).dev !== lstatSync(directory).dev) hold('evidence and owned storage must use the budgeted filesystem');
|
|
140
|
+
privateDirectory(dir, true);
|
|
141
|
+
const bytes = `${JSON.stringify(p)}\n`;
|
|
142
|
+
if (new TextEncoder().encode(bytes).length * 2 > p.policy.receiptMaxBytes) hold('effective plan exceeds host receipt directory cap');
|
|
143
|
+
writeFileSync(`${dir}/plan.json`, bytes, { mode: 0o600 });
|
|
144
|
+
writeFileSync(`${evidenceDir}/${p.runId}-plan.json`, bytes, { mode: 0o600 });
|
|
145
|
+
return bytes;
|
|
146
|
+
}
|
|
147
|
+
export async function removeRecord(p) {
|
|
148
|
+
const dir = `${ownedDirectory}/${p.runId}`;
|
|
149
|
+
if (p.sourceExport.path !== `${dir}/source`) hold('unexpected source cleanup path');
|
|
150
|
+
privateDirectory(dir);
|
|
151
|
+
rmSync(dir, { recursive: true, force: true });
|
|
152
|
+
}
|
|
153
|
+
export function setDeadline(wallMs, graceMs, cancel) {
|
|
154
|
+
const timer = setTimeout(() => cancel('wall-time'), wallMs);
|
|
155
|
+
const hard = setTimeout(() => cancel('wall-time-plus-grace'), wallMs + graceMs);
|
|
156
|
+
return () => { clearTimeout(timer); clearTimeout(hard); };
|
|
157
|
+
}
|
|
158
|
+
export function onSignal(cancel) {
|
|
159
|
+
const listeners = new Map();
|
|
160
|
+
for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) { const fn = () => cancel(signal); process.on(signal, fn); listeners.set(signal, fn); }
|
|
161
|
+
return () => { for (const [signal, fn] of listeners) process.off(signal, fn); };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Fixed startup grace for trusted pinned sidecars, inside the run wall-time.
|
|
165
|
+
export async function settleSidecars() { await Bun.sleep(10000); }
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Sandbox interface v1
|
|
2
|
+
|
|
3
|
+
Int owns B–E interfaces; return conflicts to Int.
|
|
4
|
+
[JSDoc contracts](launcher-contracts.js) own signatures;
|
|
5
|
+
[wire schema](launcher-contract.schema.json) owns assets/plans/receipts.
|
|
6
|
+
`bun launcher.js --help` owns operational flags, effects and holds.
|
|
7
|
+
Plans/results grant no authority. Retain [peer execution](host-execution.md).
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { proxyArgv } from './network.js';
|
|
3
|
+
|
|
4
|
+
const definitions = JSON.parse(readFileSync(new URL('./launcher-contract.schema.json', import.meta.url), 'utf8')).$defs;
|
|
5
|
+
export const fact = (id, status, evidence) => ({ id, status, evidence: [String(evidence)] });
|
|
6
|
+
/** @returns {never} */
|
|
7
|
+
export function hold(message, terms = []) { throw Object.assign(Error(message), { sandboxHold: true, terms }); }
|
|
8
|
+
export function requirePass(terms, context) {
|
|
9
|
+
if (!Array.isArray(terms) || !terms.length || terms.some(t => t.status !== 'pass' && t.status !== 'n/a')) hold(`${context}: failed/unknown facts`, terms);
|
|
10
|
+
}
|
|
11
|
+
export function matches(value, rule) {
|
|
12
|
+
if (rule.$ref) return matches(value, definitions[rule.$ref.split('/').at(-1)]);
|
|
13
|
+
if ('const' in rule && JSON.stringify(value) !== JSON.stringify(rule.const)) return false;
|
|
14
|
+
if (rule.enum && !rule.enum.includes(value)) return false;
|
|
15
|
+
const type = value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
|
|
16
|
+
if (rule.type) {
|
|
17
|
+
const types = Array.isArray(rule.type) ? rule.type : [rule.type];
|
|
18
|
+
if (!types.includes(type) && !(types.includes('integer') && Number.isSafeInteger(value))) return false;
|
|
19
|
+
}
|
|
20
|
+
if (typeof value === 'number' && (!Number.isFinite(value) || value < (rule.minimum ?? -Infinity) || value <= (rule.exclusiveMinimum ?? -Infinity))) return false;
|
|
21
|
+
if (typeof value === 'string' && (value.includes('\0') || value.length < (rule.minLength ?? 0) || (rule.pattern && !new RegExp(rule.pattern).test(value)))) return false;
|
|
22
|
+
if (Array.isArray(value)) return value.length >= (rule.minItems ?? 0) && value.every(v => matches(v, rule.items ?? {}));
|
|
23
|
+
if (type === 'object') {
|
|
24
|
+
if ((rule.required ?? []).some(k => !Object.hasOwn(value, k))) return false;
|
|
25
|
+
return Object.entries(value).every(([key, v]) => rule.properties?.[key] ? matches(v, rule.properties[key]) : rule.additionalProperties !== false);
|
|
26
|
+
}
|
|
27
|
+
return true;
|
|
28
|
+
}
|
|
29
|
+
export function validate(name, value) {
|
|
30
|
+
if (!matches(value, definitions[name])) throw Error(`invalid ${name}`);
|
|
31
|
+
}
|
|
32
|
+
export function safePath(path, { allowGitMetadata = false } = {}) {
|
|
33
|
+
if (typeof path !== 'string' || !path.startsWith('/') || path === '/' || /[\0\n\r,:]/.test(path) || path.split('/').some(s => s === '.' || s === '..' || !allowGitMetadata && s === '.git')) throw Error(`unsafe absolute path: ${path}`);
|
|
34
|
+
return path;
|
|
35
|
+
}
|
|
36
|
+
export function checkAssets(a) {
|
|
37
|
+
if (!a) hold('missing packaged assets');
|
|
38
|
+
for (const [key, def] of [['hostBinding', 'hostBinding'], ['hostBudget', 'hostBudget'], ['policy', 'launchPolicy'], ['proxy', 'proxyConfig'], ['sidecars', 'sidecars'], ['workloadImage', 'image']]) {
|
|
39
|
+
if (a[key] == null) hold(`unprovisioned ${key}`);
|
|
40
|
+
validate(def, a[key]);
|
|
41
|
+
}
|
|
42
|
+
safePath(a.ownedDir);
|
|
43
|
+
if (!Array.isArray(a.registryAllowlist) || !a.registryAllowlist.length || a.registryAllowlist.some(s => typeof s !== 'string' || !/^[a-z0-9][a-z0-9.-]*$/.test(s))) hold('missing/invalid inventory registry allowlist');
|
|
44
|
+
const p = a.policy;
|
|
45
|
+
if (p.wallTimeSeconds + p.graceSeconds > p.maxWallTimeSeconds || p.maxWallTimeSeconds > 910) throw Error('wall-time plus grace exceeds fixed maximum 910');
|
|
46
|
+
for (const c of [p.workloadCaps, p.proxyCaps, p.sidecarCaps]) if (c.memorySwapBytes !== c.memoryBytes) throw Error('memory swap must equal memory');
|
|
47
|
+
const names = p.environment.map(e => e.name);
|
|
48
|
+
if (new Set(names).size !== names.length || names.some(n => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))) throw Error('invalid literal environment');
|
|
49
|
+
const ids = a.sidecars.images.map(s => s.id);
|
|
50
|
+
if (new Set(ids).size !== ids.length) throw Error('duplicate sidecar IDs');
|
|
51
|
+
for (const s of a.sidecars.images) {
|
|
52
|
+
if (!/^[a-z0-9][a-z0-9-]*$/.test(s.id)) throw Error('invalid sidecar ID');
|
|
53
|
+
for (const t of s.declaredVolumes) {
|
|
54
|
+
safePath(t.path);
|
|
55
|
+
if (['/work', '/tmp', '/source', '/dependencies', '/proc', '/sys', '/dev', '/etc'].some(r => t.path === r || t.path.startsWith(`${r}/`) || r.startsWith(`${t.path}/`))) throw Error('unsafe image VOLUME path');
|
|
56
|
+
if (!/^0[0-7]{3}$/.test(t.mode) || t.noexec !== true) throw Error('unsafe image VOLUME permissions');
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export const sameHost = (binding, host) => binding?.hostname === 'axat-vps' && host?.hostname === binding.hostname && /^[a-f0-9]{64}$/.test(binding.machineIdSha256) && binding.machineIdSha256 === host.machineIdSha256;
|
|
61
|
+
|
|
62
|
+
function container({ id, role, image, networkIds, caps, declaredVolumes = [], environment, policy, owner, source, storage, networks, command, dns = [] }) {
|
|
63
|
+
const [uid, gid] = policy.user.split(':').map(Number);
|
|
64
|
+
const tmpfs = [{ path: '/tmp', bytes: Math.min(policy.writableBytes, 16777216), uid, gid, mode: '0700', noexec: true }, ...declaredVolumes];
|
|
65
|
+
if (role === 'fetch' || role === 'test') tmpfs.push({ path: '/work', bytes: policy.writableBytes, uid, gid, mode: '0700', noexec: false });
|
|
66
|
+
const argv = ['docker', 'create', '--pull', 'never', '--name', id,
|
|
67
|
+
'--user', policy.user, '--read-only', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges=true',
|
|
68
|
+
'--cpus', String(caps.cpus), '--memory', String(caps.memoryBytes), '--memory-swap', String(caps.memorySwapBytes), '--pids-limit', String(caps.pids),
|
|
69
|
+
'--log-driver', 'local', '--log-opt', `max-size=${caps.logMaxBytes}`, '--log-opt', 'max-file=1', '--log-opt', 'compress=false', '--restart', 'no'];
|
|
70
|
+
for (const [key, value] of Object.entries(owner)) argv.push('--label', `axstack.sandbox.${key}=${value}`);
|
|
71
|
+
argv.push('--label', 'axstack.sandbox=true');
|
|
72
|
+
// Docker defaults retain the daemon's seccomp profile and private PID namespace.
|
|
73
|
+
argv.push('--network', networkIds.length ? networks.find(n => n.id === networkIds[0]).name : 'none');
|
|
74
|
+
if (role === 'proxy') argv.push('--network-alias', 'axstack-proxy');
|
|
75
|
+
for (const resolver of dns) argv.push('--dns', resolver);
|
|
76
|
+
for (const e of environment) argv.push('--env', `${e.name}=${e.value}`);
|
|
77
|
+
for (const t of tmpfs) argv.push('--tmpfs', `${t.path}:rw,nosuid,nodev,${t.noexec ? 'noexec' : 'exec'},size=${t.bytes},uid=${t.uid},gid=${t.gid},mode=${t.mode}`);
|
|
78
|
+
if (role === 'fetch' || role === 'test') {
|
|
79
|
+
argv.push('--mount', `type=bind,src=${source},dst=/source,readonly,bind-recursive=disabled`, '--mount', `type=volume,src=${storage.volumeName},dst=/dependencies,volume-nocopy${role === 'test' ? ',readonly' : ''}`);
|
|
80
|
+
argv.push('--workdir', '/work');
|
|
81
|
+
}
|
|
82
|
+
if (command) argv.push(image, ...command);
|
|
83
|
+
else argv.push('--entrypoint', '/bin/sh', image, '-c', 'while :; do sleep 3600; done');
|
|
84
|
+
return { id, role, image, networkIds, argv, caps: structuredClone(caps), tmpfs };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** @returns {import('./launcher-contracts.js').Plan} */
|
|
88
|
+
export function buildPlan(input, deps) {
|
|
89
|
+
const { runId, owner, request, assets: a, host, enumeration } = input;
|
|
90
|
+
checkAssets(a); validate('owner', owner); validate('request', request); validate('enumeration', enumeration);
|
|
91
|
+
if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(runId) || owner.runId !== runId || enumeration.runId !== runId) throw Error('run identity mismatch');
|
|
92
|
+
safePath(request.repo);
|
|
93
|
+
if (![request.head, request.base].every(s => /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(s))) throw Error('head/base must be exact commits');
|
|
94
|
+
if (!request.testArgv.length || new Set(request.sidecarIds).size !== request.sidecarIds.length) throw Error('invalid requested commands/sidecars');
|
|
95
|
+
const selected = request.sidecarIds.map(id => {
|
|
96
|
+
const item = a.sidecars.images.find(s => s.id === id);
|
|
97
|
+
if (!item) throw Error(`unknown sidecar: ${id}`);
|
|
98
|
+
return item;
|
|
99
|
+
});
|
|
100
|
+
const network = deps.planNetwork({ runId, host, proxy: a.proxy, registryAllowlist: a.registryAllowlist, sidecarIds: request.sidecarIds });
|
|
101
|
+
const storage = deps.planStorage({ runId, ownedDir: a.ownedDir, policy: a.policy });
|
|
102
|
+
validate('storage', storage);
|
|
103
|
+
const sourceExport = { path: `${a.ownedDir}/${runId}/source`, commit: request.head, maxBytes: a.policy.sourceMaxBytes };
|
|
104
|
+
const findNetwork = profile => {
|
|
105
|
+
const n = network.networks.find(n => n.profile === profile);
|
|
106
|
+
if (!n) throw Error(`missing ${profile} network`);
|
|
107
|
+
return n.id;
|
|
108
|
+
};
|
|
109
|
+
const common = { policy: a.policy, owner, source: sourceExport.path, storage, networks: network.networks };
|
|
110
|
+
const definitions = [
|
|
111
|
+
{ id: `${runId}-fetch`, role: 'fetch', image: a.workloadImage, networkIds: [findNetwork('fetch')], caps: a.policy.workloadCaps, environment: [...a.policy.environment, ...['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy'].map(name => ({ name, value: `http://${runId}-proxy:${a.proxy.port}` })), ...['NO_PROXY', 'no_proxy'].map(name => ({ name, value: '' }))] },
|
|
112
|
+
{ id: `${runId}-test`, role: 'test', image: a.workloadImage, networkIds: selected.length ? [findNetwork('service')] : [], caps: a.policy.workloadCaps, environment: a.policy.environment },
|
|
113
|
+
{ id: `${runId}-proxy`, role: 'proxy', image: network.proxy.image, networkIds: network.proxy.networkIds, caps: a.policy.proxyCaps, environment: [...a.policy.environment, ...network.proxy.environment], command: proxyArgv(), dns: [a.proxy.resolverIpv4, a.proxy.resolverIpv6] },
|
|
114
|
+
...selected.map(s => ({ id: `${runId}-${s.id}`, role: 'sidecar', image: s.image, networkIds: [findNetwork('service')], caps: a.policy.sidecarCaps, declaredVolumes: s.declaredVolumes, environment: a.policy.environment, command: s.argv })),
|
|
115
|
+
];
|
|
116
|
+
const containers = definitions.map(d => container({ ...common, ...d }));
|
|
117
|
+
/** @type {import('./launcher-contracts.js').Caps} */
|
|
118
|
+
const caps = { maxConcurrent: 2,
|
|
119
|
+
// Conservative accounting also reserves tmpfs in addition to cgroup memory.
|
|
120
|
+
perRunMemoryBytes: containers.reduce((s, c) => s + c.caps.memoryBytes + c.tmpfs.reduce((n, t) => n + t.bytes, 0), 0),
|
|
121
|
+
perRunDiskBytes: a.policy.dependencyBytes + a.policy.sourceMaxBytes + a.policy.captureMaxBytes + a.policy.receiptMaxBytes + containers.reduce((s, c) => s + c.caps.logMaxBytes, 0),
|
|
122
|
+
sourceMaxBytes: a.policy.sourceMaxBytes, captureMaxBytes: a.policy.captureMaxBytes, receiptMaxBytes: a.policy.receiptMaxBytes, wallTimeSeconds: a.policy.wallTimeSeconds, graceSeconds: a.policy.graceSeconds };
|
|
123
|
+
const b = a.hostBudget;
|
|
124
|
+
const budgetFits = caps.perRunMemoryBytes * 2 + b.reserveMemoryBytes <= b.memoryBudgetBytes && caps.perRunDiskBytes * 2 + b.reserveDiskBytes <= b.diskBudgetBytes;
|
|
125
|
+
const freeKnown = Number.isFinite(host?.freeMemoryBytes) && Number.isFinite(host?.freeDiskBytes);
|
|
126
|
+
const terms = [fact('host-identity', sameHost(a.hostBinding, host) ? 'pass' : 'fail', 'hostname and SHA-256(trimmed /etc/machine-id)'),
|
|
127
|
+
fact('host-budget', budgetFits ? 'pass' : 'fail', `two complete runs plus reserves; inventory ${b.inventoryDate}`),
|
|
128
|
+
fact('free-capacity', !freeKnown ? 'unknown' : host.freeMemoryBytes >= caps.perRunMemoryBytes + b.reserveMemoryBytes && host.freeDiskBytes >= caps.perRunDiskBytes + b.reserveDiskBytes ? 'pass' : 'fail', 'free memory/disk must cover one run plus host reserves'),
|
|
129
|
+
...(host?.terms?.length ? host.terms : [fact('host-facts', 'unknown', 'host observations absent')])];
|
|
130
|
+
const probes = deps.planProbes({ runId, containers, networks: network.networks, enumeration, storage });
|
|
131
|
+
/** @type {import('./launcher-contracts.js').Plan} */
|
|
132
|
+
const result = { schemaVersion: 1, runId, owner, request, hostBinding: a.hostBinding, hostBudget: b, policy: a.policy, sourceExport, containers, networks: network.networks, rules: network.rules, storage, enumeration, probes, caps, terms };
|
|
133
|
+
validate('plan', result);
|
|
134
|
+
return structuredClone(result);
|
|
135
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": 1,
|
|
3
|
+
"user": "61234:61234",
|
|
4
|
+
"environment": [
|
|
5
|
+
{
|
|
6
|
+
"name": "HOME",
|
|
7
|
+
"value": "/work"
|
|
8
|
+
},
|
|
9
|
+
{
|
|
10
|
+
"name": "PATH",
|
|
11
|
+
"value": "/opt/swift/usr/bin:/opt/swiftlint:/opt/node-24/bin:/opt/rust/bin:/opt/cargo-tools/bin:/opt/jdk-25/bin:/opt/go/bin:/opt/gradle/gradle-9.6.0/bin:/opt/kotlin/kotlinc/bin:/opt/android/cmdline-tools/23.0/bin:/opt/android/platform-tools:/opt/foundry:/opt/terraform:/opt/python-3.12/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/lib/postgresql/16/bin:/usr/lib/postgresql/17/bin:/usr/share/grafana/bin"
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
"name": "LANG",
|
|
15
|
+
"value": "C.UTF-8"
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
"name": "CI",
|
|
19
|
+
"value": "true"
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
"name": "TMPDIR",
|
|
23
|
+
"value": "/work"
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"name": "npm_config_cache",
|
|
27
|
+
"value": "/dependencies/npm"
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
"name": "PIP_CACHE_DIR",
|
|
31
|
+
"value": "/dependencies/pip"
|
|
32
|
+
},
|
|
33
|
+
{
|
|
34
|
+
"name": "CARGO_HOME",
|
|
35
|
+
"value": "/dependencies/cargo"
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
"name": "GOCACHE",
|
|
39
|
+
"value": "/work/.cache/go-build"
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
"name": "GOMODCACHE",
|
|
43
|
+
"value": "/dependencies/go-mod"
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
"name": "GRADLE_USER_HOME",
|
|
47
|
+
"value": "/work/.gradle"
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
"name": "JAVA_HOME",
|
|
51
|
+
"value": "/opt/jdk-25"
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
"name": "JAVA_11_HOME",
|
|
55
|
+
"value": "/opt/jdk-11"
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
"name": "ANDROID_HOME",
|
|
59
|
+
"value": "/opt/android"
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
"name": "ANDROID_SDK_ROOT",
|
|
63
|
+
"value": "/opt/android"
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
"name": "SVM_HOME",
|
|
67
|
+
"value": "/opt/svm"
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
"name": "GRADLE_RO_DEP_CACHE",
|
|
71
|
+
"value": "/opt/gradle-cache/caches"
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
"name": "JAVA_TOOL_OPTIONS",
|
|
75
|
+
"value": "-Djava.io.tmpdir=/work -Djansi.tmpdir=/work -Duser.home=/work"
|
|
76
|
+
},
|
|
77
|
+
{
|
|
78
|
+
"name": "GOTMPDIR",
|
|
79
|
+
"value": "/work"
|
|
80
|
+
}
|
|
81
|
+
],
|
|
82
|
+
"workloadCaps": {
|
|
83
|
+
"cpus": 2,
|
|
84
|
+
"memoryBytes": 2147483648,
|
|
85
|
+
"memorySwapBytes": 2147483648,
|
|
86
|
+
"pids": 256,
|
|
87
|
+
"logMaxBytes": 8388608,
|
|
88
|
+
"logMaxFiles": 1,
|
|
89
|
+
"logDriver": "local",
|
|
90
|
+
"restart": "no"
|
|
91
|
+
},
|
|
92
|
+
"proxyCaps": {
|
|
93
|
+
"cpus": 0.5,
|
|
94
|
+
"memoryBytes": 268435456,
|
|
95
|
+
"memorySwapBytes": 268435456,
|
|
96
|
+
"pids": 64,
|
|
97
|
+
"logMaxBytes": 8388608,
|
|
98
|
+
"logMaxFiles": 1,
|
|
99
|
+
"logDriver": "local",
|
|
100
|
+
"restart": "no"
|
|
101
|
+
},
|
|
102
|
+
"sidecarCaps": {
|
|
103
|
+
"cpus": 0.5,
|
|
104
|
+
"memoryBytes": 268435456,
|
|
105
|
+
"memorySwapBytes": 268435456,
|
|
106
|
+
"pids": 128,
|
|
107
|
+
"logMaxBytes": 8388608,
|
|
108
|
+
"logMaxFiles": 1,
|
|
109
|
+
"logDriver": "local",
|
|
110
|
+
"restart": "no"
|
|
111
|
+
},
|
|
112
|
+
"writableBytes": 805306368,
|
|
113
|
+
"dependencyBytes": 8589934592,
|
|
114
|
+
"dependencyInodes": 1048576,
|
|
115
|
+
"sourceMaxBytes": 268435456,
|
|
116
|
+
"captureMaxBytes": 8388608,
|
|
117
|
+
"receiptMaxBytes": 16777216,
|
|
118
|
+
"wallTimeSeconds": 900,
|
|
119
|
+
"graceSeconds": 10,
|
|
120
|
+
"maxWallTimeSeconds": 910
|
|
121
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { buildPlan, checkAssets, fact, hold, requirePass, sameHost, validate } from './launcher-policy.js';
|
|
2
|
+
import { sha256 } from '../scripts/capture-identity.js';
|
|
3
|
+
|
|
4
|
+
function checkHost(a, host) {
|
|
5
|
+
if (!sameHost(a.hostBinding, host)) hold('wrong host: require axat-vps and packaged SHA-256(trimmed /etc/machine-id); no sandbox state changed');
|
|
6
|
+
}
|
|
7
|
+
function networkPlan(p) {
|
|
8
|
+
const proxy = p.containers.find(c => c.role === 'proxy');
|
|
9
|
+
const environment = [];
|
|
10
|
+
for (let i = 0; i < proxy.argv.indexOf(proxy.image); i++) if (proxy.argv[i] === '--env') {
|
|
11
|
+
const value = proxy.argv[++i], equals = value.indexOf('=');
|
|
12
|
+
environment.push({ name: value.slice(0, equals), value: value.slice(equals + 1) });
|
|
13
|
+
}
|
|
14
|
+
return { networks: p.networks, rules: p.rules, proxy: { image: proxy.image, networkIds: proxy.networkIds, environment } };
|
|
15
|
+
}
|
|
16
|
+
async function cleanup(p, deps) {
|
|
17
|
+
const terms = [];
|
|
18
|
+
// rm --force also stops signal-ignoring workloads. Absence readback is authoritative.
|
|
19
|
+
for (const c of p.containers) {
|
|
20
|
+
try { await deps.removeContainer(p.owner, c); }
|
|
21
|
+
catch { /* Re-check absence: another reaper may have removed it. */ }
|
|
22
|
+
}
|
|
23
|
+
if (!await deps.containersGone(p)) hold(`containers remain for ${p.runId}; rules retained`);
|
|
24
|
+
terms.push(fact('containers-gone', 'pass', p.containers.map(c => c.id).join(', ')));
|
|
25
|
+
const network = networkPlan(p);
|
|
26
|
+
// Containers are independently gone; storage cleanup is safe even when a
|
|
27
|
+
// network readback is uncertain. Retain the owner plan until both succeed.
|
|
28
|
+
let networkError;
|
|
29
|
+
try {
|
|
30
|
+
const n = await deps.cleanupNetwork({ owner: p.owner, plan: network });
|
|
31
|
+
requirePass(n, 'network cleanup'); terms.push(...n);
|
|
32
|
+
} catch (error) { networkError = error; }
|
|
33
|
+
const s = await deps.cleanupStorage({ owner: p.owner, plan: p.storage });
|
|
34
|
+
requirePass(s, 'storage cleanup'); terms.push(...s);
|
|
35
|
+
if (networkError) throw networkError;
|
|
36
|
+
await deps.removeRecord(p);
|
|
37
|
+
return terms;
|
|
38
|
+
}
|
|
39
|
+
async function reapInside(a, deps) {
|
|
40
|
+
const terms = [], live = [];
|
|
41
|
+
for (const p of await deps.records(a)) {
|
|
42
|
+
validate('plan', p);
|
|
43
|
+
if (p.hostBinding.machineIdSha256 !== a.hostBinding.machineIdSha256) hold(`foreign host record ${p.runId}`);
|
|
44
|
+
const state = await deps.liveness(p.owner);
|
|
45
|
+
if (state === 'unknown') hold(`unreadable liveness ${p.runId}; owning driver must clear PID/start/boot uncertainty`);
|
|
46
|
+
if (state === 'live') { live.push(p); continue; }
|
|
47
|
+
if (state !== 'dead') hold(`unknown liveness ${p.runId}`);
|
|
48
|
+
terms.push(...await cleanup(p, deps));
|
|
49
|
+
}
|
|
50
|
+
return { terms, live };
|
|
51
|
+
}
|
|
52
|
+
export async function reapRuns({ assets: _suppliedAssets, host: _suppliedHost }, deps) {
|
|
53
|
+
// Caller observations never authorize writers; refresh even when HostFacts were supplied.
|
|
54
|
+
const assets = await deps.loadAssets();
|
|
55
|
+
const host = await deps.observeHost(assets);
|
|
56
|
+
checkHost(assets, host); checkAssets(assets);
|
|
57
|
+
requirePass(host.terms, 'host process visibility');
|
|
58
|
+
return deps.withAdmission(async () => {
|
|
59
|
+
const fresh = await deps.observeHost(assets);
|
|
60
|
+
checkHost(assets, fresh); requirePass(fresh.terms, 'fresh host process visibility');
|
|
61
|
+
return (await reapInside(assets, deps)).terms;
|
|
62
|
+
}, undefined, true);
|
|
63
|
+
}
|
|
64
|
+
function checkVolumes(p, imageVolumes) {
|
|
65
|
+
for (const c of p.containers) {
|
|
66
|
+
const observed = imageVolumes[c.image];
|
|
67
|
+
if (!Array.isArray(observed)) hold(`image VOLUME configuration unavailable: ${c.image}`);
|
|
68
|
+
for (const path of observed) if (!c.tmpfs.some(t => t.path === path)) hold(`uncovered image VOLUME: ${c.id} ${path}`);
|
|
69
|
+
// Fixed policy may also cap a required writable data path (e.g. Grafana)
|
|
70
|
+
// when the pinned image has no VOLUME instruction. Effective mounts are
|
|
71
|
+
// independently checked; every actual image VOLUME must still match above.
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export async function runPlan({ plan: supplied, evidenceDir }, deps) {
|
|
75
|
+
const assets = await deps.loadAssets();
|
|
76
|
+
const host = await deps.observeHost(assets);
|
|
77
|
+
checkHost(assets, host); checkAssets(assets); validate('plan', supplied);
|
|
78
|
+
const owner = await deps.currentOwner(supplied.runId);
|
|
79
|
+
let p = buildPlan({ runId: supplied.runId, owner, request: supplied.request, assets, host, enumeration: supplied.enumeration }, deps);
|
|
80
|
+
requirePass(p.terms, 'host admission');
|
|
81
|
+
let admitted = false, cancelled = null, planBytes;
|
|
82
|
+
const cancel = signal => {
|
|
83
|
+
cancelled = signal;
|
|
84
|
+
// Deadline/signal stops containers immediately; ordered resource cleanup waits
|
|
85
|
+
// for in-flight create/start calls to settle, so their late objects cannot leak.
|
|
86
|
+
if (admitted) for (const c of p.containers) void deps.removeContainer(p.owner, c).catch(() => {});
|
|
87
|
+
};
|
|
88
|
+
const detachSignals = deps.onSignal(cancel);
|
|
89
|
+
const clearDeadline = deps.setDeadline(p.policy.wallTimeSeconds * 1000, p.policy.graceSeconds * 1000, cancel);
|
|
90
|
+
const active = () => { if (cancelled) hold(`run cancelled: ${cancelled}`); };
|
|
91
|
+
let receipt;
|
|
92
|
+
try {
|
|
93
|
+
await deps.withAdmission(async () => {
|
|
94
|
+
active();
|
|
95
|
+
const freshHost = await deps.observeHost(assets); checkHost(assets, freshHost);
|
|
96
|
+
p = buildPlan({ runId: p.runId, owner, request: p.request, assets, host: freshHost, enumeration: p.enumeration }, deps);
|
|
97
|
+
requirePass(p.terms, 'fresh host admission');
|
|
98
|
+
const { live } = await reapInside(assets, deps);
|
|
99
|
+
if (live.some(r => r.runId === p.runId)) hold(`run ID already live: ${p.runId}`);
|
|
100
|
+
if (live.length >= 2) hold('concurrency limit 2 reached');
|
|
101
|
+
active();
|
|
102
|
+
// Persist PID/start/boot identity BEFORE the attach-before-volume crash window.
|
|
103
|
+
planBytes = await deps.savePlan(p, evidenceDir);
|
|
104
|
+
admitted = true;
|
|
105
|
+
const prepared = await deps.prepareStorage({ owner, plan: p.storage, policy: p.policy });
|
|
106
|
+
requirePass(prepared.terms, 'storage attachment');
|
|
107
|
+
if (!/^\/dev\/loop\d+$/.test(prepared.loopDevice)) hold('unobserved loop device');
|
|
108
|
+
p.terms.push(...prepared.terms, fact('loop-device', 'pass', `${prepared.loopDevice} backing ${p.storage.imageFile}`));
|
|
109
|
+
});
|
|
110
|
+
active();
|
|
111
|
+
await deps.exportSource(p);
|
|
112
|
+
checkVolumes(p, await deps.inspectImages(p));
|
|
113
|
+
const network = networkPlan(p);
|
|
114
|
+
requirePass(await deps.installNetwork({ owner, plan: network }), 'network installation'); active();
|
|
115
|
+
// No untrusted command is part of create/start. Workloads idle for fresh probes.
|
|
116
|
+
for (const c of p.containers) {
|
|
117
|
+
const result = await deps.execute(c.argv); if (result.exitCode !== 0) hold(`container create failed: ${c.id}`);
|
|
118
|
+
for (const id of c.networkIds.slice(1)) {
|
|
119
|
+
const n = p.networks.find(n => n.id === id);
|
|
120
|
+
const r = await deps.execute(['docker', 'network', 'connect', n.name, c.id]);
|
|
121
|
+
if (r.exitCode !== 0) hold(`network attachment failed: ${c.id}`);
|
|
122
|
+
}
|
|
123
|
+
const start = await deps.execute(['docker', 'start', c.id]);
|
|
124
|
+
if (start.exitCode !== 0) hold(`container start failed: ${c.id}`);
|
|
125
|
+
active();
|
|
126
|
+
}
|
|
127
|
+
requirePass(await deps.inspectMounts(p), 'effective mounts');
|
|
128
|
+
if (p.containers.some(c => c.role === 'sidecar')) { await deps.settleSidecars(); active(); }
|
|
129
|
+
const enumeration = await deps.enumerateTargets({ runId: p.runId, networks: p.networks });
|
|
130
|
+
validate('enumeration', enumeration); requirePass(enumeration.terms, 'fresh target enumeration');
|
|
131
|
+
if (enumeration.runId !== p.runId) hold('stale target enumeration');
|
|
132
|
+
p.enumeration = enumeration;
|
|
133
|
+
p.probes = deps.planProbes({ runId: p.runId, containers: p.containers, networks: p.networks, enumeration, storage: p.storage });
|
|
134
|
+
validate('plan', p);
|
|
135
|
+
planBytes = await deps.savePlan(p, evidenceDir);
|
|
136
|
+
const probeResults = await deps.runProbes({ plan: p, onPlan: async candidate => {
|
|
137
|
+
active(); validate('plan', candidate);
|
|
138
|
+
planBytes = await deps.savePlan(candidate, evidenceDir);
|
|
139
|
+
} });
|
|
140
|
+
requirePass(probeResults, 'per-run containment probes');
|
|
141
|
+
if (p.probes.some(probe => !probeResults.some(t => t.id === probe.id && t.status === 'pass'))) hold('missing per-run probe result');
|
|
142
|
+
active();
|
|
143
|
+
const engineVersion = await deps.engineVersion();
|
|
144
|
+
const capture = await deps.recordCapture(p, evidenceDir, active);
|
|
145
|
+
active();
|
|
146
|
+
receipt = { schemaVersion: 1, runId: p.runId, planSha256: sha256(planBytes), owner, hostBinding: assets.hostBinding, engineVersion,
|
|
147
|
+
imageDigests: [...new Set(p.containers.map(c => c.image.slice(c.image.indexOf('@') + 1)))], effectivePolicy: p.policy, probeResults,
|
|
148
|
+
terms: p.terms, capture };
|
|
149
|
+
validate('receipt', receipt);
|
|
150
|
+
} finally {
|
|
151
|
+
try {
|
|
152
|
+
if (admitted) { const terms = await cleanup(p, deps); if (receipt) receipt.terms.push(...terms); }
|
|
153
|
+
} finally { clearDeadline(); detachSignals(); }
|
|
154
|
+
}
|
|
155
|
+
await deps.saveReceipt(receipt, evidenceDir, p);
|
|
156
|
+
return receipt;
|
|
157
|
+
}
|