1#![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#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct Bundle {
47 pub bundle_id: String,
50 pub built_at: DateTime<Utc>,
53 pub kind: String,
55 pub workspace: String,
58 pub plan: Plan,
60 pub outcome: Option<Outcome>,
63 pub drift: DriftReport,
65 pub lifecycle: LifecycleState,
67 pub audit: Vec<Event>,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub gem_tree_attestation: Option<String>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
102 pub observation: Option<magma_types::Observation>,
103}
104
105impl Bundle {
106 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 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 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 #[must_use]
200 pub fn observation(&self) -> Option<&magma_types::Observation> {
201 self.observation.as_ref()
202 }
203
204 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 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 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 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 pub fn plan_id(&self) -> &PlanId {
312 &self.plan.id
313 }
314
315 pub fn change_count(&self) -> usize {
317 self.plan.change_count()
318 }
319
320 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 pub fn to_json(&self) -> Result<serde_json::Value, BundleError> {
331 Ok(serde_json::to_value(self)?)
332 }
333
334 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#[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 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 assert_eq!(bundle.bundle_id.len(), 64);
433 bundle.verify().unwrap();
435 }
436
437 #[test]
438 fn bundle_id_deterministic_across_calls() {
439 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 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 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 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 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 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 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); 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 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}