a3s-box-runtime 3.2.3

MicroVM runtime engine — VM lifecycle, OCI images, attestation, networking
Documentation
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
//! Closed A3S ACL contract for OCI image builds owned by A3S Box.
//!
//! A build plan contains immutable product intent. Invocation-only values such
//! as the destination tag and output verbosity stay outside the canonical ACL
//! identity.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use a3s_acl::{
    canonical_bytes_with_schema, canonical_digest_with_schema, parse_with_limits,
    validate_document, AttributeSchema, Block, BlockSchema, CanonicalError, Cardinality, Document,
    ParseLimits, Schema, SchemaDiagnosticCode, Value, ValueSchema,
};
use a3s_box_core::platform::Platform;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::engine::{BuildConfig, BuildNetworkPolicy};

const BUILD_LABEL: &str = "oci";
const MAX_PLAN_PATH_BYTES: usize = 255;
const MAX_TARGET_BYTES: usize = 128;
const BUILD_PLAN_LIMITS: ParseLimits = ParseLimits {
    max_document_bytes: 16 * 1024,
    max_nesting_depth: 2,
    max_collection_items: 16,
    max_token_bytes: 1024,
    max_diagnostics: 16,
};

/// Cache behavior admitted by the Box build-plan contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum BuildCachePolicy {
    /// Reuse only content-addressed native build-engine cache entries.
    ContentAddressed,
    /// Rebuild every layer.
    Disabled,
}

impl BuildCachePolicy {
    fn parse(value: &str) -> Result<Self, BoxBuildPlanError> {
        match value {
            "content-addressed" => Ok(Self::ContentAddressed),
            "disabled" => Ok(Self::Disabled),
            _ => Err(BoxBuildPlanError::invalid(
                "cache",
                "must be content-addressed or disabled",
            )),
        }
    }

    /// Stable ACL representation.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ContentAddressed => "content-addressed",
            Self::Disabled => "disabled",
        }
    }
}

/// Invocation-only options excluded from the canonical build-plan digest.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BoxBuildOptions {
    /// Optional local image reference assigned by the native image store.
    pub tag: Option<String>,
    /// Suppress native build-engine progress output.
    pub quiet: bool,
}

/// Immutable, closed Box-owned OCI build plan.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BoxBuildPlan {
    context: String,
    file: String,
    platform: Platform,
    target: Option<String>,
    network: BuildNetworkPolicy,
    cache: BuildCachePolicy,
}

impl BoxBuildPlan {
    /// Current closed ACL schema identity.
    pub const SCHEMA: &'static str = "a3s.box.build-plan.v1";

    /// Parse and validate one bounded A3S ACL build plan.
    pub fn parse_acl(source: &str) -> Result<Self, BoxBuildPlanError> {
        let document = parse_with_limits(source, BUILD_PLAN_LIMITS).map_err(|error| {
            BoxBuildPlanError::AclParse {
                message: error.message,
                line: error.line,
                column: error.column,
            }
        })?;
        let schema = build_plan_schema();
        let report = validate_document(&document, &schema);
        if let Some(diagnostic) = report.diagnostics.into_iter().next() {
            return Err(BoxBuildPlanError::Schema {
                code: diagnostic.code,
                path: diagnostic.path,
            });
        }

        let block = document.blocks.first().ok_or_else(|| {
            BoxBuildPlanError::invalid("build", "must contain exactly one build block")
        })?;
        if block.labels.first().map(String::as_str) != Some(BUILD_LABEL) {
            return Err(BoxBuildPlanError::invalid(
                "label",
                "must be the exact value oci",
            ));
        }

        let schema_value = required_string(block, "schema")?;
        if schema_value != Self::SCHEMA {
            return Err(BoxBuildPlanError::invalid(
                "schema",
                "is not a supported Box build-plan schema",
            ));
        }
        let context = normalize_repository_path(required_string(block, "context")?, true)
            .map_err(|reason| BoxBuildPlanError::invalid("context", reason))?;
        let file = normalize_repository_path(required_string(block, "file")?, false)
            .map_err(|reason| BoxBuildPlanError::invalid("file", reason))?;
        let platform = parse_platform(required_string(block, "platform")?)?;
        let network = BuildNetworkPolicy::parse_acl(required_string(block, "network")?)
            .ok_or_else(|| BoxBuildPlanError::invalid("network", "must be none or outbound"))?;
        let cache = BuildCachePolicy::parse(required_string(block, "cache")?)?;
        let target = block
            .attributes
            .get("target")
            .map(|value| {
                value
                    .as_str()
                    .ok_or_else(|| BoxBuildPlanError::invalid("target", "must be a string"))
            })
            .transpose()?
            .map(normalize_target)
            .transpose()
            .map_err(|reason| BoxBuildPlanError::invalid("target", reason))?;

        Ok(Self {
            context,
            file,
            platform,
            target,
            network,
            cache,
        })
    }

