use std::collections::BTreeSet;
use serde_json::{json, Map, Value};
use crate::error::{CoreError, Result};
use crate::time::{parse_protocol_time_ns, MAX_CLOCK_SKEW_SECONDS};
pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991;
pub const MAX_JSON_NESTING: usize = 128;
pub const MAX_CHAIN_BYTES: usize = 1024 * 1024;
const NS_PER_SECOND: i128 = 1_000_000_000;
const MAX_DURATION_DIGITS: usize = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Dimension {
Action,
Target,
Resource,
Time,
Rate,
Policy,
}
impl Dimension {
pub fn as_str(self) -> &'static str {
match self {
Dimension::Action => "action",
Dimension::Target => "target",
Dimension::Resource => "resource",
Dimension::Time => "time",
Dimension::Rate => "rate",
Dimension::Policy => "policy",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DelegationReject {
ScopeExceedsParent { dimension: Dimension },
VerifierBudgetExceeded { limit: String },
DelegationRevoked { link_index: usize },
SubjectIssuerMismatch { link_index: usize },
UntrustedPrincipal,
OutsideValidityWindow,
Malformed { detail: String },
}
impl DelegationReject {
pub fn code(&self) -> &'static str {
match self {
DelegationReject::ScopeExceedsParent { .. } => "scope_exceeds_parent",
DelegationReject::VerifierBudgetExceeded { .. } => "verifier_budget_exceeded",
DelegationReject::DelegationRevoked { .. } => "delegation_revoked",
DelegationReject::SubjectIssuerMismatch { .. } => "subject_issuer_mismatch",
DelegationReject::UntrustedPrincipal => "untrusted_principal",
DelegationReject::OutsideValidityWindow => "outside_validity_window",
DelegationReject::Malformed { .. } => "malformed_delegation",
}
}
}
#[derive(Debug, Clone, Default)]
pub struct VerifierBudget {
pub max_depth: Option<usize>,
pub max_cumulative_ttl_seconds: Option<i64>,
}
type DResult = std::result::Result<(), DelegationReject>;
pub fn as_int(v: &Value, low: i64, high: i64) -> Option<i64> {
let Value::Number(n) = v else {
return None;
};
let value: i64 = if let Some(i) = n.as_i64() {
i
} else if n.as_u64().is_some() {
return None; } else {
let f = n.as_f64()?;
if !f.is_finite() || f.fract() != 0.0 || f.abs() > MAX_SAFE_INTEGER as f64 {
return None;
}
f as i64
};
(low..=high).contains(&value).then_some(value)
}
pub fn json_nesting_exceeds(value: &Value, limit: usize) -> bool {
let mut stack: Vec<(&Value, usize)> = vec![(value, 0)];
while let Some((item, depth)) = stack.pop() {
let children: Box<dyn Iterator<Item = &Value>> = match item {
Value::Array(a) => Box::new(a.iter()),
Value::Object(o) => Box::new(o.values()),
_ => continue,
};
let depth = depth + 1;
if depth > limit {
return true;
}
for child in children {
if child.is_array() || child.is_object() {
stack.push((child, depth));
}
}
}
false
}
pub fn encoded_size(value: &Value) -> usize {
crate::jcs::canonicalize(value).len()
}
pub fn chain_budget_exceeded(
chain: &Value,
max_depth: Option<usize>,
) -> std::result::Result<Option<&'static str>, String> {
if let (Some(max), Some(links)) = (max_depth, chain.as_array()) {
if links.len() > max {
return Ok(Some("depth"));
}
}
if json_nesting_exceeds(chain, MAX_JSON_NESTING) {
return Err("delegation chain nests too deeply".into());
}
if encoded_size(chain) > MAX_CHAIN_BYTES {
return Ok(Some("size"));
}
Ok(None)
}
fn is_number(v: &Value) -> bool {
matches!(v, Value::Number(_))
}
pub fn json_equal(a: &Value, b: &Value) -> bool {
match (a, b) {
(Value::Number(x), Value::Number(y)) => {
if let (Some(i), Some(j)) = (x.as_i64(), y.as_i64()) {
return i == j;
}
if let (Some(i), Some(j)) = (x.as_u64(), y.as_u64()) {
return i == j;
}
match (x.as_f64(), y.as_f64()) {
(Some(i), Some(j)) => i == j,
_ => false,
}
}
(Value::Array(x), Value::Array(y)) => {
x.len() == y.len() && x.iter().zip(y).all(|(i, j)| json_equal(i, j))
}
(Value::Object(x), Value::Object(y)) => {
x.len() == y.len()
&& x.iter()
.all(|(k, v)| y.get(k).map(|w| json_equal(v, w)).unwrap_or(false))
}
_ => a == b,
}
}
fn intent(link: &Value) -> Option<&Map<String, Value>> {
link.get("intent").and_then(|i| i.as_object())
}
fn string_set(v: &Value) -> Result<BTreeSet<String>> {
match v {
Value::String(s) => Ok(BTreeSet::from([s.clone()])),
Value::Array(arr) => {
let mut set = BTreeSet::new();
for item in arr {
match item.as_str() {
Some(s) => {
set.insert(s.to_string());
}
None => {
return Err(CoreError::Json(
"action/target array must be strings".into(),
))
}
}
}
Ok(set)
}
_ => Err(CoreError::Json(
"action/target must be a string or array of strings".into(),
)),
}
}
pub fn resource_is_unsafe(resource: &str) -> bool {
let lowered = resource.to_ascii_lowercase();
if resource.contains('\\') || lowered.contains("%2f") || lowered.contains("%5c") {
return true;
}
if resource.bytes().any(|c| c < 0x20 || c == 0x7f) {
return true;
}
let path = lowered.split(['?', '#']).next().unwrap_or("");
path.split('/').any(|segment| {
let s = segment.replace("%2e", ".");
s == "." || s == ".."
})
}
pub fn resource_within(child: &str, parent: &str) -> bool {
if resource_is_unsafe(child) {
return false;
}
let c = child.trim_end_matches('/');
let p = parent.trim_end_matches('/');
if c == p {
return true;
}
c.len() > p.len() && c.starts_with(p) && c.as_bytes()[p.len()] == b'/'
}
pub fn parse_duration_seconds(s: &str) -> Result<i64> {
let bad = || {
CoreError::Json(format!(
"invalid duration: {:?}",
s.chars().take(64).collect::<String>()
))
};
let b = s.as_bytes();
if b.first() != Some(&b'P') || s == "P" || s == "PT" || s.ends_with('T') {
return Err(bad());
}
const DATE: [(u8, i64); 2] = [(b'M', 2_592_000), (b'D', 86_400)];
const TIME: [(u8, i64); 3] = [(b'H', 3_600), (b'M', 60), (b'S', 1)];
let mut units: &[(u8, i64)] = &DATE;
let mut in_time = false;
let mut total: i64 = 0;
let mut saw_field = false;
let mut i = 1usize;
while i < b.len() {
if b[i] == b'T' {
if in_time {
return Err(bad());
}
in_time = true;
units = &TIME;
i += 1;
continue;
}
let start = i;
while i < b.len() && b[i].is_ascii_digit() {
i += 1;
}
let digits = &s[start..i];
if digits.is_empty() || i >= b.len() {
return Err(bad());
}
if digits.len() > MAX_DURATION_DIGITS {
return Err(CoreError::Json("duration field is too large".into()));
}
let unit = b[i];
let Some(pos) = units.iter().position(|(u, _)| *u == unit) else {
return Err(bad());
};
let n: i64 = digits.parse().map_err(|_| bad())?;
total = n
.checked_mul(units[pos].1)
.and_then(|v| total.checked_add(v))
.ok_or_else(|| CoreError::Json("duration is too large".into()))?;
units = &units[pos + 1..];
saw_field = true;
i += 1;
}
if !saw_field {
return Err(bad());
}
if total > MAX_SAFE_INTEGER {
return Err(CoreError::Json("duration is too large".into()));
}
Ok(total)
}
fn parse_rate(rate: &Value) -> Result<(i64, i64)> {
let obj = rate
.as_object()
.ok_or_else(|| CoreError::Json("rate must be an object".into()))?;
let limit = obj
.get("limit")
.and_then(|v| as_int(v, 0, MAX_SAFE_INTEGER))
.ok_or_else(|| {
CoreError::Json("rate.limit must be an integer from 0 to 2^53 - 1".into())
})?;
let window = obj
.get("window")
.and_then(|v| v.as_str())
.ok_or_else(|| CoreError::Json("rate.window must be an ISO-8601 duration".into()))?;
let secs = parse_duration_seconds(window)?;
if secs <= 0 {
return Err(CoreError::Json("rate.window must be positive".into()));
}
Ok((limit, secs))
}
pub fn rate_within(
child_limit: i64,
child_window: i64,
parent_limit: i64,
parent_window: i64,
) -> bool {
if child_limit < 0 || parent_limit < 0 || child_window <= 0 || parent_window <= 0 {
return false;
}
let (cl, cw, pl, pw) = (
i128::from(child_limit),
i128::from(child_window),
i128::from(parent_limit),
i128::from(parent_window),
);
let repeats = (pw + cw - 1) / cw; cl <= pl && cl * repeats <= pl
}
fn policy_not_weaker(parent: &Value, child: &Value) -> bool {
let (pobj, cobj) = match (parent.as_object(), child.as_object()) {
(Some(p), Some(c)) => (p, c),
_ => return false, };
for (k, pv) in pobj {
let Some(cv) = cobj.get(k) else {
return false; };
match (is_number(pv), is_number(cv)) {
(true, true) => {
let (Some(pn), Some(cn)) = (pv.as_f64(), cv.as_f64()) else {
return false;
};
let weaker = if k.starts_with("max") {
cn > pn } else if k.starts_with("min") {
cn < pn } else {
!json_equal(pv, cv) };
if weaker {
return false;
}
}
(true, false) | (false, true) => return false, (false, false) => {
if !json_equal(pv, cv) {
return false; }
}
}
}
true
}
fn bound(link: &Value, key: &str) -> Result<Option<i128>> {
match link.get(key) {
None => Ok(None),
Some(Value::String(s)) => Ok(Some(parse_protocol_time_ns(s)?)),
Some(_) => Err(CoreError::Json(format!("{key} must be a time string"))),
}
}
fn window(link: &Value) -> Result<(Option<i128>, Option<i128>)> {
Ok((bound(link, "validFrom")?, bound(link, "validUntil")?))
}
pub fn malformed_dimension(link: &Value) -> Option<Dimension> {
let Some(obj) = link.as_object() else {
return Some(Dimension::Action);
};
let intent = match obj.get("intent") {
None => None,
Some(Value::Object(i)) => Some(i),
Some(_) => return Some(Dimension::Action),
};
if let Some(i) = intent {
for (key, dim) in [("action", Dimension::Action), ("target", Dimension::Target)] {
if let Some(v) = i.get(key) {
if string_set(v).is_err() {
return Some(dim);
}
}
}
if let Some(res) = i.get("resource") {
match res.as_str() {
Some(r) if !resource_is_unsafe(r) => {}
_ => return Some(Dimension::Resource),
}
}
}
if window(link).is_err() {
return Some(Dimension::Time);
}
if let Some(rate) = obj.get("rate") {
if parse_rate(rate).is_err() {
return Some(Dimension::Rate);
}
}
if let Some(policy) = obj.get("policy") {
if !policy.is_object() || json_nesting_exceeds(policy, MAX_JSON_NESTING) {
return Some(Dimension::Policy);
}
}
None
}
pub fn non_expansion(parent: &Value, child: &Value) -> std::result::Result<(), Dimension> {
if let Some(dim) = malformed_dimension(child) {
return Err(dim);
}
if let Some(dim) = malformed_dimension(parent) {
return Err(dim);
}
let empty = Map::new();
let p_intent = intent(parent).unwrap_or(&empty);
let c_intent = intent(child).unwrap_or(&empty);
for (key, dim) in [("action", Dimension::Action), ("target", Dimension::Target)] {
if let (Some(c), Some(p)) = (c_intent.get(key), p_intent.get(key)) {
match (string_set(c), string_set(p)) {
(Ok(cs), Ok(ps)) if cs.is_subset(&ps) => {}
_ => return Err(dim),
}
}
}
if let (Some(c), Some(p)) = (c_intent.get("resource"), p_intent.get("resource")) {
match (c.as_str(), p.as_str()) {
(Some(cr), Some(pr)) if resource_within(cr, pr) => {}
_ => return Err(Dimension::Resource),
}
}
let (Ok((cf, cu)), Ok((pf, pu))) = (window(child), window(parent)) else {
return Err(Dimension::Time);
};
if let (Some(f), Some(pf)) = (cf, pf) {
if f < pf {
return Err(Dimension::Time);
}
}
if let (Some(u), Some(pu)) = (cu, pu) {
if u > pu {
return Err(Dimension::Time);
}
}
if let (Some(cr), Some(pr)) = (child.get("rate"), parent.get("rate")) {
let (Ok((c_limit, c_secs)), Ok((p_limit, p_secs))) = (parse_rate(cr), parse_rate(pr))
else {
return Err(Dimension::Rate);
};
if !rate_within(c_limit, c_secs, p_limit, p_secs) {
return Err(Dimension::Rate);
}
}
let p_pol = parent.get("policy").filter(|p| !p.is_null());
if let (Some(cp), Some(pp)) = (child.get("policy"), p_pol) {
if !policy_not_weaker(pp, cp) {
return Err(Dimension::Policy);
}
}
if let Some(cap) = p_pol
.and_then(|p| p.as_object())
.and_then(|p| p.get("maxSpend"))
{
if let Some(amount) = c_intent.get("amount") {
match (amount.as_f64(), cap.as_f64()) {
(Some(a), Some(c)) if a <= c => {}
_ => return Err(Dimension::Policy),
}
}
}
Ok(())
}
pub fn inherit(parent_effective: &Value, child: &Value) -> Value {
let mut out = child.as_object().cloned().unwrap_or_default();
let mut c_intent = child
.get("intent")
.and_then(|i| i.as_object())
.cloned()
.unwrap_or_default();
if let Some(p_intent) = parent_effective.get("intent").and_then(|i| i.as_object()) {
for k in ["action", "target", "resource"] {
if !c_intent.contains_key(k) {
if let Some(v) = p_intent.get(k) {
c_intent.insert(k.into(), v.clone());
}
}
}
}
out.insert("intent".into(), Value::Object(c_intent));
for k in ["rate", "policy", "validFrom", "validUntil"] {
let absent = out.get(k).map(|v| v.is_null()).unwrap_or(true);
if absent {
if let Some(v) = parent_effective.get(k).filter(|v| !v.is_null()) {
out.insert(k.into(), v.clone());
}
}
}
Value::Object(out)
}
pub fn first_broader_step(views: &[Value]) -> std::result::Result<(), Dimension> {
let Some(first) = views.first() else {
return Ok(());
};
if let Some(dim) = malformed_dimension(first) {
return Err(dim);
}
let mut effective = first.clone();
for child in &views[1..] {
non_expansion(&effective, child)?;
effective = inherit(&effective, child);
}
Ok(())
}
fn link_str<'a>(link: &'a Value, key: &str) -> Option<&'a str> {
link.get(key).and_then(|v| v.as_str())
}
fn malformed(detail: impl Into<String>) -> DelegationReject {
DelegationReject::Malformed {
detail: detail.into(),
}
}
pub fn validate_chain(
chain: &[Value],
trusted_roots: Option<&[String]>,
revoked_link_indices: &[usize],
budget: &VerifierBudget,
now_iso: &str,
clock_skew_seconds: i64,
) -> DResult {
if !(0..=MAX_CLOCK_SKEW_SECONDS).contains(&clock_skew_seconds) {
return Err(malformed(format!(
"clockSkewSeconds must be an integer from 0 to {MAX_CLOCK_SKEW_SECONDS}"
)));
}
let skew = i128::from(clock_skew_seconds) * NS_PER_SECOND;
let now = parse_protocol_time_ns(now_iso).map_err(|e| malformed(format!("nowIso: {e}")))?;
if chain.is_empty() {
return Err(malformed("empty delegation chain"));
}
let chain_value = Value::Array(chain.to_vec());
match chain_budget_exceeded(&chain_value, budget.max_depth) {
Ok(None) => {}
Ok(Some(limit)) => {
return Err(DelegationReject::VerifierBudgetExceeded {
limit: limit.into(),
})
}
Err(detail) => return Err(malformed(detail)),
}
for (i, link) in chain.iter().enumerate() {
let shape_ok = link.is_object()
&& link_str(link, "issuer").is_some()
&& link_str(link, "subject").is_some()
&& link.get("intent").map(|v| v.is_object()).unwrap_or(true);
if !shape_ok {
return Err(malformed(format!("link {i} malformed")));
}
}
if let Some(roots) = trusted_roots {
let root_issuer = link_str(&chain[0], "issuer").unwrap_or("");
if !roots
.iter()
.any(|r| crate::delegation::root_matches(r, root_issuer))
{
return Err(DelegationReject::UntrustedPrincipal);
}
}
if let Some(&idx) = revoked_link_indices.iter().min() {
if idx < chain.len() {
return Err(DelegationReject::DelegationRevoked { link_index: idx });
}
}
if let Some(dimension) = malformed_dimension(&chain[0]) {
return Err(DelegationReject::ScopeExceedsParent { dimension });
}
let mut effective = chain[0].clone();
let mut windows = vec![window(&chain[0]).map_err(|e| malformed(e.to_string()))?];
for i in 1..chain.len() {
let parent = &chain[i - 1];
let child = &chain[i];
if link_str(parent, "subject") != link_str(child, "issuer") {
return Err(DelegationReject::SubjectIssuerMismatch { link_index: i });
}
non_expansion(&effective, child)
.map_err(|dimension| DelegationReject::ScopeExceedsParent { dimension })?;
effective = inherit(&effective, child);
windows.push(window(&effective).map_err(|e| malformed(e.to_string()))?);
}
let eff_start = windows.iter().filter_map(|w| w.0).max();
let eff_end = windows.iter().filter_map(|w| w.1).min();
if let (Some(f), Some(u)) = (eff_start, eff_end) {
if f > u {
return Err(DelegationReject::OutsideValidityWindow);
}
}
if let Some(f) = eff_start {
if now < f - skew {
return Err(DelegationReject::OutsideValidityWindow);
}
}
if let Some(u) = eff_end {
if now > u + skew {
return Err(DelegationReject::OutsideValidityWindow);
}
}
if let Some(max) = budget.max_cumulative_ttl_seconds {
let exceeded = || DelegationReject::VerifierBudgetExceeded {
limit: "cumulative_ttl".into(),
};
let mut total: i128 = 0;
for (vf, vu) in &windows {
let (Some(f), Some(u)) = (vf, vu) else {
return Err(exceeded());
};
total += (u - f).max(0);
}
if total > i128::from(max) * NS_PER_SECOND {
return Err(exceeded());
}
}
Ok(())
}
pub fn validate_chain_json(request_json: &str) -> String {
let req: Value = match serde_json::from_str(request_json) {
Ok(v) => v,
Err(e) => return verdict_malformed(&format!("request json: {e}")),
};
let Some(req) = req.as_object() else {
return verdict_malformed("request must be a JSON object");
};
let chain: Vec<Value> = match req.get("chain").and_then(|v| v.as_array()) {
Some(c) => c.clone(),
None => return verdict_malformed("missing chain array"),
};
for key in [
"trustedRoots",
"revokedIndices",
"budget",
"nowIso",
"clockSkewSeconds",
] {
if matches!(req.get(key), Some(Value::Null)) {
return verdict_malformed(&format!("{key} must not be null"));
}
}
let trusted_roots: Option<Vec<String>> = match req.get("trustedRoots") {
None => None,
Some(Value::Array(a)) => {
let mut roots = Vec::with_capacity(a.len());
for r in a {
match r.as_str() {
Some(s) => roots.push(s.to_string()),
None => return verdict_malformed("trustedRoots must be a list of strings"),
}
}
Some(roots)
}
Some(_) => return verdict_malformed("trustedRoots must be a list of strings"),
};
let revoked: Vec<usize> = match req.get("revokedIndices") {
None => Vec::new(),
Some(Value::Array(a)) => {
let mut out = Vec::with_capacity(a.len());
for v in a {
match as_int(v, 0, MAX_SAFE_INTEGER) {
Some(n) => out.push(n as usize),
None => {
return verdict_malformed(
"revokedIndices must be integers from 0 to 2^53 - 1",
)
}
}
}
out
}
Some(_) => return verdict_malformed("revokedIndices must be a list of integers"),
};
let mut budget = VerifierBudget::default();
match req.get("budget") {
None => {}
Some(Value::Object(b)) => {
for key in ["maxDepth", "maxCumulativeTtlSeconds"] {
if let Some(v) = b.get(key) {
let Some(n) = as_int(v, 0, MAX_SAFE_INTEGER) else {
return verdict_malformed(&format!(
"budget.{key} must be an integer from 0 to 2^53 - 1"
));
};
if key == "maxDepth" {
budget.max_depth = Some(n as usize);
} else {
budget.max_cumulative_ttl_seconds = Some(n);
}
}
}
}
Some(_) => return verdict_malformed("budget must be an object"),
}
let skew = match req.get("clockSkewSeconds") {
None => 30,
Some(v) => match as_int(v, 0, MAX_CLOCK_SKEW_SECONDS) {
Some(n) => n,
None => {
return verdict_malformed(&format!(
"clockSkewSeconds must be an integer from 0 to {MAX_CLOCK_SKEW_SECONDS}"
))
}
},
};
let now = match req.get("nowIso") {
None => "",
Some(Value::String(s)) => s.as_str(),
Some(_) => return verdict_malformed("nowIso must be a time string"),
};
match validate_chain(
&chain,
trusted_roots.as_deref(),
&revoked,
&budget,
now,
skew,
) {
Ok(()) => json!({ "valid": true }).to_string(),
Err(r) => reject_to_json(&r).to_string(),
}
}
fn verdict_malformed(detail: &str) -> String {
json!({ "valid": false, "code": "malformed_delegation", "detail": detail }).to_string()
}
fn reject_to_json(r: &DelegationReject) -> Value {
let mut v = json!({ "valid": false, "code": r.code() });
let o = v.as_object_mut().unwrap();
match r {
DelegationReject::ScopeExceedsParent { dimension } => {
o.insert("dimension".into(), json!(dimension.as_str()));
}
DelegationReject::VerifierBudgetExceeded { limit } => {
o.insert("limit".into(), json!(limit));
}
DelegationReject::DelegationRevoked { link_index }
| DelegationReject::SubjectIssuerMismatch { link_index } => {
o.insert("linkIndex".into(), json!(link_index));
}
DelegationReject::Malformed { detail } => {
o.insert("detail".into(), json!(detail));
}
DelegationReject::UntrustedPrincipal | DelegationReject::OutsideValidityWindow => {}
}
v
}
pub fn effective_capability(credential: &Value, include_time: bool) -> Value {
let mut effective: Option<Value> = None;
if let Some(links) = credential
.get("credentialSubject")
.and_then(|s| s.get("delegationChain"))
.and_then(Value::as_array)
{
for link in links {
let Some(grant) = link.get("parentCredential").filter(|g| g.is_object()) else {
continue;
};
let view = crate::delegation::capability_view(grant, include_time);
effective = Some(match effective {
None => view,
Some(e) => inherit(&e, &view),
});
}
}
let own = crate::delegation::capability_view(credential, include_time);
match effective {
None => own,
Some(e) => inherit(&e, &own),
}
}
pub fn rules_json(request: &Value) -> Result<Value> {
let arg = |name: &str| request.get(name).unwrap_or(&Value::Null);
let name = request.get("fn").and_then(Value::as_str).unwrap_or("");
let ok = match name {
"capabilityView" => crate::delegation::capability_view(
arg("credential"),
arg("includeTime").as_bool().unwrap_or(true),
),
"nonExpansion" => match non_expansion(arg("parent"), arg("child")) {
Ok(()) => Value::Null,
Err(dim) => json!(dim.as_str()),
},
"inherit" => inherit(arg("parentEffective"), arg("child")),
"encodedSize" => json!(encoded_size(arg("value"))),
"chainBudgetExceeded" => {
let max_depth = arg("maxDepth")
.as_u64()
.and_then(|d| usize::try_from(d).ok());
match chain_budget_exceeded(arg("chain"), max_depth) {
Ok(limit) => json!(limit),
Err(e) => return Ok(json!({ "error": e })),
}
}
"resourceIsUnsafe" => json!(resource_is_unsafe(arg("resource").as_str().unwrap_or(""))),
"resourceWithin" => json!(resource_within(
arg("child").as_str().unwrap_or(""),
arg("parent").as_str().unwrap_or("")
)),
"parseDurationSeconds" => match arg("value").as_str() {
None => return Ok(json!({ "error": "a duration is a string" })),
Some(s) => match parse_duration_seconds(s) {
Ok(n) => json!(n),
Err(e) => {
let msg = e.to_string();
let msg = msg.strip_prefix("json error: ").unwrap_or(&msg).to_string();
return Ok(json!({ "error": msg }));
}
},
},
"rateWithin" => {
let n = |k: &str| arg(k).as_i64().unwrap_or(0);
json!(rate_within(
n("childLimit"),
n("childWindow"),
n("parentLimit"),
n("parentWindow")
))
}
"malformedDimension" => json!(malformed_dimension(arg("link")).map(|d| d.as_str())),
"firstBroaderStep" => {
let views = arg("views").as_array().cloned().unwrap_or_default();
match first_broader_step(&views) {
Ok(()) => Value::Null,
Err(dim) => json!(dim.as_str()),
}
}
"effectiveCapability" => effective_capability(
arg("credential"),
arg("includeTime").as_bool().unwrap_or(true),
),
other => {
return Err(CoreError::Json(format!(
"unknown capability rule {:?}",
other.chars().take(40).collect::<String>()
)))
}
};
Ok(json!({ "ok": ok }))
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn rules_json_answers_every_rule_a_binding_calls() {
let ok = |req: Value| rules_json(&req).unwrap()["ok"].clone();
assert_eq!(
ok(json!({"fn": "resourceWithin", "child": "https://x/a/b", "parent": "https://x/a"})),
json!(true)
);
assert_eq!(
ok(
json!({"fn": "resourceWithin", "child": "https://x/a/../b", "parent": "https://x/a"})
),
json!(false)
);
assert_eq!(
ok(json!({"fn": "resourceIsUnsafe", "resource": "https://x/a%2fb"})),
json!(true)
);
assert_eq!(
ok(json!({"fn": "parseDurationSeconds", "value": "PT1H"})),
json!(3600)
);
assert!(
rules_json(&json!({"fn": "parseDurationSeconds", "value": "PT"})).unwrap()["error"]
.is_string()
);
assert!(
rules_json(&json!({"fn": "parseDurationSeconds", "value": 5})).unwrap()["error"]
.is_string()
);
assert_eq!(
ok(
json!({"fn": "rateWithin", "childLimit": 2, "childWindow": 720, "parentLimit": 10, "parentWindow": 3600})
),
json!(true)
);
assert_eq!(
ok(
json!({"fn": "rateWithin", "childLimit": -1, "childWindow": 1, "parentLimit": 1, "parentWindow": 1})
),
json!(false)
);
assert_eq!(
ok(json!({"fn": "chainBudgetExceeded", "chain": [1, 2, 3], "maxDepth": 2})),
json!("depth")
);
assert_eq!(
ok(json!({"fn": "chainBudgetExceeded", "chain": [1]})),
Value::Null
);
assert_eq!(
ok(json!({"fn": "malformedDimension", "link": {"intent": {"action": null}}})),
json!("action")
);
let views = json!([{"intent": {"action": "read"}}, {"intent": {"action": "write"}}]);
assert_eq!(
ok(json!({"fn": "firstBroaderStep", "views": views})),
json!("action")
);
let grant =
json!({"credentialSubject": {"intent": {"action": "read", "resource": "https://x/a"}}});
let cred = json!({"credentialSubject": {"intent": {"resource": "https://x/a/b"},
"delegationChain": [{"parentCredential": grant}]}});
let eff =
ok(json!({"fn": "effectiveCapability", "credential": cred, "includeTime": false}));
assert_eq!(eff["intent"]["action"], json!("read"));
assert_eq!(eff["intent"]["resource"], json!("https://x/a/b"));
assert!(rules_json(&json!({"fn": "nope"})).is_err());
}
fn link(issuer: &str, subject: &str, intent: Value) -> Value {
json!({
"issuer": issuer,
"subject": subject,
"intent": intent,
"validFrom": "2026-04-26T09:00:00Z",
"validUntil": "2026-04-26T12:00:00Z"
})
}
fn now() -> &'static str {
"2026-04-26T10:00:00Z"
}
#[test]
fn restate_unchanged_is_valid() {
let i = json!({"action":"read","target":"t","resource":"https://x/a"});
let chain = vec![
link("did:web:root", "did:web:a", i.clone()),
link("did:web:a", "did:web:b", i.clone()),
];
assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
}
#[test]
fn resource_narrowing_is_valid() {
let chain = vec![
link(
"did:web:root",
"did:web:a",
json!({"resource":"https://x/a"}),
),
link(
"did:web:a",
"did:web:b",
json!({"resource":"https://x/a/b"}),
),
];
assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
}
#[test]
fn resource_widening_rejected_naming_dimension() {
let chain = vec![
link(
"did:web:root",
"did:web:a",
json!({"resource":"https://x/a/b"}),
),
link("did:web:a", "did:web:b", json!({"resource":"https://x/a"})),
];
let err =
validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
assert_eq!(err.code(), "scope_exceeds_parent");
assert_eq!(
err,
DelegationReject::ScopeExceedsParent {
dimension: Dimension::Resource
}
);
}
#[test]
fn sibling_prefix_is_not_sub_resource() {
assert!(!resource_within("https://x/a2", "https://x/a"));
assert!(resource_within("https://x/a/b", "https://x/a"));
assert!(resource_within("https://x/a", "https://x/a/"));
}
#[test]
fn action_superset_rejected() {
let chain = vec![
link("did:web:root", "did:web:a", json!({"action":"read"})),
link("did:web:a", "did:web:b", json!({"action":["read","write"]})),
];
let err =
validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
assert_eq!(
err,
DelegationReject::ScopeExceedsParent {
dimension: Dimension::Action
}
);
}
#[test]
fn action_subset_ok() {
let chain = vec![
link(
"did:web:root",
"did:web:a",
json!({"action":["read","write"]}),
),
link("did:web:a", "did:web:b", json!({"action":"read"})),
];
assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
}
#[test]
fn rate_widening_rejected() {
let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
a["rate"] = json!({"limit":100,"window":"PT1H"});
let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
b["rate"] = json!({"limit":100,"window":"PT30M"}); let chain = vec![a, b];
let err =
validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
assert_eq!(
err,
DelegationReject::ScopeExceedsParent {
dimension: Dimension::Rate
}
);
}
#[test]
fn rate_narrowing_ok() {
let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
a["rate"] = json!({"limit":100,"window":"PT1H"});
let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
b["rate"] = json!({"limit":50,"window":"PT1H"});
let chain = vec![a, b];
assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
}
#[test]
fn policy_weakening_rejected() {
let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
a["policy"] = json!({"minHeartbeatAgeSeconds":300});
let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
b["policy"] = json!({"minHeartbeatAgeSeconds":100}); let chain = vec![a, b];
let err =
validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
assert_eq!(
err,
DelegationReject::ScopeExceedsParent {
dimension: Dimension::Policy
}
);
}
#[test]
fn policy_dropping_constraint_rejected() {
let mut a = link("did:web:root", "did:web:a", json!({"action":"read"}));
a["policy"] = json!({"minHeartbeatAgeSeconds":300});
let mut b = link("did:web:a", "did:web:b", json!({"action":"read"}));
b["policy"] = json!({"unrelated":true}); let chain = vec![a, b];
assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_err());
}
#[test]
fn time_widening_rejected() {
let chain = vec![
json!({"issuer":"did:web:root","subject":"did:web:a","intent":{"action":"read"},
"validFrom":"2026-04-26T10:00:00Z","validUntil":"2026-04-26T11:00:00Z"}),
json!({"issuer":"did:web:a","subject":"did:web:b","intent":{"action":"read"},
"validFrom":"2026-04-26T09:00:00Z","validUntil":"2026-04-26T12:00:00Z"}),
];
let err = validate_chain(
&chain,
None,
&[],
&VerifierBudget::default(),
"2026-04-26T10:30:00Z",
30,
)
.unwrap_err();
assert_eq!(
err,
DelegationReject::ScopeExceedsParent {
dimension: Dimension::Time
}
);
}
#[test]
fn subject_issuer_mismatch_rejected() {
let i = json!({"action":"read"});
let chain = vec![
link("did:web:root", "did:web:a", i.clone()),
link("did:web:WRONG", "did:web:b", i.clone()),
];
let err =
validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).unwrap_err();
assert_eq!(
err,
DelegationReject::SubjectIssuerMismatch { link_index: 1 }
);
}
#[test]
fn untrusted_root_rejected() {
let i = json!({"action":"read"});
let chain = vec![link("did:web:root", "did:web:a", i)];
let err = validate_chain(
&chain,
Some(&["did:web:other".to_string()]),
&[],
&VerifierBudget::default(),
now(),
30,
)
.unwrap_err();
assert_eq!(err, DelegationReject::UntrustedPrincipal);
}
#[test]
fn cascade_revocation_rejects_whole_chain() {
let i = json!({"action":"read"});
let chain = vec![
link("did:web:root", "did:web:a", i.clone()),
link("did:web:a", "did:web:b", i.clone()),
link("did:web:b", "did:web:c", i.clone()),
];
let err =
validate_chain(&chain, None, &[1], &VerifierBudget::default(), now(), 30).unwrap_err();
assert_eq!(err, DelegationReject::DelegationRevoked { link_index: 1 });
}
#[test]
fn budget_depth_exceeded() {
let i = json!({"action":"read"});
let chain = vec![
link("did:web:root", "did:web:a", i.clone()),
link("did:web:a", "did:web:b", i.clone()),
link("did:web:b", "did:web:c", i.clone()),
];
let budget = VerifierBudget {
max_depth: Some(2),
max_cumulative_ttl_seconds: None,
};
let err = validate_chain(&chain, None, &[], &budget, now(), 30).unwrap_err();
assert_eq!(
err,
DelegationReject::VerifierBudgetExceeded {
limit: "depth".into()
}
);
}
#[test]
fn deep_but_attenuating_chain_is_valid_without_depth_cap() {
let mut chain = Vec::new();
let i = json!({"action":"read","resource":"https://x/a"});
for n in 0..10 {
let issuer = if n == 0 {
"did:web:root".to_string()
} else {
format!("did:web:h{}", n - 1)
};
let subject = format!("did:web:h{n}");
chain.push(link(&issuer, &subject, i.clone()));
}
assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
}
#[test]
fn now_outside_effective_window_rejected() {
let chain = vec![link("did:web:root", "did:web:a", json!({"action":"read"}))];
let err = validate_chain(
&chain,
None,
&[],
&VerifierBudget::default(),
"2026-04-26T20:00:00Z",
30,
)
.unwrap_err();
assert_eq!(err, DelegationReject::OutsideValidityWindow);
}
#[test]
fn absent_child_dimension_inherits_and_passes() {
let chain = vec![
link(
"did:web:root",
"did:web:a",
json!({"action":"read","resource":"https://x/a"}),
),
link(
"did:web:a",
"did:web:b",
json!({"resource":"https://x/a/b"}),
), ];
assert!(validate_chain(&chain, None, &[], &VerifierBudget::default(), now(), 30).is_ok());
}
#[test]
fn duration_parser() {
assert_eq!(parse_duration_seconds("PT1H").unwrap(), 3600);
assert_eq!(parse_duration_seconds("PT30M").unwrap(), 1800);
assert_eq!(parse_duration_seconds("PT1H30M15S").unwrap(), 5415);
assert_eq!(parse_duration_seconds("P1D").unwrap(), 86400);
assert!(parse_duration_seconds("1H").is_err());
assert!(parse_duration_seconds("PT").is_err());
}
#[test]
fn duration_parser_is_strict_and_never_overflows() {
assert_eq!(parse_duration_seconds("P1M").unwrap(), 2_592_000);
assert_eq!(parse_duration_seconds("P1DT1S").unwrap(), 86_401);
for bad in [
"P",
"PT",
"P1DT",
"P1H",
"PT1D",
"P1D1M",
"PT1S1M",
"P\u{0661}D",
"PT-1S",
"PT1.5S",
"p1D",
"P1DTT1S",
] {
assert!(parse_duration_seconds(bad).is_err(), "{bad}");
}
assert!(parse_duration_seconds("P9999999999999999D").is_err());
assert!(parse_duration_seconds("P99999999999999999D").is_err());
assert!(parse_duration_seconds(&format!("PT{}S", "9".repeat(40))).is_err());
}
#[test]
fn unsafe_resources_never_sit_inside_a_parent() {
for r in [
"https://x/a/../b",
"https://x/a/./b",
"https://x/a/%2e%2E/b",
"https://x/a/.%2e",
"https://x/a\\..\\b",
"https://x/a/..%2Fb",
"https://x/a/%5c",
"https://x/a/\u{0007}",
] {
assert!(resource_is_unsafe(r), "{r}");
assert!(!resource_within(r, "https://x/a"), "{r}");
}
assert!(resource_within("https://x/a/b?next=../c", "https://x/a"));
}
#[test]
fn integers_are_whole_numbers_in_range() {
assert_eq!(as_int(&json!(2), 0, 10), Some(2));
assert_eq!(as_int(&json!(2.0), 0, 10), Some(2));
for v in [
json!(2.5),
json!(-1),
json!(11),
json!(true),
json!("2"),
Value::Null,
] {
assert_eq!(as_int(&v, 0, 10), None, "{v}");
}
assert_eq!(as_int(&json!(u64::MAX), 0, MAX_SAFE_INTEGER), None);
let verdict: Value = serde_json::from_str(&validate_chain_json(
&json!({"chain": [
{"issuer":"did:web:r","subject":"did:web:a","intent":{"action":"read"}},
{"issuer":"did:web:a","subject":"did:web:b","intent":{"action":"read"}}],
"revokedIndices": [1.0], "nowIso": "2026-04-26T10:00:00Z"})
.to_string(),
))
.unwrap();
assert_eq!(verdict["code"], json!("delegation_revoked"));
let verdict: Value = serde_json::from_str(&validate_chain_json(
&json!({"chain": [{"issuer":"did:web:r","subject":"did:web:a"}],
"budget": {"maxDepth": -1}, "nowIso": "2026-04-26T10:00:00Z"})
.to_string(),
))
.unwrap();
assert_eq!(verdict["code"], json!("malformed_delegation"));
}
}