Repository navigation
Expand file tree
/
Copy pathpreflight.ts
More file actions
748 lines (718 loc) · 27.7 KB
/
Copy pathpreflight.ts
File metadata and controls
748 lines (718 loc) · 27.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
import { constants, promises as fs } from 'fs';
import * as path from 'path';
import execa from 'execa';
import {
CLOUD_HYPERVISOR_RELEASE_VERSION,
type CloudHypervisorArtifactDigests,
type CloudHypervisorOptions,
} from '../types/runtime-options';
import {
CLOUD_HYPERVISOR_ARTIFACT_REPOSITORY,
CLOUD_HYPERVISOR_ARTIFACT_SIGNER_WORKFLOW,
artifactDigestsFromManifest,
assertArtifactBasenames,
parseCloudHypervisorArtifactManifest,
} from './artifact-manifest';
import { CloudHypervisorUnsupportedHostError } from './errors';
import { logger } from '../logger';
import {
buildExecutionFailureDiagnostics,
describeAcl,
describeMountForPath,
describePathComponent,
findMountForPath,
pathComponents,
resolveDiagnosticGetfaclPath,
} from './preflight-diagnostics';
import {
createArtifactSnapshot,
copySparseFileWithRsync,
type CloudHypervisorArtifactSnapshot,
type CloudHypervisorArtifactSnapshotSources,
} from './artifact-snapshot';
import {
assertDigest,
assertTrustedAncestorChain,
assertTrustedHostTool,
assertTrustedRegularFile,
calculateSha256,
type CloudHypervisorArtifactTrustDependencies,
hasCompleteArtifactDigests,
parsePositiveUid,
resolveTrustedOperatorUid,
resolveTrustedHostTool,
} from './artifact-trust';
import {
HostPreflightReporter, hostPreflightReason, markHostPreflightError,
} from './host-preflight-progress';
/**
* Fail-closed host and artifact validation for the Cloud Hypervisor v53.0
* runtime. Trust checks cover absolute paths, root/operator-owned
* non-writable regular files, trusted ancestor
* directories, digest pinning, PATH-resolved but ownership-verified host
* tools) so both VMM backends share the same fail-closed posture.
*
* Cloud Hypervisor has no jailer-equivalent process. AWF instead requires
* the pinned v1.13.3 virtiofsd sibling used for directory exports, while
* `src/cloud-hypervisor/launcher.ts` builds an equivalent
* network-namespace-join + privilege-drop + Landlock/seccomp launch using
* the `setpriv` tool resolved here, and `src/cloud-hypervisor/manager.ts`
* stages artifacts into a private, non-world-readable run directory.
*/
export interface CloudHypervisorPreflightDependencies extends CloudHypervisorArtifactTrustDependencies {
hostPreflightReporter?: HostPreflightReporter;
platform: NodeJS.Platform;
arch: string;
runVersion(binaryPath: string): Promise<string>;
readFile(filePath: string): Promise<string>;
createArtifactSnapshot(
sources: CloudHypervisorArtifactSnapshotSources,
copySparseFile: (source: string, destination: string) => Promise<void>,
): Promise<CloudHypervisorArtifactSnapshot>;
copySparseFile(rsyncBinaryPath: string, source: string, destination: string): Promise<void>;
removeArtifactSnapshot(directory: string): Promise<void>;
verifyManifestAttestation(
ghBinaryPath: string,
manifestPath: string,
bundlePath: string,
): Promise<void>;
assertToolAvailable(tool: string): Promise<string>;
assertHostPolicy(report?: HostPreflightReporter): Promise<2>;
assertDockerInfrastructure(dockerBinaryPath: string, report?: HostPreflightReporter): Promise<void>;
/** Resolves the group ID that owns `/dev/kvm`, so the launcher can retain
* exactly that supplementary group instead of the full operator group set. */
resolveKvmGid(): Promise<number>;
}
export type CloudHypervisorHostToolPaths = Readonly<{
getfacl: string;
getent: string;
groupdel: string;
id: string;
ip: string;
docker: string;
nft: string;
sysctl: string;
/** util-linux `flock`, used to serialize durable microVM network reservations. */
flock: string;
mke2fs: string;
debugfs: string;
e2fsck: string;
rsync: string;
mount: string;
umount: string;
/**
* util-linux `setpriv`, used by the launcher to drop to the non-root
* operator uid/gid and clear capabilities/groups after joining the
* per-run network namespace (there is no jailer-equivalent process to do
* this for Cloud Hypervisor). See `src/cloud-hypervisor/launcher.ts`.
*/
setpriv: string;
setfacl: string;
useradd: string;
userdel: string;
}>;
const CLOUD_HYPERVISOR_HOST_TOOLS: (keyof CloudHypervisorHostToolPaths)[] = [
'getent', 'getfacl', 'groupdel', 'id', 'ip', 'nft', 'sysctl', 'flock', 'mke2fs', 'debugfs', 'e2fsck',
'rsync', 'mount', 'umount', 'setfacl', 'setpriv', 'useradd', 'userdel',
];
async function versionProbeExecutionError(
binaryPath: string,
details: string,
code?: string,
): Promise<Error> {
let message: string;
if (code === 'ENOENT') {
message =
`Required external binary "${binaryPath}" is unavailable: the binary or its interpreter ` +
`was not found${details ? ` (${details})` : ''}`;
} else if (code === 'EACCES') {
message =
`Permission denied executing "${binaryPath} --version"; verify path traversal permissions ` +
`and that the artifact is on an exec-capable mount${details ? `: ${details}` : ''}`;
message += await buildExecutionFailureDiagnostics(binaryPath);
} else {
message =
`Unable to execute required external binary "${binaryPath} --version"; verify the trusted ` +
`artifact exists, is executable, and is complete${details ? `: ${details}` : ''}`;
message += await buildExecutionFailureDiagnostics(binaryPath);
}
return Object.assign(new Error(message), code ? { code } : {});
}
const defaultDependencies: CloudHypervisorPreflightDependencies = {
platform: process.platform,
arch: process.arch,
uid: -1,
access: fs.access,
lstat: fs.lstat,
runVersion: async (binaryPath) => {
let result;
try {
result = await execa(binaryPath, ['--version'], {
reject: false,
timeout: 5_000,
stdio: ['ignore', 'pipe', 'pipe'],
});
} catch (error) {
const code = error && typeof error === 'object' &&
typeof (error as { code?: unknown }).code === 'string'
? (error as { code: string }).code
: undefined;
const details = [
code ? `code=${code}` : '',
error instanceof Error ? error.message : String(error),
].filter(Boolean).join('; ');
throw await versionProbeExecutionError(
binaryPath,
details,
code,
);
}
if (result.exitCode == null && !result.signal) {
const executionError = result as typeof result & {
code?: unknown;
shortMessage?: unknown;
};
const codeValue = typeof executionError.code === 'string' ? executionError.code : undefined;
const code = codeValue ? `code=${codeValue}` : '';
const shortMessage = typeof executionError.shortMessage === 'string'
? executionError.shortMessage
: '';
const details = [code, shortMessage, result.stderr.trim()].filter(Boolean).join('; ');
throw await versionProbeExecutionError(binaryPath, details, codeValue);
}
if (result.exitCode !== 0) {
const stderr = result.stderr.trim();
const signalCode = result.signal ?? null;
const exitCode = result.exitCode ?? null;
const termination = signalCode
? `terminated by signal ${signalCode}`
: `exited with code ${exitCode}`;
throw markHostPreflightError(new Error(
`"${binaryPath} --version" ${termination} ` +
`(exitCode=${exitCode}, signalCode=${signalCode})${stderr ? `: ${stderr}` : ''}`,
), 'command-failed');
}
return `${result.stdout}\n${result.stderr}`.trim();
},
sha256: calculateSha256,
readFile: async (filePath) => fs.readFile(filePath, 'utf8'),
createArtifactSnapshot: createArtifactSnapshot,
copySparseFile: copySparseFileWithRsync,
removeArtifactSnapshot: async (directory) => {
await fs.rm(directory, { recursive: true, force: true });
},
verifyManifestAttestation: async (ghBinaryPath, manifestPath, bundlePath) => {
const result = await execa(ghBinaryPath, [
'attestation',
'verify',
manifestPath,
'--repo',
CLOUD_HYPERVISOR_ARTIFACT_REPOSITORY,
'--bundle',
bundlePath,
'--signer-workflow',
CLOUD_HYPERVISOR_ARTIFACT_SIGNER_WORKFLOW,
'--deny-self-hosted-runners',
], {
reject: false,
timeout: 30_000,
stdio: ['ignore', 'pipe', 'pipe'],
});
if (result.exitCode !== 0) {
throw markHostPreflightError(new Error(
`GitHub artifact attestation verification failed with code ${result.exitCode}: ${result.stderr.trim()
}`,
), 'command-failed');
}
},
assertToolAvailable: (tool) => resolveTrustedHostTool(tool, process.env),
assertHostPolicy: async (report = new HostPreflightReporter('bounded-runtime')) => {
await report.check('root', () => {
if (process.getuid?.() !== 0) {
throw markHostPreflightError(new CloudHypervisorUnsupportedHostError(
'Cloud Hypervisor network setup requires root; invoke awf through sudo from a non-root account',
), 'requirement-not-met');
}
});
try {
await report.check('ipv4-control', () => fs.access('/proc/sys/net/ipv4/ip_forward', constants.R_OK));
await report.check('ipv6-control', () => fs.access('/proc/sys/net/ipv6/conf/all/disable_ipv6', constants.R_OK));
await report.check('seccomp-control', () => fs.access('/proc/sys/kernel/seccomp/actions_avail', constants.R_OK));
} catch (error) {
throw markHostPreflightError(new CloudHypervisorUnsupportedHostError(
'host kernel policy does not expose required network namespace and seccomp controls: ' +
`${error instanceof Error ? error.message : String(error)}`,
error,
), hostPreflightReason(error));
}
try {
await report.check('cgroup-v2', () => fs.access('/sys/fs/cgroup/cgroup.controllers', constants.R_OK));
return 2;
} catch (error) {
// Cloud Hypervisor's launcher manages an explicit memory/CPU/PID
// cgroup for the launched process (see `src/cloud-hypervisor/launcher.ts`
// `CloudHypervisorCgroup`), which requires the cgroup v2 unified
// hierarchy's `cgroup.subtree_control` delegation model. A cgroup v1
// fallback would need separate per-controller mount points
// (`memory`, `cpu,cpuacct`, `pids`) that this launcher does not
// manage, so it is rejected explicitly rather than silently
// constructing a broken cgroup. GitHub-hosted Ubuntu runners (the
// only supported host) always run cgroup v2.
throw markHostPreflightError(new CloudHypervisorUnsupportedHostError(
'Cloud Hypervisor requires the cgroup v2 unified hierarchy ' +
'(/sys/fs/cgroup/cgroup.controllers); cgroup v1-only hosts are not supported: ' +
`${error instanceof Error ? error.message : String(error)}`,
error,
), hostPreflightReason(error));
}
},
assertDockerInfrastructure: async (dockerBinaryPath, report = new HostPreflightReporter('bounded-runtime')) => {
for (const args of [['info'], ['compose', 'version']] as const) {
await report.check(args[0] === 'info' ? 'docker-info' : 'docker-compose', async () => {
const result = await execa(dockerBinaryPath, [...args], {
reject: false,
timeout: 10_000,
stdio: ['ignore', 'pipe', 'pipe'],
});
if (result.exitCode !== 0) {
throw markHostPreflightError(new Error(
`${dockerBinaryPath} ${args.join(' ')} failed with code ${result.exitCode}: ${result.stderr.trim()}`,
), 'command-failed');
}
});
}
},
resolveKvmGid: async () => {
const stat = await fs.stat('/dev/kvm');
return stat.gid;
},
};
export {
buildExecutionFailureDiagnostics,
describeAcl,
describeMountForPath,
describePathComponent,
findMountForPath,
pathComponents,
resolveDiagnosticGetfaclPath,
copySparseFileWithRsync,
createArtifactSnapshot,
assertDigest,
assertTrustedAncestorChain,
assertTrustedHostTool,
assertTrustedRegularFile,
calculateSha256,
hasCompleteArtifactDigests,
parsePositiveUid,
resolveTrustedOperatorUid,
};
export type {
CloudHypervisorArtifactSnapshot,
CloudHypervisorArtifactSnapshotSources,
};
/** @internal Exposed only for focused host-probe tests. */
export const cloudHypervisorPreflightTestHelpers = {
defaultDependencies,
createArtifactSnapshot,
};
export interface CloudHypervisorPreflightResult {
version: string;
cloudHypervisorBinary: string;
virtiofsdBinary: string;
kernelPath: string;
rootfsPath: string;
supervisorPath: string;
artifactSnapshotDirectory: string;
artifactDigests: Required<CloudHypervisorArtifactDigests>;
tools: CloudHypervisorHostToolPaths;
cgroupVersion: 2;
/** Group ID that owns `/dev/kvm`, retained as the launcher's sole supplementary group. */
kvmGid: number;
}
export const CLOUD_HYPERVISOR_MAX_BOOT_ATTEMPTS = 3;
/**
* Number of attempts for the post-digest-verification `--version` probe.
* The staged artifact's content is already digest-verified before this runs,
* so a probe failure here reflects a transient host/exec hiccup (e.g. a
* momentary I/O error copying/executing the just-staged binary) rather than
* a corrupt or wrong artifact. Retrying a couple of times avoids failing an
* entire run over a fleeting condition. See gh-aw-firewall#8767.
*/
const CLOUD_HYPERVISOR_VERSION_PROBE_ATTEMPTS = 3;
const CLOUD_HYPERVISOR_VERSION_PROBE_RETRY_DELAY_MS = 250;
/**
* Error codes indicating a deterministic, non-transient version-probe
* failure: the binary is missing, not a regular file, or not executable.
* These will not resolve on retry, so they are allowed to fail closed
* immediately instead of paying the retry delay. The default `runVersion`
* attaches a structured `code` property when the underlying spawn failure
* carries one (see its `Object.assign(new Error(...), { code })` above);
* the `code=XXX` message fragment is used as a fallback for callers that
* inject a custom `runVersion` throwing a plain `Error`.
*/
const CLOUD_HYPERVISOR_VERSION_PROBE_PERMANENT_ERROR_CODES = new Set([
'ENOENT', 'EACCES', 'EISDIR', 'ENOTDIR', 'ENOEXEC',
]);
const CLOUD_HYPERVISOR_VERSION_PROBE_PERMANENT_ERROR_CODE_PATTERN = /\bcode=(ENOENT|EACCES|EISDIR|ENOTDIR|ENOEXEC)\b/;
function isPermanentVersionProbeError(error: unknown): boolean {
const code = error && typeof error === 'object' ? (error as { code?: unknown }).code : undefined;
if (typeof code === 'string' && CLOUD_HYPERVISOR_VERSION_PROBE_PERMANENT_ERROR_CODES.has(code)) {
return true;
}
const message = error instanceof Error ? error.message : String(error);
return CLOUD_HYPERVISOR_VERSION_PROBE_PERMANENT_ERROR_CODE_PATTERN.test(message);
}
async function sleep(ms: number): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Runs `dependencies.runVersion` with a small bounded retry for transient
* execution failures. The binary's digest has already been verified to
* match the trusted manifest by the time this is called, so any rejection
* here is an execution-environment problem, not an artifact integrity
* problem, and is generally safe to retry. Deterministic failures (missing
* file, permission denied, etc.) are not retried since they would not
* resolve on their own.
*/
async function runVersionWithRetry(
dependencies: Pick<CloudHypervisorPreflightDependencies, 'runVersion'>,
binaryPath: string,
attempts: number = CLOUD_HYPERVISOR_VERSION_PROBE_ATTEMPTS,
retryDelayMs: number = CLOUD_HYPERVISOR_VERSION_PROBE_RETRY_DELAY_MS,
): Promise<string> {
let lastError: unknown;
for (let attempt = 1; attempt <= attempts; attempt += 1) {
try {
return await dependencies.runVersion(binaryPath);
} catch (error) {
lastError = error;
if (attempt < attempts && !isPermanentVersionProbeError(error)) {
logger.warn(
`Cloud Hypervisor version probe failed for "${binaryPath}" ` +
`(attempt ${attempt}/${attempts}); retrying: ` +
`${error instanceof Error ? error.message : String(error)}`,
);
await sleep(retryDelayMs);
continue;
}
break;
}
}
throw lastError;
}
type CloudHypervisorReadinessStage =
| 'guest-network-readiness'
| 'guest-connectivity';
/** @internal Structured sentinel used to permit only pre-agent boot retries. */
// ts-prune-ignore-next
export class CloudHypervisorRetryableReadinessError extends Error {
readonly code = 'CLOUD_HYPERVISOR_RETRYABLE_READINESS';
readonly retryable = true;
diagnosticDirectories: readonly string[] = [];
constructor(
readonly stage: CloudHypervisorReadinessStage,
readonly bootAttempt: number,
detail: string,
cause?: unknown,
) {
super(
`Cloud Hypervisor retryable readiness failure ` +
`(stage=${stage}, boot attempt=${bootAttempt}/${CLOUD_HYPERVISOR_MAX_BOOT_ATTEMPTS}): ${detail}`,
);
this.name = 'CloudHypervisorRetryableReadinessError';
if (cause !== undefined) Object.defineProperty(this, 'cause', { value: cause });
}
attachDiagnostics(directories: readonly string[], exhausted: boolean): void {
this.diagnosticDirectories = [...directories];
if (exhausted) {
this.message +=
`; boot recovery exhausted after ${CLOUD_HYPERVISOR_MAX_BOOT_ATTEMPTS} attempts` +
(directories.length > 0 ? `; diagnostics: ${directories.join(', ')}` : '');
}
}
}
/**
* Parses a `cloud-hypervisor --version` output like `cloud-hypervisor v53.0`
* (also accepts the plain `v53.0`/`53.0` forms some builds emit).
*/
export function parseCloudHypervisorVersion(output: string): string {
const match = output.match(/\bv?(\d+\.\d+(?:\.\d+)?)\b/);
if (!match) {
throw markHostPreflightError(new Error(`Could not parse Cloud Hypervisor version from: ${JSON.stringify(output)}`), 'version-format');
}
return match[1];
}
export const VIRTIOFSD_RELEASE_VERSION = '1.13.3';
export function parseVirtiofsdVersion(output: string): string {
const match = output.match(/(?:^|\s)v?(\d+\.\d+\.\d+)(?:\s|$)/);
if (!match) {
throw markHostPreflightError(new Error(`Could not parse virtiofsd version from: ${JSON.stringify(output)}`), 'version-format');
}
return match[1];
}
/**
* Fail-closed host and artifact validation for Cloud Hypervisor v53.0.
*
* This checks Linux/KVM host requirements, trusted artifact
* ownership/permissions, pinned version, and pinned digests,
* adapted for Cloud Hypervisor's single-binary VMM (no jailer).
*/
export async function runCloudHypervisorPreflight(
config: CloudHypervisorOptions,
overrides: Partial<CloudHypervisorPreflightDependencies> = {},
): Promise<CloudHypervisorPreflightResult> {
const report = overrides.hostPreflightReporter ?? new HostPreflightReporter('bounded-runtime');
const dependencies = {
...defaultDependencies,
...overrides,
uid: await report.check('operator-identity', () => overrides.uid ?? resolveTrustedOperatorUid()),
};
const developmentBypass = config.developmentAllowUnattestedArtifacts === true;
await report.check('artifact-configuration', () => {
if (!config.kernelPath || !config.rootfsPath || !config.supervisorPath) {
throw new Error(
'Cloud Hypervisor requires guest kernel, rootfs, and supervisor artifact paths',
);
}
if (
developmentBypass &&
process.env.AWF_CLOUD_HYPERVISOR_DEVELOPMENT_ALLOW_UNATTESTED_ARTIFACTS !== '1'
) {
throw new Error(
'Cloud Hypervisor development artifact bypass requires ' +
'AWF_CLOUD_HYPERVISOR_DEVELOPMENT_ALLOW_UNATTESTED_ARTIFACTS=1',
);
}
if (
!developmentBypass &&
(!config.artifactManifestPath ||
!config.artifactManifestBundlePath ||
!config.artifactReleaseTag)
) {
throw new Error(
'Cloud Hypervisor requires an artifact manifest, attestation bundle, and expected release tag',
);
}
});
await report.check('cloud-hypervisor-trust', () => assertTrustedRegularFile(
'Cloud Hypervisor binary',
config.cloudHypervisorBinary,
constants.R_OK | constants.X_OK,
dependencies,
));
const virtiofsdBinary = path.join(path.dirname(config.cloudHypervisorBinary), 'virtiofsd');
await report.check('virtiofsd-trust', () => assertTrustedRegularFile(
'virtiofsd binary',
virtiofsdBinary,
constants.R_OK | constants.X_OK,
dependencies,
));
const tools = {} as Record<keyof CloudHypervisorHostToolPaths, string>;
for (const tool of CLOUD_HYPERVISOR_HOST_TOOLS) {
try {
tools[tool] = await report.check(`tool-${tool}`, () => dependencies.assertToolAvailable(tool));
} catch (error) {
throw markHostPreflightError(new Error(
`Cloud Hypervisor requires host tool "${tool}": ` +
`${error instanceof Error ? error.message : String(error)}`,
), hostPreflightReason(error));
}
}
await report.check('kernel-trust', () => assertTrustedRegularFile(
'Cloud Hypervisor guest kernel',
config.kernelPath!,
constants.R_OK,
dependencies,
));
await report.check('rootfs-trust', () => assertTrustedRegularFile(
'Cloud Hypervisor rootfs',
config.rootfsPath!,
constants.R_OK,
dependencies,
));
await report.check('supervisor-trust', () => assertTrustedRegularFile(
'Cloud Hypervisor guest supervisor',
config.supervisorPath!,
constants.R_OK,
dependencies,
));
if (!developmentBypass) {
await report.check('manifest-trust', () => assertTrustedRegularFile(
'Cloud Hypervisor artifact manifest',
config.artifactManifestPath!,
constants.R_OK,
dependencies,
));
await report.check('bundle-trust', () => assertTrustedRegularFile(
'Cloud Hypervisor artifact attestation bundle',
config.artifactManifestBundlePath!,
constants.R_OK,
dependencies,
));
}
const snapshot = await report.check('artifact-snapshot', () => dependencies.createArtifactSnapshot(
{
cloudHypervisorBinary: config.cloudHypervisorBinary,
virtiofsdBinary,
kernelPath: config.kernelPath!,
rootfsPath: config.rootfsPath!,
supervisorPath: config.supervisorPath!,
...(!developmentBypass
? {
manifestPath: config.artifactManifestPath!,
bundlePath: config.artifactManifestBundlePath!,
}
: {}),
},
(source, destination) =>
dependencies.copySparseFile(tools.rsync, source, destination),
));
try {
let artifactDigests: Required<CloudHypervisorArtifactDigests>;
if (developmentBypass) {
if (!hasCompleteArtifactDigests(config.sha256)) {
throw new Error(
'Cloud Hypervisor development artifact bypass requires SHA-256 digests for all five artifacts',
);
}
artifactDigests = config.sha256;
} else {
const ghBinaryPath = await report.check('tool-gh', () => dependencies.assertToolAvailable('gh'));
await report.check('manifest-attestation', () => dependencies.verifyManifestAttestation(
ghBinaryPath,
snapshot.manifestPath!,
snapshot.bundlePath!,
));
const manifest = await report.check('manifest-contents', async () => {
const parsed = parseCloudHypervisorArtifactManifest(
await dependencies.readFile(snapshot.manifestPath!),
config.artifactReleaseTag!,
);
assertArtifactBasenames(parsed, {
cloudHypervisor: config.cloudHypervisorBinary,
virtiofsd: virtiofsdBinary,
kernel: config.kernelPath!,
rootfs: config.rootfsPath!,
supervisor: config.supervisorPath!,
});
return parsed;
});
artifactDigests = artifactDigestsFromManifest(manifest);
}
await report.check('cloud-hypervisor-digest', () => assertDigest(
'Cloud Hypervisor binary',
snapshot.cloudHypervisorBinary,
artifactDigests.cloudHypervisor,
dependencies,
));
await report.check('virtiofsd-digest', () => assertDigest(
'virtiofsd binary',
snapshot.virtiofsdBinary,
artifactDigests.virtiofsd,
dependencies,
));
const version = await report.check('cloud-hypervisor-version', async () => {
const parsed = parseCloudHypervisorVersion(
await runVersionWithRetry(dependencies, snapshot.cloudHypervisorBinary),
);
if (parsed !== CLOUD_HYPERVISOR_RELEASE_VERSION) {
throw markHostPreflightError(new Error(
`Cloud Hypervisor is pinned to v${CLOUD_HYPERVISOR_RELEASE_VERSION}; found v${parsed}`,
), 'version-mismatch');
}
return parsed;
});
await report.check('virtiofsd-version', async () => {
const virtiofsdVersion = parseVirtiofsdVersion(
await runVersionWithRetry(dependencies, snapshot.virtiofsdBinary),
);
if (virtiofsdVersion !== VIRTIOFSD_RELEASE_VERSION) {
throw markHostPreflightError(new Error(
`virtiofsd is pinned to v${VIRTIOFSD_RELEASE_VERSION}; found v${virtiofsdVersion}`,
), 'version-mismatch');
}
});
await report.check('kernel-digest', () => assertDigest(
'Cloud Hypervisor guest kernel',
snapshot.kernelPath,
artifactDigests.kernel,
dependencies,
));
await report.check('rootfs-digest', () => assertDigest(
'Cloud Hypervisor rootfs',
snapshot.rootfsPath,
artifactDigests.rootfs,
dependencies,
));
await report.check('supervisor-digest', () => assertDigest(
'Cloud Hypervisor guest supervisor',
snapshot.supervisorPath,
artifactDigests.supervisor,
dependencies,
));
// Artifact trust must be established before any host-capability error can
// trigger the supported fallback to Docker.
await report.check('platform', () => {
if (dependencies.platform !== 'linux') {
throw markHostPreflightError(new CloudHypervisorUnsupportedHostError(
`Cloud Hypervisor requires Linux with KVM; found ${dependencies.platform}`,
), 'requirement-not-met');
}
});
await report.check('architecture', () => {
if (dependencies.arch !== 'x64') {
throw markHostPreflightError(new CloudHypervisorUnsupportedHostError(
`Cloud Hypervisor is supported only on x86_64 GitHub-hosted runners; found Node architecture ${dependencies.arch}`,
), 'requirement-not-met');
}
});
try {
await report.check('kvm-access', () => dependencies.access('/dev/kvm', constants.R_OK | constants.W_OK));
} catch (error) {
throw new CloudHypervisorUnsupportedHostError(
'Cloud Hypervisor requires readable and writable /dev/kvm: ' +
`${error instanceof Error ? error.message : String(error)}`,
error,
);
}
const kvmGid = await report.check('kvm-group', () => dependencies.resolveKvmGid());
let cgroupVersion: 2;
try {
cgroupVersion = await report.check('host-policy', () => dependencies.assertHostPolicy(report));
} catch (error) {
throw error instanceof CloudHypervisorUnsupportedHostError
? error
: new CloudHypervisorUnsupportedHostError(
`Cloud Hypervisor host policy is unsupported: ${error instanceof Error ? error.message : String(error)}`,
error,
);
}
let dockerBinaryPath: string;
try {
dockerBinaryPath = await report.check('tool-docker', () => dependencies.assertToolAvailable('docker'));
} catch (error) {
throw new Error(
'Cloud Hypervisor requires host tool "docker": ' +
`${error instanceof Error ? error.message : String(error)}`,
);
}
tools.docker = dockerBinaryPath;
await report.check('docker-infrastructure', () => dependencies.assertDockerInfrastructure(dockerBinaryPath, report));
return {
version,
cloudHypervisorBinary: snapshot.cloudHypervisorBinary,
virtiofsdBinary: snapshot.virtiofsdBinary,
kernelPath: snapshot.kernelPath,
rootfsPath: snapshot.rootfsPath,
supervisorPath: snapshot.supervisorPath,
artifactSnapshotDirectory: snapshot.directory,
artifactDigests,
tools,
cgroupVersion,
kvmGid,
};
} catch (error) {
await dependencies.removeArtifactSnapshot(snapshot.directory);
throw error;
}
}