cellos-supervisor 0.5.1

CellOS execution-cell runner — boots cells in Firecracker microVMs or gVisor, enforces narrow typed authority, emits signed CloudEvents.
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
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
//! Free helper functions split out from `supervisor.rs` (P0-2).
//!
//! This module contains:
//! - Env-flag predicates (`*_enabled()`) that gate optional supervisor features.
//! - DNS endpoint / egress-rule matching helpers.
//! - `RunTimeoutSource` + the resolver chain (`effective_run_timeout`,
//!   `run_timeout_message`, `configured_run_timeout_env`).
//! - Export-target resolution helpers (`effective_export_target_name`,
//!   `configured_export_target`, `resolve_export_target_kind`,
//!   `logical_export_destination`).
//! - Secret / lease scaffolding (`secret_ttl_for_key`,
//!   `runtime_secret_entries_for_doc`, `runtime_secret_lease_requests_for_doc`).
//! - The `cloud_event` envelope builder.
//!
//! All items are code-moves from `supervisor.rs`. No logic changes.

use std::time::Duration;

use cellos_core::{
    CloudEventV1, ExecutionCellDocument, ExportArtifact, ExportReceiptTargetKind, ExportTarget,
    RunSpec, RuntimeSecretLeaseRequest, SecretView, WorkloadIdentity, WorkloadIdentityKind,
};

use crate::runtime_secret::RuntimeSecretEntryInput;

/// SEC-21 host-controlled DNS resolver refresh — disabled by default.
///
/// Enable with `CELLOS_DNS_AUTHORITY_REFRESH=1` (mirrors `CELLOS_RESOLVE_EGRESS_DNS`
/// on/off semantics). When disabled, no `dns_authority_drift` events are emitted
/// even if the spec carries `authority.dnsAuthority.refreshPolicy`.
pub(crate) fn dns_authority_refresh_enabled() -> bool {
    std::env::var("CELLOS_DNS_AUTHORITY_REFRESH")
        .map(|v| {
            let t = v.trim().to_ascii_lowercase();
            matches!(t.as_str(), "1" | "true" | "yes" | "on")
        })
        .unwrap_or(false)
}

/// SEC-21 Phase 2 continuous-ticker daemon mode — disabled by default.
///
/// Activation predicate: `CELLOS_DNS_AUTHORITY_REFRESH=1` (the Phase 1
/// gate) AND `CELLOS_DNS_AUTHORITY_CONTINUOUS=1`. When the Phase 2 gate is
/// off, only the W2 SEC-21 startup one-tick fires; with both gates on, the
/// startup one-tick still fires AND a background tokio task keeps refreshing
/// for the cell's lifetime.
pub(crate) fn dns_authority_continuous_enabled() -> bool {
    std::env::var("CELLOS_DNS_AUTHORITY_CONTINUOUS")
        .map(|v| {
            let t = v.trim().to_ascii_lowercase();
            matches!(t.as_str(), "1" | "true" | "yes" | "on")
        })
        .unwrap_or(false)
}

/// SEC-21 Phase 2 — operator override for the inter-tick interval.
///
/// `CELLOS_DNS_AUTHORITY_TICK_INTERVAL_SECS=<u32>` sets the cadence in
/// seconds. Out-of-range or unparseable values fall back to the default;
/// values below the 5-second floor are clamped up to 5s by
/// [`cellos_supervisor::resolver_refresh::ticker::clamp_tick_interval_secs`].
///
/// Default: `min(refreshPolicy.minTtlSeconds, 60).max(5)` — short enough to
/// surface drift while the operator is still looking, long enough not to
/// hammer upstream resolvers. The 5s floor is a backstop against
/// misconfiguration.
pub(crate) fn dns_authority_tick_interval(
    policy: Option<&cellos_core::DnsRefreshPolicy>,
) -> std::time::Duration {
    let configured: Option<u64> = std::env::var("CELLOS_DNS_AUTHORITY_TICK_INTERVAL_SECS")
        .ok()
        .and_then(|s| s.trim().parse::<u64>().ok());
    let raw_secs = match configured {
        Some(s) => s,
        None => {
            let from_policy = policy
                .and_then(|p| p.min_ttl_seconds)
                .map(u64::from)
                .unwrap_or(60);
            from_policy.min(60)
        }
    };
    let clamped = cellos_supervisor::resolver_refresh::ticker::clamp_tick_interval_secs(raw_secs);
    std::time::Duration::from_secs(clamped)
}

