hl-engine 0.1.29

Safe Rust lifecycle API for the standalone HL Linux guest engine
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
use super::{
    spec_error, BTreeSet, EngineCapabilities, MachineSpec, NetworkMode, SpecError,
    SpecErrorCategory,
};

pub(super) fn validate_resources(spec: &MachineSpec, guest_fd_limit: u32) -> Result<(), SpecError> {
    let resources = &spec.resources;
    let values = [
        resources.memory_reservation_bytes,
        resources.memory_bytes,
        resources.file_size_bytes,
        resources.locked_memory_bytes,
        resources.stack_bytes,
        resources.address_space_bytes,
        resources.io_read_bytes_per_second,
        resources.io_write_bytes_per_second,
        resources.cpu_quota_micros,
    ];
    if values.into_iter().flatten().any(|value| value == 0)
        || [
            resources.process_limit,
            resources.thread_limit,
            resources.cpu_limit,
            resources.open_files,
        ]
        .into_iter()
        .flatten()
        .any(|value| value == 0)
        || resources
            .extension_budgets
            .values()
            .any(|value| *value == 0)
    {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            "resources",
            "explicit resource declarations must be greater than zero",
        ));
    }
    if resources
        .memory_reservation_bytes
        .zip(resources.memory_bytes)
        .is_some_and(|(reservation, limit)| reservation > limit)
    {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            "resources.memory_reservation_bytes",
            "memory reservation must not exceed the memory limit",
        ));
    }
    validate_open_files(resources.open_files, guest_fd_limit)?;
    if resources
        .cpu_affinity
        .iter()
        .any(|cpu| spec.cpu.count.is_some_and(|count| *cpu >= count))
    {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            "resources.cpu_affinity",
            "CPU affinity references a CPU outside the visible topology",
        ));
    }
    let providers = spec
        .extensions
        .iter()
        .map(|extension| &extension.provider)
        .collect::<BTreeSet<_>>();
    if resources
        .extension_budgets
        .keys()
        .any(|provider| !providers.contains(provider))
    {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            "resources.extension_budgets",
            "extension budgets must name an extension requested by this launch",
        ));
    }
    let unsupported = resources.memory_reservation_bytes.is_some()
        || resources.thread_limit.is_some()
        || resources.cpu_quota_micros.is_some()
        || !resources.cpu_affinity.is_empty()
        || resources.open_files.is_some()
        || resources.file_size_bytes.is_some()
        || resources.locked_memory_bytes.is_some()
        || resources.stack_bytes.is_some()
        || resources.address_space_bytes.is_some()
        || resources.io_read_bytes_per_second.is_some()
        || resources.io_write_bytes_per_second.is_some()
        || !resources.extension_budgets.is_empty()
        || resources.accounting != crate::spec::AccountingSpec::Disabled;
    if unsupported {
        return Err(spec_error(
            SpecErrorCategory::Unsupported,
            "resources",
            "one or more selected resource controls are not implemented by this backend",
        ));
    }
    Ok(())
}

fn validate_open_files(open_files: Option<u32>, guest_fd_limit: u32) -> Result<(), SpecError> {
    if open_files.is_some_and(|value| value > guest_fd_limit) {
        Err(spec_error(
            SpecErrorCategory::Limit,
            "resources.open_files",
            "open-file limit exceeds the host-backed guest descriptor ceiling",
        ))
    } else {
        Ok(())
    }
}

/// Applies the directory rules to one checkpoint directory, reporting failures against `field`.
///
/// Capture and restore directories are validated independently: a valid capture directory must never
/// mask an invalid restore directory (or the reverse).
fn validate_checkpoint_directory(
    directory: Option<&std::path::Path>,
    field: &'static str,
) -> Result<(), SpecError> {
    let Some(directory) = directory else {
        return Ok(());
    };
    if !directory.is_absolute() {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            field,
            "checkpoint directories must be absolute",
        ));
    }
    if directory.parent().is_none() || directory.file_name().is_none() {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            field,
            "checkpoint directory must name a non-root destination",
        ));
    }
    Ok(())
}

