Skip to main content

solid_pod_rs/wac/
mod.rs

1//! Web Access Control evaluator.
2//!
3//! Parses JSON-LD / Turtle ACL documents and evaluates whether a given
4//! agent URI is granted a specific access mode on a resource path.
5//! WAC 2.0 conditions (client / issuer gates) are supported via the
6//! `conditions` submodule.
7//!
8//! Reference: <https://solid.github.io/web-access-control-spec/> +
9//! <https://webacl.org/secure-access-conditions/>
10
11use serde::{Deserialize, Serialize};
12
13use crate::error::PodError;
14
15// ---------------------------------------------------------------------------
16// Parser DoS bounds.
17//
18// The ACL parsers run on untrusted bodies uploaded by external clients.
19// Without bounds, a pathological document can either exhaust memory
20// (oversize Turtle) or blow the parser stack (deeply nested JSON-LD).
21// JSS's `n3`-based parser is similarly bounded; we match for parity and
22// defence-in-depth.
23// ---------------------------------------------------------------------------
24
25/// Maximum byte length of an ACL document body. WAC 2.0 ACLs are flat
26/// declarative documents; 1 MiB is generous and prevents O(n²) parser
27/// blowup. Configurable at parse time via `JSS_MAX_ACL_BYTES`.
28pub const MAX_ACL_BYTES: usize = 1_048_576;
29
30/// Maximum JSON-LD nesting depth. Solid ACLs are ≤4 levels deep in
31/// practice; 32 is a generous fail-closed cap against depth bombs.
32/// Configurable via `JSS_MAX_ACL_JSON_DEPTH`.
33pub const MAX_ACL_JSON_DEPTH: usize = 32;
34
35/// Count the structural nesting depth of a JSON byte slice without
36/// parsing it. Ignores braces/brackets inside string literals. Fails
37/// fast as soon as `max` is exceeded so pathological documents never
38/// reach `serde_json`, which allocates stack proportional to depth.
39fn check_json_depth(body: &[u8], max: usize) -> Result<(), PodError> {
40    let mut depth: usize = 0;
41    let mut in_str = false;
42    let mut esc = false;
43    for &b in body {
44        if in_str {
45            if esc {
46                esc = false;
47            } else if b == b'\\' {
48                esc = true;
49            } else if b == b'"' {
50                in_str = false;
51            }
52            continue;
53        }
54        match b {
55            b'"' => in_str = true,
56            b'{' | b'[' => {
57                depth = depth.saturating_add(1);
58                if depth > max {
59                    return Err(PodError::BadRequest(format!(
60                        "ACL JSON depth exceeds {max}"
61                    )));
62                }
63            }
64            b'}' | b']' => {
65                depth = depth.saturating_sub(1);
66            }
67            _ => {}
68        }
69    }
70    Ok(())
71}
72
73/// Parse a JSON-LD ACL body with byte and depth bounds enforced.
74///
75/// The resolver in [`StorageAclResolver`] routes through this helper so
76/// fuzzed or malicious ACLs are rejected before `serde_json` is invoked.
77/// To supply explicit limits, use [`parse_jsonld_acl_with_limits`].
78pub fn parse_jsonld_acl(body: &[u8]) -> Result<AclDocument, PodError> {
79    let limit = std::env::var("JSS_MAX_ACL_BYTES")
80        .ok()
81        .and_then(|v| v.parse().ok())
82        .unwrap_or(MAX_ACL_BYTES);
83    let depth_limit = std::env::var("JSS_MAX_ACL_JSON_DEPTH")
84        .ok()
85        .and_then(|v| v.parse().ok())
86        .unwrap_or(MAX_ACL_JSON_DEPTH);
87    parse_jsonld_acl_with_limits(body, limit, depth_limit)
88}
89
90/// Parse a JSON-LD ACL body with caller-supplied byte and depth limits.
91///
92/// Equivalent to [`parse_jsonld_acl`] but accepts limits as parameters
93/// instead of reading from environment variables. Returns
94/// `PodError::PayloadTooLarge` (HTTP 413 equivalent) when
95/// `body.len() > max_bytes`.
96pub fn parse_jsonld_acl_with_limits(
97    body: &[u8],
98    max_bytes: usize,
99    max_depth: usize,
100) -> Result<AclDocument, PodError> {
101    if body.len() > max_bytes {
102        return Err(PodError::PayloadTooLarge(format!(
103            "ACL body exceeds {max_bytes} bytes"
104        )));
105    }
106    check_json_depth(body, max_depth)?;
107    serde_json::from_slice::<AclDocument>(body)
108        .map_err(|e| PodError::AclParse(format!("JSON-LD ACL parse: {e}")))
109}
110
111// Sub-modules — each kept under 500 LOC.
112pub mod anchor;
113pub mod client;
114pub mod conditions;
115pub mod document;
116pub mod evaluator;
117pub mod issuer;
118pub mod origin;
119pub mod parser;
120pub mod payment;
121pub mod resolver;
122pub mod serializer;
123
124// ---------------------------------------------------------------------------
125// Re-exports (preserve the pre-split public surface verbatim so no
126// consumer import breaks).
127// ---------------------------------------------------------------------------
128
129pub use anchor::{anchor_mode_of, AnchorMode, ProvenanceAnchorBody, ProvenanceAnchorEvaluator};
130pub use client::{ClientConditionBody, ClientConditionEvaluator};
131pub use conditions::{
132    validate_acl_document, validate_for_write, Condition, ConditionDispatcher, ConditionOutcome,
133    ConditionRegistry, EmptyDispatcher, RequestContext, UnsupportedCondition,
134};
135pub use document::{AclAuthorization, AclDocument, IdOrIds, IdRef};
136pub use evaluator::{
137    evaluate_access, evaluate_access_ctx, evaluate_access_ctx_with_registry,
138    evaluate_access_with_groups, granted_payment_cost, GroupMembership, StaticGroupMembership,
139};
140pub use issuer::{IssuerConditionBody, IssuerConditionEvaluator};
141pub use origin::{check_origin, extract_origin_patterns, Origin, OriginDecision, OriginPattern};
142pub use parser::{parse_turtle_acl, parse_turtle_acl_with_limit};
143pub use payment::{total_payment_cost, PaymentConditionBody, PaymentConditionEvaluator};
144pub use resolver::AclResolver;
145#[cfg(feature = "tokio-runtime")]
146pub use resolver::StorageAclResolver;
147pub use serializer::serialize_turtle_acl;
148
149/// Access modes defined by WAC.
150#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
151pub enum AccessMode {
152    Read,
153    Write,
154    Append,
155    Control,
156}
157
158pub const ALL_MODES: &[AccessMode] = &[
159    AccessMode::Read,
160    AccessMode::Write,
161    AccessMode::Append,
162    AccessMode::Control,
163];
164
165pub(crate) fn map_mode(mode_ref: &str) -> &'static [AccessMode] {
166    match mode_ref {
167        "acl:Read" | "http://www.w3.org/ns/auth/acl#Read" => &[AccessMode::Read],
168        "acl:Write" | "http://www.w3.org/ns/auth/acl#Write" => {
169            &[AccessMode::Write, AccessMode::Append]
170        }
171        "acl:Append" | "http://www.w3.org/ns/auth/acl#Append" => &[AccessMode::Append],
172        "acl:Control" | "http://www.w3.org/ns/auth/acl#Control" => &[AccessMode::Control],
173        _ => &[],
174    }
175}
176
177pub fn method_to_mode(method: &str) -> AccessMode {
178    match method.to_uppercase().as_str() {
179        "GET" | "HEAD" => AccessMode::Read,
180        "PUT" | "DELETE" | "PATCH" => AccessMode::Write,
181        "POST" => AccessMode::Append,
182        _ => AccessMode::Read,
183    }
184}
185
186pub fn mode_name(mode: AccessMode) -> &'static str {
187    match mode {
188        AccessMode::Read => "read",
189        AccessMode::Write => "write",
190        AccessMode::Append => "append",
191        AccessMode::Control => "control",
192    }
193}
194
195// ---------------------------------------------------------------------------
196// Sidecar-enforcement policy — SINGLE SOURCE OF TRUTH.
197//
198// An `.acl` / `.meta` sidecar governs *another* resource's permissions, so
199// WAC §4.3.5 requires `acl:Control` on the PROTECTED resource for ANY
200// access to the sidecar — read AND write. Encoding that rule once, in
201// wasm-safe core, keeps every runtime (native `solid-pod-rs-server`,
202// CF-Workers pods, downstream forums) on the same decision so the READ
203// and WRITE elevation cannot drift apart per-consumer.
204// ---------------------------------------------------------------------------
205
206/// Strip a `.acl` / `.meta` suffix from `path`, returning the protected
207/// resource the sidecar governs. `/victim/.acl` → `/victim/`,
208/// `/a/b.acl` → `/a/b`, `/.acl` → `/`, `.acl` → `/`. Returns `None` when
209/// `path` is not an ACL/meta sidecar.
210///
211/// Pure and I/O-free (wasm-safe). This is THE canonical
212/// "is-this-a-sidecar / what-does-it-govern" predicate; do not re-derive
213/// it per runtime.
214pub fn protected_resource_for_acl(path: &str) -> Option<String> {
215    for suffix in [".acl", ".meta"] {
216        if let Some(stripped) = path.strip_suffix(suffix) {
217            // `/.acl` and `/dir/.acl` strip to `/` and `/dir/`
218            // respectively (container ACLs); `/a/b.acl` strips to the
219            // resource `/a/b`. A bare `.acl` (no leading slash) strips to
220            // the empty string and maps to the pod root `/`.
221            if stripped.is_empty() {
222                return Some("/".to_string());
223            }
224            return Some(stripped.to_string());
225        }
226    }
227    None
228}
229
230/// Canonical sidecar-elevation decision for BOTH reads and writes.
231///
232/// Maps a `(path, base_mode)` access request to the `(resource, mode)` the
233/// WAC check must actually run against:
234///
235/// * When `path` is an `.acl`/`.meta` sidecar
236///   ([`protected_resource_for_acl`] is `Some(p)`), the check elevates to
237///   `(p, AccessMode::Control)` — because reading or writing the sidecar
238///   discloses or rewrites the full authorization graph of `p`, which WAC
239///   §4.3.5 gates on `acl:Control` of `p`, never the base mode on the
240///   sidecar path.
241/// * Otherwise the request passes through unchanged as `(path, base_mode)`.
242///
243/// Callers pass `base_mode = AccessMode::Read` for a read and the request's
244/// write mode (`Write`/`Append`/`Control`) for a write; the elevation
245/// collapses either to `Control` on the governed resource. This is the ONE
246/// function the native server's read/write enforcement and any wasm runtime
247/// share, so the sidecar rule has a single source of truth. Pure and
248/// I/O-free (wasm-safe).
249pub fn effective_acl_target(path: &str, base_mode: AccessMode) -> (String, AccessMode) {
250    match protected_resource_for_acl(path) {
251        Some(protected) => (protected, AccessMode::Control),
252        None => (path.to_string(), base_mode),
253    }
254}
255
256/// Build a `WAC-Allow` header value (WAC 1.x — no condition dispatcher).
257///
258/// Advertises static capabilities for the authenticated agent and for
259/// anonymous (public) access. The origin gate is a per-request concern,
260/// so we evaluate without an origin and leave any origin-gated rules to
261/// reject at request time.
262pub fn wac_allow_header(
263    acl_doc: Option<&AclDocument>,
264    agent_uri: Option<&str>,
265    resource_path: &str,
266) -> String {
267    let mut user_modes = Vec::new();
268    let mut public_modes = Vec::new();
269    for mode in ALL_MODES {
270        if evaluate_access(acl_doc, agent_uri, resource_path, *mode, None) {
271            user_modes.push(mode_name(*mode));
272        }
273        if evaluate_access(acl_doc, None, resource_path, *mode, None) {
274            public_modes.push(mode_name(*mode));
275        }
276    }
277    format!(
278        "user=\"{}\", public=\"{}\"",
279        user_modes.join(" "),
280        public_modes.join(" ")
281    )
282}
283
284/// WAC 2.0 — build a `WAC-Allow` header omitting modes whose conditions
285/// are unsatisfied in the current request context.
286pub fn wac_allow_header_with_dispatcher(
287    acl_doc: Option<&AclDocument>,
288    ctx: &RequestContext<'_>,
289    resource_path: &str,
290    groups: &dyn GroupMembership,
291    dispatcher: &dyn ConditionDispatcher,
292) -> String {
293    let mut user_modes = Vec::new();
294    let mut public_modes = Vec::new();
295    let public_ctx = RequestContext {
296        web_id: None,
297        client_id: ctx.client_id,
298        issuer: ctx.issuer,
299        payment_balance_sats: ctx.payment_balance_sats,
300    };
301    for mode in ALL_MODES {
302        if evaluate_access_ctx(acl_doc, ctx, resource_path, *mode, None, groups, dispatcher) {
303            user_modes.push(mode_name(*mode));
304        }
305        if evaluate_access_ctx(
306            acl_doc,
307            &public_ctx,
308            resource_path,
309            *mode,
310            None,
311            groups,
312            dispatcher,
313        ) {
314            public_modes.push(mode_name(*mode));
315        }
316    }
317    format!(
318        "user=\"{}\", public=\"{}\"",
319        user_modes.join(" "),
320        public_modes.join(" ")
321    )
322}
323
324// ---------------------------------------------------------------------------
325// Lightweight metric counter for the acl-origin gate. When a proper
326// metrics facade lands (F1/F2) this module will be swapped for its
327// `Counter` type; for now we expose a minimal atomic compatible with
328// whichever facade arrives.
329// ---------------------------------------------------------------------------
330#[cfg(feature = "acl-origin")]
331pub mod metrics {
332    use std::sync::atomic::AtomicU64;
333
334    /// Total number of WAC evaluations denied by the `acl:origin` gate.
335    pub static ACL_ORIGIN_REJECTED_TOTAL: AtomicU64 = AtomicU64::new(0);
336}
337
338// ---------------------------------------------------------------------------
339// Tests — retained from pre-split wac.rs. Exercise JSON-LD round-trip,
340// Turtle parse/serialise, and the WAC-Allow header shape.
341// ---------------------------------------------------------------------------
342
343#[cfg(test)]
344mod tests {
345    use super::*;
346
347    fn make_doc(graph: Vec<AclAuthorization>) -> AclDocument {
348        AclDocument {
349            context: None,
350            graph: Some(graph),
351            inherited: false,
352        }
353    }
354
355    fn public_read(path: &str) -> AclAuthorization {
356        AclAuthorization {
357            id: None,
358            r#type: None,
359            agent: None,
360            agent_class: Some(IdOrIds::Single(IdRef {
361                id: "foaf:Agent".into(),
362            })),
363            agent_group: None,
364            origin: None,
365            access_to: Some(IdOrIds::Single(IdRef { id: path.into() })),
366            default: None,
367            mode: Some(IdOrIds::Single(IdRef {
368                id: "acl:Read".into(),
369            })),
370            condition: None,
371        }
372    }
373
374    #[test]
375    fn no_acl_denies_all() {
376        assert!(!evaluate_access(None, None, "/foo", AccessMode::Read, None));
377    }
378
379    #[test]
380    fn public_read_grants_anonymous() {
381        let doc = make_doc(vec![public_read("/")]);
382        assert!(evaluate_access(
383            Some(&doc),
384            None,
385            "/",
386            AccessMode::Read,
387            None
388        ));
389    }
390
391    #[test]
392    fn write_implies_append() {
393        let auth = AclAuthorization {
394            id: None,
395            r#type: None,
396            agent: Some(IdOrIds::Single(IdRef {
397                id: "did:nostr:owner".into(),
398            })),
399            agent_class: None,
400            agent_group: None,
401            origin: None,
402            access_to: Some(IdOrIds::Single(IdRef { id: "/".into() })),
403            default: None,
404            mode: Some(IdOrIds::Single(IdRef {
405                id: "acl:Write".into(),
406            })),
407            condition: None,
408        };
409        let doc = make_doc(vec![auth]);
410        assert!(evaluate_access(
411            Some(&doc),
412            Some("did:nostr:owner"),
413            "/",
414            AccessMode::Append,
415            None,
416        ));
417    }
418
419    #[test]
420    fn method_mapping() {
421        assert_eq!(method_to_mode("GET"), AccessMode::Read);
422        assert_eq!(method_to_mode("PUT"), AccessMode::Write);
423        assert_eq!(method_to_mode("POST"), AccessMode::Append);
424    }
425
426    #[test]
427    fn wac_allow_shape() {
428        let doc = make_doc(vec![public_read("/")]);
429        let hdr = wac_allow_header(Some(&doc), None, "/");
430        assert_eq!(hdr, "user=\"read\", public=\"read\"");
431    }
432
433    #[test]
434    fn turtle_acl_round_trip_parses_basic_rules() {
435        let ttl = r#"
436            @prefix acl: <http://www.w3.org/ns/auth/acl#> .
437            @prefix foaf: <http://xmlns.com/foaf/0.1/> .
438
439            <#public> a acl:Authorization ;
440                acl:agentClass foaf:Agent ;
441                acl:accessTo </> ;
442                acl:mode acl:Read .
443        "#;
444        let doc = parse_turtle_acl(ttl).unwrap();
445        assert!(evaluate_access(
446            Some(&doc),
447            None,
448            "/",
449            AccessMode::Read,
450            None
451        ));
452        assert!(!evaluate_access(
453            Some(&doc),
454            None,
455            "/",
456            AccessMode::Write,
457            None
458        ));
459    }
460
461    #[test]
462    fn turtle_acl_with_owner_grants_write() {
463        let ttl = r#"
464            @prefix acl: <http://www.w3.org/ns/auth/acl#> .
465
466            <#owner> a acl:Authorization ;
467                acl:agent <did:nostr:owner> ;
468                acl:accessTo </> ;
469                acl:default </> ;
470                acl:mode acl:Write, acl:Control .
471        "#;
472        let doc = parse_turtle_acl(ttl).unwrap();
473        assert!(evaluate_access(
474            Some(&doc),
475            Some("did:nostr:owner"),
476            "/foo",
477            AccessMode::Write,
478            None,
479        ));
480    }
481
482    #[test]
483    fn serialize_turtle_acl_emits_prefixes_and_rules() {
484        let doc = make_doc(vec![public_read("/")]);
485        let out = serialize_turtle_acl(&doc);
486        assert!(out.contains("@prefix acl:"));
487        assert!(out.contains("acl:Authorization"));
488        assert!(out.contains("acl:mode"));
489    }
490
491    // ----- Sprint 12: parameterised JSON-LD size cap ----------------------
492
493    #[test]
494    fn jsonld_acl_with_limits_rejects_oversized() {
495        let body = b"{\"@context\": \"https://www.w3.org/ns/auth/acl\"}";
496        let err = parse_jsonld_acl_with_limits(body, 10, 32).unwrap_err();
497        let msg = err.to_string();
498        assert!(
499            msg.contains("payload too large") || msg.contains("exceeds"),
500            "oversized JSON-LD should be rejected: {msg}"
501        );
502    }
503
504    #[test]
505    fn jsonld_acl_with_limits_accepts_within_bounds() {
506        // Minimal valid JSON-LD ACL (empty graph).
507        let body = b"{}";
508        let doc = parse_jsonld_acl_with_limits(body, 1024, 32).unwrap();
509        assert!(doc.graph.is_none());
510    }
511
512    // ----- Sidecar-enforcement policy (single source of truth) ------------
513
514    #[test]
515    fn protected_resource_for_acl_strips_suffixes() {
516        assert_eq!(
517            protected_resource_for_acl("/victim/.acl").as_deref(),
518            Some("/victim/")
519        );
520        assert_eq!(protected_resource_for_acl("/a/b.acl").as_deref(), Some("/a/b"));
521        assert_eq!(protected_resource_for_acl("/.acl").as_deref(), Some("/"));
522        assert_eq!(protected_resource_for_acl("/a/b.meta").as_deref(), Some("/a/b"));
523        assert_eq!(protected_resource_for_acl("/dir/.meta").as_deref(), Some("/dir/"));
524        assert_eq!(protected_resource_for_acl("/.meta").as_deref(), Some("/"));
525        assert_eq!(protected_resource_for_acl(".acl").as_deref(), Some("/"));
526        // Not a sidecar.
527        assert_eq!(protected_resource_for_acl("/a/b").as_deref(), None);
528        assert_eq!(protected_resource_for_acl("/foo.aclx").as_deref(), None);
529    }
530
531    /// GOLDEN CONFORMANCE VECTORS for [`effective_acl_target`].
532    ///
533    /// Every runtime that enforces WAC (native server, CF-Workers pod,
534    /// downstream forum) MUST reproduce this table exactly: `(path,
535    /// base_mode)` → `(resource, mode)`. The sidecar rows cover both READ
536    /// and WRITE elevating to `Control` on the governed resource — the
537    /// invariant a downstream consumer previously got wrong on the READ
538    /// side.
539    #[test]
540    fn effective_acl_target_golden_conformance_vectors() {
541        use AccessMode::{Append, Control, Read, Write};
542        // (input path, base_mode) -> (expected resource, expected mode)
543        let vectors: &[(&str, AccessMode, &str, AccessMode)] = &[
544            // Ordinary resource: read / write / append pass through unchanged.
545            ("/foo", Read, "/foo", Read),
546            ("/foo", Write, "/foo", Write),
547            ("/foo", Append, "/foo", Append),
548            ("/dir/", Read, "/dir/", Read),
549            ("/dir/", Write, "/dir/", Write),
550            // `.acl` sidecar: READ *and* WRITE both elevate to Control on /foo.
551            ("/foo.acl", Read, "/foo", Control),
552            ("/foo.acl", Write, "/foo", Control),
553            ("/foo.acl", Append, "/foo", Control),
554            // Container `.acl`: /dir/.acl -> (/dir/, Control).
555            ("/dir/.acl", Read, "/dir/", Control),
556            ("/dir/.acl", Write, "/dir/", Control),
557            // Root `.acl`: /.acl -> (/, Control).
558            ("/.acl", Read, "/", Control),
559            ("/.acl", Write, "/", Control),
560            // `.meta` behaves identically to `.acl`.
561            ("/foo.meta", Read, "/foo", Control),
562            ("/foo.meta", Write, "/foo", Control),
563            ("/dir/.meta", Read, "/dir/", Control),
564            ("/.meta", Write, "/", Control),
565        ];
566        for (path, base, exp_res, exp_mode) in vectors {
567            let (res, mode) = effective_acl_target(path, *base);
568            assert_eq!(&res, exp_res, "resource for ({path:?}, {base:?})");
569            assert_eq!(mode, *exp_mode, "mode for ({path:?}, {base:?})");
570        }
571    }
572
573    #[test]
574    fn effective_acl_target_non_sidecar_is_identity() {
575        for mode in ALL_MODES {
576            let (res, out) = effective_acl_target("/data/note.ttl", *mode);
577            assert_eq!(res, "/data/note.ttl");
578            assert_eq!(out, *mode);
579        }
580    }
581}