cloudformation-validate-diagnostics 1.9.0-beta

AWS CloudFormation Validate
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
use crate::filter::Filterable;
use crate::metrics::PhaseMetric;
use crate::phase::Phase;
use rules::{RuleOrigin, Severity};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use template_model::{EntityType, JsonValue, SourceSpan};

fn serialize_sorted_optional_map<S, V>(map: &Option<HashMap<String, V>>, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
    V: Serialize,
{
    match map {
        Some(m) => {
            let sorted: BTreeMap<&String, &V> = m.iter().collect();
            sorted.serialize(serializer)
        }
        None => serializer.serialize_none(),
    }
}

/// The template resource a diagnostic is attributed to, when it targets one.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct ResourceRef {
    /// Logical ID of the resource as declared in the template.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub resource_type: Option<String>,
}

/// The named template entity a diagnostic is attributed to, when it targets
/// one. The entity type is the singular form of the top-level template
/// section the entity is declared in.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct Entity {
    /// Logical ID of the entity as declared in the template.
    pub logical_id: String,
    pub entity_type: EntityType,
    /// CloudFormation resource type, when the entity is a resource whose type
    /// is known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub resource_type: Option<String>,
}

impl Entity {
    /// An entity for a template resource. An empty logical ID yields `None` so
    /// callers can pass through an ID that may be blank.
    pub fn resource(logical_id: impl Into<String>, resource_type: Option<String>) -> Option<Entity> {
        let logical_id = logical_id.into();
        if logical_id.is_empty() {
            return None;
        }
        Some(Entity { logical_id, entity_type: EntityType::Resource, resource_type })
    }
}

/// Extra detail about a specific violation, present only in the detailed report.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct ViolationContext {
    /// The resolved property value that triggered the violation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "wasm-bindings", tsify(type = "JsonValue"))]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub actual_value: Option<JsonValue>,
    /// The constraint the value was expected to satisfy (such as the required type or allowed pattern).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub expected_constraint: Option<String>,
    /// Name of the offending property.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub property: Option<String>,
    /// Lifecycle marker for the flagged resource type or property, such as 'deprecated', 'create-only', or 'write-only'.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub lifecycle: Option<String>,
    /// How the offending value was derived, such as a Ref, Fn::GetAtt, Fn::If, or parameter.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub resolution_source: Option<String>,
    /// Additional finding-specific values keyed by name.
    #[serde(default, skip_serializing_if = "Option::is_none", serialize_with = "serialize_sorted_optional_map")]
    #[cfg_attr(feature = "wasm-bindings", tsify(type = "Record<string, JsonValue>"))]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub extra: Option<HashMap<String, JsonValue>>,
}

/// Another resource involved in the diagnostic, such as the target of a reference.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct RelatedResource {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub resource: Option<ResourceRef>,
    /// Source location of the related resource.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
    pub location: Option<SourceSpan>,
    pub message: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Diagnostic {
    pub rule_id: String,
    pub severity: Severity,
    pub message: String,
    pub source: RuleOrigin,
    /// The named template entity this finding targets, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entity: Option<Entity>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub property_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub suggested_fix: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub documentation_url: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub location: Option<SourceSpan>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub related_resources: Option<Vec<RelatedResource>>,
    #[serde(default, skip_serializing_if = "Option::is_none", serialize_with = "serialize_sorted_optional_map")]
    pub condition_scenario: Option<HashMap<String, bool>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rule_description: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub phase: Option<Phase>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context: Option<ViolationContext>,
}

impl Diagnostic {
    /// Logical ID of the targeted entity when it is a resource, `None` otherwise.
    pub fn resource_logical_id(&self) -> Option<&str> {
        self.entity.as_ref().filter(|e| e.entity_type == EntityType::Resource).map(|e| e.logical_id.as_str())
    }
}

