Skip to main content

plexus_core/plexus/
view.rs

1//! AUTH-4 — **the caller's view**: what a caller can discover of a gated hub
2//! is exactly what it can use.
3//!
4//! A hub with a gate ([`DynamicHub::with_gate`](super::DynamicHub::with_gate))
5//! answers `_info`, its own `schema` / `hash` / `hashes`, and every
6//! `<activation>.schema` from the caller's [`View`]:
7//!
8//! - **anonymous** (no principal): only the `public` methods — the auth
9//!   activation's door (`auth.providers`, `auth.login`, `auth.signup`);
10//! - **caller** (signed in): only the methods whose grant some role the
11//!   caller holds lists (within its session's ceiling), each with `held_on`
12//!   — where it is held; plus the public methods, and the methods every
13//!   signed-in caller reaches (the auth activation's `whoami`, `logout`,
14//!   `requires`). A method the caller cannot use is **absent**, not marked;
15//!   an activation left with none is absent too.
16//!
17//! The hub's own methods (`call`, `hash`, `hashes`, `schema`) are in every
18//! view: they are how a client reaches anything at all. Each activation's
19//! `schema` entry stays beside its visible methods (introspection is open).
20//! An activation's declared `roles` are left out of a gated view (they name
21//! methods the caller may not see); `auth.roles` answers them to whoever
22//! holds it.
23//!
24//! **Hashes.** Every schema in a view carries a hash of what *it* shows —
25//! its methods (with `held_on`) and, for the hub, its children's view
26//! hashes — so two callers with identical holdings share a view hash, and
27//! a client's schema cache (synapse keeps IR by hash) never mixes two
28//! callers' views. The hub's view hash is `v-anon-<hex>` for the anonymous
29//! view and `v-<hex>` for a caller's.
30//!
31//! A hub **without a gate** never builds a view on the wire: `_info` and
32//! every schema answer exactly as before. [`DynamicHub::view`](super::DynamicHub::view)
33//! there returns the whole hub as a [`ViewKind::Caller`] view whose hash is
34//! the hub's own.
35
36use std::collections::{BTreeMap, BTreeSet};
37use std::hash::{Hash, Hasher};
38
39use plexus_auth_core::grants::{Gate, Grant};
40
41use super::auth::AuthContext;
42use super::schema::{ChildHashes, ChildSummary, MethodRole, PluginHashes, PluginSchema, ViewKind};
43
44/// The hub as one caller may see it (AUTH-4).
45#[derive(Debug, Clone)]
46pub struct View {
47    /// Anonymous (the door only) or the caller's own.
48    pub kind: ViewKind,
49    /// The hub's own schema in this view: its methods, and a child summary
50    /// for each activation the view keeps, carrying that activation's view
51    /// hash. `hash` is the view's hash.
52    pub schema: PluginSchema,
53    /// The view's hash: deterministic over what the view shows.
54    pub hash: String,
55    /// Each activation the view keeps, by namespace, as its
56    /// `<ns>.schema` answers in this view.
57    pub activations: BTreeMap<String, PluginSchema>,
58}
59
60impl View {
61    /// The schema `<ns>.schema` answers in this view: the hub's own for its
62    /// namespace, else the activation's — `None` when the view does not
63    /// show it.
64    pub fn schema_of(&self, ns: &str) -> Option<&PluginSchema> {
65        if ns == self.schema.namespace {
66            Some(&self.schema)
67        } else {
68            self.activations.get(ns)
69        }
70    }
71
72    /// The grants of the `public` methods this view shows, activation by
73    /// activation (in namespace order), each in declaration order —
74    /// `_info`'s `auth.methods` for an anonymous caller.
75    pub fn public_methods(&self) -> Vec<String> {
76        self.activations
77            .values()
78            .flat_map(|s| {
79                let ns = s.namespace.clone();
80                s.methods.iter().filter(|m| m.public).map(move |m| m.grant_or(&ns)).collect::<Vec<_>>()
81            })
82            .collect()
83    }
84
85    /// The hub's `hashes` answer in this view.
86    #[allow(deprecated)]
87    pub fn hashes(&self) -> PluginHashes {
88        PluginHashes {
89            namespace: self.schema.namespace.clone(),
90            self_hash: self.schema.self_hash.clone(),
91            children_hash: self.schema.children_hash.clone(),
92            hash: self.schema.hash.clone(),
93            children: self
94                .schema
95                .children
96                .as_ref()
97                .map(|kids| kids.iter().map(|c| ChildHashes { namespace: c.namespace.clone(), hash: c.hash.clone() }).collect()),
98        }
99    }
100}
101
102/// A stable 64-bit digest of `value`'s JSON, as 16 hex digits. The JSON of
103/// a schema is deterministic (struct fields in order; maps sorted), so equal
104/// views digest equally.
105fn digest(value: &impl serde::Serialize) -> String {
106    let text = serde_json::to_string(value).unwrap_or_default();
107    let mut h = std::collections::hash_map::DefaultHasher::new();
108    text.hash(&mut h);
109    format!("{:016x}", h.finish())
110}
111
112/// What the gate needs to say about one caller, computed once per view.
113struct Asker<'a> {
114    gate: &'a Gate,
115    caller: Option<&'a AuthContext>,
116    signed_in: bool,
117    /// Grants every signed-in caller reaches (the auth activation's
118    /// `whoami`, `logout`, `requires`), whatever its roles or ceiling.
119    signed_in_grants: &'a BTreeSet<String>,
120}
121
122impl Asker<'_> {
123    /// Whether the view keeps a method, and its `held_on` there.
124    fn keep(&self, grant: &str, public: bool) -> Option<Option<Vec<String>>> {
125        if !self.signed_in {
126            return public.then_some(None);
127        }
128        let caller = self.caller.expect("signed in");
129        let held: Vec<String> =
130            self.gate.held_on(caller, &Grant::new(grant)).iter().map(|s| s.as_str().to_string()).collect();
131        if !held.is_empty() {
132            return Some(Some(held));
133        }
134        (public || self.signed_in_grants.contains(grant)).then_some(None)
135    }
136}
137
138/// One activation's schema as the view shows it, or `None` when it keeps
139/// no method of it.
140fn activation_view(asker: &Asker<'_>, kind: ViewKind, mut schema: PluginSchema) -> Option<PluginSchema> {
141    let ns = schema.namespace.clone();
142    let mut kept = Vec::new();
143    let mut schema_entry = None;
144    for mut m in std::mem::take(&mut schema.methods) {
145        let is_schema_entry = m.name == "schema" && matches!(m.role, MethodRole::Rpc) && m.hash == "auto_schema";
146        if is_schema_entry {
147            schema_entry = Some(m);
148            continue;
149        }
150        let grant = m.grant_or(&ns);
151        if let Some(held) = asker.keep(&grant, m.public) {
152            m.held_on = held;
153            kept.push(m);
154        }
155    }
156    if kept.is_empty() {
157        return None;
158    }
159    kept.extend(schema_entry);
160    schema.methods = kept;
161    #[allow(deprecated)]
162    if let Some(children) = schema.children.as_mut() {
163        // A child summary names a nested router; it stays only when the
164        // method that reaches it does.
165        let names: BTreeSet<&str> = schema.methods.iter().map(|m| m.name.as_str()).collect();
166        children.retain(|c| names.contains(c.namespace.as_str()));
167    }
168    schema.roles = BTreeMap::new();
169    schema.view = Some(kind);
170    rehash(&mut schema, None);
171    Some(schema)
172}
173
174/// Recompute `self_hash`, `children_hash` and `hash` over what the schema
175/// shows. `prefix` marks the hub's view hash.
176#[allow(deprecated)]
177fn rehash(schema: &mut PluginSchema, prefix: Option<&str>) {
178    schema.self_hash = String::new();
179    schema.children_hash = None;
180    schema.hash = String::new();
181    let self_hash = digest(&(&schema.namespace, &schema.methods, &schema.view));
182    let children_hash = schema.children.as_ref().map(|kids| digest(kids));
183    let composite = digest(&(&self_hash, &children_hash, &*schema));
184    schema.self_hash = self_hash;
185    schema.children_hash = children_hash;
186    schema.hash = match prefix {
187        Some(p) => format!("{p}{composite}"),
188        None => composite,
189    };
190}
191
192/// Build the view of a gated hub. `hub` is the hub's own schema (its
193/// methods and child summaries), `activations` every registered
194/// activation's schema.
195pub(crate) fn build(
196    gate: &Gate,
197    signed_in_grants: &BTreeSet<String>,
198    caller: Option<&AuthContext>,
199    mut hub: PluginSchema,
200    activations: Vec<PluginSchema>,
201) -> View {
202    let signed_in = caller.and_then(|c| c.principal()).is_some();
203    let kind = if signed_in { ViewKind::Caller } else { ViewKind::Anonymous };
204    let asker = Asker { gate, caller: if signed_in { caller } else { None }, signed_in, signed_in_grants };
205
206    let kept: BTreeMap<String, PluginSchema> = activations
207        .into_iter()
208        .filter_map(|s| activation_view(&asker, kind, s))
209        .map(|s| (s.namespace.clone(), s))
210        .collect();
211
212    #[allow(deprecated)]
213    {
214        let mut children: Vec<ChildSummary> = hub.children.take().unwrap_or_default();
215        children.retain(|c| kept.contains_key(&c.namespace));
216        for c in children.iter_mut() {
217            c.hash = kept[&c.namespace].hash.clone();
218        }
219        hub.children = Some(children);
220    }
221    // The hub's own methods are how a client reaches anything: in every view.
222    for m in hub.methods.iter_mut() {
223        m.held_on = None;
224    }
225    hub.roles = BTreeMap::new();
226    hub.view = Some(kind);
227    rehash(&mut hub, Some(if signed_in { "v-" } else { "v-anon-" }));
228    let hash = hub.hash.clone();
229    View { kind, schema: hub, hash, activations: kept }
230}
231
232/// The view of a hub without a gate: everything, as today.
233pub(crate) fn whole(hub: PluginSchema, activations: Vec<PluginSchema>) -> View {
234    let hash = hub.hash.clone();
235    View {
236        kind: ViewKind::Caller,
237        schema: hub,
238        hash,
239        activations: activations.into_iter().map(|s| (s.namespace.clone(), s)).collect(),
240    }
241}