Skip to main content

atomic_integration_proxy/
access.rs

1//! Who may use this proxy (issue #54, section 5).
2//!
3//! The atomic.place proxy admits agents that have a SaaS account, and checks
4//! their tier; how an agent is linked to an account is decided in
5//! ontola/atomic-saas#138. A self-hosted proxy admits every agent, or keeps
6//! its own list. Both are an [`AccessPolicy`]: the proxy asks it at
7//! `/connect/redeem` and on every signed request, always about the
8//! connection's **owner** (a delegated app agent or a frame is checked
9//! against the owner it acts for), so freemium limits count per owner.
10//!
11//! The default, [`EnvAccessPolicy`], admits everyone except the agents in
12//! `REVOKED_SUBJECTS`, and, when `ALLOWED_AGENTS` is set, only those.
13use std::{collections::HashSet, future::Future, pin::Pin};
14
15use crate::agent_id::{self, AgentId};
16
17/// The answer to "may this owner use the proxy now?".
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum Access {
20    Allowed,
21    /// Refused, with a reason safe to show the caller.
22    Denied(String),
23}
24
25/// A pluggable admission check. Implementations should answer quickly (the
26/// check runs on every request) and cache lookups as they see fit.
27pub 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
32/// Admits every agent. Useful for a self-hosted proxy and in tests.
33pub 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
44/// The policy configured from the environment: a denylist and an optional
45/// allowlist, both of agent ids in any accepted spelling.
46pub struct EnvAccessPolicy {
47    allowed: Option<HashSet<String>>,
48    revoked: HashSet<String>,
49}
50
51impl EnvAccessPolicy {
52    /// Ids that do not parse as agent ids are ignored (and logged), so a stale
53    /// entry cannot lock everyone out or in.
54    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}