impl Filterable for Diagnostic {
    fn rule_id(&self) -> &str {
        &self.rule_id
    }
    fn category(&self) -> Option<&str> {
        self.category.as_deref()
    }
    fn resource_id(&self) -> Option<&str> {
        self.resource_logical_id()
    }
    fn resource_type(&self) -> Option<&str> {
        self.entity.as_ref().and_then(|e| e.resource_type.as_deref())
    }
    fn logical_id(&self) -> Option<&str> {
        self.entity.as_ref().map(|e| e.logical_id.as_str())
    }
    fn entity_type(&self) -> Option<EntityType> {
        self.entity.as_ref().map(|e| e.entity_type)
    }
}

/// Generates a report diagnostic struct that carries the targeted entity as a
/// nested `entity` struct and inlines `location` into individual line/column
/// fields. Used by `StandardDiagnostic` and `DetailedDiagnostic`.
macro_rules! define_flattened_diagnostic {
    ($(#[$struct_meta:meta])* $name:ident $(, $(#[$extra_meta:meta])* $extra_field:ident : $extra_ty:ty)*) => {
        $(#[$struct_meta])*
        #[derive(Debug, Clone, Serialize, Deserialize)]
        #[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
        #[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
        #[serde(rename_all = "camelCase")]
        pub struct $name {
            /// Identifier of the rule that produced this finding; its leading letter encodes the severity.
            pub rule_id: String,
            pub severity: Severity,
            pub message: String,
            /// Where the rule came from, such as a provider schema, the built-in engine, or a user-supplied rule.
            pub source: RuleOrigin,
            /// The named template entity this finding targets - a resource, parameter, output, mapping, condition, or template rule - if any.
            #[serde(default, skip_serializing_if = "Option::is_none")]
            #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
            pub entity: Option<Entity>,
            /// Path to the offending property within the resource, such as 'Properties.Name'.
            #[serde(default, skip_serializing_if = "Option::is_none")]
            #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
            pub property_path: Option<String>,
            #[serde(default, skip_serializing_if = "Option::is_none")]
            #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
            pub suggested_fix: Option<String>,
            #[serde(default, skip_serializing_if = "Option::is_none")]
            #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
            pub category: Option<String>,
            /// Line in the source template where the finding begins (1-based).
            #[serde(default, skip_serializing_if = "Option::is_none")]
            #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
            pub start_line: Option<u32>,
            #[serde(default, skip_serializing_if = "Option::is_none")]
            #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
            pub start_column: Option<u32>,
            #[serde(default, skip_serializing_if = "Option::is_none")]
            #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
            pub end_line: Option<u32>,
            #[serde(default, skip_serializing_if = "Option::is_none")]
            #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
            pub end_column: Option<u32>,
            #[serde(default, skip_serializing_if = "Option::is_none")]
            #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
            pub related_resources: Option<Vec<RelatedResource>>,
            /// Condition name to boolean assignment under which this finding applies, when it depends on template conditions.
            #[serde(default, skip_serializing_if = "Option::is_none", serialize_with = "serialize_sorted_optional_map")]
            #[cfg_attr(feature = "wasm-bindings", tsify(type = "Record<string, boolean>"))]
            #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
            pub condition_scenario: Option<HashMap<String, bool>>,
            $(
                $(#[$extra_meta])*
                #[serde(default, skip_serializing_if = "Option::is_none")]
                #[cfg_attr(feature = "uniffi-bindings", uniffi(default))]
                pub $extra_field: $extra_ty,
            )*
        }
    };
}

define_flattened_diagnostic!(
    /// A single validation finding with its source location flattened into individual fields.
    StandardDiagnostic
);
define_flattened_diagnostic!(
    /// A validation finding with additional context and enrichment beyond the standard finding.
    DetailedDiagnostic,
    documentation_url: Option<String>,
    rule_description: Option<String>,
    phase: Option<Phase>,
    context: Option<ViolationContext>
);

/// Populates the shared fields of a report diagnostic from a `Diagnostic`.
macro_rules! flatten_diagnostic {
    ($self:expr $(, $extra_field:ident)* ) => {{
        let (start_line, start_column, end_line, end_column) = $self
            .location
            .map(|l| (Some(l.start_line), Some(l.start_column), Some(l.end_line), Some(l.end_column)))
            .unwrap_or((None, None, None, None));
        (
            $self.rule_id.clone(),
            $self.severity,
            $self.message.clone(),
            $self.entity.clone(),
            $self.property_path.clone(),
            $self.suggested_fix.clone(),
            $self.category.clone(),
            start_line,
            start_column,
            end_line,
            end_column,
            $self.related_resources.clone(),
            $self.condition_scenario.clone(),
            $self.source,
            $( $self.$extra_field.clone(), )*
        )
    }};
}

impl Diagnostic {
    pub fn to_standard(&self) -> StandardDiagnostic {
        let (
            rule_id,
            severity,
            message,
            entity,
            property_path,
            suggested_fix,
            category,
            start_line,
            start_column,
            end_line,
            end_column,
            related_resources,
            condition_scenario,
            source,
        ) = flatten_diagnostic!(self);
        StandardDiagnostic {
            rule_id,
            severity,
            message,
            entity,
            property_path,
            suggested_fix,
            category,
            start_line,
            start_column,
            end_line,
            end_column,
            related_resources,
            condition_scenario,
            source,
        }
    }

    pub fn to_detailed(&self) -> DetailedDiagnostic {
        let (
            rule_id,
            severity,
            message,
            entity,
            property_path,
            suggested_fix,
            category,
            start_line,
            start_column,
            end_line,
            end_column,
            related_resources,
            condition_scenario,
            source,
            documentation_url,
            rule_description,
            phase,
            context,
        ) = flatten_diagnostic!(self, documentation_url, rule_description, phase, context);
        DetailedDiagnostic {
            rule_id,
            severity,
            message,
            entity,
            property_path,
            suggested_fix,
            category,
            start_line,
            start_column,
            end_line,
            end_column,
            related_resources,
            condition_scenario,
            source,
            documentation_url,
            rule_description,
            phase,
            context,
        }
    }
}

/// Timing breakdown of the validation run, per pipeline phase.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct PerformanceMetrics {
    /// Time to load the provider schemas.
    pub schema_init: PhaseMetric,
    /// Time to initialize the rule evaluation engine.
    pub engine_init: PhaseMetric,
    /// Time to parse the template and build its model.
    pub model_build: PhaseMetric,
    pub schema_validate: PhaseMetric,
    pub rule_evaluation: PhaseMetric,
    /// Time spent enriching, filtering, sorting, and finalizing the diagnostics after rule evaluation.
    pub diagnostic_finalize: PhaseMetric,
    pub validate_total: PhaseMetric,
}

/// A single budget-exhaustion record in report metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct BudgetExhaustionRecord {
    /// Stable lower camelCase budget kind identifier.
    pub kind: String,
    /// Human-readable explanation of the exhausted budget.
    #[serde(default)]
    pub description: String,
    /// The numeric limit that was exhausted.
    pub limit: u64,
    /// Whether exhausting this budget makes the overall analysis incomplete.
    pub analysis_incomplete: bool,
}

fn budget_exhaustions_are_absent_or_empty(records: &Option<Vec<BudgetExhaustionRecord>>) -> bool {
    records.as_ref().is_none_or(Vec::is_empty)
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct ReportMetadata {
    /// Number of rules that were active for this run after any category exclusions.
    pub rules_evaluated: u32,
    /// Source-qualified cfn-lint version used to sync bundled derived data.
    pub cfn_lint_version: String,
    /// Source-qualified enhanced resource-schema version used for the bundled provider schemas.
    pub resource_schema_version: String,
    pub resources_scanned: u32,
    /// Tally of reported diagnostics by severity.
    pub counts: Summary,
    /// Number of diagnostics removed by filters and the severity threshold.
    pub suppressed: u32,
    /// Whether strict mode was enabled, promoting warnings to errors.
    pub strict: bool,
    /// Minimum severity included in the report; lower-severity findings are omitted.
    pub severity_level: Severity,
    /// Records of deterministic validation budgets exhausted during this run.
    /// Absent when no budget was exhausted.
    #[serde(default, skip_serializing_if = "budget_exhaustions_are_absent_or_empty")]
    pub budget_exhaustions: Option<Vec<BudgetExhaustionRecord>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct Summary {
    pub fatal: u32,
    pub errors: u32,
    pub warnings: u32,
    pub informational: u32,
    pub debug: u32,
}

/// Outcome of a validation run. `Ok` means validation completed without
/// correctness-affecting curtailment. `AnalysisIncomplete` means a deterministic
/// budget curtailed analysis in a way that could omit findings. `Error` means
/// the validation pipeline could not run, such as when parsing fails.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Enum))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReportStatus {
    Ok,
    AnalysisIncomplete,
    Error,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[must_use]
pub struct ValidationReport {
    pub file_path: String,
    pub status: ReportStatus,
    pub version: String,
    pub metadata: ReportMetadata,
    pub performance: PerformanceMetrics,
    pub diagnostics: Vec<Diagnostic>,
}

impl ValidationReport {
    pub fn to_standard(&self) -> StandardReport {
        StandardReport {
            file_path: self.file_path.clone(),
            status: self.status,
            version: self.version.clone(),
            diagnostics: self.diagnostics.iter().map(|d| d.to_standard()).collect(),
            metadata: self.metadata.clone(),
            performance: self.performance.clone(),
        }
    }

    pub fn to_detailed(&self) -> DetailedReport {
        DetailedReport {
            file_path: self.file_path.clone(),
            status: self.status,
            version: self.version.clone(),
            diagnostics: self.diagnostics.iter().map(|d| d.to_detailed()).collect(),
            metadata: self.metadata.clone(),
            performance: self.performance.clone(),
        }
    }
}

/// Standard validation result: the report plus flattened diagnostics.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct StandardReport {
    pub file_path: String,
    pub status: ReportStatus,
    pub version: String,
    pub metadata: ReportMetadata,
    pub performance: PerformanceMetrics,
    pub diagnostics: Vec<StandardDiagnostic>,
}

/// Detailed validation result: like the standard report but with per-diagnostic context and enrichment.
#[derive(Debug, Clone, Serialize)]
#[cfg_attr(feature = "wasm-bindings", derive(tsify::Tsify))]
#[cfg_attr(feature = "uniffi-bindings", derive(uniffi::Record))]
#[serde(rename_all = "camelCase")]
pub struct DetailedReport {
    pub file_path: String,
    pub status: ReportStatus,
    pub version: String,
    pub metadata: ReportMetadata,
    pub performance: PerformanceMetrics,
    pub diagnostics: Vec<DetailedDiagnostic>,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_diagnostic() -> Diagnostic {
        Diagnostic {
            rule_id: "E3012".into(),
            severity: Severity::Error,
            message: "Property not allowed".into(),
            entity: Entity::resource("MyBucket", Some("AWS::S3::Bucket".into())),
            property_path: Some("/Resources/MyBucket/Properties/Foo".into()),
            suggested_fix: Some("Remove the property".into()),
            documentation_url: Some("https://example.com/E3012".into()),
            category: Some("schema".into()),
            location: Some(SourceSpan { start_line: 10, start_column: 5, end_line: 10, end_column: 20 }),
            related_resources: Some(vec![RelatedResource {
                resource: Some(ResourceRef {
                    id: Some("OtherResource".into()),
                    resource_type: Some("AWS::EC2::Instance".into()),
                }),
                location: Some(SourceSpan { start_line: 20, start_column: 1, end_line: 20, end_column: 30 }),
                message: "Referenced here".into(),
            }]),
            condition_scenario: Some(HashMap::from([("IsProduction".into(), true)])),
            rule_description: Some("Disallows extra properties".into()),
            phase: Some(Phase::Schema),
            context: Some(ViolationContext {
                actual_value: Some(JsonValue::from(serde_json::json!("bad"))),
                expected_constraint: Some("Must not exist".into()),
                property: Some("Foo".into()),
                lifecycle: None,
                resolution_source: None,
                extra: None,
            }),
            source: RuleOrigin::CfnLint,
        }
    }

    fn minimal_diagnostic() -> Diagnostic {
        Diagnostic {
            rule_id: String::new(),
            severity: Severity::Info,
            message: String::new(),
            entity: None,
            property_path: None,
            suggested_fix: None,
            documentation_url: None,
            category: None,
            location: None,
            related_resources: None,
            condition_scenario: None,
            rule_description: None,
            phase: None,
            context: None,
            source: RuleOrigin::Engine,
        }
    }

    #[test]
    fn to_standard_carries_entity_and_flattens_location_fields() {
        let d = sample_diagnostic();
        let s = d.to_standard();

        assert_eq!(s.rule_id, "E3012");
        let entity = s.entity.as_ref().expect("entity should be present");
        assert_eq!(entity.logical_id, "MyBucket");
        assert_eq!(entity.entity_type, EntityType::Resource);
        assert_eq!(entity.resource_type.as_deref(), Some("AWS::S3::Bucket"));
        assert_eq!(s.start_line, Some(10));
        assert_eq!(s.start_column, Some(5));
        assert_eq!(s.end_line, Some(10));
        assert_eq!(s.end_column, Some(20));
        assert_eq!(s.message, "Property not allowed");
        assert_eq!(s.category.as_deref(), Some("schema"));
        assert_eq!(s.suggested_fix.as_deref(), Some("Remove the property"));
        assert_eq!(s.related_resources.as_ref().unwrap().len(), 1);
        assert_ne!(s.condition_scenario, None, "condition_scenario should be present");
    }

    #[test]
    fn to_full_includes_context_and_enrichment_fields() {
        let d = sample_diagnostic();
        let f = d.to_detailed();

        assert_eq!(f.rule_id, "E3012");
        assert_eq!(f.entity.as_ref().map(|e| e.logical_id.as_str()), Some("MyBucket"));
        assert!(f.context.is_some(), "full diagnostic should include context");
        let ctx = f.context.unwrap();
        assert_eq!(ctx.property.as_deref(), Some("Foo"));
        assert_eq!(ctx.expected_constraint.as_deref(), Some("Must not exist"));
        assert_eq!(f.phase, Some(Phase::Schema));
    }

    #[test]
    fn filterable_reads_identity_through_the_entity() {
        let d = sample_diagnostic();
        assert_eq!(d.rule_id(), "E3012");
        assert_eq!(d.category(), Some("schema"));
        assert_eq!(d.resource_id(), Some("MyBucket"));
        assert_eq!(d.resource_type(), Some("AWS::S3::Bucket"));
        assert_eq!(d.logical_id(), Some("MyBucket"));
    }

    #[test]
    fn filterable_resource_id_is_none_for_non_resource_entities() {
        let mut d = sample_diagnostic();
        d.entity =
            Some(Entity { logical_id: "MyParam".into(), entity_type: EntityType::Parameter, resource_type: None });
        assert_eq!(d.resource_id(), None, "a parameter is not a resource");
        assert_eq!(d.resource_type(), None);
        assert_eq!(d.logical_id(), Some("MyParam"));
    }

    #[test]
    fn entity_serializes_camel_case_with_pascal_case_type_and_omits_absent_resource_type() {
        let resource = Entity::resource("MyBucket", Some("AWS::S3::Bucket".into())).unwrap();
        let json = serde_json::to_string(&resource).unwrap();
        assert!(json.contains("\"logicalId\":\"MyBucket\""), "got: {json}");
        assert!(json.contains("\"entityType\":\"Resource\""), "got: {json}");
        assert!(json.contains("\"resourceType\":\"AWS::S3::Bucket\""), "got: {json}");

        let parameter =
            Entity { logical_id: "MyParam".into(), entity_type: EntityType::Parameter, resource_type: None };
        let json = serde_json::to_string(&parameter).unwrap();
        assert!(json.contains("\"entityType\":\"Parameter\""), "got: {json}");
        assert!(!json.contains("resourceType"), "absent resourceType must be omitted, got: {json}");
    }

    #[test]
    fn entity_resource_drops_empty_logical_id() {
        assert!(Entity::resource("", None).is_none(), "an empty logical ID must not create an entity");
    }

    #[test]
    fn diagnostic_serde_round_trips_all_fields() {
        let d = sample_diagnostic();
        let json = serde_json::to_string(&d).unwrap();
        let deserialized: Diagnostic = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.rule_id, d.rule_id);
        assert_eq!(deserialized.message, d.message);
        assert_eq!(deserialized.severity, d.severity);
        assert_eq!(deserialized.source, d.source);
        assert_eq!(deserialized.entity.as_ref().map(|e| e.logical_id.as_str()), Some("MyBucket"));
        assert_eq!(deserialized.location.as_ref().unwrap().start_line, d.location.as_ref().unwrap().start_line);
    }

    #[test]
    fn standard_diagnostic_uses_camel_case_and_excludes_context() {
        let d = sample_diagnostic();
        let s = d.to_standard();
        let json = serde_json::to_string(&s).unwrap();
        assert!(json.contains("ruleId"), "expected camelCase 'ruleId' in JSON");
        assert!(json.contains("startLine"), "expected 'startLine' in JSON");
        assert!(json.contains("\"entity\""), "expected nested 'entity' in JSON");
        assert!(json.contains("logicalId"), "expected 'logicalId' in JSON");
        assert!(json.contains("entityType"), "expected 'entityType' in JSON");
        assert!(json.contains("resourceType"), "expected 'resourceType' in JSON");
        assert!(json.contains("propertyPath"), "expected 'propertyPath' in JSON");
        assert!(!json.contains("\"context\""), "standard format should not include 'context'");
    }

    #[test]
    fn full_diagnostic_includes_context_in_serialization() {
        let d = sample_diagnostic();
        let f = d.to_detailed();
        let json = serde_json::to_string(&f).unwrap();
        assert!(json.contains("\"context\""), "full format should include 'context'");
        assert!(json.contains("actualValue"), "full format should include 'actualValue'");
        assert!(json.contains("expectedConstraint"), "full format should include 'expectedConstraint'");
    }

    #[test]
    fn none_fields_are_omitted_from_serialization() {
        let d = minimal_diagnostic();
        let json = serde_json::to_string(&d).unwrap();
        assert!(!json.contains("suggestedFix"), "None suggestedFix should be omitted");
        assert!(!json.contains("documentationUrl"), "None documentationUrl should be omitted");
        assert!(!json.contains("context"), "None context should be omitted");
        assert!(!json.contains("relatedResources"), "None relatedResources should be omitted");
        assert!(!json.contains("conditionScenario"), "None conditionScenario should be omitted");
        assert!(!json.contains("propertyPath"), "None propertyPath should be omitted");
        assert!(!json.contains("category"), "None category should be omitted");
    }

    #[test]
    fn report_metadata_serializes_all_required_fields() {
        let metadata = ReportMetadata {
            rules_evaluated: 0,
            cfn_lint_version: "https://github.com/aws-cloudformation/cfn-lint@1.54.0".to_string(),
            resource_schema_version:
                "https://github.com/aws-cloudformation/resource-provider-enhanced-schemas@2026-08-07T18:20:13Z"
                    .to_string(),
            resources_scanned: 0,
            counts: Summary { fatal: 0, errors: 0, warnings: 0, informational: 0, debug: 0 },
            suppressed: 0,
            strict: false,
            severity_level: Severity::Info,
            budget_exhaustions: None,
        };

        let json = serde_json::to_value(metadata).expect("metadata should serialize");
        assert_eq!(json["rulesEvaluated"], 0);
        assert_eq!(json["cfnLintVersion"], "https://github.com/aws-cloudformation/cfn-lint@1.54.0");
        assert_eq!(
            json["resourceSchemaVersion"],
            "https://github.com/aws-cloudformation/resource-provider-enhanced-schemas@2026-08-07T18:20:13Z"
        );
        assert!(json.get("budgetExhaustions").is_none());
    }

    #[test]
    fn budget_exhaustion_record_serializes_description() {
        let record = BudgetExhaustionRecord {
            kind: "resolverDepth".to_string(),
            description: "Resolving intrinsic functions exceeded the maximum supported nesting depth.".to_string(),
            limit: 64,
            analysis_incomplete: true,
        };

        let json = serde_json::to_value(record).expect("budget exhaustion record should serialize");
        assert_eq!(json["kind"], "resolverDepth");
        assert_eq!(json["description"], "Resolving intrinsic functions exceeded the maximum supported nesting depth.");
    }

    #[test]
    fn budget_exhaustion_record_accepts_legacy_input_without_description() {
        let record: BudgetExhaustionRecord = serde_json::from_value(serde_json::json!({
            "kind": "resolverDepth",
            "limit": 64,
            "analysisIncomplete": true
        }))
        .expect("legacy budget exhaustion record should deserialize");

        assert!(record.description.is_empty());
    }

    #[test]
    fn report_status_serializes_as_screaming_snake_case() {
        assert_eq!(serde_json::to_string(&ReportStatus::Ok).unwrap(), "\"OK\"");
        assert_eq!(serde_json::to_string(&ReportStatus::AnalysisIncomplete).unwrap(), "\"ANALYSIS_INCOMPLETE\"");
        assert_eq!(serde_json::to_string(&ReportStatus::Error).unwrap(), "\"ERROR\"");
    }

    #[test]
    fn report_metadata_rejects_missing_required_fields() {
        let complete = serde_json::json!({
            "rulesEvaluated": 0,
            "cfnLintVersion": "v",
            "resourceSchemaVersion": "v",
            "resourcesScanned": 0,
            "counts": {
                "fatal": 0,
                "errors": 0,
                "warnings": 0,
                "informational": 0,
                "debug": 0
            },
            "suppressed": 0,
            "strict": false,
            "severityLevel": "INFO"
        });

        for required_field in ["rulesEvaluated", "cfnLintVersion", "resourceSchemaVersion"] {
            let mut incomplete = complete.clone();
            incomplete.as_object_mut().unwrap().remove(required_field);
            let error = serde_json::from_value::<ReportMetadata>(incomplete).unwrap_err();
            assert!(
                error.to_string().contains(required_field),
                "missing field error must name {required_field}: {error}"
            );
        }
    }

    #[test]
    fn report_metadata_budget_exhaustions_defaults_to_none() {
        // Older reports without budget exhaustion metadata should still deserialize.
        let minimal = serde_json::json!({
            "rulesEvaluated": 0,
            "cfnLintVersion": "v",
            "resourceSchemaVersion": "v",
            "resourcesScanned": 0,
            "counts": {
                "fatal": 0,
                "errors": 0,
                "warnings": 0,
                "informational": 0,
                "debug": 0
            },
            "suppressed": 0,
            "strict": false,
            "severityLevel": "INFO"
        });
        let metadata: ReportMetadata = serde_json::from_value(minimal).unwrap();
        assert!(metadata.budget_exhaustions.is_none(), "missing metadata should deserialize to None");
    }
}