a3s-box-runtime 3.2.0

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
//! Ordered Runtime log cursors over Box's structured json-file projection.

use a3s_box_core::ExecutionManager;
use a3s_runtime::contract::{RuntimeLogChunk, RuntimeLogQuery, RuntimeLogStream};
use a3s_runtime::{RuntimeError, RuntimeResult, RuntimeUnitRecord};
use chrono::DateTime;
use sha2::{Digest, Sha256};
use zeroize::Zeroizing;

use super::metadata::{local_identity, map_execution_error, provider_identity_matches};
use super::secret::BoxSecretMaterial;
use super::BoxRuntimeDriver;

const RECORDS_PER_SECOND: u64 = 1_000_000;

impl BoxRuntimeDriver {
    pub(super) async fn read_runtime_logs(
        &self,
        unit: &RuntimeUnitRecord,
        query: &RuntimeLogQuery,
    ) -> RuntimeResult<Vec<RuntimeLogChunk>> {
        query.validate().map_err(RuntimeError::InvalidRequest)?;
        if query.unit_id != unit.spec.unit_id || query.generation != unit.spec.generation {
            return Err(RuntimeError::InvalidRequest(
                "Runtime log query identity does not match its unit record".into(),
            ));
        }
        let record =
            self.find_generation(&unit.spec)
                .await?
                .ok_or_else(|| RuntimeError::NotFound {
                    unit_id: unit.spec.unit_id.clone(),
                })?;
        provider_identity_matches(&unit.observation, &record)?;
        let (execution_id, local_generation, _) = local_identity(&record)?;
        let secret_material = self
            .secret_materialization
            .resolve_for_redaction(&unit.spec)
            .await?;
        let entries = self
            .manager
            .read_logs(&execution_id, local_generation)
            .await
            .map_err(|error| map_execution_error(&unit.spec.unit_id, error))?;
        project_logs(entries, query, &secret_material)
    }
}

fn project_logs(
    entries: Vec<a3s_box_core::log::LogEntry>,
    query: &RuntimeLogQuery,
    secret_material: &[BoxSecretMaterial],
) -> RuntimeResult<Vec<RuntimeLogChunk>> {
    let redactions = redaction_values(secret_material);
    let requested_cursor = query.cursor.as_deref().map(LogCursor::parse).transpose()?;
    if requested_cursor
        .as_ref()
        .is_some_and(|cursor| cursor.generation != query.generation)
    {
        return Err(RuntimeError::InvalidRequest(
            "Box log cursor belongs to another Runtime generation".into(),
        ));
    }
    let target = requested_cursor.as_ref().map(LogCursor::encode);
    let mut cursor_found = target.is_none();
    let mut chunks = Vec::with_capacity(query.limit as usize);
    let mut prior_timestamp = None;
    let mut current_second = None;
    let mut ordinal = 0_u64;

    for entry in entries {
        let stream = match entry.stream.as_str() {
            "stdout" => RuntimeLogStream::Stdout,
            "stderr" => RuntimeLogStream::Stderr,
            value => {
                return Err(RuntimeError::Protocol(format!(
                    "Box structured log contains unsupported stream {value:?}"
                )))
            }
        };
        if entry.log.len() > 1024 * 1024 {
            return Err(RuntimeError::Protocol(
                "Box log record exceeds the Runtime one-MiB chunk bound".into(),
            ));
        }
        let timestamp_ns = DateTime::parse_from_rfc3339(&entry.time)
            .map_err(|_| RuntimeError::Protocol("Box log timestamp is invalid".into()))?
            .timestamp_nanos_opt()
            .ok_or_else(|| RuntimeError::Protocol("Box log timestamp is out of range".into()))?;
        if prior_timestamp.is_some_and(|prior| timestamp_ns < prior) {
            return Err(RuntimeError::Protocol(
                "Box log records are not ordered by provider timestamp".into(),
            ));
        }
        prior_timestamp = Some(timestamp_ns);
        let second = timestamp_ns.div_euclid(1_000_000_000);
        if current_second != Some(second) {
            current_second = Some(second);
            ordinal = 0;
        }
        if ordinal >= RECORDS_PER_SECOND {
            return Err(RuntimeError::Protocol(
                "Box emitted more than one million log records in one second".into(),
            ));
        }
        let raw = RawLogRecord {
            generation: query.generation,
            timestamp_ns,
            ordinal,
            stream,
            data: Zeroizing::new(entry.log),
        };
        ordinal += 1;
        let redacted = Zeroizing::new(redact_log(raw.data.as_str(), &redactions));
        let cursor = LogCursor::new(&raw, redacted.as_str()).encode();
        let sequence = log_sequence(second, ordinal)?;

        if !cursor_found {
            if target.as_deref() == Some(cursor.as_str()) {
                cursor_found = true;
            }
            continue;
        }
        if query.stream.is_some_and(|requested| requested != stream) {
            continue;
        }
        let observed_at_ms = u64::try_from(timestamp_ns.div_euclid(1_000_000))
            .map_err(|_| RuntimeError::Protocol("Box log timestamp precedes the epoch".into()))?;
        let chunk = RuntimeLogChunk {
            schema: RuntimeLogChunk::SCHEMA.into(),
            cursor,
            sequence,
            observed_at_ms,
            stream,
            data: redacted.as_str().to_owned(),
        };
        chunk.validate().map_err(RuntimeError::Protocol)?;
        chunks.push(chunk);
        if chunks.len() == query.limit as usize {
            break;
        }
    }

    if !cursor_found {
        return Err(RuntimeError::Protocol(
            "Box log cursor is no longer available; the stream contains an explicit rotation gap"
                .into(),
        ));
    }
    if chunks
        .windows(2)
        .any(|pair| pair[0].sequence >= pair[1].sequence)
    {
        return Err(RuntimeError::Protocol(
            "Box log projection produced unordered Runtime chunks".into(),
        ));
    }
    Ok(chunks)
}