/// When `false`, suppresses trust-plane observability CloudEvents (SEC-20/21/24).
pub(crate) fn trust_plane_observability_enabled() -> bool {
    match std::env::var("CELLOS_TRUST_PLANE_EVENTS") {
        Ok(v) => {
            let t = v.trim().to_ascii_lowercase();
            if t.is_empty() {
                return true;
            }
            !matches!(t.as_str(), "0" | "false" | "no" | "off")
        }
        Err(_) => true,
    }
}

/// SEAM-1 / L2-04 DNS proxy — disabled by default.
///
/// When `CELLOS_DNS_PROXY=1` AND the spec carries a non-empty
/// `authority.dnsAuthority.hostnameAllowlist` AND at least one `do53-*`
/// resolver in `authority.dnsAuthority.resolvers[]`, the supervisor activates
/// the in-netns DNS proxy that enforces the allowlist at the DNS protocol
/// layer and emits per-query CloudEvents.
///
/// scope: dataplane is `do53-udp` only; `dot` / `doh` / `doq` upstream
/// resolvers are documented as follow-up work. The proxy runs on Linux only —
/// macOS compiles but the spawn path is a no-op with a warning log + a single
/// `dns_query` event emitted with `reasonCode: upstream_failure` describing
/// the platform skip.
pub(crate) fn dns_proxy_enabled() -> bool {
    std::env::var("CELLOS_DNS_PROXY")
        .map(|v| {
            let t = v.trim().to_ascii_lowercase();
            matches!(t.as_str(), "1" | "true" | "yes" | "on")
        })
        .unwrap_or(false)
}

/// SEC-22 Phase 2 SNI-aware proxy — disabled by default.
///
/// When `CELLOS_SNI_PROXY=1` AND the spec carries a non-empty
/// `authority.dnsAuthority.hostnameAllowlist`, the supervisor activates a
/// per-cell L7 proxy that inspects either the TLS ClientHello SNI (when
/// the workload speaks TLS) or the HTTP/1.x `Host` header (cleartext) and
/// matches the extracted hostname against the same allowlist the DNS proxy
/// enforces. Allowed flows are forwarded to a transparent upstream;
/// denied flows are dropped (TLS) or answered with `HTTP/1.1 403`. Each
/// decision emits one `l7_egress_decision` CloudEvent with one of the
/// eight Phase 2 reason codes (`l7_sni_*`, `l7_http_host_*`,
/// `l7_unknown_protocol`, `l7_peek_timeout`).
///
/// scope: this proxy does NOT terminate TLS. SNI ↔ Host fronting alignment
/// requires MITM termination + a workload-trusted CA and is documented as
/// future work. HTTP/2 over TLS gets SNI-only inspection; h2c and HTTP/3 /
/// QUIC are out of scope.
pub(crate) fn sni_proxy_enabled() -> bool {
    std::env::var("CELLOS_SNI_PROXY")
        .map(|v| {
            let t = v.trim().to_ascii_lowercase();
            matches!(t.as_str(), "1" | "true" | "yes" | "on")
        })
        .unwrap_or(false)
}

/// Default bind address for the SEC-22 Phase 2 SNI proxy listener inside
/// the cell's netns. Operators override via `CELLOS_SNI_PROXY_BIND=ip:port`.
const SNI_PROXY_DEFAULT_BIND: &str = "127.0.0.1:8443";

