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(
141    asker: &Asker<'_>,
142    kind: ViewKind,
143    mut schema: PluginSchema,
144    children: &[PluginSchema],
145) -> Option<PluginSchema> {
146    let ns = schema.namespace.clone();
147    let mut kept = Vec::new();
148    let mut schema_entry = None;
149    for mut m in std::mem::take(&mut schema.methods) {
150        let is_schema_entry = m.name == "schema" && matches!(m.role, MethodRole::Rpc) && m.hash == "auto_schema";
151        if is_schema_entry {
152            schema_entry = Some(m);
153            continue;
154        }
155        // MACRO-20: a static child's entry (`tickets.commits`) names no
156        // method of its own; it stays when the caller can use a method
157        // somewhere below it (`tickets.commits.link`), so the caller can
158        // navigate to what it holds.
159        // A child that describes nothing (a hand-written router) is
160        // decided as before, by the entry's own grant.
161        if matches!(m.role, MethodRole::StaticChild) {
162            if let Some(reached) = reaches_below(asker, &format!("{ns}.{}", m.name), children) {
163                if reached {
164                    m.held_on = None;
165                    kept.push(m);
166                }
167                continue;
168            }
169        }
170        let grant = m.grant_or(&ns);
171        if let Some(held) = asker.keep(&grant, m.public) {
172            m.held_on = held;
173            kept.push(m);
174        }
175    }
176    if kept.is_empty() {
177        return None;
178    }
179    kept.extend(schema_entry);
180    schema.methods = kept;
181    #[allow(deprecated)]
182    if let Some(children) = schema.children.as_mut() {
183        // A child summary names a nested router; it stays only when the
184        // method that reaches it does.
185        let names: BTreeSet<&str> = schema.methods.iter().map(|m| m.name.as_str()).collect();
186        children.retain(|c| names.contains(c.namespace.as_str()));
187    }
188    schema.roles = BTreeMap::new();
189    schema.view = Some(kind);
190    rehash(&mut schema, None);
191    Some(schema)
192}
193
194/// MACRO-20: whether the caller can use a method of a static child at
195/// `path` or of one below it (`children`: the hub's qualified static
196/// children, [`super::children`]).
197/// `None` when no child at `path` describes itself.
198fn reaches_below(asker: &Asker<'_>, path: &str, children: &[PluginSchema]) -> Option<bool> {
199    let below = format!("{path}.");
200    let mut known = children.iter().filter(|c| c.namespace == path || c.namespace.starts_with(&below)).peekable();
201    known.peek()?;
202    Some(
203        known
204            .flat_map(|c| c.methods.iter().map(move |m| (c, m)))
205            .filter(|(_, m)| matches!(m.role, MethodRole::Rpc) && !(m.name == "schema" && m.hash == "auto_schema"))
206            .any(|(c, m)| asker.keep(&m.grant_or(&c.namespace), m.public).is_some()),
207    )
208}
209
210/// Recompute `self_hash`, `children_hash` and `hash` over what the schema
211/// shows. `prefix` marks the hub's view hash.
212#[allow(deprecated)]
213fn rehash(schema: &mut PluginSchema, prefix: Option<&str>) {
214    schema.self_hash = String::new();
215    schema.children_hash = None;
216    schema.hash = String::new();
217    let self_hash = digest(&(&schema.namespace, &schema.methods, &schema.view));
218    let children_hash = schema.children.as_ref().map(|kids| digest(kids));
219    let composite = digest(&(&self_hash, &children_hash, &*schema));
220    schema.self_hash = self_hash;
221    schema.children_hash = children_hash;
222    schema.hash = match prefix {
223        Some(p) => format!("{p}{composite}"),
224        None => composite,
225    };
226}
227
228/// Build the view of a gated hub. `hub` is the hub's own schema (its
229/// methods and child summaries), `activations` every registered
230/// activation's schema.
231pub(crate) fn build(
232    gate: &Gate,
233    signed_in_grants: &BTreeSet<String>,
234    caller: Option<&AuthContext>,
235    mut hub: PluginSchema,
236    activations: Vec<PluginSchema>,
237    children: &[PluginSchema],
238) -> View {
239    let signed_in = caller.and_then(|c| c.principal()).is_some();
240    let kind = if signed_in { ViewKind::Caller } else { ViewKind::Anonymous };
241    let asker = Asker { gate, caller: if signed_in { caller } else { None }, signed_in, signed_in_grants };
242
243    let kept: BTreeMap<String, PluginSchema> = activations
244        .into_iter()
245        .filter_map(|s| activation_view(&asker, kind, s, children))
246        .map(|s| (s.namespace.clone(), s))
247        .collect();
248
249    #[allow(deprecated)]
250    {
251        let mut children: Vec<ChildSummary> = hub.children.take().unwrap_or_default();
252        children.retain(|c| kept.contains_key(&c.namespace));
253        for c in children.iter_mut() {
254            c.hash = kept[&c.namespace].hash.clone();
255        }
256        hub.children = Some(children);
257    }
258    // The hub's own methods are how a client reaches anything: in every view.
259    for m in hub.methods.iter_mut() {
260        m.held_on = None;
261    }
262    hub.roles = BTreeMap::new();
263    hub.view = Some(kind);
264    rehash(&mut hub, Some(if signed_in { "v-" } else { "v-anon-" }));
265    let hash = hub.hash.clone();
266    View { kind, schema: hub, hash, activations: kept }
267}
268
269/// The view of a hub without a gate: everything, as today.
270pub(crate) fn whole(hub: PluginSchema, activations: Vec<PluginSchema>) -> View {
271    let hash = hub.hash.clone();
272    View {
273        kind: ViewKind::Caller,
274        schema: hub,
275        hash,
276        activations: activations.into_iter().map(|s| (s.namespace.clone(), s)).collect(),
277    }
278}