Skip to main content

ratify_protocol/
resource_path.rs

1//! Resource-bound authority — the `resource_path` constraint's path model,
2//! segment-boundary matching, and the extension-constraint params value model
3//! (SPEC §5.7.1, §5.7.3). Mirrors Go's `resource_path.go` byte-for-byte.
4//!
5//! Paths are absolute logical POSIX-style paths: they name a location inside
6//! the resource's own namespace, not filesystem paths on any machine. The
7//! verifier compares bytes exactly — no Unicode normalization, no percent
8//! decoding, no case folding. Issuers and adapters pre-normalize (NFC) and
9//! pre-decode BEFORE constructing constraints and verifier context; nothing
10//! transforms a path after verification.
11
12#[cfg(not(feature = "std"))]
13use alloc::{format, string::String, string::ToString, vec::Vec};
14
15use crate::canonical::wire_int::MAX_SAFE_INTEGER;
16use crate::types::{
17    is_canonical_constraint_type, Constraint, ParamsValue, MAX_IDENTIFIER_LENGTH_BYTES,
18    MAX_JSON_NESTING_DEPTH,
19};
20
21/// Validate `p` against the logical path model (SPEC §5.7.3) and return its
22/// comparison form: at most one trailing `/` trimmed, except for the root
23/// path `/` itself. Returns `Err` when `p` is not a valid logical path:
24///
25///   - must begin with `/` (`/` is the only separator)
26///   - no NUL byte, no backslash (rejected, never translated)
27///   - no `.` or `..` segment (rejected outright, never resolved)
28///   - no empty interior segment (`/a//b` is invalid; `/` is valid)
29///
30/// `%` is an ordinary literal byte: the path model has no percent-encoding.
31pub fn normalize_resource_path(p: &str) -> Result<String, String> {
32    if p.is_empty() {
33        return Err("path is empty".to_string());
34    }
35    if !p.starts_with('/') {
36        return Err("path must begin with '/'".to_string());
37    }
38    if p.as_bytes().contains(&0x00) {
39        return Err("path contains a NUL byte".to_string());
40    }
41    if p.contains('\\') {
42        return Err("path contains a backslash; '/' is the only separator".to_string());
43    }
44    if p == "/" {
45        return Ok("/".to_string());
46    }
47    // Trim at most one trailing slash before segment validation: "/docs/" ≡
48    // "/docs", while "/docs//" leaves an empty interior segment and is invalid.
49    let trimmed = p.strip_suffix('/').unwrap_or(p);
50    for seg in trimmed[1..].split('/') {
51        match seg {
52            "" => return Err("path contains an empty segment".to_string()),
53            "." | ".." => {
54                return Err(
55                    "path contains a dot-segment; dot-segments are rejected, never resolved"
56                        .to_string(),
57                )
58            }
59            _ => {}
60        }
61    }
62    Ok(trimmed.to_string())
63}
64
65/// Report whether `requested_path` is at or below `path_prefix` under
66/// segment-boundary prefix matching (SPEC §5.7.3). This is NOT glob matching
67/// and NOT plain string-prefix matching: `/src` matches `/src` and
68/// `/src/a.ts`, never `/src-old/a.ts` or `/srcx`.
69pub fn resource_path_matches(path_prefix: &str, requested_path: &str) -> bool {
70    let prefix = match normalize_resource_path(path_prefix) {
71        Ok(p) => p,
72        Err(_) => return false,
73    };
74    let path = match normalize_resource_path(requested_path) {
75        Ok(p) => p,
76        Err(_) => return false,
77    };
78    if prefix == "/" {
79        // The root prefix matches every valid path.
80        return true;
81    }
82    if path == prefix {
83        return true;
84    }
85    path.starts_with(&format!("{}/", prefix))
86}
87
88/// Report whether two prefixes are comparable under the prefix relation (one
89/// at or below the other). An absent prefix orders as `/` (SPEC §5.7.3).
90pub(crate) fn resource_paths_nested(a: &str, b: &str) -> bool {
91    let a = if a.is_empty() { "/" } else { a };
92    let b = if b.is_empty() { "/" } else { b };
93    resource_path_matches(a, b) || resource_path_matches(b, a)
94}
95
96/// Enforce the issuance rule of SPEC §5.7.3: a certificate's `resource_path`
97/// constraints must be jointly satisfiable. Rejects constraint sets naming
98/// different `resource_id`s, and same-resource sets whose prefixes do not
99/// form a nested chain under the prefix relation. Individual constraints are
100/// also validated (non-empty `resource_id` within `MAX_IDENTIFIER_LENGTH_BYTES`;
101/// well-formed `path_prefix`).
102///
103/// Decoders do NOT call this — wire compatibility is not conditioned on
104/// issuance hygiene; verification denies unsatisfiable sets fail-closed.
105pub fn validate_resource_constraints(constraints: &[Constraint]) -> Result<(), String> {
106    let mut resource_id: Option<&str> = None;
107    let mut prefixes: Vec<&str> = Vec::new();
108    for (i, c) in constraints.iter().enumerate() {
109        if c.kind != "resource_path" {
110            continue;
111        }
112        if c.resource_id.is_empty() {
113            return Err(format!(
114                "constraint[{}]: resource_path requires a non-empty resource_id",
115                i
116            ));
117        }
118        if c.resource_id.len() > MAX_IDENTIFIER_LENGTH_BYTES {
119            return Err(format!(
120                "constraint[{}]: resource_id is {} bytes, exceeding MAX_IDENTIFIER_LENGTH_BYTES ({})",
121                i,
122                c.resource_id.len(),
123                MAX_IDENTIFIER_LENGTH_BYTES
124            ));
125        }
126        let this_prefix = c.path_prefix.as_deref().unwrap_or("");
127        if !this_prefix.is_empty() {
128            if let Err(e) = normalize_resource_path(this_prefix) {
129                return Err(format!("constraint[{}]: invalid path_prefix: {}", i, e));
130            }
131        }
132        match resource_id {
133            None => resource_id = Some(&c.resource_id),
134            Some(rid) if c.resource_id != rid => {
135                return Err(format!(
136                    "constraint[{}]: certificate carries resource_path constraints naming different resource_ids — jointly unsatisfiable (SPEC §5.7.3); issue separate certificates",
137                    i
138                ));
139            }
140            _ => {}
141        }
142        for prev in &prefixes {
143            if !resource_paths_nested(prev, this_prefix) {
144                return Err(format!(
145                    "constraint[{}]: same-resource path_prefix values \"{}\" and \"{}\" do not nest — jointly unsatisfiable (SPEC §5.7.3); narrow to one prefix or issue separate certificates",
146                    i, prev, this_prefix
147                ));
148            }
149        }
150        prefixes.push(this_prefix);
151    }
152    Ok(())
153}
154
155/// Enforce the extension-constraint params value model (SPEC §5.7.1): null,
156/// booleans, strings, safe integers (|n| ≤ 2^53−1), and arrays/objects of
157/// these. `depth` is the container nesting already consumed; nesting beyond
158/// `MAX_JSON_NESTING_DEPTH` is rejected.
159///
160/// The [`ParamsValue`] type cannot represent floats or raw bytes, so the
161/// remaining checks are the safe-integer bound and the nesting depth.
162pub fn validate_params_value(v: &ParamsValue, depth: usize) -> Result<(), String> {
163    if depth > MAX_JSON_NESTING_DEPTH {
164        return Err(format!(
165            "params nesting exceeds MAX_JSON_NESTING_DEPTH ({})",
166            MAX_JSON_NESTING_DEPTH
167        ));
168    }
169    match v {
170        ParamsValue::Null | ParamsValue::Bool(_) | ParamsValue::Str(_) => Ok(()),
171        ParamsValue::Int(n) => {
172            if *n > MAX_SAFE_INTEGER || *n < -MAX_SAFE_INTEGER {
173                return Err(
174                    "params integer exceeds the safe-integer range; carry it as a decimal string"
175                        .to_string(),
176                );
177            }
178            Ok(())
179        }
180        ParamsValue::Array(items) => {
181            for item in items {
182                validate_params_value(item, depth + 1)?;
183            }
184            Ok(())
185        }
186        ParamsValue::Object(map) => {
187            for item in map.values() {
188                validate_params_value(item, depth + 1)?;
189            }
190            Ok(())
191        }
192    }
193}
194
195/// Validate a constraint's `params` field against the value model and the
196/// canonical-type restriction (SPEC §5.7.1). Shared by issuance and decode.
197pub fn validate_constraint_params(c: &Constraint) -> Result<(), String> {
198    if let Some(params) = &c.params {
199        if is_canonical_constraint_type(&c.kind) {
200            return Err(format!(
201                "canonical constraint type \"{}\" must not carry params",
202                c.kind
203            ));
204        }
205        // The params object is the depth-0 container (Go: ValidateParamsValue
206        // on the map iterates its values at depth+1), so values start at 1.
207        for value in params.values() {
208            validate_params_value(value, 1)?;
209        }
210    }
211    Ok(())
212}