#[cfg(not(feature = "std"))]
use alloc::{format, string::String, string::ToString, vec::Vec};
use crate::canonical::wire_int::MAX_SAFE_INTEGER;
use crate::types::{
is_canonical_constraint_type, Constraint, ParamsValue, MAX_IDENTIFIER_LENGTH_BYTES,
MAX_JSON_NESTING_DEPTH,
};
pub fn normalize_resource_path(p: &str) -> Result<String, String> {
if p.is_empty() {
return Err("path is empty".to_string());
}
if !p.starts_with('/') {
return Err("path must begin with '/'".to_string());
}
if p.as_bytes().contains(&0x00) {
return Err("path contains a NUL byte".to_string());
}
if p.contains('\\') {
return Err("path contains a backslash; '/' is the only separator".to_string());
}
if p == "/" {
return Ok("/".to_string());
}
let trimmed = p.strip_suffix('/').unwrap_or(p);
for seg in trimmed[1..].split('/') {
match seg {
"" => return Err("path contains an empty segment".to_string()),
"." | ".." => {
return Err(
"path contains a dot-segment; dot-segments are rejected, never resolved"
.to_string(),
)
}
_ => {}
}
}
Ok(trimmed.to_string())
}
pub fn resource_path_matches(path_prefix: &str, requested_path: &str) -> bool {
let prefix = match normalize_resource_path(path_prefix) {
Ok(p) => p,
Err(_) => return false,
};
let path = match normalize_resource_path(requested_path) {
Ok(p) => p,
Err(_) => return false,
};
if prefix == "/" {
return true;
}
if path == prefix {
return true;
}
path.starts_with(&format!("{}/", prefix))
}
fn resource_paths_nested(a: &str, b: &str) -> bool {
let a = if a.is_empty() { "/" } else { a };
let b = if b.is_empty() { "/" } else { b };
resource_path_matches(a, b) || resource_path_matches(b, a)
}
pub fn validate_resource_constraints(constraints: &[Constraint]) -> Result<(), String> {
let mut resource_id: Option<&str> = None;
let mut prefixes: Vec<&str> = Vec::new();
for (i, c) in constraints.iter().enumerate() {
if c.kind != "resource_path" {
continue;
}
if c.resource_id.is_empty() {
return Err(format!(
"constraint[{}]: resource_path requires a non-empty resource_id",
i
));
}
if c.resource_id.len() > MAX_IDENTIFIER_LENGTH_BYTES {
return Err(format!(
"constraint[{}]: resource_id is {} bytes, exceeding MAX_IDENTIFIER_LENGTH_BYTES ({})",
i,
c.resource_id.len(),
MAX_IDENTIFIER_LENGTH_BYTES
));
}
let this_prefix = c.path_prefix.as_deref().unwrap_or("");
if !this_prefix.is_empty() {
if let Err(e) = normalize_resource_path(this_prefix) {
return Err(format!("constraint[{}]: invalid path_prefix: {}", i, e));
}
}
match resource_id {
None => resource_id = Some(&c.resource_id),
Some(rid) if c.resource_id != rid => {
return Err(format!(
"constraint[{}]: certificate carries resource_path constraints naming different resource_ids — jointly unsatisfiable (SPEC §5.7.3); issue separate certificates",
i
));
}
_ => {}
}
for prev in &prefixes {
if !resource_paths_nested(prev, this_prefix) {
return Err(format!(
"constraint[{}]: same-resource path_prefix values \"{}\" and \"{}\" do not nest — jointly unsatisfiable (SPEC §5.7.3); narrow to one prefix or issue separate certificates",
i, prev, this_prefix
));
}
}
prefixes.push(this_prefix);
}
Ok(())
}
pub fn validate_params_value(v: &ParamsValue, depth: usize) -> Result<(), String> {
if depth > MAX_JSON_NESTING_DEPTH {
return Err(format!(
"params nesting exceeds MAX_JSON_NESTING_DEPTH ({})",
MAX_JSON_NESTING_DEPTH
));
}
match v {
ParamsValue::Null | ParamsValue::Bool(_) | ParamsValue::Str(_) => Ok(()),
ParamsValue::Int(n) => {
if *n > MAX_SAFE_INTEGER || *n < -MAX_SAFE_INTEGER {
return Err(
"params integer exceeds the safe-integer range; carry it as a decimal string"
.to_string(),
);
}
Ok(())
}
ParamsValue::Array(items) => {
for item in items {
validate_params_value(item, depth + 1)?;
}
Ok(())
}
ParamsValue::Object(map) => {
for item in map.values() {
validate_params_value(item, depth + 1)?;
}
Ok(())
}
}
}
pub fn validate_constraint_params(c: &Constraint) -> Result<(), String> {
if let Some(params) = &c.params {
if is_canonical_constraint_type(&c.kind) {
return Err(format!(
"canonical constraint type \"{}\" must not carry params",
c.kind
));
}
for value in params.values() {
validate_params_value(value, 1)?;
}
}
Ok(())
}