atomic_integration_proxy/
access.rs1use std::{collections::HashSet, future::Future, pin::Pin};
14
15use crate::agent_id::{self, AgentId};
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum Access {
20 Allowed,
21 Denied(String),
23}
24
25pub trait AccessPolicy: Send + Sync + 'static {
28 fn check<'a>(&'a self, owner: &'a AgentId)
29 -> Pin<Box<dyn Future<Output = Access> + Send + 'a>>;
30}
31
32pub struct AllowAll;
34
35impl AccessPolicy for AllowAll {
36 fn check<'a>(
37 &'a self,
38 _owner: &'a AgentId,
39 ) -> Pin<Box<dyn Future<Output = Access> + Send + 'a>> {
40 Box::pin(async { Access::Allowed })
41 }
42}
43
44pub struct EnvAccessPolicy {
47 allowed: Option<HashSet<String>>,
48 revoked: HashSet<String>,
49}
50
51impl EnvAccessPolicy {
52 pub fn new(allowed: Option<Vec<String>>, revoked: Vec<String>) -> Self {
55 let canonical = |ids: Vec<String>| -> HashSet<String> {
56 ids.into_iter()
57 .filter_map(|id| match agent_id::parse(id.trim()) {
58 Some(agent) => Some(agent.as_str().to_owned()),
59 None => {
60 tracing::warn!(%id, "ignoring an access-list entry that is not an atomic:agent id");
61 None
62 }
63 })
64 .collect()
65 };
66 Self {
67 allowed: allowed.map(canonical),
68 revoked: canonical(revoked),
69 }
70 }
71}
72
73impl AccessPolicy for EnvAccessPolicy {
74 fn check<'a>(
75 &'a self,
76 owner: &'a AgentId,
77 ) -> Pin<Box<dyn Future<Output = Access> + Send + 'a>> {
78 let answer = if self.revoked.contains(owner.as_str()) {
79 Access::Denied("this agent is revoked on this proxy".into())
80 } else if self
81 .allowed
82 .as_ref()
83 .is_some_and(|allowed| !allowed.contains(owner.as_str()))
84 {
85 Access::Denied("this agent is not on this proxy's allowlist".into())
86 } else {
87 Access::Allowed
88 };
89 Box::pin(async move { answer })
90 }
91}
92
93#[cfg(test)]
94mod tests {
95 use super::*;
96 use crate::agent_id::test_signer::Agent;
97
98 #[tokio::test]
99 async fn the_env_policy_canonicalizes_and_applies_both_lists() {
100 let (a, b, c) = (Agent::new(1), Agent::new(2), Agent::new(3));
101 let parse = |agent: &Agent| agent_id::parse(&agent.id()).unwrap();
102 let open = EnvAccessPolicy::new(None, vec![b.legacy_id(), "garbage".into()]);
103 assert_eq!(open.check(&parse(&a)).await, Access::Allowed);
104 assert!(matches!(open.check(&parse(&b)).await, Access::Denied(_)));
105 let closed = EnvAccessPolicy::new(Some(vec![a.legacy_id()]), vec![]);
106 assert_eq!(closed.check(&parse(&a)).await, Access::Allowed);
107 assert!(matches!(closed.check(&parse(&c)).await, Access::Denied(_)));
108 assert_eq!(AllowAll.check(&parse(&c)).await, Access::Allowed);
109 }
110}