/// SEC-22 Phase 2 SNI proxy bind address override.
pub(crate) fn sni_proxy_bind_addr() -> std::net::SocketAddr {
    let raw = std::env::var("CELLOS_SNI_PROXY_BIND")
        .unwrap_or_else(|_| SNI_PROXY_DEFAULT_BIND.to_string());
    raw.parse().unwrap_or_else(|e| {
        tracing::warn!(
            target: "cellos.supervisor.sni_proxy",
            error = %e,
            raw = %raw,
            default = SNI_PROXY_DEFAULT_BIND,
            "CELLOS_SNI_PROXY_BIND parse failed — falling back to default"
        );
        SNI_PROXY_DEFAULT_BIND.parse().expect("default bind parses")
    })
}

/// SEC-22 Phase 2 SNI proxy upstream address override (test-only escape
/// hatch). When unset the proxy connects to its own listen address — in a
/// real deployment this would be a transparent next-hop egress NAT, but
/// for unit/integration testing operators point the upstream at a stub
/// echo server. Mirrors `CELLOS_DNS_PROXY_UPSTREAM_OVERRIDE`.
pub(crate) fn sni_proxy_upstream_override() -> Option<std::net::SocketAddr> {
    std::env::var("CELLOS_SNI_PROXY_UPSTREAM_OVERRIDE")
        .ok()
        .and_then(|raw| raw.trim().parse().ok())
}

/// SEC-22 L7 gate observability — disabled by default.
///
/// Mirrors `CELLOS_TRUST_PLANE_EVENTS` / `CELLOS_DNS_AUTHORITY_REFRESH` on/off
/// semantics. Phase 1 is **observability-only at L7**: when on, the supervisor
/// emits one extra `l7_egress_decision` event per `dnsAuthority.hostnameAllowlist`
/// entry recording the policy commitment, plus one `workload_direct_dns_blocked`
/// deny event per port-53 egress rule whose destination is not a declared
/// resolver. Kernel-level enforcement of direct DNS still runs through the
/// nft generator (see `generate_nft_ruleset`) regardless of this flag.
pub(crate) fn l7_gate_observability_enabled() -> bool {
    std::env::var("CELLOS_L7_GATE_OBSERVABILITY")
        .map(|v| {
            let t = v.trim().to_ascii_lowercase();
            matches!(t.as_str(), "1" | "true" | "yes" | "on")
        })
        .unwrap_or(false)
}

pub(crate) fn identity_resolve_key(identity: &WorkloadIdentity) -> &str {
    match identity.kind {
        // The broker input is the requested audience; `secretRef` is the logical
        // in-cell alias that a future L2 host will materialize inside the boundary.
        WorkloadIdentityKind::FederatedOidc => &identity.audience,
    }
}

pub(crate) fn effective_export_target_name<'a>(
    doc: &'a ExecutionCellDocument,
    artifact: &'a ExportArtifact,
) -> Option<&'a str> {
    if let Some(target_name) = artifact.target.as_deref() {
        return Some(target_name);
    }
    let targets = doc.spec.export.as_ref()?.targets.as_ref()?;
    if targets.len() == 1 {
        Some(targets[0].name())
    } else {
        None
    }
}

pub(crate) fn configured_export_target<'a>(
    doc: &'a ExecutionCellDocument,
    artifact: &'a ExportArtifact,
) -> Option<&'a ExportTarget> {
    let target_name = effective_export_target_name(doc, artifact)?;
    doc.spec
        .export
        .as_ref()
        .and_then(|export| export.targets.as_ref())
        .and_then(|targets| targets.iter().find(|target| target.name() == target_name))
}