/// The streaming sentinel is not a path: it selects a caller-supplied store and is never opened. It is the
/// one value allowed where an absolute directory is otherwise required.
fn is_stream_sentinel(path: Option<&std::path::Path>) -> bool {
    path.is_some_and(|path| path.as_os_str() == crate::checkpoint_stream::SENTINEL)
}

pub(super) fn validate_checkpoint(
    capabilities: &EngineCapabilities,
    spec: &MachineSpec,
) -> Result<(), SpecError> {
    let checkpoint = &spec.checkpoint;
    if checkpoint.maximum_pause_ms == Some(0) {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            "checkpoint.maximum_pause_ms",
            "checkpoint pause bounds must be greater than zero",
        ));
    }
    if !checkpoint.enabled
        && (checkpoint.capture_directory.is_some()
            || checkpoint.restore_directory.is_some()
            || checkpoint.maximum_pause_ms.is_some()
            || checkpoint.mode != crate::spec::CheckpointMode::Full
            || checkpoint.incompatible_resources != crate::spec::IncompatibleResourcePolicy::Refuse)
    {
        return Err(spec_error(
            SpecErrorCategory::Conflict,
            "checkpoint",
            "checkpoint options require checkpointing to be enabled",
        ));
    }
    if !checkpoint.enabled {
        return Ok(());
    }
    if checkpoint.capture_directory.is_none() && checkpoint.restore_directory.is_none() {
        return Err(spec_error(
            SpecErrorCategory::Conflict,
            "checkpoint",
            "a capture or restore directory is required",
        ));
    }
    if !is_stream_sentinel(checkpoint.capture_directory.as_deref()) {
        validate_checkpoint_directory(
            checkpoint.capture_directory.as_deref(),
            "checkpoint.capture_directory",
        )?;
    }
    if !is_stream_sentinel(checkpoint.restore_directory.as_deref()) {
        validate_checkpoint_directory(
            checkpoint.restore_directory.as_deref(),
            "checkpoint.restore_directory",
        )?;
    }
    // The capability set is the single source of truth for which guests can be checkpointed;
    // reading it here makes discovery and preflight structurally incapable of disagreeing.
    if !capabilities.checkpoint.supports(spec.guest.architecture) {
        return Err(spec_error(
            SpecErrorCategory::Unsupported,
            "checkpoint",
            "native checkpoint/restore is not implemented for this guest architecture",
        ));
    }
    if checkpoint.mode != crate::spec::CheckpointMode::Full || checkpoint.maximum_pause_ms.is_some()
    {
        return Err(spec_error(
            SpecErrorCategory::Unsupported,
            "checkpoint",
            "only full checkpoints without a pause deadline are supported",
        ));
    }
    Ok(())
}

pub(super) fn validate_time_entropy(spec: &MachineSpec) -> Result<(), SpecError> {
    if spec.time.rate.numerator == 0
        || spec.time.rate.denominator == 0
        || spec.time.timer_resolution_ns == Some(0)
    {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            "time",
            "time rate and timer resolution must be greater than zero",
        ));
    }
    if !matches!(spec.time.source, crate::spec::TimeSource::Host)
        || spec.time.monotonic != crate::spec::MonotonicOrigin::Host
        || spec.time.timer_resolution_ns.is_some()
        || spec.time.rate != crate::spec::TimeRate::default()
    {
        return Err(spec_error(
            SpecErrorCategory::Unsupported,
            "time",
            "virtual time selection is not implemented by this backend",
        ));
    }
    if matches!(&spec.entropy, crate::spec::EntropySpec::Deterministic(seed) if seed.is_empty()) {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            "entropy",
            "deterministic entropy requires a nonempty seed",
        ));
    }
    if !matches!(spec.entropy, crate::spec::EntropySpec::SecureHost) {
        return Err(spec_error(
            SpecErrorCategory::Unsupported,
            "entropy",
            "deterministic entropy is not implemented by this backend",
        ));
    }
    Ok(())
}

