diff --git a/crates/cmtraceopen-parser/src/sccm/findings.rs b/crates/cmtraceopen-parser/src/sccm/findings.rs index d14a2afda..c38d16497 100644 --- a/crates/cmtraceopen-parser/src/sccm/findings.rs +++ b/crates/cmtraceopen-parser/src/sccm/findings.rs @@ -1,5 +1,6 @@ use std::cmp::Ordering; use std::collections::BTreeMap; +use std::slice; use serde::de::Error as _; use serde::ser::Error as _; @@ -16,7 +17,27 @@ use super::models::{ pub const MAX_SCCM_ARTIFACT_REQUEST_REASON_CHARS: usize = 240; pub const MAX_SCCM_NEXT_ARTIFACT_REQUESTS: usize = 16; -const MAX_SCCM_COVERAGE_GAP_ARTIFACT_ID_CHARS: usize = 256; +// Shared wire bound for every opaque identifier a finding carries: finding +// ids, evidence artifact and entry ids, coverage-gap artifact ids, request +// logical ids, and extraction profile ids. Enforced inside +// is_canonical_opaque_id so no identifier path can skip it. +const MAX_SCCM_OPAQUE_ID_CHARS: usize = 256; +// Single-line display heading; twice the opaque id bound covers generated +// " " headings without admitting unbounded text. +const MAX_SCCM_FINDING_TITLE_CHARS: usize = 512; +// Multi-sentence display paragraph shown in the finding detail pane. +const MAX_SCCM_FINDING_SUMMARY_CHARS: usize = 2048; +// Correlation-key raw and normalized values. The widest canonical form is a +// 253-character server-host FQDN; 256 leaves room for braces and prefixes +// while excluding unbounded decimal ids. +// Do not lower this. normalize_server_host self-caps a host at 253 chars, so +// a worst-case ServerHost key normalizes to 254 with a trailing-dot source +// against this 256 limit, roughly 99% of the bound and the tightest headroom +// any bound in this module carries. +// Shared with the extraction producer in keys.rs so extract_keys cannot emit a +// key this validator would reject. Crate-visible rather than public: it is an +// internal agreement between the producer and the validator, not wire surface. +pub(crate) const MAX_SCCM_CORRELATION_KEY_VALUE_CHARS: usize = 256; // Intentionally empty: no extraction profile is verified as stable enough to // authorize key-only High confidence. Adding one requires contract review. const REGISTERED_STABLE_CORRELATION_PROFILE_IDS: &[&str] = &[]; @@ -152,8 +173,7 @@ impl<'de> Deserialize<'de> for SccmTerminalEvidenceKind { } } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct SccmTerminalEvidence { pub reference: SccmEvidenceRef, pub kind: SccmTerminalEvidenceKind, @@ -168,22 +188,46 @@ impl SccmTerminalEvidence { } } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] +#[derive(Debug, Clone, PartialEq)] pub struct SccmFindingCoverageGap { pub artifact_id: String, pub role: SccmRole, pub coverage: SccmCoverageState, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] +#[derive(Debug, Clone, PartialEq)] pub struct SccmArtifactRequest { pub logical_id: String, pub role: SccmRole, pub reason: String, } +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct SccmArtifactRequestSerializeWire<'a> { + logical_id: &'a str, + role: &'a SccmRole, + reason: &'a str, +} + +impl Serialize for SccmArtifactRequest { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + validate_artifact_requests(slice::from_ref(self)).map_err(|error| { + S::Error::custom(format!("invalid SCCM artifact request contract: {error:?}")) + })?; + let reason = self.reason.trim(); + SccmArtifactRequestSerializeWire { + logical_id: &self.logical_id, + role: &self.role, + reason, + } + .serialize(serializer) + } +} + #[derive(Debug, Clone, PartialEq)] pub struct SccmFinding { pub finding_id: String, @@ -269,6 +313,35 @@ struct SccmFindingWire { next_artifacts: Vec, } +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct SccmEvidenceRefSerializeWire<'a> { + artifact_id: &'a str, + entry_id: &'a str, + line_start: Option, + line_end: Option, +} + +impl Serialize for SccmEvidenceRef { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + validate_evidence_reference(self).map_err(|error| { + S::Error::custom(format!( + "invalid SCCM evidence reference contract: {error:?}" + )) + })?; + SccmEvidenceRefSerializeWire { + artifact_id: &self.artifact_id, + entry_id: &self.entry_id, + line_start: self.line_start, + line_end: self.line_end, + } + .serialize(serializer) + } +} + #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct SccmEvidenceRefWire { @@ -289,6 +362,54 @@ impl From for SccmEvidenceRef { } } +// SccmEvidenceRef is declared in models.rs, but its wire contract belongs +// here next to the validator it must satisfy. Every reference the crate +// accepts, whether standalone or nested in SccmEvidence or an extraction gap, +// clears the same bar a finding's own citations clear. +impl<'de> Deserialize<'de> for SccmEvidenceRef { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let reference = Self::from(SccmEvidenceRefWire::deserialize(deserializer)?); + validate_evidence_reference(&reference).map_err(|error| { + D::Error::custom(format!( + "invalid SCCM evidence reference contract: {error:?}" + )) + })?; + Ok(reference) + } +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct SccmTerminalEvidenceSerializeWire<'a> { + reference: &'a SccmEvidenceRef, + kind: &'a SccmTerminalEvidenceKind, +} + +impl Serialize for SccmTerminalEvidence { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + validate_evidence_reference(&self.reference) + .and_then(|()| { + validate_terminal_evidence(slice::from_ref(&self.reference), slice::from_ref(self)) + }) + .map_err(|error| { + S::Error::custom(format!( + "invalid SCCM terminal evidence contract: {error:?}" + )) + })?; + SccmTerminalEvidenceSerializeWire { + reference: &self.reference, + kind: &self.kind, + } + .serialize(serializer) + } +} + #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct SccmTerminalEvidenceWire { @@ -305,6 +426,56 @@ impl From for SccmTerminalEvidence { } } +// A standalone terminal evidence has no surrounding finding to cite, so it +// stands as its own citation set. That trivially satisfies the "must be cited" +// rule while still enforcing the kind gate: only observedFailure is terminal. +impl<'de> Deserialize<'de> for SccmTerminalEvidence { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let terminal = Self::from(SccmTerminalEvidenceWire::deserialize(deserializer)?); + validate_evidence_reference(&terminal.reference) + .and_then(|()| { + validate_terminal_evidence( + slice::from_ref(&terminal.reference), + slice::from_ref(&terminal), + ) + }) + .map_err(|error| { + D::Error::custom(format!( + "invalid SCCM terminal evidence contract: {error:?}" + )) + })?; + Ok(terminal) + } +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct SccmFindingCoverageGapSerializeWire<'a> { + artifact_id: &'a str, + role: &'a SccmRole, + coverage: &'a SccmCoverageState, +} + +impl Serialize for SccmFindingCoverageGap { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + validate_coverage_gaps(slice::from_ref(self)).map_err(|error| { + S::Error::custom(format!("invalid SCCM coverage gap contract: {error:?}")) + })?; + SccmFindingCoverageGapSerializeWire { + artifact_id: &self.artifact_id, + role: &self.role, + coverage: &self.coverage, + } + .serialize(serializer) + } +} + #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct SccmFindingCoverageGapWire { @@ -323,6 +494,58 @@ impl From for SccmFindingCoverageGap { } } +// A coverage gap deserialized on its own must clear the same bar it clears +// as a member of SccmFinding::coverage_gaps, so route it through the same +// deny_unknown_fields wire struct and the same validator. +impl<'de> Deserialize<'de> for SccmFindingCoverageGap { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let gap = Self::from(SccmFindingCoverageGapWire::deserialize(deserializer)?); + validate_coverage_gaps(slice::from_ref(&gap)).map_err(|error| { + D::Error::custom(format!("invalid SCCM coverage gap contract: {error:?}")) + })?; + Ok(gap) + } +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct SccmCorrelationKeySerializeWire<'a> { + kind: &'a SccmCorrelationKeyKind, + raw: &'a str, + normalized: &'a str, + confidence: &'a SccmKeyConfidence, + extraction_profile_id: Option<&'a str>, + evidence: Option<&'a SccmEvidenceRef>, + start: Option, + end: Option, +} + +impl Serialize for SccmCorrelationKey { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + validate_correlation_key_evidence(self.evidence.as_slice(), slice::from_ref(self)) + .map_err(|error| { + S::Error::custom(format!("invalid SCCM correlation key contract: {error:?}")) + })?; + SccmCorrelationKeySerializeWire { + kind: &self.kind, + raw: &self.raw, + normalized: &self.normalized, + confidence: &self.confidence, + extraction_profile_id: self.extraction_profile_id.as_deref(), + evidence: self.evidence.as_ref(), + start: self.start, + end: self.end, + } + .serialize(serializer) + } +} + #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct SccmCorrelationKeyWire { @@ -351,6 +574,28 @@ impl From for SccmCorrelationKey { } } +// The key's own evidence reference stands in as its citation set, exactly as +// it would inside a finding. Containment is therefore self-satisfying here, so +// validate_correlation_key_evidence validates the reference itself before it +// checks containment; the wire struct nests SccmEvidenceRefWire and cannot +// rely on the SccmEvidenceRef deserializer to do it. Crucially this keeps the +// confidence gate in force: while REGISTERED_STABLE_CORRELATION_PROFILE_IDS is +// empty, no payload can deserialize a Strong or Exact key and forge +// corroboration strength. +impl<'de> Deserialize<'de> for SccmCorrelationKey { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let key = Self::from(SccmCorrelationKeyWire::deserialize(deserializer)?); + let citations = key.evidence.as_slice(); + validate_correlation_key_evidence(citations, slice::from_ref(&key)).map_err(|error| { + D::Error::custom(format!("invalid SCCM correlation key contract: {error:?}")) + })?; + Ok(key) + } +} + #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct SccmArtifactRequestWire { @@ -369,6 +614,23 @@ impl From for SccmArtifactRequest { } } +// Same contract as a request carried inside SccmFinding::next_artifacts: the +// logical id must name a declared catalog source for the requested role and +// the reason must stay bounded and scoped to that artifact. +impl<'de> Deserialize<'de> for SccmArtifactRequest { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let mut request = Self::from(SccmArtifactRequestWire::deserialize(deserializer)?); + validate_artifact_requests(slice::from_ref(&request)).map_err(|error| { + D::Error::custom(format!("invalid SCCM artifact request contract: {error:?}")) + })?; + request.reason = request.reason.trim().to_owned(); + Ok(request) + } +} + impl<'de> Deserialize<'de> for SccmFinding { fn deserialize(deserializer: D) -> Result where @@ -393,6 +655,9 @@ impl<'de> Deserialize<'de> for SccmFinding { correlation_keys: wire.correlation_keys.into_iter().map(Into::into).collect(), next_artifacts: wire.next_artifacts.into_iter().map(Into::into).collect(), }; + validate_raw_text_bounds(&finding).map_err(|error| { + D::Error::custom(format!("invalid SCCM finding contract: {error:?}")) + })?; normalize_finding(&mut finding); finding.validate().map_err(|error| { D::Error::custom(format!("invalid SCCM finding contract: {error:?}")) @@ -403,6 +668,7 @@ impl<'de> Deserialize<'de> for SccmFinding { impl SccmFinding { pub fn validate(&self) -> Result<(), SccmFindingValidationError> { + validate_raw_text_bounds(self)?; validate_required_text(self)?; validate_roles(self)?; validate_all_evidence_references(self)?; @@ -612,16 +878,35 @@ impl SccmFindingBuilder { correlation_keys: self.correlation_keys, next_artifacts: self.next_artifacts, }; + validate_raw_text_bounds(&finding)?; normalize_finding(&mut finding); finding.validate()?; Ok(finding) } } +fn validate_raw_text_bounds(finding: &SccmFinding) -> Result<(), SccmFindingValidationError> { + if !has_at_most_chars(&finding.title, MAX_SCCM_FINDING_TITLE_CHARS) + || !has_at_most_chars(&finding.summary, MAX_SCCM_FINDING_SUMMARY_CHARS) + { + return Err(SccmFindingValidationError::MissingRequiredField); + } + if finding + .next_artifacts + .iter() + .any(|request| !has_at_most_chars(&request.reason, MAX_SCCM_ARTIFACT_REQUEST_REASON_CHARS)) + { + return Err(SccmFindingValidationError::InvalidArtifactRequestReason); + } + Ok(()) +} + fn validate_required_text(finding: &SccmFinding) -> Result<(), SccmFindingValidationError> { + let title = finding.title.trim(); + let summary = finding.summary.trim(); if !is_canonical_opaque_id(&finding.finding_id) - || finding.title.trim().is_empty() - || finding.summary.trim().is_empty() + || title.is_empty() + || summary.is_empty() || !finding.phase.has_canonical_serialized_form() { return Err(SccmFindingValidationError::MissingRequiredField); @@ -784,9 +1069,7 @@ fn validate_coverage_gaps( ) -> Result<(), SccmFindingValidationError> { let mut coverage_by_artifact: BTreeMap<&str, &SccmFindingCoverageGap> = BTreeMap::new(); for gap in coverage_gaps { - if !is_canonical_opaque_id(&gap.artifact_id) - || gap.artifact_id.chars().count() > MAX_SCCM_COVERAGE_GAP_ARTIFACT_ID_CHARS - || gap.coverage == SccmCoverageState::Captured + if !is_canonical_opaque_id(&gap.artifact_id) || gap.coverage == SccmCoverageState::Captured { return Err(SccmFindingValidationError::InvalidCoverageGap); } @@ -845,11 +1128,11 @@ fn is_bounded_request_reason( requested_logical_id: &str, ) -> bool { let trimmed = reason.trim(); - if trimmed.is_empty() + if !has_at_most_chars(reason, MAX_SCCM_ARTIFACT_REQUEST_REASON_CHARS) + || trimmed.is_empty() || !trimmed .chars() .any(|character| character.is_ascii_alphanumeric()) - || trimmed.chars().count() > MAX_SCCM_ARTIFACT_REQUEST_REASON_CHARS || contains_rooted_path(trimmed) || trimmed.contains(['*', '?', '[', ']']) { @@ -2130,8 +2413,10 @@ fn validate_correlation_key_evidence( let normalized = normalize_key(key.kind.clone(), &key.raw); let has_canonical_value = !key.raw.is_empty() && key.raw.trim() == key.raw + && has_at_most_chars(&key.raw, MAX_SCCM_CORRELATION_KEY_VALUE_CHARS) && !key.normalized.is_empty() && key.normalized.trim() == key.normalized + && has_at_most_chars(&key.normalized, MAX_SCCM_CORRELATION_KEY_VALUE_CHARS) && normalized.confidence == SccmKeyConfidence::Exact && normalized.normalized == key.normalized; let has_valid_span = match (key.start, key.end) { @@ -2161,6 +2446,12 @@ fn validate_correlation_key_evidence( let Some(reference) = &key.evidence else { return Err(SccmFindingValidationError::CorrelationKeyMissingEvidence); }; + // The containment check below only proves the reference is cited, and + // a standalone key is its own citation set, which makes containment + // self-satisfying. Validate the reference here rather than at the call + // sites so no caller can reach the trivially satisfied check with an + // unvalidated reference. + validate_evidence_reference(reference)?; if !evidence.contains(reference) { return Err(SccmFindingValidationError::CorrelationKeyEvidenceNotCited); } @@ -2227,7 +2518,11 @@ fn evidence_identity(reference: &SccmEvidenceRef) -> (&str, &str) { } fn is_canonical_opaque_id(value: &str) -> bool { - !value.is_empty() && value.trim() == value + !value.is_empty() && value.trim() == value && has_at_most_chars(value, MAX_SCCM_OPAQUE_ID_CHARS) +} + +pub(crate) fn has_at_most_chars(value: &str, maximum: usize) -> bool { + value.chars().nth(maximum).is_none() } fn normalize_finding(finding: &mut SccmFinding) { diff --git a/crates/cmtraceopen-parser/src/sccm/keys.rs b/crates/cmtraceopen-parser/src/sccm/keys.rs index a019684a0..c1821d450 100644 --- a/crates/cmtraceopen-parser/src/sccm/keys.rs +++ b/crates/cmtraceopen-parser/src/sccm/keys.rs @@ -2,6 +2,7 @@ use std::sync::OnceLock; use regex::Regex; +use super::findings::{has_at_most_chars, MAX_SCCM_CORRELATION_KEY_VALUE_CHARS}; use super::models::{ SccmCorrelationKey, SccmCorrelationKeyKind, SccmEvidence, SccmExtractionGap, SccmExtractionGapKind, SccmExtractionProfile, SccmExtractionProfileMaturity, SccmKeyConfidence, @@ -179,7 +180,12 @@ pub fn extract_keys( for candidate in candidates { let mut key = normalize_key(candidate.kind.clone(), candidate.raw); - if key.confidence != SccmKeyConfidence::Exact { + // A candidate that normalizes cleanly but carries an out-of-bound value + // is as unusable as one that fails to normalize: the crate's own + // validator rejects it, so emitting it as a key would let the producer + // hand out keys that no longer round trip. Both weigh the same way, and + // both stay visible as a recorded gap. + if key.confidence != SccmKeyConfidence::Exact || !is_bounded_key_value(&key) { result.gaps.push(gap_for( SccmExtractionGapKind::MalformedCandidate, profile, @@ -200,6 +206,14 @@ pub fn extract_keys( result } +// The normalized value can outgrow the raw one: normalize_kb_id prepends "KB", +// so a raw that fits the bound can still normalize past it. Both are on the +// wire, so both have to clear the bound the validator applies to both. +fn is_bounded_key_value(key: &SccmCorrelationKey) -> bool { + has_at_most_chars(&key.raw, MAX_SCCM_CORRELATION_KEY_VALUE_CHARS) + && has_at_most_chars(&key.normalized, MAX_SCCM_CORRELATION_KEY_VALUE_CHARS) +} + fn profile_gap_kind(profile: &SccmExtractionProfile) -> Option { if profile.selected_configmgr_version.is_none() { return Some(SccmExtractionGapKind::MissingVersion); diff --git a/crates/cmtraceopen-parser/src/sccm/models.rs b/crates/cmtraceopen-parser/src/sccm/models.rs index a87ba7802..7772e0403 100644 --- a/crates/cmtraceopen-parser/src/sccm/models.rs +++ b/crates/cmtraceopen-parser/src/sccm/models.rs @@ -147,8 +147,11 @@ pub struct SccmTimestamp { pub ordering_state: SccmTimeOrderingState, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] +// Serialize and Deserialize are implemented by hand in findings.rs, where the +// deny_unknown_fields wire struct and validate_evidence_reference live, so a +// reference cannot cross a public wire boundary through a door the finding +// contract does not guard. +#[derive(Debug, Clone, PartialEq, Eq)] pub struct SccmEvidenceRef { pub artifact_id: String, pub entry_id: String, @@ -203,8 +206,11 @@ pub enum SccmKeyConfidence { Exact, } -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] +// Serialize and Deserialize are implemented by hand in findings.rs so that a +// standalone key clears validate_correlation_key_evidence, including the +// confidence gate that keeps every key at Low while no stable extraction +// profile is registered. +#[derive(Debug, Clone, PartialEq, Eq)] pub struct SccmCorrelationKey { pub kind: SccmCorrelationKeyKind, pub raw: String, diff --git a/crates/cmtraceopen-parser/tests/sccm_spine_contract.rs b/crates/cmtraceopen-parser/tests/sccm_spine_contract.rs index 5320aa881..933c47126 100644 --- a/crates/cmtraceopen-parser/tests/sccm_spine_contract.rs +++ b/crates/cmtraceopen-parser/tests/sccm_spine_contract.rs @@ -80,6 +80,52 @@ fn finding_key( } } +/// Evidence-reference payloads that `validate_evidence_reference` rejects. +/// +/// Every door that admits a reference, standalone or nested, must reject all +/// of them. Shared so a nested door cannot be tested against a weaker list +/// than the standalone door. +fn noncanonical_evidence_ref_payloads() -> Vec<(&'static str, serde_json::Value)> { + let canonical = serde_json::to_value(finding_evidence_ref("artifact-a", "entry-a")).unwrap(); + let mut payloads: Vec<(&'static str, serde_json::Value)> = Vec::new(); + + for (label, field, value) in [ + ("a 5000-char artifact ID", "artifactId", "a".repeat(5000)), + ("an empty artifact ID", "artifactId", String::new()), + ("an untrimmed entry ID", "entryId", " entry-a ".to_owned()), + ("an empty entry ID", "entryId", String::new()), + ] { + let mut json = canonical.clone(); + json[field] = serde_json::json!(value); + payloads.push((label, json)); + } + + for (label, start, end) in [ + ( + "an inverted line range", + serde_json::json!(9), + serde_json::json!(2), + ), + ( + "a half-set line range", + serde_json::json!(7), + serde_json::Value::Null, + ), + ( + "a zero line start", + serde_json::json!(0), + serde_json::json!(1), + ), + ] { + let mut json = canonical.clone(); + json["lineStart"] = start; + json["lineEnd"] = end; + payloads.push((label, json)); + } + + payloads +} + fn finding_client_gap(artifact_id: &str, coverage: SccmCoverageState) -> SccmFindingCoverageGap { SccmFindingCoverageGap { artifact_id: artifact_id.into(), @@ -781,8 +827,18 @@ fn finding_review_invalid_profiled_keys_fail_at_every_public_boundary() { accepted.push(format!("serializer: {label}")); } + let key_json = serde_json::json!({ + "kind": &key.kind, + "raw": &key.raw, + "normalized": &key.normalized, + "confidence": &key.confidence, + "extractionProfileId": &key.extraction_profile_id, + "evidence": &key.evidence, + "start": key.start, + "end": key.end, + }); let mut json = serde_json::to_value(&canonical).unwrap(); - json["correlationKeys"] = serde_json::to_value([key]).unwrap(); + json["correlationKeys"] = serde_json::json!([key_json]); if serde_json::from_value::(json).is_ok() { accepted.push(format!("deserializer: {label}")); } @@ -1583,6 +1639,997 @@ fn finding_rejects_noncanonical_opaque_ids_across_public_boundaries() { assert!(mismatches.is_empty(), "{mismatches:#?}"); } +fn bounded_finding_with_id(finding_id: &str) -> Result { + SccmFindingBuilder::new(finding_id) + .class(SccmFindingClass::Symptom) + .phase(SccmPhase::Policy) + .role(SccmRole::Client) + .severity(Severity::Warning) + .confidence(SccmConfidence::Low) + .evidence(vec![finding_evidence_ref("artifact-a", "entry-a")]) + .build() +} + +#[test] +fn finding_rejects_overlong_opaque_ids_across_public_boundaries() { + let mut mismatches: Vec = Vec::new(); + let overlong_id = "a".repeat(257); + let bounded_id = "a".repeat(256); + + if bounded_finding_with_id(&overlong_id).err() + != Some(SccmFindingValidationError::MissingRequiredField) + { + mismatches.push("builder accepted an overlong finding ID".into()); + } + + for (label, artifact_id, entry_id) in [ + ("artifact ID", overlong_id.as_str(), "entry-a"), + ("entry ID", "artifact-a", overlong_id.as_str()), + ] { + let result = SccmFindingBuilder::new("overlong-evidence-id") + .class(SccmFindingClass::Symptom) + .phase(SccmPhase::Policy) + .role(SccmRole::Client) + .severity(Severity::Warning) + .confidence(SccmConfidence::Low) + .evidence(vec![finding_evidence_ref(artifact_id, entry_id)]) + .build(); + if result.err() != Some(SccmFindingValidationError::InvalidEvidenceReference) { + mismatches.push(format!("builder accepted an overlong evidence {label}")); + } + } + + let gap_result = SccmFindingBuilder::new("overlong-gap-artifact-id") + .class(SccmFindingClass::Symptom) + .phase(SccmPhase::Policy) + .role(SccmRole::Client) + .severity(Severity::Warning) + .confidence(SccmConfidence::Low) + .evidence(vec![finding_evidence_ref("artifact-a", "entry-a")]) + .coverage_gap(finding_client_gap( + &overlong_id, + SccmCoverageState::AccessDenied, + )) + .build(); + if gap_result.err() != Some(SccmFindingValidationError::InvalidCoverageGap) { + mismatches.push("builder accepted an overlong coverage-gap artifact ID".into()); + } + + let key_evidence = finding_evidence_ref("artifact-a", "entry-a"); + let key_result = SccmFindingBuilder::new("overlong-key-profile-id") + .class(SccmFindingClass::Symptom) + .phase(SccmPhase::Policy) + .role(SccmRole::Client) + .severity(Severity::Warning) + .confidence(SccmConfidence::Low) + .evidence(vec![key_evidence.clone()]) + .correlation_keys(vec![finding_key( + SccmCorrelationKeyKind::AssignmentId, + "{ABCDEFAB-0000-0000-0000-000000000001}", + "abcdefab-0000-0000-0000-000000000001", + SccmKeyConfidence::Low, + Some(overlong_id.as_str()), + key_evidence, + )]) + .build(); + if key_result.err() != Some(SccmFindingValidationError::InvalidCorrelationKey) { + mismatches.push("builder accepted an overlong correlation-key profile ID".into()); + } + + let mut direct = bounded_finding_with_id("overlong-direct").unwrap(); + direct.finding_id = overlong_id.clone(); + if direct.validate().err() != Some(SccmFindingValidationError::MissingRequiredField) { + mismatches.push("direct validate accepted an overlong finding ID".into()); + } + if serde_json::to_value(&direct).is_ok() { + mismatches.push("serializer accepted an overlong finding ID".into()); + } + + let canonical_json = + serde_json::to_value(bounded_finding_with_id("overlong-json").unwrap()).unwrap(); + let mut finding_id_json = canonical_json.clone(); + finding_id_json["findingId"] = serde_json::json!(overlong_id); + if serde_json::from_value::(finding_id_json).is_ok() { + mismatches.push("deserializer accepted an overlong finding ID".into()); + } + for field in ["artifactId", "entryId"] { + let mut evidence_json = canonical_json.clone(); + evidence_json["evidence"][0][field] = serde_json::json!(overlong_id); + if serde_json::from_value::(evidence_json).is_ok() { + mismatches.push(format!( + "deserializer accepted an overlong evidence {field}" + )); + } + } + + let bounded = SccmFindingBuilder::new(bounded_id.as_str()) + .class(SccmFindingClass::Symptom) + .phase(SccmPhase::Policy) + .role(SccmRole::Client) + .severity(Severity::Warning) + .confidence(SccmConfidence::Low) + .evidence(vec![finding_evidence_ref(&bounded_id, &bounded_id)]) + .build(); + match bounded { + Ok(bounded) => { + let json = serde_json::to_value(&bounded).unwrap(); + if serde_json::from_value::(json).ok().as_ref() != Some(&bounded) { + mismatches.push("bound-length opaque IDs did not round trip".into()); + } + } + Err(error) => { + mismatches.push(format!( + "builder rejected bound-length opaque IDs: {error:?}" + )); + } + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + +#[test] +fn finding_rejects_overlong_display_text_across_public_boundaries() { + let mut mismatches: Vec = Vec::new(); + let overlong_title = "t".repeat(513); + let overlong_summary = "s".repeat(2049); + + for (label, title, summary) in [ + ("title", overlong_title.as_str(), "bounded summary"), + ("summary", "bounded title", overlong_summary.as_str()), + ] { + let result = SccmFindingBuilder::new("overlong-display-text") + .class(SccmFindingClass::Symptom) + .phase(SccmPhase::Policy) + .role(SccmRole::Client) + .severity(Severity::Warning) + .confidence(SccmConfidence::Low) + .title(title) + .summary(summary) + .evidence(vec![finding_evidence_ref("artifact-a", "entry-a")]) + .build(); + if result.err() != Some(SccmFindingValidationError::MissingRequiredField) { + mismatches.push(format!("builder accepted an overlong {label}")); + } + } + + let mut direct = bounded_finding_with_id("overlong-title-direct").unwrap(); + direct.title = overlong_title.clone(); + if direct.validate().err() != Some(SccmFindingValidationError::MissingRequiredField) { + mismatches.push("direct validate accepted an overlong title".into()); + } + if serde_json::to_value(&direct).is_ok() { + mismatches.push("serializer accepted an overlong title".into()); + } + let mut direct = bounded_finding_with_id("overlong-summary-direct").unwrap(); + direct.summary = overlong_summary.clone(); + if direct.validate().err() != Some(SccmFindingValidationError::MissingRequiredField) { + mismatches.push("direct validate accepted an overlong summary".into()); + } + if serde_json::to_value(&direct).is_ok() { + mismatches.push("serializer accepted an overlong summary".into()); + } + + let canonical_json = + serde_json::to_value(bounded_finding_with_id("overlong-text-json").unwrap()).unwrap(); + for (field, value) in [("title", &overlong_title), ("summary", &overlong_summary)] { + let mut json = canonical_json.clone(); + json[field] = serde_json::json!(value); + if serde_json::from_value::(json).is_ok() { + mismatches.push(format!("deserializer accepted an overlong {field}")); + } + } + + let bounded = SccmFindingBuilder::new("bound-length-display-text") + .class(SccmFindingClass::Symptom) + .phase(SccmPhase::Policy) + .role(SccmRole::Client) + .severity(Severity::Warning) + .confidence(SccmConfidence::Low) + .title("t".repeat(512)) + .summary("s".repeat(2048)) + .evidence(vec![finding_evidence_ref("artifact-a", "entry-a")]) + .build(); + match bounded { + Ok(bounded) => { + let json = serde_json::to_value(&bounded).unwrap(); + if serde_json::from_value::(json).ok().as_ref() != Some(&bounded) { + mismatches.push("bound-length display text did not round trip".into()); + } + } + Err(error) => { + mismatches.push(format!( + "builder rejected bound-length display text: {error:?}" + )); + } + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + +#[test] +fn finding_rejects_display_text_whose_stored_form_exceeds_the_bound() { + let mut accepted = Vec::new(); + + for (label, title, summary) in [ + ( + "title", + format!("{}bounded title", " ".repeat(512)), + "bounded summary".to_owned(), + ), + ( + "summary", + "bounded title".to_owned(), + format!("{}bounded summary", " ".repeat(2048)), + ), + ] { + let builder = SccmFindingBuilder::new("padded-display-text") + .class(SccmFindingClass::Symptom) + .phase(SccmPhase::Policy) + .role(SccmRole::Client) + .severity(Severity::Warning) + .confidence(SccmConfidence::Low) + .title(&title) + .summary(&summary) + .evidence(vec![finding_evidence_ref("artifact-a", "entry-a")]) + .build(); + if builder.err() != Some(SccmFindingValidationError::MissingRequiredField) { + accepted.push(format!("builder accepted padded {label}")); + } + + let mut direct = bounded_finding_with_id("padded-display-direct").unwrap(); + direct.title = title.clone(); + direct.summary = summary.clone(); + if direct.validate().err() != Some(SccmFindingValidationError::MissingRequiredField) { + accepted.push(format!("direct validation accepted padded {label}")); + } + if serde_json::to_value(&direct).is_ok() { + accepted.push(format!("serialization accepted padded {label}")); + } + + let mut json = + serde_json::to_value(bounded_finding_with_id("padded-display-json").unwrap()).unwrap(); + json["title"] = serde_json::json!(title); + json["summary"] = serde_json::json!(summary); + if serde_json::from_value::(json).is_ok() { + accepted.push(format!("deserialization accepted padded {label}")); + } + } + + assert!( + accepted.is_empty(), + "accepted display text with an oversized stored form: {accepted:#?}" + ); +} + +fn finding_with_ci_key_value( + finding_id: &str, + digits: &str, +) -> Result { + let key_evidence = finding_evidence_ref("artifact-a", "entry-a"); + SccmFindingBuilder::new(finding_id) + .class(SccmFindingClass::Symptom) + .phase(SccmPhase::Policy) + .role(SccmRole::Client) + .severity(Severity::Warning) + .confidence(SccmConfidence::Low) + .evidence(vec![key_evidence.clone()]) + .correlation_keys(vec![finding_key( + SccmCorrelationKeyKind::CiId, + digits, + digits, + SccmKeyConfidence::Low, + Some("sccm-keys-experimental-v1"), + key_evidence, + )]) + .build() +} + +#[test] +fn finding_rejects_overlong_correlation_key_values() { + let mut mismatches: Vec = Vec::new(); + let overlong_digits = "1".repeat(257); + let bounded_digits = "1".repeat(256); + + if finding_with_ci_key_value("overlong-key-value", &overlong_digits).err() + != Some(SccmFindingValidationError::InvalidCorrelationKey) + { + mismatches.push("builder accepted an overlong correlation-key value".into()); + } + + for field in ["raw", "normalized"] { + let mut direct = finding_with_ci_key_value("overlong-key-value-direct", "71").unwrap(); + match field { + "raw" => direct.correlation_keys[0].raw = overlong_digits.clone(), + "normalized" => direct.correlation_keys[0].normalized = overlong_digits.clone(), + _ => unreachable!(), + } + if direct.validate().err() != Some(SccmFindingValidationError::InvalidCorrelationKey) { + mismatches.push(format!( + "direct validate accepted an overlong {field} value" + )); + } + if serde_json::to_value(&direct).is_ok() { + mismatches.push(format!("serializer accepted an overlong {field} value")); + } + + let mut json = serde_json::to_value( + finding_with_ci_key_value("overlong-key-value-json", "71").unwrap(), + ) + .unwrap(); + json["correlationKeys"][0][field] = serde_json::json!(overlong_digits); + if serde_json::from_value::(json).is_ok() { + mismatches.push(format!("deserializer accepted an overlong {field} value")); + } + } + + match finding_with_ci_key_value("bound-length-key-value", &bounded_digits) { + Ok(bounded) => { + let json = serde_json::to_value(&bounded).unwrap(); + if serde_json::from_value::(json).ok().as_ref() != Some(&bounded) { + mismatches.push("bound-length correlation-key value did not round trip".into()); + } + } + Err(error) => { + mismatches.push(format!( + "builder rejected a bound-length correlation-key value: {error:?}" + )); + } + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + +#[test] +fn coverage_gap_deserializes_through_the_same_wire_contract_as_a_finding() { + let mut mismatches: Vec = Vec::new(); + + let gap = finding_client_gap("client-policy-agent", SccmCoverageState::AccessDenied); + let canonical = serde_json::to_value(&gap).unwrap(); + if serde_json::from_value::(canonical.clone()) + .ok() + .as_ref() + != Some(&gap) + { + mismatches.push("a canonical coverage gap did not round trip".into()); + } + + let mut unknown_field = canonical.clone(); + unknown_field["unexpectedField"] = serde_json::json!("surplus"); + if serde_json::from_value::(unknown_field).is_ok() { + mismatches.push("coverage gap deserializer accepted an unknown field".into()); + } + + let mut captured = canonical.clone(); + captured["coverage"] = serde_json::json!("captured"); + if serde_json::from_value::(captured).is_ok() { + mismatches.push("coverage gap deserializer accepted captured coverage".into()); + } + + for (label, artifact_id) in [ + ("an empty artifact ID", String::new()), + ( + "an untrimmed artifact ID", + " client-policy-agent ".to_owned(), + ), + ("an overlong artifact ID", "a".repeat(257)), + ] { + let mut json = canonical.clone(); + json["artifactId"] = serde_json::json!(artifact_id); + if serde_json::from_value::(json).is_ok() { + mismatches.push(format!("coverage gap deserializer accepted {label}")); + } + } + + let mut untrimmed_role = canonical.clone(); + untrimmed_role["role"] = serde_json::json!(" client "); + if serde_json::from_value::(untrimmed_role).is_ok() { + mismatches.push("coverage gap deserializer accepted a nested untrimmed role".into()); + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + +#[test] +fn coverage_gap_serialization_enforces_the_full_standalone_contract() { + let mut empty_artifact = + finding_client_gap("client-policy-agent", SccmCoverageState::AccessDenied); + empty_artifact.artifact_id.clear(); + let mut overlong_artifact = + finding_client_gap("client-policy-agent", SccmCoverageState::AccessDenied); + overlong_artifact.artifact_id = "a".repeat(257); + let captured = finding_client_gap("client-policy-agent", SccmCoverageState::Captured); + let mut mismatches = Vec::new(); + + for (label, gap) in [ + ("an empty artifact ID", empty_artifact), + ("an overlong artifact ID", overlong_artifact), + ("captured coverage", captured), + ] { + match serde_json::to_value(gap) { + Ok(_) => mismatches.push(format!("serializer accepted {label}")), + Err(error) if !error.to_string().contains("InvalidCoverageGap") => { + mismatches.push(format!( + "serializer rejected {label} with the wrong contract error: {error}" + )); + } + Err(_) => {} + } + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + +#[test] +fn artifact_request_deserializes_through_the_same_wire_contract_as_a_finding() { + let mut mismatches: Vec = Vec::new(); + + let request = finding_request( + "policyAgent", + SccmRole::Client, + "Confirm the bounded policy request outcome.", + ); + let canonical = serde_json::to_value(&request).unwrap(); + if serde_json::from_value::(canonical.clone()) + .ok() + .as_ref() + != Some(&request) + { + mismatches.push("a canonical artifact request did not round trip".into()); + } + + let mut unknown_field = canonical.clone(); + unknown_field["unexpectedField"] = serde_json::json!("surplus"); + if serde_json::from_value::(unknown_field).is_ok() { + mismatches.push("artifact request deserializer accepted an unknown field".into()); + } + + for (label, logical_id) in [ + ("an empty logical ID", String::new()), + ("an untrimmed logical ID", " policyAgent ".to_owned()), + ("an overlong logical ID", "a".repeat(257)), + ( + "an undeclared logical ID", + "not-a-declared-source".to_owned(), + ), + ] { + let mut json = canonical.clone(); + json["logicalId"] = serde_json::json!(logical_id); + if serde_json::from_value::(json).is_ok() { + mismatches.push(format!("artifact request deserializer accepted {label}")); + } + } + + for (label, reason) in [ + ("an empty reason", String::new()), + ( + "a rooted-path reason", + ROOTED_ARTIFACT_REQUEST_REASONS[1].to_owned(), + ), + ( + "an overlong reason", + "a".repeat(MAX_SCCM_ARTIFACT_REQUEST_REASON_CHARS + 1), + ), + ] { + let mut json = canonical.clone(); + json["reason"] = serde_json::json!(reason); + if serde_json::from_value::(json).is_ok() { + mismatches.push(format!("artifact request deserializer accepted {label}")); + } + } + + for (label, role) in [ + ("a nested untrimmed role", " client "), + ("a nested mismatched role", "distributionPoint"), + ] { + let mut json = canonical.clone(); + json["role"] = serde_json::json!(role); + if serde_json::from_value::(json).is_ok() { + mismatches.push(format!("artifact request deserializer accepted {label}")); + } + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + +#[test] +fn artifact_request_serialization_enforces_the_full_standalone_contract() { + let cases = [ + ( + "an undeclared logical ID", + finding_request( + "not-a-declared-source", + SccmRole::Client, + "Confirm the not-a-declared-source request outcome.", + ), + "UndeclaredArtifactRequest", + ), + ( + "a role mismatch", + finding_request( + "policyAgent", + SccmRole::DistributionPoint, + "Confirm the bounded policy request outcome.", + ), + "ArtifactRequestRoleMismatch", + ), + ( + "a rooted-path reason", + finding_request( + "policyAgent", + SccmRole::Client, + ROOTED_ARTIFACT_REQUEST_REASONS[1], + ), + "InvalidArtifactRequestReason", + ), + ( + "an out-of-scope reason", + finding_request( + "policyAgent", + SccmRole::Client, + "Collect the complete CAS.log file.", + ), + "InvalidArtifactRequestReason", + ), + ]; + let mut mismatches = Vec::new(); + + for (label, request, expected_error) in cases { + match serde_json::to_value(request) { + Ok(_) => mismatches.push(format!("serializer accepted {label}")), + Err(error) if !error.to_string().contains(expected_error) => mismatches.push(format!( + "serializer rejected {label} with the wrong contract error: {error}" + )), + Err(_) => {} + } + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + +#[test] +fn artifact_request_deserialization_returns_a_canonical_reason() { + let mut json = serde_json::to_value(finding_request( + "policyAgent", + SccmRole::Client, + "Confirm the bounded policy request outcome.", + )) + .unwrap(); + json["reason"] = serde_json::json!(" Confirm the bounded policy request outcome. "); + + let request = serde_json::from_value::(json).unwrap(); + + assert_eq!( + request.reason, + "Confirm the bounded policy request outcome." + ); + + let serialized = serde_json::to_value(finding_request( + "policyAgent", + SccmRole::Client, + " Confirm the bounded policy request outcome. ", + )) + .unwrap(); + assert_eq!( + serialized["reason"], + "Confirm the bounded policy request outcome." + ); +} + +#[test] +fn artifact_request_rejects_padding_that_exceeds_the_reason_bound() { + let reason = format!( + "{}Confirm the bounded policy request outcome.", + " ".repeat(MAX_SCCM_ARTIFACT_REQUEST_REASON_CHARS) + ); + let mut accepted = Vec::new(); + + let builder = SccmFindingBuilder::new("padded-request-builder") + .class(SccmFindingClass::Symptom) + .phase(SccmPhase::Policy) + .role(SccmRole::Client) + .severity(Severity::Warning) + .confidence(SccmConfidence::Low) + .evidence(vec![finding_evidence_ref("artifact-a", "entry-a")]) + .next_artifact(finding_request("policyAgent", SccmRole::Client, &reason)) + .build(); + if builder.err() != Some(SccmFindingValidationError::InvalidArtifactRequestReason) { + accepted.push("builder".to_owned()); + } + + let mut direct = finding_with_gap_and_request("padded-request-direct"); + direct.next_artifacts[0].reason = reason.clone(); + if direct.validate().err() != Some(SccmFindingValidationError::InvalidArtifactRequestReason) { + accepted.push("direct validation".to_owned()); + } + if serde_json::to_value(&direct).is_ok() { + accepted.push("serialization".to_owned()); + } + + let mut finding_json = + serde_json::to_value(finding_with_gap_and_request("padded-request-json")).unwrap(); + finding_json["nextArtifacts"][0]["reason"] = serde_json::json!(&reason); + if serde_json::from_value::(finding_json).is_ok() { + accepted.push("finding deserialization".to_owned()); + } + + let mut request_json = serde_json::to_value(finding_request( + "policyAgent", + SccmRole::Client, + "Confirm the bounded policy request outcome.", + )) + .unwrap(); + request_json["reason"] = serde_json::json!(reason); + if serde_json::from_value::(request_json).is_ok() { + accepted.push("standalone request deserialization".to_owned()); + } + if serde_json::to_value(finding_request("policyAgent", SccmRole::Client, &reason)).is_ok() { + accepted.push("standalone request serialization".to_owned()); + } + + assert!( + accepted.is_empty(), + "accepted an artifact request whose stored reason exceeds the bound: {accepted:#?}" + ); +} + +#[test] +fn evidence_ref_deserializes_through_the_same_wire_contract_as_a_finding() { + let mut mismatches: Vec = Vec::new(); + + let reference = finding_evidence_ref("artifact-a", "entry-a"); + let canonical = serde_json::to_value(&reference).unwrap(); + if serde_json::from_value::(canonical.clone()) + .ok() + .as_ref() + != Some(&reference) + { + mismatches.push("a canonical evidence ref did not round trip".into()); + } + + let mut unknown_field = canonical.clone(); + unknown_field["unexpectedField"] = serde_json::json!("surplus"); + if serde_json::from_value::(unknown_field).is_ok() { + mismatches.push("evidence ref deserializer accepted an unknown field".into()); + } + + for (label, json) in noncanonical_evidence_ref_payloads() { + if serde_json::from_value::(json).is_ok() { + mismatches.push(format!("evidence ref deserializer accepted {label}")); + } + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + +#[test] +fn evidence_ref_serialization_enforces_the_full_standalone_contract() { + let canonical = finding_evidence_ref("artifact-a", "entry-a"); + let mut empty_artifact = canonical.clone(); + empty_artifact.artifact_id.clear(); + let mut overlong_entry = canonical.clone(); + overlong_entry.entry_id = "e".repeat(257); + let mut half_set_range = canonical.clone(); + half_set_range.line_end = None; + let mut zero_start = canonical.clone(); + zero_start.line_start = Some(0); + let mut inverted_range = canonical; + inverted_range.line_start = Some(9); + inverted_range.line_end = Some(2); + + let mut mismatches = Vec::new(); + for (label, reference) in [ + ("an empty artifact ID", empty_artifact), + ("an overlong entry ID", overlong_entry), + ("a half-set line range", half_set_range), + ("a zero line start", zero_start), + ("an inverted line range", inverted_range), + ] { + match serde_json::to_value(reference) { + Ok(_) => mismatches.push(format!("serializer accepted {label}")), + Err(error) if !error.to_string().contains("InvalidEvidenceReference") => { + mismatches.push(format!( + "serializer rejected {label} with the wrong contract error: {error}" + )); + } + Err(_) => {} + } + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + +#[test] +fn terminal_evidence_deserializes_through_the_same_wire_contract_as_a_finding() { + let mut mismatches: Vec = Vec::new(); + + let terminal = + SccmTerminalEvidence::observed_failure(finding_evidence_ref("artifact-a", "entry-a")); + let canonical = serde_json::to_value(&terminal).unwrap(); + if serde_json::from_value::(canonical.clone()) + .ok() + .as_ref() + != Some(&terminal) + { + mismatches.push("a canonical terminal evidence did not round trip".into()); + } + + let mut unknown_field = canonical.clone(); + unknown_field["unexpectedField"] = serde_json::json!("surplus"); + if serde_json::from_value::(unknown_field).is_ok() { + mismatches.push("terminal evidence deserializer accepted an unknown field".into()); + } + + let mut nested_unknown = canonical.clone(); + nested_unknown["reference"]["unexpectedField"] = serde_json::json!("surplus"); + if serde_json::from_value::(nested_unknown).is_ok() { + mismatches.push("terminal evidence deserializer accepted a nested unknown field".into()); + } + + for (label, reference) in noncanonical_evidence_ref_payloads() { + let mut json = canonical.clone(); + json["reference"] = reference; + if serde_json::from_value::(json).is_ok() { + mismatches.push(format!( + "terminal evidence deserializer accepted nested {label}" + )); + } + } + + let mut non_terminal_kind = canonical.clone(); + non_terminal_kind["kind"] = serde_json::json!("observedRecovery"); + if serde_json::from_value::(non_terminal_kind).is_ok() { + mismatches.push("terminal evidence deserializer accepted a non-failure kind".into()); + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + +#[test] +fn terminal_evidence_serialization_enforces_the_full_standalone_contract() { + let mut invalid_reference = + SccmTerminalEvidence::observed_failure(finding_evidence_ref("artifact-a", "entry-a")); + invalid_reference.reference.artifact_id.clear(); + let non_terminal_kind = SccmTerminalEvidence { + reference: finding_evidence_ref("artifact-a", "entry-a"), + kind: SccmTerminalEvidenceKind::Unknown("observedRecovery".to_owned()), + }; + let mut mismatches = Vec::new(); + + for (label, terminal, expected_error) in [ + ( + "an invalid nested reference", + invalid_reference, + "InvalidEvidenceReference", + ), + ( + "a non-failure terminal kind", + non_terminal_kind, + "InvalidTerminalEvidence", + ), + ] { + match serde_json::to_value(terminal) { + Ok(_) => mismatches.push(format!("serializer accepted {label}")), + Err(error) if !error.to_string().contains(expected_error) => mismatches.push(format!( + "serializer rejected {label} with the wrong contract error: {error}" + )), + Err(_) => {} + } + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + +#[test] +fn correlation_key_deserializes_through_the_same_wire_contract_as_a_finding() { + let mut mismatches: Vec = Vec::new(); + + let key = finding_key( + SccmCorrelationKeyKind::CiId, + "71", + "71", + SccmKeyConfidence::Low, + Some("sccm-keys-experimental-v1"), + finding_evidence_ref("artifact-a", "entry-a"), + ); + let canonical = serde_json::to_value(&key).unwrap(); + if serde_json::from_value::(canonical.clone()) + .ok() + .as_ref() + != Some(&key) + { + mismatches.push("a canonical correlation key did not round trip".into()); + } + + let mut unknown_field = canonical.clone(); + unknown_field["unexpectedField"] = serde_json::json!("surplus"); + if serde_json::from_value::(unknown_field).is_ok() { + mismatches.push("correlation key deserializer accepted an unknown field".into()); + } + + // The trust-signal bypass. REGISTERED_STABLE_CORRELATION_PROFILE_IDS is + // deliberately empty, so validate_correlation_key_evidence holds every key + // at Low; standalone deserialization must not let a payload forge a + // stronger confidence than any registered profile can authorize. + for forged in ["exact", "strong"] { + let mut json = canonical.clone(); + json["confidence"] = serde_json::json!(forged); + if serde_json::from_value::(json).is_ok() { + mismatches.push(format!( + "correlation key deserializer accepted forged {forged} confidence" + )); + } + } + + for (label, field, value) in [ + ("a 5000-char raw value", "raw", "1".repeat(5000)), + ( + "a 5000-char normalized value", + "normalized", + "1".repeat(5000), + ), + ("an empty raw value", "raw", String::new()), + ] { + let mut json = canonical.clone(); + json[field] = serde_json::json!(value); + if serde_json::from_value::(json).is_ok() { + mismatches.push(format!("correlation key deserializer accepted {label}")); + } + } + + let mut incoherent_span = canonical.clone(); + incoherent_span["start"] = serde_json::json!(99999); + incoherent_span["end"] = serde_json::json!(1); + if serde_json::from_value::(incoherent_span).is_ok() { + mismatches.push("correlation key deserializer accepted an incoherent span".into()); + } + + let mut overlong_profile = canonical.clone(); + overlong_profile["extractionProfileId"] = serde_json::json!("p".repeat(257)); + if serde_json::from_value::(overlong_profile).is_ok() { + mismatches.push("correlation key deserializer accepted an overlong profile ID".into()); + } + + let mut no_evidence = canonical.clone(); + no_evidence["evidence"] = serde_json::Value::Null; + if serde_json::from_value::(no_evidence).is_ok() { + mismatches.push("correlation key deserializer accepted a key with no evidence".into()); + } + + // The key's own evidence reference is the citation set the contract checks + // it against, so `evidence.contains(reference)` is self-satisfying here. It + // proves nothing about the reference itself, which must still clear the + // same bar a standalone SccmEvidenceRef clears. + let mut nested_unknown = canonical.clone(); + nested_unknown["evidence"]["unexpectedField"] = serde_json::json!("surplus"); + if serde_json::from_value::(nested_unknown).is_ok() { + mismatches.push("correlation key deserializer accepted a nested unknown field".into()); + } + + for (label, evidence) in noncanonical_evidence_ref_payloads() { + let mut json = canonical.clone(); + json["evidence"] = evidence; + if serde_json::from_value::(json).is_ok() { + mismatches.push(format!( + "correlation key deserializer accepted nested {label}" + )); + } + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + +#[test] +fn correlation_key_serialization_enforces_the_full_standalone_contract() { + let canonical = finding_key( + SccmCorrelationKeyKind::CiId, + "71", + "71", + SccmKeyConfidence::Low, + Some("sccm-keys-experimental-v1"), + finding_evidence_ref("artifact-a", "entry-a"), + ); + let mut overlong_raw = canonical.clone(); + overlong_raw.raw = "1".repeat(257); + let mut overlong_normalized = canonical.clone(); + overlong_normalized.normalized = "1".repeat(257); + let mut forged_confidence = canonical.clone(); + forged_confidence.confidence = SccmKeyConfidence::Strong; + let mut invalid_evidence = canonical.clone(); + invalid_evidence + .evidence + .as_mut() + .unwrap() + .artifact_id + .clear(); + let mut missing_evidence = canonical.clone(); + missing_evidence.evidence = None; + let mut incoherent_span = canonical; + incoherent_span.start = Some(8); + incoherent_span.end = Some(9); + + let mut mismatches = Vec::new(); + for (label, key, expected_error) in [ + ( + "an overlong raw value", + overlong_raw, + "InvalidCorrelationKey", + ), + ( + "an overlong normalized value", + overlong_normalized, + "InvalidCorrelationKey", + ), + ( + "forged strong confidence", + forged_confidence, + "InvalidCorrelationKey", + ), + ( + "an invalid evidence reference", + invalid_evidence, + "InvalidEvidenceReference", + ), + ( + "a missing evidence reference", + missing_evidence, + "CorrelationKeyMissingEvidence", + ), + ( + "an incoherent UTF-16 span", + incoherent_span, + "InvalidCorrelationKey", + ), + ] { + match serde_json::to_value(key) { + Ok(_) => mismatches.push(format!("serializer accepted {label}")), + Err(error) if !error.to_string().contains(expected_error) => mismatches.push(format!( + "serializer rejected {label} with the wrong contract error: {error}" + )), + Err(_) => {} + } + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + +#[test] +fn key_extraction_result_deserializes_keys_through_the_same_wire_contract() { + let mut mismatches: Vec = Vec::new(); + + let result = SccmKeyExtractionResult { + profile_id: "sccm-keys-experimental-v1".into(), + keys: vec![finding_key( + SccmCorrelationKeyKind::CiId, + "71", + "71", + SccmKeyConfidence::Low, + Some("sccm-keys-experimental-v1"), + finding_evidence_ref("artifact-a", "entry-a"), + )], + gaps: Vec::new(), + }; + let canonical = serde_json::to_value(&result).unwrap(); + if serde_json::from_value::(canonical.clone()) + .ok() + .as_ref() + != Some(&result) + { + mismatches.push("a canonical key extraction result did not round trip".into()); + } + + for (label, evidence) in noncanonical_evidence_ref_payloads() { + let mut json = canonical.clone(); + json["keys"][0]["evidence"] = evidence; + if serde_json::from_value::(json).is_ok() { + mismatches.push(format!( + "key extraction result deserializer accepted nested {label}" + )); + } + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + #[test] fn finding_rejects_whitespace_wrapped_declared_phase_shadow() { let result = SccmFindingBuilder::new("wrapped-phase-shadow") @@ -2628,8 +3675,11 @@ fn finding_review_passive_unbounded_confirmation_requests_fail_at_every_public_b } let mut json = serde_json::to_value(&canonical).unwrap(); - json["nextArtifacts"][0] = - serde_json::to_value(finding_request(logical_id, SccmRole::Client, reason)).unwrap(); + json["nextArtifacts"][0] = serde_json::json!({ + "logicalId": logical_id, + "role": "client", + "reason": reason, + }); if serde_json::from_value::(json).is_ok() { accepted.push(format!("deserializer: {reason}")); } @@ -4561,6 +5611,69 @@ fn key_profile_and_extraction_result_have_deterministic_json_round_trips() { ); } +#[test] +fn key_extraction_never_emits_a_key_its_own_contract_rejects() { + let mut mismatches: Vec = Vec::new(); + let profile = SccmExtractionProfile::for_version(Some("5.00.9128.1010")); + + // Both raws are inside the regexes' token grammar but outside the + // correlation-key value bound. The KB case is bounded as a raw and only + // crosses the bound once normalization prepends "KB", so the producer has + // to weigh the normalized value too. + for (label, message, raw) in [ + ( + "an overlong CI ID", + format!("CI ID={} status=71", "1".repeat(300)), + "1".repeat(300), + ), + ( + "a KB ID that normalizes past the bound", + format!("KB ID={}", "9".repeat(255)), + "9".repeat(255), + ), + ] { + let evidence = evidence_with_message(&message); + let result = extract_keys(&evidence, &profile); + + for key in &result.keys { + let key_json = serde_json::to_value(key).unwrap(); + if serde_json::from_value::(key_json) + .ok() + .as_ref() + != Some(key) + { + mismatches.push(format!( + "extract_keys emitted a key its own validator rejects for {label}" + )); + } + } + + let result_json = serde_json::to_value(&result).unwrap(); + if serde_json::from_value::(result_json) + .ok() + .as_ref() + != Some(&result) + { + mismatches.push(format!( + "extract_keys emitted a result that does not round trip for {label}" + )); + } + + // An out-of-bound candidate must stay visible as a gap rather than + // disappear, exactly as a candidate that fails to normalize does. + if !result.gaps.iter().any(|gap| { + gap.kind == SccmExtractionGapKind::MalformedCandidate + && gap.candidate_raw.as_deref() == Some(raw.as_str()) + }) { + mismatches.push(format!( + "extract_keys dropped the out-of-bound candidate for {label}" + )); + } + } + + assert!(mismatches.is_empty(), "{mismatches:#?}"); +} + #[test] fn public_ccm_malformed_continuation_stays_plain() { let text = "