pub(crate) fn resolve_export_target_kind(
    doc: &ExecutionCellDocument,
    artifact: &ExportArtifact,
    sink_kind: Option<ExportReceiptTargetKind>,
) -> ExportReceiptTargetKind {
    let spec_kind = configured_export_target(doc, artifact).map(|target| match target {
        ExportTarget::Http(_) => ExportReceiptTargetKind::Http,
        ExportTarget::S3(_) => ExportReceiptTargetKind::S3,
    });
    spec_kind
        .or(sink_kind)
        .unwrap_or(ExportReceiptTargetKind::Local)
}

pub(crate) fn logical_export_destination(
    doc: &ExecutionCellDocument,
    artifact: &ExportArtifact,
    sink_destination: Option<&str>,
) -> Option<String> {
    match configured_export_target(doc, artifact) {
        Some(ExportTarget::S3(target)) => {
            let mut key = target
                .key_prefix
                .as_deref()
                .unwrap_or("")
                .trim_matches('/')
                .to_string();
            if !key.is_empty() {
                key.push('/');
            }
            key.push_str(&artifact.name);
            Some(format!("s3://{}/{}", target.bucket, key))
        }
        Some(ExportTarget::Http(target)) => sink_destination
            .map(str::to_string)
            .or_else(|| Some(target.base_url.clone())),
        None => sink_destination.map(str::to_string),
    }
}

/// When `CELLOS_RUN_ARGV0_ALLOW_PREFIXES` is set to a non-empty comma-separated list of path
/// prefixes, `argv[0]` must be an **absolute** path under one of those prefixes (after normalizing
/// `\` → `/`). Empty `argv` or an empty first token is rejected. Unset or whitespace-only env → no
/// check (backward compatible). See SEC-03 in `docs/sec_roadmap.md`.
pub(crate) fn argv0_allow_prefixes_error(argv: &[String]) -> Option<String> {
    let raw = std::env::var("CELLOS_RUN_ARGV0_ALLOW_PREFIXES").ok()?;
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    let prefixes: Vec<String> = trimmed
        .split(',')
        .map(|s| s.trim().trim_end_matches(['/', '\\']).replace('\\', "/"))
        .filter(|p| !p.is_empty())
        .collect();
    if prefixes.is_empty() {
        return None;
    }

    let Some(argv0) = argv.first() else {
        return Some("spec.run.argv is empty".into());
    };
    if argv0.is_empty() {
        return Some("spec.run.argv[0] is empty".into());
    }

    let norm = argv0.replace('\\', "/");
    let is_absolute = if cfg!(unix) {
        norm.starts_with('/')
    } else {
        let b = norm.as_bytes();
        (b.len() >= 3
            && b[0].is_ascii_alphabetic()
            && b[1] == b':'
            && (b[2] == b'/' || b[2] == b'\\'))
            || norm.starts_with("//")
    };
    if !is_absolute {
        return Some(format!(
            "CELLOS_RUN_ARGV0_ALLOW_PREFIXES is set but argv[0] is not an absolute path (got {argv0:?}); use a full path such as /usr/bin/true"
        ));
    }

    let ok = prefixes
        .iter()
        .any(|p| norm == *p || norm.starts_with(&format!("{p}/")));
    if !ok {
        return Some(format!(
            "argv[0] {argv0:?} is not under any allowed prefix from CELLOS_RUN_ARGV0_ALLOW_PREFIXES: {prefixes:?}"
        ));
    }
    None
}

pub(crate) fn configured_run_timeout_env() -> Result<Option<Duration>, String> {
    match std::env::var("CELLOS_RUN_TIMEOUT_MS") {
        Err(_) => Ok(None),
        Ok(raw) => {
            let t = raw.trim();
            if t.is_empty() {
                return Ok(None);
            }
            let ms: u64 = t
                .parse()
                .map_err(|_| format!("invalid CELLOS_RUN_TIMEOUT_MS: {raw:?}"))?;
            if ms == 0 {
                return Err("CELLOS_RUN_TIMEOUT_MS must be > 0".into());
            }
            Ok(Some(Duration::from_millis(ms)))
        }
    }
}