    /// Canonical A3S ACL bytes represented as UTF-8 text with one final LF.
    pub fn canonical_acl(&self) -> Result<String, BoxBuildPlanError> {
        let bytes = canonical_bytes_with_schema(&self.document(), &build_plan_schema())?;
        String::from_utf8(bytes).map_err(|_| BoxBuildPlanError::CanonicalEncoding)
    }

    /// Lowercase SHA-256 identity over the canonical ACL bytes.
    pub fn canonical_digest(&self) -> Result<String, BoxBuildPlanError> {
        canonical_digest_with_schema(&self.document(), &build_plan_schema())
            .map_err(BoxBuildPlanError::from)
    }

    /// Resolve repository-relative paths and compile into Box's existing native
    /// build engine. Both paths are canonicalized once, so later symlink swaps
    /// cannot redirect this compiled invocation outside the admitted source.
    pub fn compile(
        &self,
        source_root: &Path,
        options: BoxBuildOptions,
    ) -> Result<BuildConfig, BoxBuildPlanError> {
        let source_root = canonical_source_root(source_root)?;
        let context_dir = resolve_plan_path(&source_root, &self.context, "context", PathKind::Dir)?;
        let dockerfile_path = resolve_plan_path(&source_root, &self.file, "file", PathKind::File)?;

        Ok(BuildConfig {
            context_dir,
            dockerfile_path,
            tag: options.tag,
            build_args: HashMap::new(),
            quiet: options.quiet,
            platforms: vec![self.platform.clone()],
            target: self.target.clone(),
            no_cache: self.cache == BuildCachePolicy::Disabled,
            network: self.network,
            metrics: None,
            run_pool: None,
        })
    }

    /// Repository-relative build context.
    pub fn context(&self) -> &str {
        &self.context
    }

    /// Repository-relative Dockerfile or Containerfile.
    pub fn file(&self) -> &str {
        &self.file
    }

    /// Exact single target platform.
    pub fn platform(&self) -> &Platform {
        &self.platform
    }

    /// Optional multi-stage target.
    pub fn target(&self) -> Option<&str> {
        self.target.as_deref()
    }

    /// Network policy for Dockerfile execution instructions.
    pub const fn network(&self) -> BuildNetworkPolicy {
        self.network
    }

    /// Native build-cache policy.
    pub const fn cache(&self) -> BuildCachePolicy {
        self.cache
    }

    /// Whether two per-platform plans represent the same build intent once
    /// their target platform is deliberately excluded.
    pub(in crate::oci::build) fn has_same_non_platform_intent(&self, other: &Self) -> bool {
        self.context == other.context
            && self.file == other.file
            && self.target == other.target
            && self.network == other.network
            && self.cache == other.cache
    }

    fn document(&self) -> Document {
        let mut attributes = HashMap::from([
            (
                "cache".to_string(),
                Value::String(self.cache.as_str().to_string()),
            ),
            ("context".to_string(), Value::String(self.context.clone())),
            ("file".to_string(), Value::String(self.file.clone())),
            (
                "network".to_string(),
                Value::String(self.network.as_acl().to_string()),
            ),
            (
                "platform".to_string(),
                Value::String(self.platform.to_string()),
            ),
            (
                "schema".to_string(),
                Value::String(Self::SCHEMA.to_string()),
            ),
        ]);
        if let Some(target) = &self.target {
            attributes.insert("target".to_string(), Value::String(target.clone()));
        }
        Document {
            blocks: vec![Block {
                name: "build".to_string(),
                labels: vec![BUILD_LABEL.to_string()],
                blocks: Vec::new(),
                attributes,
            }],
        }
    }
}