struct RawLogRecord {
    generation: u64,
    timestamp_ns: i64,
    ordinal: u64,
    stream: RuntimeLogStream,
    data: Zeroizing<String>,
}

fn redaction_values(material: &[BoxSecretMaterial]) -> Vec<&str> {
    let mut values = material
        .iter()
        .filter_map(|material| std::str::from_utf8(material.as_bytes()).ok())
        .filter(|value| !value.is_empty())
        .collect::<Vec<_>>();
    values
        .sort_unstable_by(|left, right| right.len().cmp(&left.len()).then_with(|| left.cmp(right)));
    values.dedup();
    values
}

fn redact_log(value: &str, redactions: &[&str]) -> String {
    let mut redacted = String::with_capacity(value.len());
    let mut offset = 0;
    while offset < value.len() {
        if let Some(secret) = redactions
            .iter()
            .copied()
            .find(|secret| value[offset..].starts_with(secret))
        {
            redacted.push_str("[REDACTED]");
            offset += secret.len();
            continue;
        }
        let Some(character) = value[offset..].chars().next() else {
            break;
        };
        redacted.push(character);
        offset += character.len_utf8();
    }
    redacted
}

struct LogCursor {
    generation: u64,
    timestamp_ns: i64,
    ordinal: u64,
    stream: RuntimeLogStream,
    digest: String,
}

impl LogCursor {
    fn new(record: &RawLogRecord, redacted_data: &str) -> Self {
        let mut hash = Sha256::new();
        hash.update(b"a3s-box-log-cursor-v1\0");
        hash.update(record.generation.to_be_bytes());
        hash.update(record.timestamp_ns.to_be_bytes());
        hash.update(record.ordinal.to_be_bytes());
        hash.update(match record.stream {
            RuntimeLogStream::Stdout => b"stdout".as_slice(),
            RuntimeLogStream::Stderr => b"stderr".as_slice(),
        });
        // A cursor must never become an offline verifier for low-entropy
        // Secret material that a workload wrote to its raw provider log.
        hash.update(redacted_data.as_bytes());
        let digest = format!("{:x}", hash.finalize());
        Self {
            generation: record.generation,
            timestamp_ns: record.timestamp_ns,
            ordinal: record.ordinal,
            stream: record.stream,
            digest: digest[..16].into(),
        }
    }

    fn parse(value: &str) -> RuntimeResult<Self> {
        let fields = value.split(':').collect::<Vec<_>>();
        if fields.len() != 6 || fields[0] != "v1" {
            return Err(RuntimeError::InvalidRequest(
                "invalid Box log cursor".into(),
            ));
        }
        let generation = fields[1]
            .parse::<u64>()
            .ok()
            .filter(|value| *value > 0)
            .ok_or_else(|| RuntimeError::InvalidRequest("invalid Box log cursor".into()))?;
        let timestamp_ns = fields[2]
            .parse::<i64>()
            .map_err(|_| RuntimeError::InvalidRequest("invalid Box log cursor".into()))?;
        let ordinal = fields[3]
            .parse::<u64>()
            .map_err(|_| RuntimeError::InvalidRequest("invalid Box log cursor".into()))?;
        if ordinal >= RECORDS_PER_SECOND {
            return Err(RuntimeError::InvalidRequest(
                "invalid Box log cursor".into(),
            ));
        }
        let stream = match fields[4] {
            "o" => RuntimeLogStream::Stdout,
            "e" => RuntimeLogStream::Stderr,
            _ => {
                return Err(RuntimeError::InvalidRequest(
                    "invalid Box log cursor".into(),
                ))
            }
        };
        let digest = fields[5];
        if digest.len() != 16 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) {
            return Err(RuntimeError::InvalidRequest(
                "invalid Box log cursor".into(),
            ));
        }
        Ok(Self {
            generation,
            timestamp_ns,
            ordinal,
            stream,
            digest: digest.into(),
        })
    }

    fn encode(&self) -> String {
        let stream = match self.stream {
            RuntimeLogStream::Stdout => "o",
            RuntimeLogStream::Stderr => "e",
        };
        format!(
            "v1:{}:{}:{}:{stream}:{}",
            self.generation, self.timestamp_ns, self.ordinal, self.digest
        )
    }
}