pub(super) fn validate_cache(spec: &MachineSpec) -> Result<(), SpecError> {
    let cache = &spec.cache;
    if cache.budget_bytes == Some(0)
        || cache
            .identity
            .iter()
            .any(|item| item.name.is_empty() || item.bytes.is_empty())
    {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            "cache",
            "cache budgets and identity components must be nonempty",
        ));
    }
    let mut identities = BTreeSet::new();
    let identity_bytes = cache.identity.iter().try_fold(0_usize, |total, item| {
        if !identities.insert(&item.name) {
            return Err(spec_error(
                SpecErrorCategory::Conflict,
                "cache.identity",
                "cache identity component names must be unique",
            ));
        }
        total
            .checked_add(item.name.len() + item.bytes.len())
            .ok_or_else(|| {
                spec_error(
                    SpecErrorCategory::Limit,
                    "cache.identity",
                    "cache identity components overflow engine bounds",
                )
            })
    })?;
    if identity_bytes > 1024 * 1024 {
        return Err(spec_error(
            SpecErrorCategory::Limit,
            "cache.identity",
            "cache identity components exceed the engine limit",
        ));
    }
    if cache
        .directory
        .as_ref()
        .is_some_and(|path| !path.is_absolute() || path.as_os_str().as_encoded_bytes().contains(&0))
    {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            "cache.directory",
            "translation-cache host paths must be absolute and contain no NUL",
        ));
    }
    match cache.policy {
        crate::spec::CachePolicy::Disabled
            if cache.directory.is_some()
                || cache.budget_bytes.is_some()
                || !cache.identity.is_empty() =>
        {
            return Err(spec_error(
                SpecErrorCategory::Conflict,
                "cache.policy",
                "cache settings require an enabled cache policy",
            ))
        }
        crate::spec::CachePolicy::ReadWrite if cache.directory.is_none() => {
            return Err(spec_error(
                SpecErrorCategory::Invalid,
                "cache.directory",
                "read-write cache policy requires a cache directory",
            ))
        }
        crate::spec::CachePolicy::ReadOnly | crate::spec::CachePolicy::Refresh => {
            return Err(spec_error(
                SpecErrorCategory::Unsupported,
                "cache.policy",
                "the selected cache policy is not implemented by this backend",
            ))
        }
        _ => {}
    }
    if cache.budget_bytes.is_some() || !cache.identity.is_empty() {
        return Err(spec_error(
            SpecErrorCategory::Unsupported,
            "cache",
            "cache budgets and caller identity components are not implemented by this backend",
        ));
    }
    Ok(())
}

pub(super) fn validate_observability(
    spec: &MachineSpec,
    capabilities: &EngineCapabilities,
) -> Result<(), SpecError> {
    let value = &spec.observability;
    if value.syscall_sampling == Some(0)
        || value.syscall_sampling.is_some_and(|rate| rate > 1_000_000)
        || value.queue_capacity == Some(0)
        || value
            .queue_capacity
            .is_some_and(|size| size > capabilities.limits.queued_events)
        || value.trace.as_ref().is_some_and(|trace| {
            trace.queue_capacity == 0
                || trace.queue_capacity > capabilities.limits.queued_events
                || !(trace.include_guest_time || trace.include_host_time)
        })
    {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            "observability",
            "sampling, queue, or trace bounds are invalid",
        ));
    }
    if !value.metrics && !value.metric_kinds.is_empty() {
        return Err(spec_error(
            SpecErrorCategory::Conflict,
            "observability.metric_kinds",
            "metric kinds require metrics to be enabled",
        ));
    }
    if value != &crate::spec::ObservabilitySpec::default() {
        return Err(spec_error(
            SpecErrorCategory::Unsupported,
            "observability",
            "structured observability selection is not implemented by this backend",
        ));
    }
    Ok(())
}

