Skip to main content

menger_notes/
caller.rs

1//! **The caller, as the gate admitted it** (FRAME-5's pattern: the ui
2//! service's and the media service's `caller.rs`). plexus-core's gate
3//! decides every call before a method runs — the method's grant held
4//! somewhere, within the session's ceiling — so this service's resolver
5//! ([`Callers::verify`]) takes the identity the upgrade proved and the
6//! reach the gate answered (`current_reach()`), and refuses only what the
7//! gate cannot have admitted. Where a note is — its organization — is
8//! asked of the gate again by the methods ([`crate::seam::Seam::holds`]).
9
10use crate::events::WatchEnd;
11use plexus_rpc::core::plexus::{current_reach, AuthContext, PlexusError, Reach, Refusal};
12use plexus_rpc::macros::PlexusRequest;
13
14/// The per-call context every method of the service reads: the identity the
15/// connection's upgrade proved, when one did.
16#[derive(PlexusRequest)]
17pub struct NotesRequest {
18    /// The identity the connection's upgrade proved (none: anonymous).
19    #[from_auth_context]
20    pub auth: Option<AuthContext>,
21}
22
23/// The resolver every method verifies its caller by.
24#[derive(Clone, Copy, Debug, Default)]
25pub struct Callers;
26
27/// A caller the gate admitted: its principal, its identity, and the reach
28/// the gate answered for the call.
29#[derive(Clone, Debug)]
30pub struct Caller {
31    principal: String,
32    ctx: AuthContext,
33    reach: Reach,
34}
35
36impl Callers {
37    /// The caller of the call being dispatched: signed in, naming a
38    /// principal. Refused typed (`unauthenticated`) otherwise.
39    pub async fn verify(&self, ctx: &AuthContext) -> Result<Caller, PlexusError> {
40        if !ctx.is_authenticated() {
41            return Err(PlexusError::Unauthenticated("sign in first".into()));
42        }
43        let principal = ctx.principal().map(|p| p.to_string()).ok_or_else(|| PlexusError::Unauthenticated("this identity names no principal".into()))?;
44        Ok(Caller { principal, ctx: ctx.clone(), reach: current_reach()? })
45    }
46}
47
48impl Caller {
49    /// Its principal (`key:…`, `idp:…`).
50    pub fn principal(&self) -> &str {
51        &self.principal
52    }
53
54    /// Its name — the agent it signed in as (`builder`), else the name its
55    /// identity carries, else its principal: what a write says `by`.
56    pub fn name(&self) -> String {
57        ["agent", "name"].iter().find_map(|k| self.ctx.get_metadata_string(k).filter(|n| !n.is_empty())).unwrap_or_else(|| self.principal.clone())
58    }
59
60    /// Whether it signed in as an agent's key (its proof names one).
61    pub fn agent(&self) -> bool {
62        self.ctx.get_metadata_string("agent").is_some_and(|a| !a.is_empty())
63    }
64
65    /// Who it is, as a presence says it.
66    pub fn who(&self) -> crate::presence::Who {
67        crate::presence::Who { principal: self.principal.clone(), name: self.name(), agent: self.agent() }
68    }
69
70    /// The identity the gate admitted — what the gate is asked of again.
71    pub fn context(&self) -> &AuthContext {
72        &self.ctx
73    }
74
75    /// The reach the gate answered for the call.
76    pub fn reach(&self) -> &Reach {
77        &self.reach
78    }
79
80    /// When its sign-in expires (unix seconds), if it says.
81    pub fn expires_at(&self) -> Option<i64> {
82        self.ctx.metadata.get("expires_at").and_then(|v| v.as_i64())
83    }
84
85    /// The caller as it stands now: its sign-in not expired, its grant still
86    /// held somewhere. `Err`: why a watch ends.
87    pub fn again(&self) -> Result<(), (WatchEnd, String)> {
88        if self.expires_at().is_some_and(|at| at <= crate::store::now()) {
89            return Err((WatchEnd::Expired, "your access changed: your sign-in has expired".into()));
90        }
91        match self.reach.recheck() {
92            Ok(_) => Ok(()),
93            Err(r) => {
94                let reason = match &r {
95                    Refusal::Ended { reason } if reason.contains("expired") => WatchEnd::Expired,
96                    Refusal::Ended { .. } => WatchEnd::SignedOut,
97                    Refusal::MissingGrant { .. } => WatchEnd::Revoked,
98                    _ => WatchEnd::Refused,
99                };
100                Err((reason, format!("your access changed: {r}")))
101            }
102        }
103    }
104}