fn log_sequence(second: i64, ordinal_after_increment: u64) -> RuntimeResult<u64> {
    u64::try_from(second)
        .ok()
        .and_then(|second| second.checked_mul(RECORDS_PER_SECOND))
        .and_then(|base| base.checked_add(ordinal_after_increment))
        .ok_or_else(|| RuntimeError::Protocol("Box log sequence overflowed".into()))
}

#[cfg(test)]
mod tests {
    use a3s_box_core::log::LogEntry;

    use super::*;

    fn query(cursor: Option<String>, stream: Option<RuntimeLogStream>) -> RuntimeLogQuery {
        RuntimeLogQuery {
            schema: RuntimeLogQuery::SCHEMA.into(),
            unit_id: "unit-1".into(),
            generation: 7,
            cursor,
            limit: 10,
            stream,
        }
    }

    #[test]
    fn cursor_resume_preserves_same_timestamp_total_order_and_filtering() {
        let entries = vec![
            LogEntry {
                log: "first\n".into(),
                stream: "stdout".into(),
                time: "2026-07-17T00:00:00.123456789Z".into(),
            },
            LogEntry {
                log: "second\n".into(),
                stream: "stderr".into(),
                time: "2026-07-17T00:00:00.123456789Z".into(),
            },
            LogEntry {
                log: "third\n".into(),
                stream: "stdout".into(),
                time: "2026-07-17T00:00:01Z".into(),
            },
        ];
        let all = project_logs(entries.clone(), &query(None, None), &[]).unwrap();
        assert_eq!(all.len(), 3);
        assert!(all[0].sequence < all[1].sequence && all[1].sequence < all[2].sequence);

        let resumed = project_logs(
            entries,
            &query(Some(all[0].cursor.clone()), Some(RuntimeLogStream::Stdout)),
            &[],
        )
        .unwrap();
        assert_eq!(resumed.len(), 1);
        assert_eq!(resumed[0].data, "third\n");
    }

    #[test]
    fn missing_valid_cursor_reports_an_explicit_gap() {
        let cursor = LogCursor {
            generation: 7,
            timestamp_ns: 1,
            ordinal: 0,
            stream: RuntimeLogStream::Stdout,
            digest: "0123456789abcdef".into(),
        }
        .encode();
        let error = project_logs(Vec::new(), &query(Some(cursor), None), &[]).unwrap_err();
        assert!(error.to_string().contains("rotation gap"));
    }

    #[test]
    fn exact_overlapping_secret_values_are_redacted_longest_first() {
        let entries = vec![LogEntry {
            log: "token=abc123 fallback=abc untouched=abcd\n".into(),
            stream: "stdout".into(),
            time: "2026-07-17T00:00:00Z".into(),
        }];
        let secrets = [
            BoxSecretMaterial::new(b"abc".to_vec()).unwrap(),
            BoxSecretMaterial::new(b"abc123".to_vec()).unwrap(),
        ];
        let chunks = project_logs(entries, &query(None, None), &secrets).unwrap();
        assert_eq!(
            chunks[0].data,
            "token=[REDACTED] fallback=[REDACTED] untouched=[REDACTED]d\n"
        );
        assert!(!chunks[0].data.contains("abc"));
    }

    #[test]
    fn replacement_markers_are_not_reprocessed_as_secret_material() {
        assert_eq!(
            redact_log("abc123 RED", &["abc123", "RED"]),
            "[REDACTED] [REDACTED]"
        );
    }

    #[test]
    fn cursor_digest_uses_redacted_data_instead_of_secret_plaintext() {
        let first = project_logs(
            vec![LogEntry {
                log: "token=alpha\n".into(),
                stream: "stdout".into(),
                time: "2026-07-17T00:00:00Z".into(),
            }],
            &query(None, None),
            &[BoxSecretMaterial::new(b"alpha".to_vec()).unwrap()],
        )
        .unwrap();
        let second = project_logs(
            vec![LogEntry {
                log: "token=bravo\n".into(),
                stream: "stdout".into(),
                time: "2026-07-17T00:00:00Z".into(),
            }],
            &query(None, None),
            &[BoxSecretMaterial::new(b"bravo".to_vec()).unwrap()],
        )
        .unwrap();

        assert_eq!(first[0].data, "token=[REDACTED]\n");
        assert_eq!(first[0].cursor, second[0].cursor);
    }
}