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 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 #[test]
459 fn local_wildcard_allows_any_hash_prefixed_caller() {
460 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 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 let acl = m(&[
478 ("#", allow(&[CAP_INBOX, CAP_IPFS])),
479 ("#fortune", allow(&[CAP_INBOX])), ]);
481 assert!(check_cap(&acl, "#fortune", CAP_INBOX).is_ok());
482 assert!(check_cap(&acl, "#fortune", CAP_IPFS).is_err());
483 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])), ]);
493 assert!(check_cap(&acl, "#fortune", CAP_INBOX).is_err());
494 assert!(check_cap(&acl, "#any", CAP_INBOX).is_err());
495 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 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 let acl = m(&[("#", CapabilityEntry::Deny), ("*", allow(&[CAP_INBOX]))]);
514 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 let acl = m(&[("did:ma:bandit", CapabilityEntry::Deny)]);
530 assert!(check_cap(&acl, "did:ma:bandit", CAP_INBOX).is_err());
531 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 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 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 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}