Skip to main content

weirdnet_service/
auth.rs

1//! Who is calling, what they ask for, and the hook that decides.
2
3use std::sync::Arc;
4
5use serde::{Deserialize, Serialize};
6use serde_bytes::ByteBuf;
7
8use crate::ServiceError;
9
10/// What a caller presents once per stream, as opaque CBOR bytes for the [`Authorize`] hook to
11/// check. On Weirdnet: the caller's `NodeCert`, its user `Card` and any `Membership`s (see
12/// [`with_node_cert`](Self::with_node_cert) and friends with the `net` feature). None of it
13/// is trusted on its own: hooks check it against the transport-authenticated peer.
14#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
15pub struct Credentials {
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    cert: Option<ByteBuf>,
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    card: Option<ByteBuf>,
20    #[serde(default, skip_serializing_if = "Vec::is_empty")]
21    memberships: Vec<ByteBuf>,
22}
23
24impl Credentials {
25    pub fn new() -> Self {
26        Self::default()
27    }
28
29    /// A CBOR device certificate (`weirdnet_net::user::NodeCert`).
30    pub fn with_cert(mut self, cert: Vec<u8>) -> Self {
31        self.cert = Some(ByteBuf::from(cert));
32        self
33    }
34
35    /// A CBOR user card (`weirdnet_net::user::Card`) certifying the calling device.
36    pub fn with_card(mut self, card: Vec<u8>) -> Self {
37        self.card = Some(ByteBuf::from(card));
38        self
39    }
40
41    /// Adds a CBOR membership (`weirdnet_net::member::Membership`).
42    pub fn with_membership(mut self, membership: Vec<u8>) -> Self {
43        self.memberships.push(ByteBuf::from(membership));
44        self
45    }
46
47    pub fn cert(&self) -> Option<&[u8]> {
48        self.cert.as_deref().map(|b| b.as_slice())
49    }
50
51    pub fn card(&self) -> Option<&[u8]> {
52        self.card.as_deref().map(|b| b.as_slice())
53    }
54
55    pub fn memberships(&self) -> impl Iterator<Item = &[u8]> {
56        self.memberships.iter().map(|b| b.as_slice())
57    }
58}
59
60/// Who is calling. `peer` is the transport-authenticated peer id (Noise on Weirdnet), never
61/// one the caller sent.
62#[derive(Debug, Clone, PartialEq, Eq, Default)]
63pub struct Caller {
64    pub peer: String,
65    pub credentials: Credentials,
66}
67
68impl Caller {
69    pub fn new(peer: impl Into<String>, credentials: Credentials) -> Self {
70        Self { peer: peer.into(), credentials }
71    }
72}
73
74/// What a request or subscription needs: a permission, optionally on a resource (an account,
75/// a site, a project).
76#[derive(Debug, Clone, PartialEq, Eq, Hash)]
77pub struct Access {
78    pub permission: String,
79    pub resource: Option<String>,
80}
81
82impl Access {
83    /// The permission checked when a session opens.
84    pub const SESSION: &'static str = "session";
85
86    pub fn new(permission: impl Into<String>) -> Self {
87        Self { permission: permission.into(), resource: None }
88    }
89
90    /// The check when a session opens: no resource, permission [`SESSION`](Self::SESSION).
91    pub fn session() -> Self {
92        Self::new(Self::SESSION)
93    }
94
95    /// The same permission on `resource`.
96    pub fn on(mut self, resource: impl Into<String>) -> Self {
97        self.resource = Some(resource.into());
98        self
99    }
100
101    pub fn is_session(&self) -> bool {
102        self.permission == Self::SESSION && self.resource.is_none()
103    }
104}
105
106/// A caller the hook let in, and what it learned about them. Handlers get it with each call.
107#[derive(Debug, Clone, PartialEq, Eq, Default)]
108#[non_exhaustive]
109pub struct Admitted {
110    /// The transport-authenticated peer.
111    pub peer: String,
112    /// The user id the peer resolves to, when the hook knows it.
113    pub user: Option<String>,
114    /// Device roles granted to the peer (weirdnet-sync grants), when known.
115    pub device_roles: Option<Vec<String>>,
116    /// The resource the access was on.
117    pub resource: Option<String>,
118    /// The caller's role on that resource (`owner`, a membership role, `guest`), when known.
119    pub role: Option<String>,
120}
121
122impl Admitted {
123    pub fn new(peer: impl Into<String>) -> Self {
124        Self { peer: peer.into(), ..Self::default() }
125    }
126
127    pub fn with_user(mut self, user: impl Into<String>) -> Self {
128        self.user = Some(user.into());
129        self
130    }
131
132    pub fn with_device_roles(mut self, roles: Option<Vec<String>>) -> Self {
133        self.device_roles = roles;
134        self
135    }
136
137    pub fn with_resource(mut self, resource: impl Into<String>) -> Self {
138        self.resource = Some(resource.into());
139        self
140    }
141
142    pub fn with_role(mut self, role: impl Into<String>) -> Self {
143        self.role = Some(role.into());
144        self
145    }
146
147    pub fn has_device_role(&self, role: &str) -> bool {
148        self.device_roles.as_ref().is_some_and(|r| r.iter().any(|x| x == role))
149    }
150
151    /// Fills what `self` does not know from `other` (same peer).
152    pub fn merge(mut self, other: Admitted) -> Self {
153        self.user = self.user.or(other.user);
154        self.device_roles = self.device_roles.or(other.device_roles);
155        self.resource = self.resource.or(other.resource);
156        self.role = self.role.or(other.role);
157        self
158    }
159}
160
161/// Decides whether a caller may have an [`Access`]. Called when a session opens (with
162/// [`Access::session`]), for every call, when a subscription starts and again every
163/// [`FeedOptions::recheck`](crate::FeedOptions::recheck) while it runs.
164///
165/// It is synchronous and should be quick: keep rosters, revocations and role sets in memory
166/// and refresh them from storage in the background. A closure works too.
167pub trait Authorize: Send + Sync {
168    fn authorize(&self, caller: &Caller, access: &Access) -> Result<Admitted, ServiceError>;
169}
170
171impl<F> Authorize for F
172where
173    F: Fn(&Caller, &Access) -> Result<Admitted, ServiceError> + Send + Sync,
174{
175    fn authorize(&self, caller: &Caller, access: &Access) -> Result<Admitted, ServiceError> {
176        self(caller, access)
177    }
178}
179
180/// Lets everyone in. For tests and genuinely public services only.
181#[derive(Debug, Clone, Copy, Default)]
182pub struct AllowAll;
183
184impl Authorize for AllowAll {
185    fn authorize(&self, caller: &Caller, access: &Access) -> Result<Admitted, ServiceError> {
186        let a = Admitted::new(caller.peer.clone());
187        Ok(match &access.resource {
188            Some(r) => a.with_resource(r.clone()),
189            None => a,
190        })
191    }
192}
193
194/// Every hook must agree; the first refusal is the answer, and what they learned is merged.
195/// An empty list refuses.
196#[derive(Clone)]
197pub struct AllOf(pub Vec<Arc<dyn Authorize>>);
198
199impl Authorize for AllOf {
200    fn authorize(&self, caller: &Caller, access: &Access) -> Result<Admitted, ServiceError> {
201        let mut out: Option<Admitted> = None;
202        for a in &self.0 {
203            let got = a.authorize(caller, access)?;
204            out = Some(match out {
205                None => got,
206                Some(prev) => prev.merge(got),
207            });
208        }
209        out.ok_or_else(|| ServiceError::refused("no-authorizer"))
210    }
211}
212
213/// The first hook that lets the caller in wins. When all refuse, the last refusal is the
214/// answer. An empty list refuses.
215#[derive(Clone)]
216pub struct AnyOf(pub Vec<Arc<dyn Authorize>>);
217
218impl Authorize for AnyOf {
219    fn authorize(&self, caller: &Caller, access: &Access) -> Result<Admitted, ServiceError> {
220        let mut last = ServiceError::refused("no-authorizer");
221        for a in &self.0 {
222            match a.authorize(caller, access) {
223                Ok(got) => return Ok(got),
224                Err(e) => last = e,
225            }
226        }
227        Err(last)
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234    use crate::codec::{from_cbor, to_cbor};
235
236    #[test]
237    fn combinators_merge_and_refuse() {
238        let user = |c: &Caller, _: &Access| Ok(Admitted::new(c.peer.clone()).with_user("u1"));
239        let role = |c: &Caller, a: &Access| {
240            if a.permission == "write" { Err(ServiceError::refused("role")) } else { Ok(Admitted::new(c.peer.clone()).with_role("viewer")) }
241        };
242        let caller = Caller::new("p", Credentials::new());
243        let all = AllOf(vec![Arc::new(user), Arc::new(role)]);
244        let got = all.authorize(&caller, &Access::new("read")).unwrap();
245        assert_eq!((got.user.as_deref(), got.role.as_deref()), (Some("u1"), Some("viewer")));
246        assert_eq!(all.authorize(&caller, &Access::new("write")), Err(ServiceError::refused("role")));
247        assert!(AllOf(vec![]).authorize(&caller, &Access::session()).is_err());
248        let any = AnyOf(vec![Arc::new(role), Arc::new(user)]);
249        assert_eq!(any.authorize(&caller, &Access::new("write")).unwrap().user.as_deref(), Some("u1"));
250        assert!(AnyOf(vec![]).authorize(&caller, &Access::session()).is_err());
251        assert_eq!(AllowAll.authorize(&caller, &Access::new("x").on("acct")).unwrap().resource.as_deref(), Some("acct"));
252    }
253
254    #[test]
255    fn credentials_travel_as_byte_strings() {
256        let c = Credentials::new().with_cert(vec![1, 2]).with_membership(vec![3]).with_membership(vec![4, 5]);
257        let bytes = to_cbor(&c).unwrap();
258        assert!(bytes.len() < 30, "byte strings, not arrays of numbers");
259        let back: Credentials = from_cbor(&bytes).unwrap();
260        assert_eq!(back, c);
261        assert_eq!(back.memberships().collect::<Vec<_>>(), [&[3u8][..], &[4, 5][..]]);
262        assert_eq!(from_cbor::<Credentials>(&to_cbor(&Credentials::new()).unwrap()).unwrap(), Credentials::new());
263        assert!(Access::session().is_session() && !Access::session().on("x").is_session());
264    }
265}