Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
208 changes: 195 additions & 13 deletions crates/cmtraceopen-parser/src/sccm/findings.rs
Original file line number Diff line number Diff line change
@@ -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 _;
Expand All @@ -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
// "<subject> <outcome>" 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] = &[];
Expand Down Expand Up @@ -152,7 +173,7 @@ impl<'de> Deserialize<'de> for SccmTerminalEvidenceKind {
}
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SccmTerminalEvidence {
pub reference: SccmEvidenceRef,
Expand All @@ -168,22 +189,51 @@ impl SccmTerminalEvidence {
}
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
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<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let reason = self.reason.trim();
if !has_at_most_chars(&self.reason, MAX_SCCM_ARTIFACT_REQUEST_REASON_CHARS)
|| reason.is_empty()
{
return Err(S::Error::custom(
"invalid SCCM artifact request contract: InvalidArtifactRequestReason",
));
}
SccmArtifactRequestSerializeWire {
logical_id: &self.logical_id,
role: &self.role,
reason,
}
.serialize(serializer)
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

#[derive(Debug, Clone, PartialEq)]
pub struct SccmFinding {
pub finding_id: String,
Expand Down Expand Up @@ -289,6 +339,25 @@ impl From<SccmEvidenceRefWire> 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<D>(deserializer: D) -> Result<Self, D::Error>
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(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct SccmTerminalEvidenceWire {
Expand All @@ -305,6 +374,31 @@ impl From<SccmTerminalEvidenceWire> 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<D>(deserializer: D) -> Result<Self, D::Error>
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(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct SccmFindingCoverageGapWire {
Expand All @@ -323,6 +417,22 @@ impl From<SccmFindingCoverageGapWire> 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<D>(deserializer: D) -> Result<Self, D::Error>
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(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
struct SccmCorrelationKeyWire {
Expand Down Expand Up @@ -351,6 +461,28 @@ impl From<SccmCorrelationKeyWire> 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<D>(deserializer: D) -> Result<Self, D::Error>
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 {
Expand All @@ -369,6 +501,23 @@ impl From<SccmArtifactRequestWire> 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<D>(deserializer: D) -> Result<Self, D::Error>
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<D>(deserializer: D) -> Result<Self, D::Error>
where
Expand All @@ -393,6 +542,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:?}"))
Expand All @@ -403,6 +555,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)?;
Expand Down Expand Up @@ -611,16 +764,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);
Expand Down Expand Up @@ -699,9 +871,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);
}
Expand Down Expand Up @@ -760,11 +930,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(['*', '?', '[', ']'])
{
Expand Down Expand Up @@ -2045,8 +2215,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) {
Expand Down Expand Up @@ -2076,6 +2248,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);
}
Expand Down Expand Up @@ -2142,7 +2320,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)
}

fn has_at_most_chars(value: &str, maximum: usize) -> bool {
value.chars().nth(maximum).is_none()
}

fn normalize_finding(finding: &mut SccmFinding) {
Expand Down
16 changes: 15 additions & 1 deletion crates/cmtraceopen-parser/src/sccm/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::sync::OnceLock;

use regex::Regex;

use super::findings::MAX_SCCM_CORRELATION_KEY_VALUE_CHARS;
use super::models::{
SccmCorrelationKey, SccmCorrelationKeyKind, SccmEvidence, SccmExtractionGap,
SccmExtractionGapKind, SccmExtractionProfile, SccmExtractionProfileMaturity, SccmKeyConfidence,
Expand Down Expand Up @@ -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,
Expand All @@ -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 {
key.raw.chars().count() <= MAX_SCCM_CORRELATION_KEY_VALUE_CHARS
&& key.normalized.chars().count() <= MAX_SCCM_CORRELATION_KEY_VALUE_CHARS
}

fn profile_gap_kind(profile: &SccmExtractionProfile) -> Option<SccmExtractionGapKind> {
if profile.selected_configmgr_version.is_none() {
return Some(SccmExtractionGapKind::MissingVersion);
Expand Down
Loading