Skip to main content

ma_core/acl/
mod.rs

1//! Capability-based access control for ma identities.
2//!
3//! An [`AclMap`] maps principal strings to [`CapabilityEntry`] values.
4//! Deny always wins over allow; a wildcard deny closes access to everyone.
5//!
6//! # Capabilities
7//!
8//! Capabilities are plain strings. Built-in system capabilities:
9//!
10//! | Capability | Meaning |
11//! |------------|---------|
12//! | `"inbox"`  | Deliver messages via `/ma/inbox/0.0.1` |
13//! | `"ipfs"`   | Store generic content via `/ma/ipfs/0.0.1` |
14//! | `"identity-publish"` | Publish DID documents via `/ma/ipfs/0.0.1` |
15//! | `"crud"`   | Access `/ma/crud/0.0.1` |
16//! | `"read"`   | Read entities, config, and namespace contents |
17//! | `"create"` | Create new namespaces or entities |
18//! | `"update"` | Update existing namespaces or entities |
19//! | `"delete"` | Delete namespaces or entities |
20//! | `"*"`      | Wildcard — grants **all** capabilities at this level |
21//!
22//! Entity and namespace ACLs may also use arbitrary capability strings that
23//! correspond to verb names or sub-namespace names.
24//!
25//! # Key forms in an [`AclMap`]
26//!
27//! Keys are **principal strings** — exactly one of:
28//!
29//! | Form | Meaning |
30//! |------|---------|
31//! | `"*"` | Wildcard — matches any caller |
32//! | `"did:ma:<identity>"` | Bare DID (no fragment) |
33//! | `"#<local>"` | Local entity identifier |
34//! | `"+<handle>.<path>"` | Named group of principals (unlimited depth) |
35//!
36//! # YAML format
37//!
38//! ```yaml
39//! acl:
40//!   "*": [rpc, create]          # everyone: RPC + create
41//!   "did:ma:alice": ["*"]        # alice: all capabilities
42//!   "did:ma:bob": [rpc, read]   # bob: restricted
43//!   "did:ma:eve":               # null / absent → explicit deny
44//!   "+carlotta.friends": [rpc]         # group: all members get rpc
45//!   "+alice.project4.admins": ["*"]  # deep path: project4 admins get all caps
46//!   "+alice.enemies":                # group: all members denied
47//! ```
48//!
49//! # Example
50//!
51//! ```rust
52//! # use ma_core::{AclMap, CapabilityEntry, check_cap, CAP_INBOX};
53//! let mut acl = AclMap::new();
54//! acl.insert("*".to_string(), CapabilityEntry::from_caps([CAP_INBOX]));
55//! acl.insert("did:ma:k51evil".to_string(), CapabilityEntry::Deny);
56//! assert!(check_cap(&acl, "did:ma:k51good", CAP_INBOX).is_ok());
57//! assert!(check_cap(&acl, "did:ma:k51evil", CAP_INBOX).is_err());
58//! ```
59
60use std::collections::{BTreeSet, HashMap};
61
62use serde::{Deserialize, Deserializer, Serialize, Serializer};
63
64#[cfg(feature = "acl")]
65use crate::{Error, Result};
66
67// ── Capability constants ───────────────────────────────────────────────────────
68
69/// Deliver messages to an endpoint's inbox (`/ma/inbox/0.0.1`).
70pub const CAP_INBOX: &str = "inbox";
71/// Store generic content via `/ma/ipfs/0.0.1` (fire-and-forget).
72pub const CAP_IPFS: &str = "ipfs";
73/// Publish DID documents via `/ma/ipfs/0.0.1`.
74///
75/// Separated from [`CAP_IPFS`] because identity-publish transmits an IPNS
76/// secret key and may need to be gated more tightly than generic content
77/// storage.
78pub const CAP_IDENTITY_PUBLISH: &str = "identity-publish";
79/// Access the structured CRUD service via `/ma/crud/0.0.1`.
80pub const CAP_CRUD: &str = "crud";
81/// Read entities, config, and namespace contents.
82pub const CAP_READ: &str = "read";
83/// Create new namespaces or entities.
84pub const CAP_CREATE: &str = "create";
85/// Update existing namespaces or entities.
86pub const CAP_UPDATE: &str = "update";
87/// Delete namespaces or entities.
88pub const CAP_DELETE: &str = "delete";
89/// Read or modify ACL documents.
90///
91/// Separates ACL-administration rights from general CRUD access.
92/// A principal with `acl` capability can read and update ACL documents
93/// without necessarily having access to the resources those ACLs protect.
94pub const CAP_ACL: &str = "acl";
95
96// ── Group-principal prefix ─────────────────────────────────────────────────────
97
98/// Sigil that marks a group principal in an [`AclMap`] key.
99///
100/// A group key has the form `+<handle>.<path>` where `<handle>` is the owning
101/// identity's handle and `<path>` is a dot-separated path of arbitrary depth
102/// into that handle's group tree (e.g. `+alice.project4.admins`).
103pub const GROUP_PREFIX: &str = "+";
104
105/// Local-entity wildcard principal.
106///
107/// The bare `"#"` key in an [`AclMap`] matches **any** caller whose principal
108/// starts with `"#"` — i.e. any entity running on the same runtime instance.
109///
110/// It sits between the specific `"#<name>"` form and the global `"*"` wildcard
111/// in lookup priority:
112///
113/// ```text
114/// // specific entity  > local wildcard  > global wildcard
115/// //   "#fortune"         "#"                 "*"
116/// ```
117///
118/// The runtime pre-normalises intra-runtime callers from their full DID-URL form
119/// (`did:ma:<our_did>#fortune`) to the bare fragment form (`#fortune`) before
120/// the ACL lookup, so that these keys resolve correctly.
121///
122/// ## YAML example
123///
124/// ```yaml
125/// acl:
126///   "#": [handle_cast]        # any local entity on this runtime may call
127///   "did:ma:alice": ["*"]     # remote alice: all caps
128///   "*":                      # everyone else: deny
129/// ```
130pub const LOCAL_ENTITY_WILDCARD: &str = "#";
131
132// ── CapabilityEntry ────────────────────────────────────────────────────────────
133
134/// Capability set for a principal in an [`AclMap`].
135///
136/// Serialises as:
137/// - `null` → [`Deny`](CapabilityEntry::Deny)
138/// - YAML sequence → [`Allow`](CapabilityEntry::Allow)
139#[derive(Debug, Clone, PartialEq, Eq)]
140pub enum CapabilityEntry {
141    /// Explicit deny. Wins over any wildcard allow for the same principal.
142    Deny,
143    /// Allow the listed capabilities. `["*"]` grants all capabilities.
144    Allow(BTreeSet<String>),
145}
146
147impl CapabilityEntry {
148    /// Construct an `Allow` entry from an iterator of capability name strings.
149    pub fn from_caps<I, S>(caps: I) -> Self
150    where
151        I: IntoIterator<Item = S>,
152        S: Into<String>,
153    {
154        Self::Allow(caps.into_iter().map(Into::into).collect())
155    }
156
157    /// Return `true` if this entry grants `cap`.
158    /// `"*"` in the capability set grants any capability.
159    pub fn has(&self, cap: &str) -> bool {
160        match self {
161            Self::Deny => false,
162            Self::Allow(caps) => caps.contains(cap) || caps.contains("*"),
163        }
164    }
165
166    /// Return `true` if this is an explicit deny.
167    pub fn is_deny(&self) -> bool {
168        matches!(self, Self::Deny)
169    }
170}
171
172impl Serialize for CapabilityEntry {
173    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
174        match self {
175            Self::Deny => serializer.serialize_none(),
176            Self::Allow(caps) => {
177                use serde::ser::SerializeSeq;
178                let mut seq = serializer.serialize_seq(Some(caps.len()))?;
179                for cap in caps {
180                    seq.serialize_element(cap)?;
181                }
182                seq.end()
183            }
184        }
185    }
186}
187
188impl<'de> Deserialize<'de> for CapabilityEntry {
189    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
190        #[derive(Deserialize)]
191        #[serde(untagged)]
192        enum Raw {
193            #[allow(dead_code)]
194            Str(String),
195            Seq(Vec<String>),
196        }
197        let opt: Option<Raw> = Option::deserialize(deserializer)?;
198        match opt {
199            None => Ok(Self::Deny),
200            Some(Raw::Seq(v)) if v.is_empty() => Ok(Self::Deny),
201            Some(Raw::Seq(v)) => Ok(Self::Allow(v.into_iter().collect())),
202            Some(Raw::Str(_)) => Err(serde::de::Error::custom(
203                "invalid ACL entry: use a YAML sequence for Allow or null for Deny",
204            )),
205        }
206    }
207}
208
209// ── AclMap ─────────────────────────────────────────────────────────────────────
210
211/// Capability-based access control map.
212///
213/// Keys are principal strings — exactly one of:
214/// - `"*"` — wildcard
215/// - `"did:ma:<identity>"` — bare DID, no fragment
216/// - `"#<local>"` — local entity identifier
217/// - `"+<handle>.<path>"` — named group of principals (unlimited depth)
218///
219/// DID-URLs with fragments (`did:ma:foo#bar`) are **not** valid keys;
220/// use [`is_valid_acl_key`] to validate before inserting.
221pub type AclMap = HashMap<String, CapabilityEntry>;
222
223// ── check_cap ──────────────────────────────────────────────────────────────────
224
225/// Check whether `caller` has capability `cap` in `acl`.
226///
227/// 1. Normalise `caller` (strip fragment from DID-URLs).
228/// 2. Look up the normalised caller directly — if a principal entry, apply and stop.
229/// 3. Fall back to the `"*"` wildcard principal entry.
230/// 4. Explicit deny → `Err`; capability absent → `Err`; no entry → `Err`.
231///
232/// Group principals (`+<handle>.<path>`) are **not** resolved here;
233/// they are expanded by the runtime's async `check_full`.
234///
235/// A `"*"` item inside an `Allow` set grants **all** capabilities.
236/// Evaluate a single [`CapabilityEntry`] for `cap` and `caller`.
237///
238/// Returns `Ok(())` when the entry grants `cap`, or the appropriate `Err`.
239#[cfg(feature = "acl")]
240fn apply_entry(entry: &CapabilityEntry, cap: &str, caller: &str) -> Result<()> {
241    match entry {
242        CapabilityEntry::Deny => Err(Error::Acl(format!("operation denied for {caller}"))),
243        CapabilityEntry::Allow(caps) if caps.contains(cap) || caps.contains("*") => Ok(()),
244        CapabilityEntry::Allow(_) => Err(Error::Acl(format!(
245            "capability '{cap}' denied for {caller}"
246        ))),
247    }
248}
249
250#[cfg(feature = "acl")]
251pub fn check_cap(acl: &AclMap, caller: &str, cap: &str) -> Result<()> {
252    let normalized = normalize_principal(caller);
253
254    // 1. Direct principal match (highest priority).
255    if let Some(direct) = acl.get(normalized) {
256        return apply_entry(direct, cap, caller);
257    }
258
259    // 2. Local-entity wildcard "#" — matches any `#`-prefixed caller.
260    if normalized.starts_with('#') {
261        if let Some(local_wild) = acl.get(LOCAL_ENTITY_WILDCARD) {
262            return apply_entry(local_wild, cap, caller);
263        }
264    }
265
266    // 3. Global wildcard "*" (lowest priority).
267    match acl.get("*") {
268        None => Err(Error::Acl(format!("no ACL entry for {caller}"))),
269        Some(entry) => apply_entry(entry, cap, caller),
270    }
271}
272
273/// Return `true` if `key` is a valid [`AclMap`] key.
274///
275/// Valid keys: `"*"`, `"did:ma:<id>"`, `"#<local>"`, `"+<handle>.<path>"`
276/// (where `<path>` is dot-separated with unlimited depth),
277/// and arbitrary capability/verb name strings (non-empty).
278pub fn is_valid_acl_key(key: &str) -> bool {
279    !key.is_empty()
280}
281
282/// Return `true` if `key` is a principal key (identifies *who*).
283///
284/// Valid principal key forms:
285/// - `"*"` — global wildcard
286/// - `"did:ma:<id>"` — bare DID (no fragment)
287/// - `"#"` — local-entity wildcard (any entity on this runtime)
288/// - `"#<name>"` — specific local entity by fragment name
289/// - `"+<handle>.<path>"` — group principal
290pub fn is_principal_key(key: &str) -> bool {
291    key == "*"
292        || (key.starts_with("did:") && !key.contains('#'))
293        || key.starts_with('#')   // covers both "#" (local wildcard) and "#name" (specific)
294        || is_valid_group_key(key)
295}
296
297/// Return `true` if `key` is a valid group principal.
298///
299/// Form: `+<handle>.<path>` where `<handle>` is non-empty and `<path>` is a
300/// non-empty dot-separated string of arbitrary depth
301/// (e.g. `+alice.admins`, `+alice.project4.admins`).
302fn is_valid_group_key(key: &str) -> bool {
303    if let Some(rest) = key.strip_prefix(GROUP_PREFIX) {
304        if let Some(dot) = rest.find('.') {
305            let handle = &rest[..dot];
306            let path = &rest[dot + 1..];
307            return !handle.is_empty() && !path.is_empty();
308        }
309    }
310    false
311}
312
313/// Validate all keys in an [`AclMap`], returning a descriptive error for the
314/// first invalid key found.
315///
316/// Call this immediately after loading an ACL from YAML or any external source.
317#[cfg(feature = "acl")]
318pub fn validate_acl_map(acl: &AclMap) -> Result<()> {
319    for key in acl.keys() {
320        if !is_valid_acl_key(key) {
321            return Err(Error::Acl(format!(
322                "invalid ACL key {key:?}: key must be non-empty"
323            )));
324        }
325    }
326    Ok(())
327}
328
329/// Normalise a caller identity for [`AclMap`] lookup.
330///
331/// - `did:ma:foo#bar` → `did:ma:foo` (strips fragment from **remote** DID-URLs)
332/// - `#local` → `#local` (already-normalised local entity, passed through)
333/// - `#` → `#` (local-entity wildcard, passed through)
334/// - `*` → `*` (global wildcard, passed through)
335///
336/// **Note:** Callers from the same runtime arrive as `did:ma:<our_did>#fragment`.
337/// The runtime is responsible for converting those to `#fragment` *before*
338/// calling this function (or [`check_cap`]) so that `"#<name>"` and `"#"`
339/// ACL keys resolve correctly.  This function only strips fragments from
340/// foreign DID-URLs; it does not know which DID belongs to the local runtime.
341pub fn normalize_principal(did: &str) -> &str {
342    if did.starts_with("did:") {
343        if let Some(pos) = did.find('#') {
344            return &did[..pos];
345        }
346    }
347    did
348}
349
350// ── Tests ──────────────────────────────────────────────────────────────────────
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355    use noyalib::compat::serde_yaml;
356
357    fn allow(caps: &[&str]) -> CapabilityEntry {
358        CapabilityEntry::from_caps(caps.iter().copied())
359    }
360
361    fn m(entries: &[(&str, CapabilityEntry)]) -> AclMap {
362        entries
363            .iter()
364            .map(|(k, v)| (k.to_string(), v.clone()))
365            .collect()
366    }
367
368    #[test]
369    fn wildcard_rpc_allows_rpc() {
370        let acl = m(&[("*", allow(&[CAP_INBOX]))]);
371        assert!(check_cap(&acl, "did:ma:alice", CAP_INBOX).is_ok());
372    }
373
374    #[test]
375    fn wildcard_rpc_denies_ipfs() {
376        let acl = m(&[("*", allow(&[CAP_INBOX]))]);
377        assert!(check_cap(&acl, "did:ma:alice", CAP_IPFS).is_err());
378    }
379
380    #[test]
381    fn explicit_deny_wins_over_wildcard_allow() {
382        let acl = m(&[
383            ("*", allow(&[CAP_INBOX, CAP_IPFS])),
384            ("did:ma:bandit", CapabilityEntry::Deny),
385        ]);
386        assert!(check_cap(&acl, "did:ma:bandit", CAP_INBOX).is_err());
387    }
388
389    #[test]
390    fn exact_match_restricts_below_wildcard() {
391        let acl = m(&[
392            ("*", allow(&[CAP_INBOX, CAP_IPFS])),
393            ("did:ma:bob", allow(&[CAP_INBOX])),
394        ]);
395        assert!(check_cap(&acl, "did:ma:bob", CAP_INBOX).is_ok());
396        assert!(check_cap(&acl, "did:ma:bob", CAP_IPFS).is_err());
397    }
398
399    #[test]
400    fn did_url_caller_is_normalized() {
401        let acl = m(&[("did:ma:alice", allow(&[CAP_INBOX, CAP_IPFS]))]);
402        assert!(check_cap(&acl, "did:ma:alice#sign", CAP_INBOX).is_ok());
403    }
404
405    #[test]
406    fn no_entry_default_deny() {
407        assert!(check_cap(&AclMap::new(), "did:ma:anyone", CAP_INBOX).is_err());
408    }
409
410    #[test]
411    fn wildcard_deny_blocks_all() {
412        let acl = m(&[("*", CapabilityEntry::Deny)]);
413        assert!(check_cap(&acl, "did:ma:anyone", CAP_INBOX).is_err());
414    }
415
416    #[test]
417    fn local_entity_key_allowed() {
418        let acl = m(&[("#agent", allow(&[CAP_INBOX]))]);
419        assert!(check_cap(&acl, "#agent", CAP_INBOX).is_ok());
420        assert!(check_cap(&acl, "#other", CAP_INBOX).is_err());
421    }
422
423    #[test]
424    fn arbitrary_capability_works() {
425        let acl = m(&[("did:ma:alice", allow(&["emote", "reply"]))]);
426        assert!(check_cap(&acl, "did:ma:alice", "emote").is_ok());
427        assert!(check_cap(&acl, "did:ma:alice", "reply").is_ok());
428        assert!(check_cap(&acl, "did:ma:alice", "admin").is_err());
429    }
430
431    #[test]
432    fn wildcard_cap_grants_all_capabilities() {
433        let acl = m(&[("did:ma:alice", allow(&["*"]))]);
434        assert!(check_cap(&acl, "did:ma:alice", CAP_INBOX).is_ok());
435        assert!(check_cap(&acl, "did:ma:alice", CAP_IPFS).is_ok());
436        assert!(check_cap(&acl, "did:ma:alice", "emote").is_ok());
437        assert!(check_cap(&acl, "did:ma:alice", "admin").is_ok());
438    }
439
440    #[test]
441    fn owner_capability_is_just_a_string() {
442        let acl = m(&[("did:ma:alice", allow(&["owner"]))]);
443        assert!(check_cap(&acl, "did:ma:alice", "owner").is_ok());
444        assert!(check_cap(&acl, "did:ma:alice", CAP_INBOX).is_err());
445    }
446
447    #[test]
448    fn normalize_strips_fragment() {
449        assert_eq!(normalize_principal("did:ma:foo#bar"), "did:ma:foo");
450        assert_eq!(normalize_principal("did:ma:foo"), "did:ma:foo");
451        assert_eq!(normalize_principal("#local"), "#local");
452        assert_eq!(normalize_principal("#"), "#");
453        assert_eq!(normalize_principal("*"), "*");
454    }
455
456    // ── Local-entity wildcard ("#") tests ─────────────────────────────────────
457
458    #[test]
459    fn local_wildcard_allows_any_hash_prefixed_caller() {
460        // "#" matches any #-prefixed caller when there is no specific entry.
461        let acl = m(&[("#", allow(&[CAP_INBOX]))]);
462        assert!(check_cap(&acl, "#fortune", CAP_INBOX).is_ok());
463        assert!(check_cap(&acl, "#scheduler", CAP_INBOX).is_ok());
464        assert!(check_cap(&acl, "#any_entity", CAP_INBOX).is_ok());
465    }
466
467    #[test]
468    fn local_wildcard_does_not_match_remote_callers() {
469        // Remote DIDs do not start with '#', so "#" should not grant them.
470        let acl = m(&[("#", allow(&[CAP_INBOX]))]);
471        assert!(check_cap(&acl, "did:ma:remote", CAP_INBOX).is_err());
472    }
473
474    #[test]
475    fn specific_local_entity_wins_over_local_wildcard() {
476        // "#fortune" is more specific: it restricts below the "#" wildcard.
477        let acl = m(&[
478            ("#", allow(&[CAP_INBOX, CAP_IPFS])),
479            ("#fortune", allow(&[CAP_INBOX])), // only rpc, not ipfs
480        ]);
481        assert!(check_cap(&acl, "#fortune", CAP_INBOX).is_ok());
482        assert!(check_cap(&acl, "#fortune", CAP_IPFS).is_err());
483        // Other local entities still get rpc+ipfs from the wildcard.
484        assert!(check_cap(&acl, "#other", CAP_IPFS).is_ok());
485    }
486
487    #[test]
488    fn local_wildcard_deny_blocks_all_local_entities() {
489        let acl = m(&[
490            ("#", CapabilityEntry::Deny),
491            ("*", allow(&[CAP_INBOX])), // global wildcard would allow, but # deny wins
492        ]);
493        assert!(check_cap(&acl, "#fortune", CAP_INBOX).is_err());
494        assert!(check_cap(&acl, "#any", CAP_INBOX).is_err());
495        // Remote callers are unaffected by the "#" deny.
496        assert!(check_cap(&acl, "did:ma:remote", CAP_INBOX).is_ok());
497    }
498
499    #[test]
500    fn specific_local_entity_allow_overrides_local_wildcard_deny() {
501        // "#fortune" explicit allow wins over "#" deny for that entity.
502        let acl = m(&[
503            ("#", CapabilityEntry::Deny),
504            ("#fortune", allow(&[CAP_INBOX])),
505        ]);
506        assert!(check_cap(&acl, "#fortune", CAP_INBOX).is_ok());
507        assert!(check_cap(&acl, "#other", CAP_INBOX).is_err());
508    }
509
510    #[test]
511    fn global_wildcard_not_triggered_for_hash_caller_when_local_wildcard_present() {
512        // When "#" deny is set, "*" allow must NOT override it for local callers.
513        let acl = m(&[("#", CapabilityEntry::Deny), ("*", allow(&[CAP_INBOX]))]);
514        // Local entity is denied by "#" — must not fall through to "*".
515        assert!(check_cap(&acl, "#fortune", CAP_INBOX).is_err());
516    }
517
518    #[test]
519    fn local_wildcard_is_key_form_valid() {
520        assert!(is_principal_key("#"));
521        assert!(is_principal_key("#fortune"));
522        assert!(is_principal_key("*"));
523        assert!(is_principal_key("did:ma:alice"));
524    }
525
526    #[test]
527    fn explicit_deny_without_wildcard() {
528        // A bare Deny entry with no wildcard still denies.
529        let acl = m(&[("did:ma:bandit", CapabilityEntry::Deny)]);
530        assert!(check_cap(&acl, "did:ma:bandit", CAP_INBOX).is_err());
531        // Others get default deny too (no wildcard).
532        assert!(check_cap(&acl, "did:ma:alice", CAP_INBOX).is_err());
533    }
534
535    #[test]
536    fn multiple_caps_in_single_entry() {
537        let acl = m(&[("did:ma:alice", allow(&[CAP_INBOX, CAP_IPFS, CAP_READ]))]);
538        assert!(check_cap(&acl, "did:ma:alice", CAP_INBOX).is_ok());
539        assert!(check_cap(&acl, "did:ma:alice", CAP_IPFS).is_ok());
540        assert!(check_cap(&acl, "did:ma:alice", CAP_READ).is_ok());
541        assert!(check_cap(&acl, "did:ma:alice", CAP_CREATE).is_err());
542        assert!(check_cap(&acl, "did:ma:alice", CAP_DELETE).is_err());
543    }
544
545    #[test]
546    fn direct_entry_restricts_even_when_wildcard_is_broader() {
547        // Wildcard gives everyone rpc+ipfs, but bob only gets rpc.
548        // Direct entry wins and caps don't accumulate from wildcard.
549        let acl = m(&[
550            ("*", allow(&[CAP_INBOX, CAP_IPFS])),
551            ("did:ma:bob", allow(&[CAP_INBOX])),
552        ]);
553        assert!(check_cap(&acl, "did:ma:bob", CAP_INBOX).is_ok());
554        assert!(check_cap(&acl, "did:ma:bob", CAP_IPFS).is_err());
555        // Alice (no direct entry) still gets both from wildcard.
556        assert!(check_cap(&acl, "did:ma:alice", CAP_INBOX).is_ok());
557        assert!(check_cap(&acl, "did:ma:alice", CAP_IPFS).is_ok());
558    }
559
560    #[test]
561    fn group_principal_allowed() {
562        // "+group" keys are not resolved by check_cap; they pass through.
563        // Resolution happens in the runtime's async check_full.
564        let acl = m(&[("*", allow(&[CAP_INBOX]))]);
565        assert!(check_cap(&acl, "did:ma:anyone", CAP_INBOX).is_ok());
566    }
567
568    #[test]
569    fn valid_acl_keys() {
570        assert!(is_valid_acl_key("*"));
571        assert!(is_valid_acl_key("did:ma:k51foo"));
572        assert!(is_valid_acl_key("#agent"));
573        assert!(is_valid_acl_key("+alice.venner"));
574        assert!(is_valid_acl_key("+runtime.admins"));
575        assert!(is_valid_acl_key("fortune"));
576        assert!(is_valid_acl_key("admin"));
577        assert!(is_valid_acl_key("emote"));
578        assert!(!is_valid_acl_key(""));
579    }
580
581    #[cfg(feature = "acl")]
582    #[test]
583    fn capability_serde_roundtrip() {
584        let acl: AclMap = [
585            (
586                "*".to_string(),
587                CapabilityEntry::from_caps(["rpc", "create"]),
588            ),
589            ("did:ma:bandit".to_string(), CapabilityEntry::Deny),
590        ]
591        .into_iter()
592        .collect();
593        let yaml = serde_yaml::to_string(&acl).unwrap();
594        let roundtrip: AclMap = serde_yaml::from_str(&yaml).unwrap();
595        assert_eq!(acl, roundtrip);
596    }
597
598    #[cfg(feature = "acl")]
599    #[test]
600    fn yaml_null_deserializes_to_deny() {
601        let yaml = "'did:ma:x': ~\n'*':\n- rpc\n- create\n";
602        let acl: AclMap = serde_yaml::from_str(yaml).unwrap();
603        assert_eq!(acl.get("did:ma:x"), Some(&CapabilityEntry::Deny));
604        assert_eq!(
605            acl.get("*"),
606            Some(&CapabilityEntry::from_caps(["rpc", "create"]))
607        );
608    }
609}