Skip to main content

magma_bundle/
lib.rs

1//! magma-bundle — compliance-ready reconcile artifact.
2//!
3//! Every reconcile produces typed artifacts: a `Plan` (what was
4//! intended), an `Outcome` (what landed), a `DriftReport` (how
5//! policy classified each change), a `LifecycleState` (which phases
6//! it went through), an audit chain (every event with BLAKE3
7//! linkage). This crate combines them into one `Bundle` with a
8//! BLAKE3 bundle_id over the canonical serialization.
9//!
10//! Useful for:
11//!
12//! * **Compliance audits** — one tamper-evident artifact per
13//!   reconcile.
14//! * **Operator support** — "send us the bundle for this CR" and
15//!   the bundle has everything.
16//! * **Disaster recovery** — bundle pins what happened; replay
17//!   verifies pre/post state.
18//! * **Cross-team handoffs** — typed shape, no missing pieces.
19
20#![deny(unsafe_code)]
21
22use chrono::{DateTime, Utc};
23use serde::{Deserialize, Serialize};
24use thiserror::Error;
25
26use magma_converge::{Outcome, Plan, PlanId};
27use magma_drift::DriftReport;
28use magma_fsm::LifecycleState;
29use magma_stream::Event;
30
31#[derive(Debug, Error)]
32pub enum BundleError {
33    #[error("serialize: {0}")]
34    Serialize(#[from] serde_json::Error),
35    #[error("bundle id mismatch: have {have:?}, recomputed {recomputed:?}")]
36    IdMismatch { have: String, recomputed: String },
37    #[error("missing required field: {0}")]
38    Missing(&'static str),
39}
40
41/// Compliance-ready bundle. Carries every typed artifact a single
42/// reconcile produces, plus a BLAKE3 `bundle_id` over the canonical
43/// projection. Round-trips through serde + verifies via
44/// `Bundle::verify`.
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct Bundle {
47    /// BLAKE3 hash over the canonical projection (every field
48    /// except `bundle_id` itself + `built_at`).
49    pub bundle_id: String,
50    /// When the bundle was built (NOT in the hash so two bundles
51    /// over the same reconcile data hash equally).
52    pub built_at: DateTime<Utc>,
53    /// Reconciler kind that produced this reconcile.
54    pub kind: String,
55    /// Workspace identifier (CR name + namespace, or operator-side
56    /// state-name triple).
57    pub workspace: String,
58    /// The typed Plan.
59    pub plan: Plan,
60    /// The Outcome of applying the Plan (may be a no-op outcome
61    /// if the plan never applied — e.g. HeldForApproval).
62    pub outcome: Option<Outcome>,
63    /// Drift classification report.
64    pub drift: DriftReport,
65    /// FSM lifecycle snapshot at bundle-build time.
66    pub lifecycle: LifecycleState,
67    /// Audit events (typically the magma-stream chain for this
68    /// reconcile). May be empty if no stream was wired.
69    pub audit: Vec<Event>,
70    /// BLAKE3 attestation of the materialized `magma-rubygems`
71    /// gem tree this reconcile ran against. `None` means the
72    /// reconcile ran outside a magma-rubygems-materialized
73    /// closure (e.g. legacy `bundle install` workspace). Once
74    /// magma-rubygems M5 lands, every Pangea-side
75    /// reconcile populates this — operators can verify the gem
76    /// closure end-to-end alongside plan + drift + lifecycle.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub gem_tree_attestation: Option<String>,
79    /// How much of this reconcile's `before` side was real, observed
80    /// fact — the plan-time refresh's own trustworthiness.
81    ///
82    /// **Why a receipt needs this.** A refresh in which every
83    /// `ReadResource` failed leaves state untouched, so the plan is
84    /// all-`NoOp` and the bundle looks exactly like a reconcile in which
85    /// reality genuinely matched. A compliance artifact that cannot tell
86    /// "we checked and it was fine" from "we could not check" is not
87    /// evidence of anything.
88    ///
89    /// **Covered by `bundle_id`** — unlike the plan's own copy, which is
90    /// deliberately outside `PlanId` (see `magma_types::Plan::observation`).
91    /// A `PlanId` addresses a change set and must stay stable under
92    /// transient RPC weather; a bundle id attests to what actually
93    /// happened, so the record that a pass was blind must not be
94    /// strippable without breaking verification.
95    ///
96    /// `None` means "not recorded", never "clean" — an honest absence
97    /// rather than a default that flatters. Populated by whoever assembled
98    /// the reconcile (the `pangea-operator` reconcile loop is the intended
99    /// writer; nothing inside magma builds a bundle from a refreshed plan
100    /// today).
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub observation: Option<magma_types::Observation>,
103}
104
105impl Bundle {
106    /// Construct a Bundle. Computes `bundle_id` from the canonical
107    /// projection of every field except `bundle_id` + `built_at`.
108    pub fn new(
109        kind: impl Into<String>,
110        workspace: impl Into<String>,
111        plan: Plan,
112        outcome: Option<Outcome>,
113        drift: DriftReport,
114        lifecycle: LifecycleState,
115        audit: Vec<Event>,
116    ) -> Result<Self, BundleError> {
117        Self::new_with_gem_tree(
118            kind, workspace, plan, outcome, drift, lifecycle, audit, None,
119        )
120    }
121
122    /// Like `new`, but also records a `magma-rubygems` gem tree
123    /// attestation alongside the reconcile artifacts. Once
124    /// magma-rubygems M5 lands, every Pangea-side reconcile
125    /// constructs the bundle via this path; legacy
126    /// bundle-install workspaces still go through `new` and set
127    /// the field to `None`.
128    pub fn new_with_gem_tree(
129        kind: impl Into<String>,
130        workspace: impl Into<String>,
131        plan: Plan,
132        outcome: Option<Outcome>,
133        drift: DriftReport,
134        lifecycle: LifecycleState,
135        audit: Vec<Event>,
136        gem_tree_attestation: Option<String>,
137    ) -> Result<Self, BundleError> {
138        let kind = kind.into();
139        let workspace = workspace.into();
140        let bundle_id = Self::derive_id(
141            &kind,
142            &workspace,
143            &plan,
144            &outcome,
145            &drift,
146            &lifecycle,
147            &audit,
148            gem_tree_attestation.as_deref(),
149            None,
150        )?;
151        Ok(Self {
152            bundle_id,
153            built_at: Utc::now(),
154            kind,
155            workspace,
156            plan,
157            outcome,
158            drift,
159            lifecycle,
160            audit,
161            gem_tree_attestation,
162            observation: None,
163        })
164    }
165
166    /// Record how much of this reconcile's `before` side was real,
167    /// observed fact, re-deriving `bundle_id` to cover it.
168    ///
169    /// Re-deriving is the point, not a side effect: a receipt from which
170    /// the "this pass was blind" record can be stripped without breaking
171    /// verification is not a receipt. Attaching an observation therefore
172    /// mints a new id, and a tampered-with one fails
173    /// [`Bundle::verify`] exactly like any other field.
174    pub fn with_observation(
175        mut self,
176        observation: magma_types::Observation,
177    ) -> Result<Self, BundleError> {
178        self.observation = Some(observation);
179        self.bundle_id = Self::derive_id(
180            &self.kind,
181            &self.workspace,
182            &self.plan,
183            &self.outcome,
184            &self.drift,
185            &self.lifecycle,
186            &self.audit,
187            self.gem_tree_attestation.as_deref(),
188            self.observation.as_ref(),
189        )?;
190        Ok(self)
191    }
192
193    /// The honest answer to "how much of this bundle is real?".
194    ///
195    /// `None` means the assembler never recorded one — an absence, never
196    /// a clean bill of health. Callers deciding whether a bundle is
197    /// evidence of convergence must treat `None` and
198    /// `Some(_)`-with-blind-coverage the same way.
199    #[must_use]
200    pub fn observation(&self) -> Option<&magma_types::Observation> {
201        self.observation.as_ref()
202    }
203
204    /// Re-derive `bundle_id` from the canonical projection. The
205    /// optional `gem_tree_attestation` is included in the projection
206    /// so identical reconciles against different gem closures hash
207    /// to different bundle_ids (catches gem-closure drift).
208    ///
209    /// `observation` is included the same way, and for the sharper
210    /// reason: two reconciles with an identical plan, outcome, drift and
211    /// lifecycle are NOT the same event when one of them read reality and
212    /// the other could not. It is added to the projection only when
213    /// present, so every bundle stored before this field existed still
214    /// verifies byte-for-byte — an upgrade must not manufacture tamper
215    /// alarms.
216    pub fn derive_id(
217        kind: &str,
218        workspace: &str,
219        plan: &Plan,
220        outcome: &Option<Outcome>,
221        drift: &DriftReport,
222        lifecycle: &LifecycleState,
223        audit: &[Event],
224        gem_tree_attestation: Option<&str>,
225        observation: Option<&magma_types::Observation>,
226    ) -> Result<String, BundleError> {
227        // Plan and Outcome carry timestamps that vary across runs.
228        // We project the plan via its (stable) id + canonical
229        // change shape, NOT the chrono `created_at`. Same for
230        // Outcome (use plan_id + applied/failed counts).
231        let mut canonical = serde_json::json!({
232            "kind":      kind,
233            "workspace": workspace,
234            "plan_id":   plan.id,
235            "plan_changes": plan.changes,
236            "outcome":   outcome.as_ref().map(|o| serde_json::json!({
237                "plan_id": o.plan_id,
238                "applied": o.applied,
239                "failed":  o.failed,
240            })),
241            "drift": serde_json::json!({
242                "plan_id":  drift.plan_id,
243                "summary":  drift.summary,
244                "events":   drift.events.iter().map(|e| serde_json::json!({
245                    "kind":        e.kind,
246                    "address":     e.address,
247                    "action":      e.action,
248                    "severity":    e.severity,
249                    "decision":    e.decision,
250                    "fingerprint": e.fingerprint,
251                })).collect::<Vec<_>>(),
252            }),
253            "lifecycle": serde_json::json!({
254                "current": lifecycle.current,
255                "history": lifecycle.history.iter().map(|t| serde_json::json!({
256                    "from":    t.from,
257                    "to":      t.to,
258                    "plan_id": t.plan_id,
259                    "reason":  t.reason,
260                })).collect::<Vec<_>>(),
261            }),
262            "audit": audit.iter().map(|e| serde_json::json!({
263                "seq":       e.seq,
264                "payload":   e.payload,
265                "prev_hash": e.prev_hash,
266                "hash":      e.hash,
267            })).collect::<Vec<_>>(),
268            "gem_tree_attestation": gem_tree_attestation,
269        });
270        // Inserted only when present: a bundle that never carried an
271        // observation must project EXACTLY the bytes it did before this
272        // field existed, or every stored receipt fails verification on
273        // upgrade. `json!({"observation": None::<T>})` would emit a
274        // `null` key and break precisely that.
275        if let Some(observation) = observation {
276            if let Some(map) = canonical.as_object_mut() {
277                map.insert(
278                    "observation".to_string(),
279                    serde_json::to_value(observation)?,
280                );
281            }
282        }
283        let bytes = serde_json::to_vec(&canonical)?;
284        Ok(hex::encode(blake3::hash(&bytes).as_bytes()))
285    }
286
287    /// Verify the bundle's stored `bundle_id` matches a freshly-
288    /// computed one. Use after deserialization to catch tampering.
289    pub fn verify(&self) -> Result<(), BundleError> {
290        let recomputed = Self::derive_id(
291            &self.kind,
292            &self.workspace,
293            &self.plan,
294            &self.outcome,
295            &self.drift,
296            &self.lifecycle,
297            &self.audit,
298            self.gem_tree_attestation.as_deref(),
299            self.observation.as_ref(),
300        )?;
301        if recomputed != self.bundle_id {
302            return Err(BundleError::IdMismatch {
303                have: self.bundle_id.clone(),
304                recomputed,
305            });
306        }
307        Ok(())
308    }
309
310    /// The plan_id the bundle is keyed at (convenience accessor).
311    pub fn plan_id(&self) -> &PlanId {
312        &self.plan.id
313    }
314
315    /// Convenience: how many changes the bundle's plan carried.
316    pub fn change_count(&self) -> usize {
317        self.plan.change_count()
318    }
319
320    /// True iff the bundle reflects a successful end-to-end apply.
321    pub fn fully_succeeded(&self) -> bool {
322        match &self.outcome {
323            Some(o) => o.fully_succeeded() && self.lifecycle.current == magma_fsm::Phase::Stable,
324            None => false,
325        }
326    }
327
328    /// Serialize to a single JSON value. Suitable for storage in
329    /// any blob store (S3, Postgres jsonb, K8s ConfigMap).
330    pub fn to_json(&self) -> Result<serde_json::Value, BundleError> {
331        Ok(serde_json::to_value(self)?)
332    }
333
334    /// Deserialize + verify. The "import this bundle" path.
335    pub fn from_json_verified(value: serde_json::Value) -> Result<Self, BundleError> {
336        let bundle: Bundle = serde_json::from_value(value)?;
337        bundle.verify()?;
338        Ok(bundle)
339    }
340}
341
342// ── Tests ──────────────────────────────────────────────────────────
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347    use magma_converge::{Action, ChangeSeverity, Outcome, change};
348    use magma_drift::{DriftPolicy, classify};
349    use magma_fsm::{LifecycleState, Phase};
350    use magma_stream::{Event, EventPayload};
351    use serde_json::json;
352
353    fn sample_plan() -> Plan {
354        Plan::new(
355            "terraform",
356            vec![change(
357                "aws_vpc.net",
358                Action::Create,
359                None,
360                Some(json!({"cidr": "10.0.0.0/16"})),
361            )],
362        )
363    }
364
365    fn sample_outcome(plan: &Plan) -> Outcome {
366        Outcome {
367            plan_id: plan.id.clone(),
368            kind: plan.kind.clone(),
369            applied: vec![magma_converge::AppliedChange {
370                address: "aws_vpc.net".into(),
371                action: Action::Create,
372            }],
373            failed: vec![],
374            started_at: Utc::now(),
375            finished_at: Utc::now(),
376        }
377    }
378
379    fn sample_lifecycle(plan_id: &PlanId) -> LifecycleState {
380        let mut l = LifecycleState::new();
381        l.transition(Phase::Planning, Some(plan_id.clone()), "trigger")
382            .unwrap();
383        l.transition(Phase::Applying, Some(plan_id.clone()), "auto")
384            .unwrap();
385        l.transition(Phase::Verifying, Some(plan_id.clone()), "applied")
386            .unwrap();
387        l.transition(Phase::Stable, Some(plan_id.clone()), "verified")
388            .unwrap();
389        l
390    }
391
392    fn sample_audit() -> Vec<Event> {
393        // Two events with a valid hash chain (built directly).
394        let e0 = Event::new(
395            0,
396            EventPayload::Custom {
397                category: "test".into(),
398                message: "a".into(),
399            },
400            "0".repeat(64),
401        );
402        let e1 = Event::new(
403            1,
404            EventPayload::Custom {
405                category: "test".into(),
406                message: "b".into(),
407            },
408            e0.hash.clone(),
409        );
410        vec![e0, e1]
411    }
412
413    #[test]
414    fn build_and_verify_round_trip() {
415        let plan = sample_plan();
416        let outcome = sample_outcome(&plan);
417        let drift = classify(&plan, &DriftPolicy::conservative_default());
418        let lifecycle = sample_lifecycle(&plan.id);
419        let audit = sample_audit();
420
421        let bundle = Bundle::new(
422            "terraform",
423            "ws-1",
424            plan,
425            Some(outcome),
426            drift,
427            lifecycle,
428            audit,
429        )
430        .unwrap();
431        // bundle_id is 64-char hex.
432        assert_eq!(bundle.bundle_id.len(), 64);
433        // Verify passes immediately.
434        bundle.verify().unwrap();
435    }
436
437    #[test]
438    fn bundle_id_deterministic_across_calls() {
439        // Two bundles built from the same artifacts (different
440        // built_at timestamps) hash equally.
441        let plan = sample_plan();
442        let outcome = sample_outcome(&plan);
443        let drift = classify(&plan, &DriftPolicy::conservative_default());
444        let lifecycle = sample_lifecycle(&plan.id);
445        let audit = sample_audit();
446
447        let id1 = Bundle::derive_id(
448            "terraform",
449            "ws-1",
450            &plan,
451            &Some(outcome.clone()),
452            &drift,
453            &lifecycle,
454            &audit,
455            None,
456            None,
457        )
458        .unwrap();
459        let id2 = Bundle::derive_id(
460            "terraform",
461            "ws-1",
462            &plan,
463            &Some(outcome),
464            &drift,
465            &lifecycle,
466            &audit,
467            None,
468            None,
469        )
470        .unwrap();
471        assert_eq!(id1, id2);
472    }
473
474    #[test]
475    fn bundle_id_changes_when_gem_tree_attestation_differs() {
476        // Two bundles with identical reconcile inputs but different
477        // gem-tree closures must hash differently. Catches the
478        // "same Plan ran against a drifted gem tree" case.
479        let plan = sample_plan();
480        let outcome = sample_outcome(&plan);
481        let drift = classify(&plan, &DriftPolicy::conservative_default());
482        let lifecycle = sample_lifecycle(&plan.id);
483        let audit = sample_audit();
484        let id_a = Bundle::derive_id(
485            "terraform",
486            "ws-1",
487            &plan,
488            &Some(outcome.clone()),
489            &drift,
490            &lifecycle,
491            &audit,
492            Some("a".repeat(64).as_str()),
493            None,
494        )
495        .unwrap();
496        let id_b = Bundle::derive_id(
497            "terraform",
498            "ws-1",
499            &plan,
500            &Some(outcome),
501            &drift,
502            &lifecycle,
503            &audit,
504            Some("b".repeat(64).as_str()),
505            None,
506        )
507        .unwrap();
508        assert_ne!(id_a, id_b);
509    }
510
511    #[test]
512    fn bundle_id_distinguishes_a_blind_reconcile_from_a_clean_one() {
513        // The receipt-layer half of the bug. Same plan, same outcome, same
514        // drift, same lifecycle — one read reality, one could not. If
515        // these hashed equally the receipt would be attesting to a fact it
516        // does not have.
517        use magma_types::{Observation, RefreshCounts};
518        let plan = sample_plan();
519        let outcome = sample_outcome(&plan);
520        let drift = classify(&plan, &DriftPolicy::conservative_default());
521        let lifecycle = sample_lifecycle(&plan.id);
522        let audit = sample_audit();
523
524        let clean = Observation::of(RefreshCounts {
525            refreshed: 9,
526            ..RefreshCounts::default()
527        });
528        let blind = Observation::of(RefreshCounts {
529            kept_on_error: 9,
530            ..RefreshCounts::default()
531        });
532        assert_eq!(clean.coverage(), magma_types::Coverage::Complete);
533        assert_eq!(blind.coverage(), magma_types::Coverage::Blind);
534
535        let mk = |obs| {
536            Bundle::new(
537                "terraform",
538                "ws-1",
539                plan.clone(),
540                Some(outcome.clone()),
541                drift.clone(),
542                lifecycle.clone(),
543                audit.clone(),
544            )
545            .unwrap()
546            .with_observation(obs)
547            .unwrap()
548        };
549        let a = mk(clean);
550        let b = mk(blind);
551        assert_ne!(a.bundle_id, b.bundle_id);
552        a.verify().unwrap();
553        b.verify().unwrap();
554    }
555
556    #[test]
557    fn stripping_the_observation_breaks_verification() {
558        // A receipt from which "this pass was blind" can be removed
559        // without consequence is not a receipt.
560        use magma_types::{Observation, RefreshCounts};
561        let plan = sample_plan();
562        let drift = classify(&plan, &DriftPolicy::conservative_default());
563        let lifecycle = sample_lifecycle(&plan.id);
564        let mut bundle = Bundle::new(
565            "terraform",
566            "ws-1",
567            plan,
568            None,
569            drift,
570            lifecycle,
571            sample_audit(),
572        )
573        .unwrap()
574        .with_observation(Observation::of(RefreshCounts {
575            kept_on_error: 4,
576            ..RefreshCounts::default()
577        }))
578        .unwrap();
579        bundle.verify().unwrap();
580        bundle.observation = None;
581        match bundle.verify() {
582            Err(BundleError::IdMismatch { .. }) => {}
583            other => panic!("expected IdMismatch, got {other:?}"),
584        }
585    }
586
587    #[test]
588    fn a_bundle_without_an_observation_hashes_exactly_as_it_did_before() {
589        // Back-compat forcing function. This reproduces the canonical
590        // projection AS IT WAS before `observation` existed; if a future
591        // edit changes the projection for observation-less bundles, every
592        // already-stored receipt would start failing verification and this
593        // test is the thing that screams first.
594        let plan = sample_plan();
595        let outcome = sample_outcome(&plan);
596        let drift = classify(&plan, &DriftPolicy::conservative_default());
597        let lifecycle = sample_lifecycle(&plan.id);
598        let audit = sample_audit();
599
600        let historical = serde_json::json!({
601            "kind":      "terraform",
602            "workspace": "ws-1",
603            "plan_id":   plan.id,
604            "plan_changes": plan.changes,
605            "outcome":   serde_json::json!({
606                "plan_id": outcome.plan_id,
607                "applied": outcome.applied,
608                "failed":  outcome.failed,
609            }),
610            "drift": serde_json::json!({
611                "plan_id":  drift.plan_id,
612                "summary":  drift.summary,
613                "events":   drift.events.iter().map(|e| serde_json::json!({
614                    "kind":        e.kind,
615                    "address":     e.address,
616                    "action":      e.action,
617                    "severity":    e.severity,
618                    "decision":    e.decision,
619                    "fingerprint": e.fingerprint,
620                })).collect::<Vec<_>>(),
621            }),
622            "lifecycle": serde_json::json!({
623                "current": lifecycle.current,
624                "history": lifecycle.history.iter().map(|t| serde_json::json!({
625                    "from":    t.from,
626                    "to":      t.to,
627                    "plan_id": t.plan_id,
628                    "reason":  t.reason,
629                })).collect::<Vec<_>>(),
630            }),
631            "audit": audit.iter().map(|e| serde_json::json!({
632                "seq":       e.seq,
633                "payload":   e.payload,
634                "prev_hash": e.prev_hash,
635                "hash":      e.hash,
636            })).collect::<Vec<_>>(),
637            "gem_tree_attestation": None::<&str>,
638        });
639        let expected =
640            hex::encode(blake3::hash(&serde_json::to_vec(&historical).unwrap()).as_bytes());
641        let actual = Bundle::derive_id(
642            "terraform",
643            "ws-1",
644            &plan,
645            &Some(outcome),
646            &drift,
647            &lifecycle,
648            &audit,
649            None,
650            None,
651        )
652        .unwrap();
653        assert_eq!(
654            actual, expected,
655            "an observation-less bundle must project the pre-observation bytes",
656        );
657    }
658
659    #[test]
660    fn gem_tree_attestation_round_trips_through_serde() {
661        // The optional field round-trips through serde JSON
662        // serialization without disturbing the bundle_id.
663        let plan = sample_plan();
664        let outcome = sample_outcome(&plan);
665        let drift = classify(&plan, &DriftPolicy::conservative_default());
666        let lifecycle = sample_lifecycle(&plan.id);
667        let audit = sample_audit();
668        let bundle = Bundle::new_with_gem_tree(
669            "terraform",
670            "ws-1",
671            plan,
672            Some(outcome),
673            drift,
674            lifecycle,
675            audit,
676            Some("c".repeat(64)),
677        )
678        .unwrap();
679        let v = bundle.to_json().unwrap();
680        let back = Bundle::from_json_verified(v).unwrap();
681        assert_eq!(
682            back.gem_tree_attestation.as_deref(),
683            Some("c".repeat(64).as_str())
684        );
685        assert_eq!(back.bundle_id, bundle.bundle_id);
686    }
687
688    #[test]
689    fn json_round_trip_verified() {
690        let plan = sample_plan();
691        let drift = classify(&plan, &DriftPolicy::conservative_default());
692        let lifecycle = sample_lifecycle(&plan.id);
693        let audit = sample_audit();
694        let outcome = sample_outcome(&plan);
695        let bundle = Bundle::new(
696            "terraform",
697            "ws-1",
698            plan,
699            Some(outcome),
700            drift,
701            lifecycle,
702            audit,
703        )
704        .unwrap();
705
706        let json_value = bundle.to_json().unwrap();
707        let restored = Bundle::from_json_verified(json_value).unwrap();
708        assert_eq!(restored.bundle_id, bundle.bundle_id);
709        assert_eq!(restored.workspace, "ws-1");
710    }
711
712    #[test]
713    fn tampered_workspace_fails_verify() {
714        let plan = sample_plan();
715        let drift = classify(&plan, &DriftPolicy::conservative_default());
716        let lifecycle = sample_lifecycle(&plan.id);
717        let audit = sample_audit();
718        let outcome = sample_outcome(&plan);
719        let mut bundle = Bundle::new(
720            "terraform",
721            "ws-1",
722            plan,
723            Some(outcome),
724            drift,
725            lifecycle,
726            audit,
727        )
728        .unwrap();
729        // Tamper with the workspace after build.
730        bundle.workspace = "ws-evil".into();
731        match bundle.verify() {
732            Err(BundleError::IdMismatch { .. }) => {}
733            other => panic!("expected IdMismatch, got {other:?}"),
734        }
735    }
736
737    #[test]
738    fn fully_succeeded_requires_stable_and_no_apply_failures() {
739        let plan = sample_plan();
740        let drift = classify(&plan, &DriftPolicy::conservative_default());
741        let lifecycle = sample_lifecycle(&plan.id); // Stable
742        let outcome = sample_outcome(&plan);
743        let audit = sample_audit();
744        let bundle = Bundle::new(
745            "terraform",
746            "ws-1",
747            plan,
748            Some(outcome),
749            drift,
750            lifecycle,
751            audit,
752        )
753        .unwrap();
754        assert!(bundle.fully_succeeded());
755    }
756
757    #[test]
758    fn not_fully_succeeded_when_lifecycle_not_stable() {
759        let plan = sample_plan();
760        let drift = classify(&plan, &DriftPolicy::conservative_default());
761        let mut lifecycle = LifecycleState::new();
762        lifecycle
763            .transition(Phase::Planning, Some(plan.id.clone()), "x")
764            .unwrap();
765        // Stops at Planning — not Stable.
766        let outcome = sample_outcome(&plan);
767        let audit = sample_audit();
768        let bundle = Bundle::new(
769            "terraform",
770            "ws-1",
771            plan,
772            Some(outcome),
773            drift,
774            lifecycle,
775            audit,
776        )
777        .unwrap();
778        assert!(!bundle.fully_succeeded());
779    }
780
781    #[test]
782    fn not_fully_succeeded_when_no_outcome() {
783        let plan = sample_plan();
784        let drift = classify(&plan, &DriftPolicy::conservative_default());
785        let lifecycle = sample_lifecycle(&plan.id);
786        let audit = sample_audit();
787        let bundle = Bundle::new("terraform", "ws-1", plan, None, drift, lifecycle, audit).unwrap();
788        assert!(!bundle.fully_succeeded());
789    }
790
791    #[test]
792    fn empty_audit_still_bundles() {
793        let plan = sample_plan();
794        let drift = classify(&plan, &DriftPolicy::conservative_default());
795        let lifecycle = sample_lifecycle(&plan.id);
796        let outcome = sample_outcome(&plan);
797        let bundle = Bundle::new(
798            "terraform",
799            "ws-1",
800            plan,
801            Some(outcome),
802            drift,
803            lifecycle,
804            vec![],
805        )
806        .unwrap();
807        bundle.verify().unwrap();
808    }
809}