Skip to main content

weirdnet_agent/
serve.rs

1//! The `serve` feature: the inference side of remote inference over `weirdnet-net`.
2//!
3//! [`Server::start`] accepts `/weirdnet-agent/infer/1`, `/weirdnet-agent/infer/2` and
4//! `/weirdnet-agent/catalog/1` streams on a node and serves each through the transport-neutral
5//! serve functions, with the stream's Noise-authenticated peer as the [`Caller`]. It announces
6//! [`INFERENCE_APP`] so pools find the node (model nodes serving raw infer/2 to inference nodes
7//! pass `announce: false`).
8//!
9//! [`RosterAuth`] is the authorize hook for hosts: `weirdnet_sync::Roster::check_caller` with
10//! the peer and the certificate the caller presented. Hosts call it from
11//! [`InferHost::authorize`] and [`CatalogHost::authorize`]. With
12//! [`require_roles`](RosterAuth::require_roles) it also needs one of the device roles the user
13//! granted the caller (the grants in the `weirdnet-sync` 0.7 or later roster, `Roster::roles_of`).
14//!
15//! [`Server::start_with`] also serves `/weirdnet-agent/task/1` ([`ServingExtras::tasks`]): each
16//! task is admitted by the given [`Authorize`] and built by [`TaskHost::session_for`].
17//!
18//! # Guests: sharing a pool with another Weirdnet identity (since 0.5.9)
19//!
20//! [`GuestAuth`] admits a caller whose certificate chains to a *different* Weirdnet user (a
21//! guest), with the same checks as the roster makes for the user's own devices: the guest
22//! presents a credential ([`encode_credential`]: its `NodeCert` plus its user's public key);
23//! the key must hash to the certificate's user id, the user's signature over the peer id must
24//! verify, the certificate must be for the transport-authenticated peer, and it must not be
25//! revoked (a revocation must carry its signature) nor issued in the future (beyond the clock
26//! skew). Only then does the host's guest policy (a closure over its synced guest list) see the
27//! [`Guest`] and the [`GuestScope`] (`catalog` or `infer`) and decide. Guests are never
28//! members of the roster, never get the root seed or synced types, and are never admitted to
29//! task/1 or any protocol the host does not ask [`GuestAuth`] about.
30//!
31//! [`SharedPoolAuth`] puts the two together for an inference node's [`InferHost::authorize`]
32//! and [`CatalogHost::authorize`]: the user's own devices by the roster ([`RosterAuth`],
33//! unchanged), guests by [`GuestAuth`]. Without [`with_guests`](SharedPoolAuth::with_guests) it
34//! is exactly the roster check: guests are refused (`wrong-user`), as by every host before
35//! 0.5.9. A guest credential naming the host's own user always goes to the roster.
36//!
37//! Every infer/2 request kind (chat, embeddings, transcription and, since 0.5.11, speech out) goes
38//! through the same [`InferHost::authorize`], so a guest needs [`GuestScope::Infer`] for each;
39//! what a guest may do beyond that (which speakers, whether it may clone a voice) is the host's
40//! call in [`InferHost::open_speak`], which sees the caller and the whole request
41//! ([`SharedPoolAuth::identify`] tells a guest from the user's own devices).
42//!
43//! Revocation is live: the policy runs on every infer/1 and infer/2 request (one per stream) and
44//! every catalog query; a catalog subscription is re-checked before each update and every few
45//! seconds when the host re-checks ([`CatalogHost::recheck`], [`CatalogFeed::rechecking`]), and
46//! closed with the policy's refusal. An answer already streaming finishes.
47
48use std::sync::Arc;
49
50use weirdnet_net::node::Message;
51use weirdnet_net::profile::Profile;
52use weirdnet_net::user::NodeCert;
53use weirdnet_net::{AppBody, AppResponse, Incoming, Node, PublicKey};
54use weirdnet_sync::{CallerCheck, Roster};
55
56pub use crate::net::{INFERENCE_APP, Presented, channel, decode_cert, decode_presented, encode_cert, encode_credential, stream_limits};
57pub use crate::remote::catalog::{CatalogFeed, CatalogHost};
58pub use crate::remote::infer::v2::{
59    AudioHeader, AudioSink, AudioStream, EmbedBackend, InferBackend, ModelAdapter, Output, SpeakBackend, SpeechPiece, TranscribeBackend,
60};
61pub use crate::remote::infer::{Admission, InferHost};
62pub use crate::remote::task::TaskHost;
63use crate::remote::{Admitted, Authorize, Caller, RemoteError, catalog, infer, task};
64
65/// The roster as it is now (the app keeps it current from `weirdnet-sync`).
66pub type RosterView = Arc<dyn Fn() -> Roster + Send + Sync>;
67
68/// The device roles a peer holds, `None` without a grant. With `weirdnet-sync` 0.7 or later:
69/// `Arc::new(move |peer| identity.roster().roles_of(peer))`.
70pub type RoleView = Arc<dyn Fn(&str) -> Option<Vec<String>> + Send + Sync>;
71
72/// Admits only the user's linked devices (`Roster::check_caller`). Refusals carry the roster's
73/// reason (`unknown-device`, `revoked`, `wrong-user`, `needs-admission`).
74///
75/// With [`require_roles`](Self::require_roles) a linked caller also needs one of the roles
76/// (refused with `role` otherwise); without it any linked device is let in, as before.
77pub struct RosterAuth {
78    profile: &'static Profile,
79    user: PublicKey,
80    roster: RosterView,
81    roles: Option<RoleView>,
82    any_of: Vec<String>,
83}
84
85impl RosterAuth {
86    pub fn new(profile: &'static Profile, user: PublicKey, roster: RosterView) -> Self {
87        Self { profile, user, roster, roles: None, any_of: Vec::new() }
88    }
89
90    /// Needs one of `any_of` among the caller's granted roles. An empty `any_of` needs none but
91    /// still reports roles in [`admit`](Authorize::admit).
92    pub fn require_roles(mut self, any_of: &[&str], roles: RoleView) -> Self {
93        self.any_of = any_of.iter().map(|r| r.to_string()).collect();
94        self.roles = Some(roles);
95        self
96    }
97
98    /// The roster's verdict on `caller`. The presented certificate may be bare or (since 0.5.9)
99    /// inside a guest credential; either way it is checked against this user's key, so a
100    /// certificate of another user is `WrongUser`.
101    pub fn check(&self, caller: &Caller) -> CallerCheck {
102        let presented = match caller.cert_bytes.as_deref().map(decode_presented) {
103            None => None,
104            Some(Ok(p)) => Some(p.cert),
105            Some(Err(_)) => return CallerCheck::WrongUser,
106        };
107        (self.roster)().check_caller(self.profile, &self.user, &caller.peer, presented.as_ref())
108    }
109}
110
111impl Authorize for RosterAuth {
112    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
113        self.admit(caller).map(|_| ())
114    }
115
116    fn admit(&self, caller: &Caller) -> Result<Admitted, RemoteError> {
117        if let Some(reason) = self.check(caller).reason() {
118            return Err(RemoteError::refused(reason));
119        }
120        let roles = self.roles.as_ref().and_then(|view| view(&caller.peer));
121        if !self.any_of.is_empty() && !roles.as_ref().is_some_and(|have| have.iter().any(|r| self.any_of.contains(r))) {
122            return Err(RemoteError::refused("role"));
123        }
124        Ok(Admitted::new(caller.peer.clone(), roles))
125    }
126}
127
128/// What a guest may use: the protocol being asked for. A guest policy decides per scope.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
130#[non_exhaustive]
131pub enum GuestScope {
132    /// catalog/1: query or subscribe.
133    Catalog,
134    /// infer/1 and infer/2: chat, embeddings, transcription, speech out.
135    Infer,
136}
137
138impl GuestScope {
139    pub fn as_str(self) -> &'static str {
140        match self {
141            GuestScope::Catalog => "catalog",
142            GuestScope::Infer => "infer",
143        }
144    }
145}
146
147/// A verified guest: a device of another Weirdnet user, its certificate checked against that
148/// user's key and the transport peer. Who may use the pool is the guest policy's decision.
149#[derive(Debug, Clone, PartialEq)]
150#[non_exhaustive]
151pub struct Guest {
152    /// The guest's Weirdnet user id (32 hex characters).
153    pub user_id: String,
154    /// The guest's user public key (protobuf), which hashes to `user_id`.
155    pub user_key: Vec<u8>,
156    /// The transport-authenticated peer id (equal to `cert.peer_id`).
157    pub peer: String,
158    /// The device label its user gave it (not authenticated: the signature covers user, peer and
159    /// time only).
160    pub label: String,
161    /// When its user certified the device (Unix ms).
162    pub issued_at: i64,
163    pub cert: NodeCert,
164}
165
166/// The host's guest policy: `Ok` admits the guest for the scope, an error is sent back as the
167/// refusal (for example `RemoteError::refused("not-shared")`). Called on every check, so it
168/// should read the current synced guest list (revoking there takes effect on the next request).
169pub type GuestPolicy = Arc<dyn Fn(&Guest, GuestScope) -> Result<(), RemoteError> + Send + Sync>;
170
171/// How far in the future a certificate's `issued_at` may be by default (clock skew): 10 minutes.
172pub const DEFAULT_CLOCK_SKEW: std::time::Duration = std::time::Duration::from_secs(600);
173
174/// Verifies guests (devices of another Weirdnet user) and asks the [`GuestPolicy`]. See the
175/// [module docs](self#guests-sharing-a-pool-with-another-weirdnet-identity-since-059).
176///
177/// Refusal reasons: `guest-no-cert` (nothing presented), `guest-no-key` (a bare certificate,
178/// not a guest credential), `guest-bad-key` (the key does not decode or does not hash to the
179/// certificate's user id), `wrong-peer` (the certificate is for another peer), `guest-bad-cert`
180/// (the signature, or a revocation's, does not verify), `revoked`, `guest-future-cert`, and
181/// `own-user` (the host's own user: that is the roster's call, never a guest's); then whatever
182/// the policy answers.
183pub struct GuestAuth {
184    profile: &'static Profile,
185    host_user_id: String,
186    policy: GuestPolicy,
187    skew_ms: i64,
188}
189
190impl GuestAuth {
191    /// Guests of the pool owned by `host_user`, admitted by `policy`.
192    pub fn new(profile: &'static Profile, host_user: &PublicKey, policy: GuestPolicy) -> Self {
193        Self { profile, host_user_id: weirdnet_net::user::user_id(host_user), policy, skew_ms: DEFAULT_CLOCK_SKEW.as_millis() as i64 }
194    }
195
196    /// How far in the future `issued_at` may be ([`DEFAULT_CLOCK_SKEW`]).
197    pub fn with_clock_skew(mut self, skew: std::time::Duration) -> Self {
198        self.skew_ms = i64::try_from(skew.as_millis()).unwrap_or(i64::MAX);
199        self
200    }
201
202    /// The cryptographic checks only (no policy): who the caller is, if a valid guest.
203    pub fn verify(&self, caller: &Caller) -> Result<Guest, RemoteError> {
204        self.verify_at(caller, weirdnet_net::now_ms())
205    }
206
207    fn verify_at(&self, caller: &Caller, now_ms: i64) -> Result<Guest, RemoteError> {
208        let bytes = caller.cert_bytes.as_deref().ok_or_else(|| RemoteError::refused("guest-no-cert"))?;
209        let presented = decode_presented(bytes).map_err(|_| RemoteError::refused("guest-bad-cert"))?;
210        let cert = presented.cert;
211        let key_bytes = presented.user_key.ok_or_else(|| RemoteError::refused("guest-no-key"))?;
212        let key = weirdnet_net::user::decode_public(&key_bytes).map_err(|_| RemoteError::refused("guest-bad-key"))?;
213        let user_id = weirdnet_net::user::user_id(&key);
214        if user_id != cert.user_id {
215            return Err(RemoteError::refused("guest-bad-key"));
216        }
217        if user_id == self.host_user_id {
218            return Err(RemoteError::refused("own-user"));
219        }
220        if cert.peer_id != caller.peer {
221            return Err(RemoteError::refused("wrong-peer"));
222        }
223        if !self.profile.verify_cert(&key, &cert) {
224            return Err(RemoteError::refused("guest-bad-cert"));
225        }
226        if !cert.active() {
227            return Err(RemoteError::refused("revoked"));
228        }
229        if cert.issued_at > now_ms.saturating_add(self.skew_ms) {
230            return Err(RemoteError::refused("guest-future-cert"));
231        }
232        Ok(Guest { user_id, user_key: key_bytes, peer: caller.peer.clone(), label: cert.label.clone(), issued_at: cert.issued_at, cert })
233    }
234
235    /// [`verify`](Self::verify), then the policy for `scope`.
236    pub fn admit(&self, caller: &Caller, scope: GuestScope) -> Result<Guest, RemoteError> {
237        let guest = self.verify(caller)?;
238        (self.policy)(&guest, scope)?;
239        Ok(guest)
240    }
241}
242
243/// Who an inference node let in ([`SharedPoolAuth::identify`]).
244#[derive(Debug, Clone, PartialEq)]
245#[non_exhaustive]
246pub enum CallerIdentity {
247    /// One of the user's own linked devices, by the roster.
248    Own(Admitted),
249    /// A guest of another Weirdnet user, by the guest policy.
250    Guest(Guest),
251}
252
253impl CallerIdentity {
254    pub fn is_guest(&self) -> bool {
255        matches!(self, CallerIdentity::Guest(_))
256    }
257
258    pub fn guest(&self) -> Option<&Guest> {
259        match self {
260            CallerIdentity::Guest(g) => Some(g),
261            CallerIdentity::Own(_) => None,
262        }
263    }
264
265    pub fn peer(&self) -> &str {
266        match self {
267            CallerIdentity::Own(a) => &a.peer,
268            CallerIdentity::Guest(g) => &g.peer,
269        }
270    }
271}
272
273/// An inference node's caller check with optional guests: the roster for the user's own
274/// devices, [`GuestAuth`] for other users' (only with [`with_guests`](Self::with_guests);
275/// without it this is exactly [`RosterAuth`]). Use [`authorize_for`](Self::authorize_for) in
276/// [`InferHost::authorize`] (with [`GuestScope::Infer`]) and give
277/// [`scoped`](Self::scoped)`(GuestScope::Catalog)` to a [`CatalogFeed`]. It deliberately does not
278/// implement [`Authorize`] itself, so it can't be handed to task/1 or another protocol by
279/// mistake: hand those the [`RosterAuth`].
280#[derive(Clone)]
281pub struct SharedPoolAuth {
282    roster: Arc<RosterAuth>,
283    guests: Option<Arc<GuestAuth>>,
284}
285
286impl SharedPoolAuth {
287    /// The roster only (guests refused).
288    pub fn new(roster: Arc<RosterAuth>) -> Self {
289        Self { roster, guests: None }
290    }
291
292    /// Also admit guests by `guests`.
293    pub fn with_guests(mut self, guests: Arc<GuestAuth>) -> Self {
294        self.guests = Some(guests);
295        self
296    }
297
298    pub fn admits_guests(&self) -> bool {
299        self.guests.is_some()
300    }
301
302    /// Who `caller` is, if let in for `scope`. A caller presenting a guest credential of another
303    /// user goes to the guest check (when guests are on); everyone else to the roster.
304    pub fn identify(&self, caller: &Caller, scope: GuestScope) -> Result<CallerIdentity, RemoteError> {
305        if let Some(guests) = &self.guests
306            && let Some(Ok(p)) = caller.cert_bytes.as_deref().map(decode_presented)
307            && p.user_key.is_some()
308            && p.cert.user_id != guests.host_user_id
309        {
310            return guests.admit(caller, scope).map(CallerIdentity::Guest);
311        }
312        self.roster.admit(caller).map(CallerIdentity::Own)
313    }
314
315    pub fn authorize_for(&self, caller: &Caller, scope: GuestScope) -> Result<(), RemoteError> {
316        self.identify(caller, scope).map(|_| ())
317    }
318
319    /// An [`Authorize`] for one scope (for [`CatalogFeed::new`]). Its `admit` reports a guest's
320    /// peer with no roles.
321    pub fn scoped(&self, scope: GuestScope) -> Arc<dyn Authorize> {
322        Arc::new(Scoped { auth: self.clone(), scope })
323    }
324}
325
326struct Scoped {
327    auth: SharedPoolAuth,
328    scope: GuestScope,
329}
330
331impl Authorize for Scoped {
332    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
333        self.auth.authorize_for(caller, self.scope)
334    }
335
336    fn admit(&self, caller: &Caller) -> Result<Admitted, RemoteError> {
337        match self.auth.identify(caller, self.scope)? {
338            CallerIdentity::Own(a) => Ok(a),
339            CallerIdentity::Guest(g) => Ok(Admitted::new(g.peer, None)),
340        }
341    }
342}
343
344/// Serving tasks on a node; dropping it stops accepting (calls under way carry on).
345pub struct Server {
346    tasks: Vec<tokio::task::JoinHandle<()>>,
347    announced: Option<Box<dyn Fn() + Send + Sync>>,
348}
349
350/// What a [`Server`] serves.
351#[derive(Clone)]
352pub struct Serving {
353    /// infer/1 and infer/2, sharing the admission slots.
354    pub infer: Option<(Arc<dyn InferHost>, Admission)>,
355    pub catalog: Option<Arc<dyn CatalogHost>>,
356    /// Announce [`INFERENCE_APP`] (inference nodes; not model nodes).
357    pub announce: bool,
358}
359
360/// What a [`Server`] serves beyond [`Serving`] (a separate struct so `Serving` literals keep
361/// compiling in 0.4.x; it folds into `Serving` in 0.5).
362#[derive(Clone, Default)]
363#[non_exhaustive]
364pub struct ServingExtras {
365    /// task/1: whole agent tasks, admitted by the `Authorize` (usually a [`RosterAuth`]).
366    pub tasks: Option<(Arc<dyn TaskHost>, Arc<dyn Authorize>)>,
367}
368
369impl ServingExtras {
370    pub fn tasks(mut self, host: Arc<dyn TaskHost>, auth: Arc<dyn Authorize>) -> Self {
371        self.tasks = Some((host, auth));
372        self
373    }
374}
375
376fn accept_loop(mut incoming: Incoming, serve: impl Fn(crate::remote::Channel, Caller) + Send + 'static) -> tokio::task::JoinHandle<()> {
377    tokio::spawn(async move {
378        while let Some(stream) = incoming.next().await {
379            let caller = Caller::new(stream.peer().to_string());
380            serve(channel(stream), caller);
381        }
382    })
383}
384
385impl Server {
386    /// Starts serving on `node`. Call from a Tokio runtime.
387    pub fn start<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, serving: Serving) -> Result<Server, RemoteError> {
388        Self::start_with(node, serving, ServingExtras::default())
389    }
390
391    /// [`start`](Self::start) plus [`ServingExtras`]. When tasks are served, task/1 is added to
392    /// the [`INFERENCE_APP`] announcement.
393    pub fn start_with<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, serving: Serving, extras: ServingExtras) -> Result<Server, RemoteError> {
394        let net = |e: weirdnet_net::NetError| RemoteError::Failed { message: e.to_string() };
395        let mut tasks = Vec::new();
396        if let Some((host, admission)) = serving.infer {
397            let (h, a) = (host.clone(), admission.clone());
398            tasks.push(accept_loop(node.accept_streams(infer::PROTOCOL, stream_limits()).map_err(net)?, move |ch, caller| {
399                let (h, a) = (h.clone(), a.clone());
400                tokio::spawn(async move {
401                    let _ = infer::serve(ch, &caller, h.as_ref(), &a).await;
402                });
403            }));
404            tasks.push(accept_loop(node.accept_streams(infer::v2::PROTOCOL, stream_limits()).map_err(net)?, move |ch, caller| {
405                let (h, a) = (host.clone(), admission.clone());
406                tokio::spawn(async move {
407                    let _ = infer::v2::serve(ch, caller, h.as_ref(), &a).await;
408                });
409            }));
410        }
411        if let Some(host) = serving.catalog {
412            tasks.push(accept_loop(node.accept_streams(catalog::PROTOCOL, stream_limits()).map_err(net)?, move |ch, caller| {
413                let h = host.clone();
414                tokio::spawn(async move {
415                    let _ = catalog::serve(ch, caller, h.as_ref()).await;
416                });
417            }));
418        }
419        let serves_tasks = extras.tasks.is_some();
420        if let Some((host, auth)) = extras.tasks {
421            tasks.push(accept_loop(node.accept_streams(task::PROTOCOL, stream_limits()).map_err(net)?, move |ch, caller| {
422                let (h, a) = (host.clone(), auth.clone());
423                tokio::spawn(async move {
424                    let _ = task::serve_for(ch, caller, a.as_ref(), h.as_ref()).await;
425                });
426            }));
427        }
428        let mut announced: Option<Box<dyn Fn() + Send + Sync>> = None;
429        if serving.announce {
430            let mut protocols = vec![infer::PROTOCOL, infer::v2::PROTOCOL, catalog::PROTOCOL];
431            if serves_tasks {
432                protocols.push(task::PROTOCOL);
433            }
434            let body = crate::remote::to_cbor(&protocols)?;
435            node.serve_app(
436                INFERENCE_APP,
437                Arc::new(move |_peer, _req| {
438                    let body = body.clone();
439                    async move { Ok(AppResponse::new(200).header("content-type", "application/cbor").body(AppBody::bytes(body))) }
440                }),
441            )
442            .map_err(|e| RemoteError::Failed { message: e.to_string() })?;
443            let n = node.clone();
444            announced = Some(Box::new(move || {
445                n.stop_serving_app(INFERENCE_APP);
446            }));
447        }
448        Ok(Server { tasks, announced })
449    }
450}
451
452impl Drop for Server {
453    fn drop(&mut self) {
454        for t in &self.tasks {
455            t.abort();
456        }
457        if let Some(stop) = self.announced.take() {
458            stop();
459        }
460    }
461}
462
463#[cfg(test)]
464mod guest_tests {
465    use std::sync::Mutex;
466
467    use weirdnet_net::{Keypair, WEIRDNET};
468
469    use super::*;
470
471    const PEER: &str = "12D3KooWGuestPeer";
472
473    struct Fixture {
474        host: Keypair,
475        guest: Keypair,
476        cert: NodeCert,
477        allowed: Arc<Mutex<Vec<(String, GuestScope)>>>,
478    }
479
480    fn fixture() -> Fixture {
481        let (host, guest) = (Keypair::generate_ed25519(), Keypair::generate_ed25519());
482        let uid = weirdnet_net::user::user_id(&guest.public());
483        let cert = WEIRDNET.certify(&guest, &uid, PEER, "morph", weirdnet_net::now_ms()).unwrap();
484        let allowed = Arc::new(Mutex::new(vec![(uid, GuestScope::Catalog), (weirdnet_net::user::user_id(&guest.public()), GuestScope::Infer)]));
485        Fixture { host, guest, cert, allowed }
486    }
487
488    fn guests(f: &Fixture) -> GuestAuth {
489        let allowed = f.allowed.clone();
490        let policy: GuestPolicy = Arc::new(move |g: &Guest, scope| {
491            if allowed.lock().unwrap().iter().any(|(u, s)| *u == g.user_id && *s == scope) { Ok(()) } else { Err(RemoteError::refused("not-shared")) }
492        });
493        GuestAuth::new(&WEIRDNET, &f.host.public(), policy)
494    }
495
496    fn caller(peer: &str, key: &Keypair, cert: &NodeCert) -> Caller {
497        Caller::new(peer).with_cert(encode_credential(&key.public(), cert))
498    }
499
500    fn refused(r: Result<impl std::fmt::Debug, RemoteError>) -> String {
501        match r {
502            Err(RemoteError::Refused { message }) => message,
503            other => panic!("not refused: {other:?}"),
504        }
505    }
506
507    #[test]
508    fn a_valid_guest_is_verified_and_admitted_per_scope() {
509        let f = fixture();
510        let auth = guests(&f);
511        let g = auth.admit(&caller(PEER, &f.guest, &f.cert), GuestScope::Infer).unwrap();
512        assert_eq!((g.user_id.as_str(), g.peer.as_str(), g.label.as_str()), (f.cert.user_id.as_str(), PEER, "morph"));
513        assert_eq!(g.user_key, f.guest.public().encode_protobuf());
514        // Scope: catalog only.
515        f.allowed.lock().unwrap().retain(|(_, s)| *s == GuestScope::Catalog);
516        assert!(auth.admit(&caller(PEER, &f.guest, &f.cert), GuestScope::Catalog).is_ok());
517        assert_eq!(refused(auth.admit(&caller(PEER, &f.guest, &f.cert), GuestScope::Infer)), "not-shared");
518        // Revoked in the policy: refused on the very next check.
519        f.allowed.lock().unwrap().clear();
520        assert_eq!(refused(auth.admit(&caller(PEER, &f.guest, &f.cert), GuestScope::Catalog)), "not-shared");
521        assert!(auth.verify(&caller(PEER, &f.guest, &f.cert)).is_ok(), "verify alone does not ask the policy");
522    }
523
524    #[test]
525    fn forged_wrong_peer_revoked_and_future_certs_are_refused() {
526        let f = fixture();
527        let auth = guests(&f);
528        let s = GuestScope::Infer;
529        // Nothing, or a bare certificate (no key to check it with).
530        assert_eq!(refused(auth.admit(&Caller::new(PEER), s)), "guest-no-cert");
531        assert_eq!(refused(auth.admit(&Caller::new(PEER).with_cert(encode_cert(&f.cert)), s)), "guest-no-key");
532        assert_eq!(refused(auth.admit(&Caller::new(PEER).with_cert(b"junk".to_vec()), s)), "guest-bad-cert");
533        // Presented by another peer than the certified one.
534        assert_eq!(refused(auth.admit(&caller("12D3KooWOther", &f.guest, &f.cert), s)), "wrong-peer");
535        // A key that is not the certificate's user.
536        let other = Keypair::generate_ed25519();
537        assert_eq!(refused(auth.admit(&caller(PEER, &other, &f.cert), s)), "guest-bad-key");
538        // A bad signature: tampered bytes, or a certificate claiming the guest's id signed by another key.
539        let mut bad = f.cert.clone();
540        bad.cert[0] ^= 1;
541        assert_eq!(refused(auth.admit(&caller(PEER, &f.guest, &bad), s)), "guest-bad-cert");
542        let forged = WEIRDNET.certify(&other, &f.cert.user_id, PEER, "x", weirdnet_net::now_ms()).unwrap();
543        assert_eq!(refused(auth.admit(&caller(PEER, &f.guest, &forged), s)), "guest-bad-cert");
544        let mut relabeled = f.cert.clone();
545        relabeled.issued_at += 1;
546        assert_eq!(refused(auth.admit(&caller(PEER, &f.guest, &relabeled), s)), "guest-bad-cert");
547        // Revoked by its user (signed), or a revocation time without its signature.
548        let mut revoked = f.cert.clone();
549        let at = weirdnet_net::now_ms();
550        revoked.revoked_at = Some(at);
551        revoked.revocation = Some(WEIRDNET.revoke(&f.guest, &f.cert.user_id, PEER, at).unwrap());
552        assert_eq!(refused(auth.admit(&caller(PEER, &f.guest, &revoked), s)), "revoked");
553        revoked.revocation = None;
554        assert_eq!(refused(auth.admit(&caller(PEER, &f.guest, &revoked), s)), "guest-bad-cert");
555        // Issued in the future beyond the skew.
556        let later = WEIRDNET.certify(&f.guest, &f.cert.user_id, PEER, "x", weirdnet_net::now_ms() + 3_600_000).unwrap();
557        assert_eq!(refused(auth.admit(&caller(PEER, &f.guest, &later), s)), "guest-future-cert");
558        let lenient = guests(&f).with_clock_skew(std::time::Duration::from_secs(7200));
559        assert!(lenient.admit(&caller(PEER, &f.guest, &later), s).is_ok());
560        // The host's own user is never a guest.
561        let own = WEIRDNET.certify(&f.host, &weirdnet_net::user::user_id(&f.host.public()), PEER, "x", weirdnet_net::now_ms()).unwrap();
562        assert_eq!(refused(auth.admit(&caller(PEER, &f.host, &own), s)), "own-user");
563        // A credential of an unknown version.
564        let v2 = crate::remote::to_cbor(&serde_json::json!({"guest": 2, "key": f.guest.public().encode_protobuf(), "cert": f.cert})).unwrap();
565        assert_eq!(refused(auth.admit(&Caller::new(PEER).with_cert(v2), s)), "guest-bad-cert");
566    }
567
568    #[test]
569    fn shared_pool_auth_is_the_roster_unless_guests_are_on() {
570        let f = fixture();
571        let host_uid = weirdnet_net::user::user_id(&f.host.public());
572        let own_peer = "12D3KooWOwnDevice";
573        let own = weirdnet_sync::Roster::self_certify(&WEIRDNET, &f.host, own_peer, "phone", weirdnet_net::now_ms()).unwrap();
574        let mut roster = weirdnet_sync::Roster::new();
575        roster.upsert(own.clone());
576        let roster = Arc::new(Mutex::new(roster));
577        let view: RosterView = {
578            let r = roster.clone();
579            Arc::new(move || r.lock().unwrap().clone())
580        };
581        let roster_auth = Arc::new(RosterAuth::new(&WEIRDNET, f.host.public(), view));
582        let guest = caller(PEER, &f.guest, &f.cert);
583
584        // Default deny: no guests, the guest credential is another user's certificate.
585        let plain = SharedPoolAuth::new(roster_auth.clone());
586        assert!(!plain.admits_guests());
587        for scope in [GuestScope::Catalog, GuestScope::Infer] {
588            assert_eq!(refused(plain.identify(&guest, scope)), "wrong-user");
589        }
590        assert_eq!(refused(roster_auth.authorize(&guest)), "wrong-user", "RosterAuth itself is unchanged");
591        assert_eq!(refused(plain.scoped(GuestScope::Catalog).authorize(&guest)), "wrong-user");
592
593        // Guests on: the guest by the policy, own devices by the roster as before.
594        let shared = SharedPoolAuth::new(roster_auth.clone()).with_guests(Arc::new(guests(&f)));
595        let who = shared.identify(&guest, GuestScope::Infer).unwrap();
596        assert!(who.is_guest());
597        assert_eq!((who.peer(), who.guest().unwrap().user_id.as_str()), (PEER, f.cert.user_id.as_str()));
598        let admitted = shared.scoped(GuestScope::Catalog).admit(&guest).unwrap();
599        assert_eq!((admitted.peer.as_str(), admitted.roles.clone()), (PEER, None));
600        let mine = Caller::new(own_peer).with_cert(encode_cert(&own));
601        assert!(matches!(shared.identify(&mine, GuestScope::Infer).unwrap(), CallerIdentity::Own(a) if a.peer == own_peer));
602        // An own device presenting its certificate inside a credential still goes to the roster.
603        let mine_cred = caller(own_peer, &f.host, &own);
604        assert!(!shared.identify(&mine_cred, GuestScope::Infer).unwrap().is_guest());
605        assert_eq!(own.user_id, host_uid);
606        // A revoked own device is not let in through the guest path.
607        let at = weirdnet_net::now_ms();
608        let mut gone = own.clone();
609        gone.revoked_at = Some(at);
610        gone.revocation = Some(WEIRDNET.revoke(&f.host, &host_uid, own_peer, at).unwrap());
611        roster.lock().unwrap().upsert(gone);
612        assert_eq!(refused(shared.identify(&mine_cred, GuestScope::Infer)), "revoked");
613        // Revoking the guest: refused at once.
614        f.allowed.lock().unwrap().clear();
615        assert_eq!(refused(shared.identify(&guest, GuestScope::Infer)), "not-shared");
616        // A stranger with a bare certificate of its own user: the roster's answer.
617        let stranger = Keypair::generate_ed25519();
618        let sc = WEIRDNET.certify(&stranger, &weirdnet_net::user::user_id(&stranger.public()), "12D3KooWS", "x", 1).unwrap();
619        assert_eq!(refused(shared.identify(&Caller::new("12D3KooWS").with_cert(encode_cert(&sc)), GuestScope::Infer)), "wrong-user");
620    }
621
622    #[test]
623    fn credentials_round_trip_and_bare_certs_still_decode() {
624        let f = fixture();
625        let p = decode_presented(&encode_credential(&f.guest.public(), &f.cert)).unwrap();
626        assert_eq!((p.cert, p.user_key), (f.cert.clone(), Some(f.guest.public().encode_protobuf())));
627        let p = decode_presented(&encode_cert(&f.cert)).unwrap();
628        assert_eq!((p.cert, p.user_key), (f.cert.clone(), None));
629        assert!(decode_cert(&encode_credential(&f.guest.public(), &f.cert)).is_err(), "older hosts can't read a credential as a cert");
630    }
631}