/// Which configured cap won the `min` race in `effective_run_timeout`.
///
/// I2: callers attribute the kill in `spawnError` so operators can tell
/// whether the TTL watchdog fired (supervisor-enforced hard cap from
/// `spec.lifetime.ttlSeconds`), the workload-declared soft cap fired
/// (`spec.run.timeoutMs`), or the operator env override fired
/// (`CELLOS_RUN_TIMEOUT_MS`).
#[derive(Debug, Clone, Copy)]
pub(crate) enum RunTimeoutSource {
    /// TTL ceiling fired — supervisor watchdog killed the cell at
    /// `spec.lifetime.ttlSeconds * 1000` ms.
    TtlCeiling { ttl_seconds: u64 },
    /// Workload-declared soft cap fired (`spec.run.timeoutMs`).
    SpecTimeout,
    /// Operator env override fired (`CELLOS_RUN_TIMEOUT_MS`).
    EnvTimeout,
}

/// Effective wall-clock cap for `spec.run`: minimum of spec `timeoutMs`,
/// `CELLOS_RUN_TIMEOUT_MS`, and the TTL ceiling derived from
/// `spec.lifetime.ttlSeconds`. Returns the winning duration **and** which
/// configured source it came from, so the caller can attribute the kill
/// in `spawnError`.
///
/// **TTL watchdog (I2 / D5):** the cell's lifetime is a destruction guarantee.
/// `ttl_seconds * 1000` becomes a hard ceiling on the run-phase wall clock so
/// that even a workload that ignores its own `timeoutMs` (or that has no
/// `timeoutMs` at all) is killed at TTL. The spec validator already rejects
/// `timeout_ms > ttl_seconds * 1000`, so when both are set the spec timeout
/// wins by construction; this `min` is the belt-and-braces.
pub(crate) fn effective_run_timeout(
    run: &RunSpec,
    ttl_seconds: u64,
) -> Result<Option<(Duration, RunTimeoutSource)>, String> {
    let env_timeout = configured_run_timeout_env()?;
    let spec_timeout = run.timeout_ms.map(Duration::from_millis);
    // I2: TTL is *always* a ceiling — derived from spec.lifetime.ttlSeconds,
    // saturating at u64::MAX milliseconds (functionally infinite).
    let ttl_ceiling = Duration::from_millis(ttl_seconds.saturating_mul(1000));
    let combined: Option<(Duration, RunTimeoutSource)> = match (spec_timeout, env_timeout) {
        (Some(s), Some(e)) => Some(if s <= e {
            (s, RunTimeoutSource::SpecTimeout)
        } else {
            (e, RunTimeoutSource::EnvTimeout)
        }),
        (Some(s), None) => Some((s, RunTimeoutSource::SpecTimeout)),
        (None, Some(e)) => Some((e, RunTimeoutSource::EnvTimeout)),
        (None, None) => None,
    };
    Ok(Some(match combined {
        Some((d, source)) => {
            if d <= ttl_ceiling {
                (d, source)
            } else {
                (ttl_ceiling, RunTimeoutSource::TtlCeiling { ttl_seconds })
            }
        }
        None => (ttl_ceiling, RunTimeoutSource::TtlCeiling { ttl_seconds }),
    }))
}

pub(crate) fn run_timeout_message(timeout: Duration, source: RunTimeoutSource) -> String {
    match source {
        RunTimeoutSource::TtlCeiling { ttl_seconds } => format!(
            "cell killed by TTL watchdog after {} ms (ttl_seconds={ttl_seconds})",
            timeout.as_millis()
        ),
        RunTimeoutSource::SpecTimeout => format!(
            "command timed out after {} ms (spec.run.timeoutMs)",
            timeout.as_millis()
        ),
        RunTimeoutSource::EnvTimeout => format!(
            "command timed out after {} ms (CELLOS_RUN_TIMEOUT_MS)",
            timeout.as_millis()
        ),
    }
}

