1use std::collections::{BTreeSet, HashMap};
61
62use serde::{Deserialize, Deserializer, Serialize, Serializer};
63
64#[cfg(feature = "acl")]
65use crate::{Error, Result};
66
67pub const CAP_INBOX: &str = "inbox";
71pub const CAP_IPFS: &str = "ipfs";
73pub const CAP_IDENTITY_PUBLISH: &str = "identity-publish";
79pub const CAP_CRUD: &str = "crud";
81pub const CAP_READ: &str = "read";
83pub const CAP_CREATE: &str = "create";
85pub const CAP_UPDATE: &str = "update";
87pub const CAP_DELETE: &str = "delete";
89pub const CAP_ACL: &str = "acl";
95
96pub const GROUP_PREFIX: &str = "+";
104
105pub const LOCAL_ENTITY_WILDCARD: &str = "#";
131
132#[derive(Debug, Clone, PartialEq, Eq)]
140pub enum CapabilityEntry {
141 Deny,
143 Allow(BTreeSet<String>),
145}
146
147impl CapabilityEntry {
148 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 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 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
209pub type AclMap = HashMap<String, CapabilityEntry>;
222
223#[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 if let Some(direct) = acl.get(normalized) {
256 return apply_entry(direct, cap, caller);
257 }
258
259 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 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
273pub fn is_valid_acl_key(key: &str) -> bool {
279 !key.is_empty()
280}
281
282pub fn is_principal_key(key: &str) -> bool {
291 key == "*"
292 || (key.starts_with("did:") && !key.contains('#'))
293 || key.starts_with('#') || is_valid_group_key(key)
295}
296
297fn 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#[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
329pub 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#[cfg(test)]
353mod tests {
354 use super::*;
355
356 fn allow(caps: &[&str]) -> CapabilityEntry {
357 CapabilityEntry::from_caps(caps.iter().copied())
358 }
359
360 fn m(entries: &[(&str, CapabilityEntry)]) -> AclMap {
361 entries
362 .iter()
363 .map(|(k, v)| (k.to_string(), v.clone()))
364 .collect()
365 }
366
367 #[test]
368 fn wildcard_rpc_allows_rpc() {
369 let acl = m(&[("*", allow(&[CAP_INBOX]))]);
370 assert!(check_cap(&acl, "did:ma:alice", CAP_INBOX).is_ok());
371 }
372
373 #[test]
374 fn wildcard_rpc_denies_ipfs() {
375 let acl = m(&[("*", allow(&[CAP_INBOX]))]);
376 assert!(check_cap(&acl, "did:ma:alice", CAP_IPFS).is_err());
377 }
378
379 #[test]
380 fn explicit_deny_wins_over_wildcard_allow() {
381 let acl = m(&[
382 ("*", allow(&[CAP_INBOX, CAP_IPFS])),
383 ("did:ma:bandit", CapabilityEntry::Deny),
384 ]);
385 assert!(check_cap(&acl, "did:ma:bandit", CAP_INBOX).is_err());
386 }
387
388 #[test]
389 fn exact_match_restricts_below_wildcard() {
390 let acl = m(&[
391 ("*", allow(&[CAP_INBOX, CAP_IPFS])),
392 ("did:ma:bob", allow(&[CAP_INBOX])),
393 ]);
394 assert!(check_cap(&acl, "did:ma:bob", CAP_INBOX).is_ok());
395 assert!(check_cap(&acl, "did:ma:bob", CAP_IPFS).is_err());
396 }
397
398 #[test]
399 fn did_url_caller_is_normalized() {
400 let acl = m(&[("did:ma:alice", allow(&[CAP_INBOX, CAP_IPFS]))]);
401 assert!(check_cap(&acl, "did:ma:alice#sign", CAP_INBOX).is_ok());
402 }
403
404 #[test]
405 fn no_entry_default_deny() {
406 assert!(check_cap(&AclMap::new(), "did:ma:anyone", CAP_INBOX).is_err());
407 }
408
409 #[test]
410 fn wildcard_deny_blocks_all() {
411 let acl = m(&[("*", CapabilityEntry::Deny)]);
412 assert!(check_cap(&acl, "did:ma:anyone", CAP_INBOX).is_err());
413 }
414
415 #[test]
416 fn local_entity_key_allowed() {
417 let acl = m(&[("#agent", allow(&[CAP_INBOX]))]);
418 assert!(check_cap(&acl, "#agent", CAP_INBOX).is_ok());
419 assert!(check_cap(&acl, "#other", CAP_INBOX).is_err());
420 }
421
422 #[test]
423 fn arbitrary_capability_works() {
424 let acl = m(&[("did:ma:alice", allow(&["emote", "reply"]))]);
425 assert!(check_cap(&acl, "did:ma:alice", "emote").is_ok());
426 assert!(check_cap(&acl, "did:ma:alice", "reply").is_ok());
427 assert!(check_cap(&acl, "did:ma:alice", "admin").is_err());
428 }
429
430 #[test]
431 fn wildcard_cap_grants_all_capabilities() {
432 let acl = m(&[("did:ma:alice", allow(&["*"]))]);
433 assert!(check_cap(&acl, "did:ma:alice", CAP_INBOX).is_ok());
434 assert!(check_cap(&acl, "did:ma:alice", CAP_IPFS).is_ok());
435 assert!(check_cap(&acl, "did:ma:alice", "emote").is_ok());
436 assert!(check_cap(&acl, "did:ma:alice", "admin").is_ok());
437 }
438
439 #[test]
440 fn owner_capability_is_just_a_string() {
441 let acl = m(&[("did:ma:alice", allow(&["owner"]))]);
442 assert!(check_cap(&acl, "did:ma:alice", "owner").is_ok());
443 assert!(check_cap(&acl, "did:ma:alice", CAP_INBOX).is_err());
444 }
445
446 #[test]
447 fn normalize_strips_fragment() {
448 assert_eq!(normalize_principal("did:ma:foo#bar"), "did:ma:foo");
449 assert_eq!(normalize_principal("did:ma:foo"), "did:ma:foo");
450 assert_eq!(normalize_principal("#local"), "#local");
451 assert_eq!(normalize_principal("#"), "#");
452 assert_eq!(normalize_principal("*"), "*");
453 }
454
455 #[test]
458 fn local_wildcard_allows_any_hash_prefixed_caller() {
459 let acl = m(&[("#", allow(&[CAP_INBOX]))]);
461 assert!(check_cap(&acl, "#fortune", CAP_INBOX).is_ok());
462 assert!(check_cap(&acl, "#scheduler", CAP_INBOX).is_ok());
463 assert!(check_cap(&acl, "#any_entity", CAP_INBOX).is_ok());
464 }
465
466 #[test]
467 fn local_wildcard_does_not_match_remote_callers() {
468 let acl = m(&[("#", allow(&[CAP_INBOX]))]);
470 assert!(check_cap(&acl, "did:ma:remote", CAP_INBOX).is_err());
471 }
472
473 #[test]
474 fn specific_local_entity_wins_over_local_wildcard() {
475 let acl = m(&[
477 ("#", allow(&[CAP_INBOX, CAP_IPFS])),
478 ("#fortune", allow(&[CAP_INBOX])), ]);
480 assert!(check_cap(&acl, "#fortune", CAP_INBOX).is_ok());
481 assert!(check_cap(&acl, "#fortune", CAP_IPFS).is_err());
482 assert!(check_cap(&acl, "#other", CAP_IPFS).is_ok());
484 }
485
486 #[test]
487 fn local_wildcard_deny_blocks_all_local_entities() {
488 let acl = m(&[
489 ("#", CapabilityEntry::Deny),
490 ("*", allow(&[CAP_INBOX])), ]);
492 assert!(check_cap(&acl, "#fortune", CAP_INBOX).is_err());
493 assert!(check_cap(&acl, "#any", CAP_INBOX).is_err());
494 assert!(check_cap(&acl, "did:ma:remote", CAP_INBOX).is_ok());
496 }
497
498 #[test]
499 fn specific_local_entity_allow_overrides_local_wildcard_deny() {
500 let acl = m(&[
502 ("#", CapabilityEntry::Deny),
503 ("#fortune", allow(&[CAP_INBOX])),
504 ]);
505 assert!(check_cap(&acl, "#fortune", CAP_INBOX).is_ok());
506 assert!(check_cap(&acl, "#other", CAP_INBOX).is_err());
507 }
508
509 #[test]
510 fn global_wildcard_not_triggered_for_hash_caller_when_local_wildcard_present() {
511 let acl = m(&[("#", CapabilityEntry::Deny), ("*", allow(&[CAP_INBOX]))]);
513 assert!(check_cap(&acl, "#fortune", CAP_INBOX).is_err());
515 }
516
517 #[test]
518 fn local_wildcard_is_key_form_valid() {
519 assert!(is_principal_key("#"));
520 assert!(is_principal_key("#fortune"));
521 assert!(is_principal_key("*"));
522 assert!(is_principal_key("did:ma:alice"));
523 }
524
525 #[test]
526 fn explicit_deny_without_wildcard() {
527 let acl = m(&[("did:ma:bandit", CapabilityEntry::Deny)]);
529 assert!(check_cap(&acl, "did:ma:bandit", CAP_INBOX).is_err());
530 assert!(check_cap(&acl, "did:ma:alice", CAP_INBOX).is_err());
532 }
533
534 #[test]
535 fn multiple_caps_in_single_entry() {
536 let acl = m(&[("did:ma:alice", allow(&[CAP_INBOX, CAP_IPFS, CAP_READ]))]);
537 assert!(check_cap(&acl, "did:ma:alice", CAP_INBOX).is_ok());
538 assert!(check_cap(&acl, "did:ma:alice", CAP_IPFS).is_ok());
539 assert!(check_cap(&acl, "did:ma:alice", CAP_READ).is_ok());
540 assert!(check_cap(&acl, "did:ma:alice", CAP_CREATE).is_err());
541 assert!(check_cap(&acl, "did:ma:alice", CAP_DELETE).is_err());
542 }
543
544 #[test]
545 fn direct_entry_restricts_even_when_wildcard_is_broader() {
546 let acl = m(&[
549 ("*", allow(&[CAP_INBOX, CAP_IPFS])),
550 ("did:ma:bob", allow(&[CAP_INBOX])),
551 ]);
552 assert!(check_cap(&acl, "did:ma:bob", CAP_INBOX).is_ok());
553 assert!(check_cap(&acl, "did:ma:bob", CAP_IPFS).is_err());
554 assert!(check_cap(&acl, "did:ma:alice", CAP_INBOX).is_ok());
556 assert!(check_cap(&acl, "did:ma:alice", CAP_IPFS).is_ok());
557 }
558
559 #[test]
560 fn group_principal_allowed() {
561 let acl = m(&[("*", allow(&[CAP_INBOX]))]);
564 assert!(check_cap(&acl, "did:ma:anyone", CAP_INBOX).is_ok());
565 }
566
567 #[test]
568 fn valid_acl_keys() {
569 assert!(is_valid_acl_key("*"));
570 assert!(is_valid_acl_key("did:ma:k51foo"));
571 assert!(is_valid_acl_key("#agent"));
572 assert!(is_valid_acl_key("+alice.venner"));
573 assert!(is_valid_acl_key("+runtime.admins"));
574 assert!(is_valid_acl_key("fortune"));
575 assert!(is_valid_acl_key("admin"));
576 assert!(is_valid_acl_key("emote"));
577 assert!(!is_valid_acl_key(""));
578 }
579
580 #[cfg(feature = "acl")]
581 #[test]
582 fn capability_serde_roundtrip() {
583 let acl: AclMap = [
584 (
585 "*".to_string(),
586 CapabilityEntry::from_caps(["rpc", "create"]),
587 ),
588 ("did:ma:bandit".to_string(), CapabilityEntry::Deny),
589 ]
590 .into_iter()
591 .collect();
592 let yaml = serde_yaml::to_string(&acl).unwrap();
593 let roundtrip: AclMap = serde_yaml::from_str(&yaml).unwrap();
594 assert_eq!(acl, roundtrip);
595 }
596
597 #[cfg(feature = "acl")]
598 #[test]
599 fn yaml_null_deserializes_to_deny() {
600 let yaml = "'did:ma:x': ~\n'*':\n- rpc\n- create\n";
601 let acl: AclMap = serde_yaml::from_str(yaml).unwrap();
602 assert_eq!(acl.get("did:ma:x"), Some(&CapabilityEntry::Deny));
603 assert_eq!(
604 acl.get("*"),
605 Some(&CapabilityEntry::from_caps(["rpc", "create"]))
606 );
607 }
608}