pub(super) fn validate_debug(spec: &MachineSpec) -> Result<(), SpecError> {
    let value = &spec.debug;
    let selected = !value.operations.is_empty() || value.breakpoints != 0 || value.watchpoints != 0;
    if value.breakpoints > 65_536 || value.watchpoints > 65_536 {
        return Err(spec_error(
            SpecErrorCategory::Limit,
            "debug",
            "debug point count exceeds the engine limit",
        ));
    }
    if selected && value.authorization.is_none() {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            "debug.authorization",
            "debug operations require explicit authorization",
        ));
    }
    if value
        .authorization
        .as_ref()
        .is_some_and(|value| value.capability.is_empty())
    {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            "debug.authorization",
            "debug authorization capabilities must be nonempty",
        ));
    }
    if value.authorization.is_some() && !selected {
        return Err(spec_error(
            SpecErrorCategory::Conflict,
            "debug",
            "debug authorization requires at least one selected operation",
        ));
    }
    if selected {
        return Err(spec_error(
            SpecErrorCategory::Unsupported,
            "debug",
            "debug control is not implemented by this backend",
        ));
    }
    Ok(())
}

pub(super) fn validate_network(
    capabilities: &EngineCapabilities,
    spec: &MachineSpec,
) -> Result<(), SpecError> {
    let network = &spec.network;
    if network.mode == NetworkMode::Host && spec.security.sandbox != crate::Sandbox::Disabled {
        return Err(spec_error(
            SpecErrorCategory::Conflict,
            "network.mode",
            "host networking requires the host socket transport, which is unavailable in the selected sandbox",
        ));
    }
    let configured = network.namespace.is_some()
        || !network.interfaces.is_empty()
        || !network.port_forwards.is_empty()
        || network.external_listeners;
    match network.mode {
        NetworkMode::Host if configured => {
            return Err(spec_error(
                SpecErrorCategory::Conflict,
                "network",
                "host networking cannot carry virtual network configuration",
            ))
        }
        NetworkMode::None
            if !network.interfaces.is_empty()
                || !network.port_forwards.is_empty()
                || network.external_listeners =>
        {
            return Err(spec_error(
                SpecErrorCategory::Conflict,
                "network",
                "disabled networking cannot carry interfaces, forwards, or listeners",
            ))
        }
        NetworkMode::Virtual if network.namespace.is_none() => {
            return Err(spec_error(
                SpecErrorCategory::Invalid,
                "network.namespace",
                "virtual networking requires an opaque namespace identity",
            ))
        }
        _ => {}
    }
    if network.interfaces.len() > capabilities.networking.maximum_interfaces as usize {
        return Err(spec_error(
            SpecErrorCategory::Limit,
            "network.interfaces",
            "interface count exceeds the engine limit",
        ));
    }
    if network.port_forwards.len() > capabilities.networking.maximum_port_forwards as usize {
        return Err(spec_error(
            SpecErrorCategory::Limit,
            "network.port_forwards",
            "port-forward count exceeds the engine limit",
        ));
    }
    if network.external_listeners && network.port_forwards.is_empty() {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            "network.external_listeners",
            "external listeners require at least one port forward",
        ));
    }
    Ok(())
}

pub(super) fn validate_guest_path(
    path: &std::path::Path,
    maximum: u32,
    field: &'static str,
) -> Result<(), SpecError> {
    if !path.is_absolute() || path.as_os_str().as_encoded_bytes().len() > maximum as usize {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            field,
            "guest paths must be absolute and within the engine path limit",
        ));
    }
    if path.as_os_str().as_encoded_bytes().contains(&0) {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            field,
            "guest paths must not contain NUL",
        ));
    }
    if path
        .components()
        .any(|component| matches!(component, std::path::Component::ParentDir))
    {
        return Err(spec_error(
            SpecErrorCategory::Invalid,
            field,
            "guest paths must not escape through '..'",
        ));
    }
    Ok(())
}