Skip to main content

openakb_validate/
validator.rs

1//! Public validation entry points.
2
3use serde::Serialize;
4use serde_json::Value;
5
6use crate::{
7    Code, ContentReport, Finding, Resolver, STRUCTURAL_DEPTH_MAX, ValidationResult, check_content,
8    schema::schema_findings,
9    semantic::{semantic_findings, semantic_warnings},
10    strict::strict_findings,
11};
12
13/// Validation mode.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum Mode {
16    /// Schema and semantic validation without future strict-profile findings.
17    #[default]
18    Lenient,
19    /// Schema and semantic validation plus AKB006 unknown-core-property lint.
20    Strict,
21}
22
23/// Combined structural and opt-in content validation result.
24#[derive(Debug, Clone, Serialize)]
25pub struct FullReport {
26    /// Schema, semantic, and optional strict-profile validation result.
27    pub validation: ValidationResult,
28    /// Opt-in content validation result.
29    pub content: ContentReport,
30}
31
32impl FullReport {
33    /// Returns true when both structural validation and content checks pass.
34    #[must_use]
35    pub fn ok(&self) -> bool {
36        self.validation.ok() && self.content.ok()
37    }
38}
39
40/// Validates a parsed OpenAKB descriptor against the embedded schema and
41/// descriptor-local semantic rules.
42///
43/// [`Mode::Strict`] adds `AKB006` findings for unknown core members outside
44/// extension payloads. Content behind URIs is never fetched here; use
45/// [`validate_with_content`] for opt-in content verification.
46///
47/// # Preconditions
48///
49/// None. Validation is total on any [`Value`]. A descriptor nested deeper than
50/// [`STRUCTURAL_DEPTH_MAX`] is diagnosed as an `AKB011` structural finding rather
51/// than descending into the recursive `jsonschema` walk, so even a
52/// programmatically-built or recursion-limit-disabled value that would otherwise
53/// overflow the stack is turned into a diagnostic instead of an uncatchable
54/// abort. [`serde_json::from_str`] caps nesting at 128, far below the cap, so no
55/// parsed descriptor is ever affected by the guard.
56#[must_use]
57pub fn validate(descriptor: &Value, mode: Mode) -> ValidationResult {
58    if exceeds_structural_depth(descriptor) {
59        return ValidationResult {
60            findings: vec![structural_depth_finding()],
61            warnings: Vec::new(),
62        };
63    }
64
65    let mut findings = schema_findings(descriptor);
66    findings.extend(semantic_findings(descriptor));
67    if mode == Mode::Strict {
68        findings.extend(strict_findings(descriptor));
69    }
70    findings.sort();
71    findings.dedup();
72
73    ValidationResult {
74        findings,
75        warnings: semantic_warnings(descriptor),
76    }
77}
78
79/// Returns true when any value nests deeper than [`STRUCTURAL_DEPTH_MAX`].
80///
81/// The traversal is iterative (an explicit worklist stack, never recursion) so
82/// the depth check itself cannot overflow the call stack on the very inputs it
83/// guards against. The root sits at depth 1 and every nested array or object
84/// element is one level deeper; the walk stops as soon as the cap is exceeded.
85fn exceeds_structural_depth(descriptor: &Value) -> bool {
86    let mut worklist = vec![(descriptor, 1usize)];
87
88    while let Some((value, depth)) = worklist.pop() {
89        if depth > STRUCTURAL_DEPTH_MAX {
90            return true;
91        }
92        match value {
93            Value::Array(items) => {
94                worklist.extend(items.iter().map(|item| (item, depth + 1)));
95            }
96            Value::Object(members) => {
97                worklist.extend(members.values().map(|member| (member, depth + 1)));
98            }
99            _ => {}
100        }
101    }
102
103    false
104}
105
106/// Builds the structural-depth guard finding.
107///
108/// An absurdly deep descriptor is structurally invalid at the root, so this
109/// reuses `AKB011` — the same code the schema layer emits when the descriptor is
110/// not a well-formed object of the expected shape.
111fn structural_depth_finding() -> Finding {
112    Finding {
113        code: Code::Akb011,
114        path: String::new(),
115        message: format!(
116            "descriptor nesting exceeds the structural depth limit of {STRUCTURAL_DEPTH_MAX}; \
117             it is not a well-formed OpenAKB descriptor"
118        ),
119    }
120}
121
122/// Runs structural validation and opt-in content checks.
123///
124/// # Preconditions
125///
126/// None. Structural validation shares [`validate`]'s depth guard: a descriptor
127/// nested deeper than [`STRUCTURAL_DEPTH_MAX`] is diagnosed as `AKB011` rather
128/// than descending into the recursive schema walk.
129pub async fn validate_with_content(
130    descriptor: &Value,
131    resolver: &dyn Resolver,
132    mode: Mode,
133) -> FullReport {
134    FullReport {
135        validation: validate(descriptor, mode),
136        content: check_content(descriptor, resolver).await,
137    }
138}