/// Stable failures from build-plan admission and source resolution.
#[derive(Debug, Error)]
pub enum BoxBuildPlanError {
    /// The bounded ACL parser rejected the source.
    #[error("Box build plan ACL is invalid at {line}:{column}: {message}")]
    AclParse {
        message: String,
        line: usize,
        column: usize,
    },
    /// The closed schema rejected an attribute, block, label count, or type.
    #[error("Box build plan schema rejected {path}: {code}")]
    Schema {
        code: SchemaDiagnosticCode,
        path: String,
    },
    /// A closed contract value was invalid.
    #[error("Box build plan field {field} {reason}")]
    InvalidValue {
        field: &'static str,
        reason: &'static str,
    },
    /// The caller did not provide a usable absolute source root.
    #[error("Box build source root {reason}")]
    InvalidSourceRoot { reason: &'static str },
    /// A plan path was missing, the wrong kind, or escaped the source root.
    #[error("Box build plan {field} path {reason}")]
    UnsafePath {
        field: &'static str,
        reason: &'static str,
    },
    /// The validated AST could not be canonicalized.
    #[error("Box build plan canonicalization failed: {0}")]
    Canonical(#[from] CanonicalError),
    /// ACL canonical bytes must always be UTF-8.
    #[error("Box build plan canonical output was not UTF-8")]
    CanonicalEncoding,
}

impl BoxBuildPlanError {
    fn invalid(field: &'static str, reason: &'static str) -> Self {
        Self::InvalidValue { field, reason }
    }
}

#[derive(Clone, Copy)]
enum PathKind {
    Dir,
    File,
}

fn build_plan_schema() -> Schema {
    let body = Schema::new()
        .attribute("schema", AttributeSchema::required(ValueSchema::string()))
        .attribute("context", AttributeSchema::required(ValueSchema::string()))
        .attribute("file", AttributeSchema::required(ValueSchema::string()))
        .attribute("platform", AttributeSchema::required(ValueSchema::string()))
        .attribute("target", AttributeSchema::optional(ValueSchema::string()))
        .attribute("network", AttributeSchema::required(ValueSchema::string()))
        .attribute("cache", AttributeSchema::required(ValueSchema::string()));
    Schema::new().block(
        "build",
        BlockSchema::new(body)
            .occurrences(Cardinality::exactly(1))
            .labels(Cardinality::exactly(1)),
    )
}

fn required_string<'a>(
    block: &'a Block,
    field: &'static str,
) -> Result<&'a str, BoxBuildPlanError> {
    block
        .attributes
        .get(field)
        .and_then(Value::as_str)
        .ok_or_else(|| BoxBuildPlanError::invalid(field, "must be a string"))
}

fn normalize_repository_path(value: &str, allow_root: bool) -> Result<String, &'static str> {
    if value.is_empty()
        || value.len() > MAX_PLAN_PATH_BYTES
        || value.starts_with('/')
        || value.contains(['\0', '\\', '%'])
    {
        return Err("must be a bounded relative POSIX path");
    }
    let value = value.strip_prefix("./").unwrap_or(value);
    if value == "." {
        return allow_root
            .then(|| ".".to_string())
            .ok_or("cannot be the repository root");
    }
    let segments = value.split('/').collect::<Vec<_>>();
    if segments.iter().any(|segment| {
        segment.is_empty()
            || matches!(*segment, "." | "..")
            || !segment.bytes().all(|byte| {
                byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'@' | b'+')
            })
    }) {
        return Err("contains an unsafe path segment");
    }
    Ok(segments.join("/"))
}

fn normalize_target(value: &str) -> Result<String, &'static str> {
    if value.is_empty()
        || value.len() > MAX_TARGET_BYTES
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.'))
    {
        return Err("must be a bounded Dockerfile stage name");
    }
    Ok(value.to_string())
}

fn parse_platform(value: &str) -> Result<Platform, BoxBuildPlanError> {
    match value {
        "linux/amd64" => Ok(Platform::linux_amd64()),
        "linux/arm64" => Ok(Platform::linux_arm64()),
        _ => Err(BoxBuildPlanError::invalid(
            "platform",
            "must be linux/amd64 or linux/arm64",
        )),
    }
}

fn canonical_source_root(source_root: &Path) -> Result<PathBuf, BoxBuildPlanError> {
    if !source_root.is_absolute() {
        return Err(BoxBuildPlanError::InvalidSourceRoot {
            reason: "must be absolute",
        });
    }
    let root = source_root
        .canonicalize()
        .map_err(|_| BoxBuildPlanError::InvalidSourceRoot {
            reason: "does not exist or cannot be resolved",
        })?;
    if !root.is_dir() {
        return Err(BoxBuildPlanError::InvalidSourceRoot {
            reason: "must be a directory",
        });
    }
    Ok(root)
}

fn resolve_plan_path(
    source_root: &Path,
    relative: &str,
    field: &'static str,
    kind: PathKind,
) -> Result<PathBuf, BoxBuildPlanError> {
    let unresolved = if relative == "." {
        source_root.to_path_buf()
    } else {
        source_root.join(relative)
    };
    let resolved = unresolved
        .canonicalize()
        .map_err(|_| BoxBuildPlanError::UnsafePath {
            field,
            reason: "does not exist or cannot be resolved",
        })?;
    if !resolved.starts_with(source_root) {
        return Err(BoxBuildPlanError::UnsafePath {
            field,
            reason: "escapes the admitted source root",
        });
    }
    let expected_kind = match kind {
        PathKind::Dir => resolved.is_dir(),
        PathKind::File => resolved.is_file(),
    };
    if !expected_kind {
        return Err(BoxBuildPlanError::UnsafePath {
            field,
            reason: match kind {
                PathKind::Dir => "must resolve to a directory",
                PathKind::File => "must resolve to a regular file",
            },
        });
    }
    Ok(resolved)
}

#[cfg(test)]
mod tests;