pub(crate) fn secret_ttl_for_key(doc: &ExecutionCellDocument, key: &str) -> u64 {
    if let Some(identity) = &doc.spec.identity {
        if identity.secret_ref == key {
            return identity
                .ttl_seconds
                .unwrap_or(doc.spec.lifetime.ttl_seconds);
        }
    }
    doc.spec.lifetime.ttl_seconds
}

pub(crate) fn runtime_secret_entries_for_doc(
    doc: &ExecutionCellDocument,
    secrets: &[SecretView],
) -> Vec<RuntimeSecretEntryInput> {
    secrets
        .iter()
        .map(|secret| RuntimeSecretEntryInput {
            key: secret.key.clone(),
            // CELLOS-ZEROIZE: clone the inner String into a fresh `Zeroizing` so
            // the copied value is wiped on drop. `secret.value` is already
            // `Zeroizing<String>`; reach through with `.as_str().to_string()`.
            value: zeroize::Zeroizing::new(secret.value.as_str().to_string()),
            ttl_seconds: secret_ttl_for_key(doc, &secret.key),
        })
        .collect()
}

pub(crate) fn runtime_secret_lease_requests_for_doc(
    doc: &ExecutionCellDocument,
) -> Vec<RuntimeSecretLeaseRequest> {
    let mut requests = Vec::new();

    if let Some(identity) = &doc.spec.identity {
        requests.push(RuntimeSecretLeaseRequest {
            key: identity.secret_ref.clone(),
            ttl_seconds: identity
                .ttl_seconds
                .unwrap_or(doc.spec.lifetime.ttl_seconds),
        });
    }

    if let Some(secret_refs) = &doc.spec.authority.secret_refs {
        for key in secret_refs {
            if doc
                .spec
                .identity
                .as_ref()
                .is_some_and(|identity| identity.secret_ref == *key)
            {
                continue;
            }
            requests.push(RuntimeSecretLeaseRequest {
                key: key.clone(),
                ttl_seconds: secret_ttl_for_key(doc, key),
            });
        }
    }

    requests
}

/// Best-effort label for the configured secret broker, used in fail-fast error
/// messages and the structured `cellos.supervisor.secrets` ERROR log when a
/// declared `secretRef` cannot be resolved. Mirrors the selection ladder in
/// `composition::build_secret_broker` so an operator reading the log knows
/// exactly which adapter returned nothing for the missing key.
pub(crate) fn configured_broker_name() -> &'static str {
    match std::env::var("CELLOS_BROKER").unwrap_or_default().as_str() {
        "env" => "env",
        "file" => "file",
        "github-oidc" => "github-oidc",
        "vault-approle" => "vault-approle",
        _ => "memory",
    }
}

/// Build a CloudEvent envelope.
pub(crate) fn cloud_event(ty: impl Into<String>, data: serde_json::Value) -> CloudEventV1 {
    CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: "cellos-supervisor".into(),
        ty: ty.into(),
        datacontenttype: Some("application/json".into()),
        data: Some(data),
        time: Some(chrono::Utc::now().to_rfc3339()),
        traceparent: None,
    }
}

#[cfg(test)]
mod tests {
    use super::{
        effective_export_target_name, effective_run_timeout, logical_export_destination,
        RunTimeoutSource,
    };
    use cellos_core::types::SecretDeliveryMode;
    use cellos_core::{
        AuthorityBundle, ExecutionCellDocument, ExecutionCellSpec, ExportArtifact, ExportChannels,
        ExportTarget, HttpExportTarget, Lifetime, RunSpec, S3ExportTarget,
    };
    use std::time::Duration;

    fn run_with_timeout(timeout_ms: Option<u64>) -> RunSpec {
        RunSpec {
            argv: vec!["/usr/bin/true".into()],
            working_directory: None,
            timeout_ms,
            limits: None,
            secret_delivery: SecretDeliveryMode::Env,
        }
    }

    /// I2 / D5: TTL is the upper bound when no other timeout is set.
    /// `effective_run_timeout` must always return `Some(_)` so the watchdog
    /// fires.
    #[test]
    fn effective_run_timeout_falls_back_to_ttl_ceiling() {
        std::env::remove_var("CELLOS_RUN_TIMEOUT_MS");
        let run = run_with_timeout(None);
        let (got, source) = effective_run_timeout(&run, 60).expect("ok").expect("some");
        assert_eq!(got, Duration::from_secs(60));
        assert!(matches!(
            source,
            RunTimeoutSource::TtlCeiling { ttl_seconds: 60 }
        ));
    }

    /// I2: when spec.timeoutMs is set <= TTL ceiling, spec timeout wins.
    #[test]
    fn effective_run_timeout_prefers_spec_when_below_ttl() {
        std::env::remove_var("CELLOS_RUN_TIMEOUT_MS");
        let run = run_with_timeout(Some(5_000));
        let (got, source) = effective_run_timeout(&run, 60).expect("ok").expect("some");
        assert_eq!(got, Duration::from_millis(5_000));
        assert!(matches!(source, RunTimeoutSource::SpecTimeout));
    }

    /// I2: TTL is a hard ceiling. Even if spec.timeoutMs accidentally exceeds
    /// TTL (the validator rejects this earlier, but defence in depth), the
    /// effective timeout is capped at TTL.
    #[test]
    fn effective_run_timeout_caps_at_ttl_ceiling() {
        std::env::remove_var("CELLOS_RUN_TIMEOUT_MS");
        let run = run_with_timeout(Some(120_000));
        let (got, source) = effective_run_timeout(&run, 60).expect("ok").expect("some");
        assert_eq!(got, Duration::from_secs(60));
        assert!(matches!(
            source,
            RunTimeoutSource::TtlCeiling { ttl_seconds: 60 }
        ));
    }

    fn doc_with_targets(targets: Vec<ExportTarget>) -> ExecutionCellDocument {
        ExecutionCellDocument {
            api_version: "cellos.io/v1".into(),
            kind: "ExecutionCell".into(),
            spec: ExecutionCellSpec {
                id: "cell-1".into(),
                correlation: None,
                ingress: None,
                environment: None,
                placement: None,
                policy: None,
                identity: None,
                run: None,
                authority: AuthorityBundle::default(),
                lifetime: Lifetime { ttl_seconds: 60 },
                export: Some(ExportChannels {
                    artifacts: None,
                    targets: Some(targets),
                }),
                telemetry: None,
            },
        }
    }

    #[test]
    fn infers_single_target_name_when_artifact_target_missing() {
        let doc = doc_with_targets(vec![ExportTarget::Http(HttpExportTarget {
            name: "artifact-api".into(),
            base_url: "https://example.com/upload".into(),
            secret_ref: None,
        })]);
        let artifact = ExportArtifact {
            name: "coverage-summary".into(),
            path: "/tmp/coverage.txt".into(),
            target: None,
            content_type: None,
        };

        assert_eq!(
            effective_export_target_name(&doc, &artifact),
            Some("artifact-api")
        );
    }

    #[test]
    fn computes_logical_s3_destination_from_target_metadata() {
        let doc = doc_with_targets(vec![ExportTarget::S3(S3ExportTarget {
            name: "artifact-bucket".into(),
            bucket: "acme-cellos-artifacts".into(),
            key_prefix: Some("github/acme/widget/123456790".into()),
            region: Some("eu-west-1".into()),
            secret_ref: None,
        })]);
        let artifact = ExportArtifact {
            name: "test-results".into(),
            path: "/tmp/junit.xml".into(),
            target: None,
            content_type: None,
        };

        assert_eq!(
            logical_export_destination(&doc, &artifact, Some("https://ignored.example/upload")),
            Some("s3://acme-cellos-artifacts/github/acme/widget/123456790/test-results".into())
        );
    }
}