1use plexus_auth_core::grants::{CallAddress, DispatchedCall, Gate, Grant, Reach, Refusal};
85use serde_json::Value;
86
87use super::auth::AuthContext;
88use super::plexus::{AuthzDenyReason, PlexusError};
89use super::scope_gate::MethodGateInfo;
90
91pub fn current_reach() -> Result<Reach, PlexusError> {
104 let ctx = crate::call::context()?;
105 ctx.reach().cloned().ok_or_else(|| crate::call::CallError::ThroughHop.into())
106}
107
108pub async fn with_reach<F: std::future::Future>(reach: Reach, fut: F) -> Result<F::Output, PlexusError> {
121 let ctx = crate::call::context()?;
122 let current = ctx.reach().ok_or(crate::call::CallError::ThroughHop)?;
123 if let Err(why) = narrows(current, &reach) {
124 return Err(PlexusError::Unauthenticated(why.into()));
125 }
126 Ok(crate::call::scope(ctx.with_reach(reach), fut).await)
127}
128
129fn narrows(current: &Reach, reach: &Reach) -> Result<(), &'static str> {
131 let within = current.is_everywhere() || reach.held_on().iter().all(|s| current.held_on().contains(s));
132 if !within {
133 return Err("with_reach narrows a call's reach; it holds a scope the call does not");
134 }
135 if reach.holds_activation() && !current.holds_activation() {
136 return Err("with_reach narrows a call's reach; it holds the activation, and the call does not");
137 }
138 if is_door(reach) && reach.grant() != current.grant() {
139 return Err("with_reach narrows a call's reach; it is the door of another grant than the call's");
140 }
141 Ok(())
142}
143
144pub(crate) fn is_door(reach: &Reach) -> bool {
147 reach.holds_activation() && !reach.is_everywhere()
148}
149
150pub(crate) fn door_is_own(call: &DispatchedCall) -> bool {
158 let path = call.at().path();
159 let grant = call.grant().as_str();
160 path.split('.').count() == grant.split('.').count()
161 && path.split('.').zip(grant.split('.')).all(|(p, g)| p == g || is_slot_segment(g))
162}
163
164pub(crate) fn door_shape(call: &DispatchedCall, peer_slot: Option<&str>) -> String {
169 let grant = call.grant().as_str();
170 let Some(slot) = peer_slot else { return grant.to_string() };
171 let at = slot.split('.').count();
172 grant
173 .split('.')
174 .enumerate()
175 .map(|(i, s)| if i == at { "{peer}" } else { s })
176 .collect::<Vec<_>>()
177 .join(".")
178}
179
180pub(crate) fn is_slot_segment(segment: &str) -> bool {
182 segment.len() > 2 && segment.starts_with('{') && segment.ends_with('}')
183}
184
185pub(crate) enum Admit {
195 Reach(Reach, Option<DispatchedCall>, Option<Vec<String>>),
196 Open,
197}
198
199pub(crate) fn dispatched(path: &str, grant: &Grant, ambiguous: &std::collections::HashSet<String>) -> Option<DispatchedCall> {
214 let segments: Vec<&str> = path.split('.').collect();
215 let (method, activation) = segments.split_last()?;
216 let at = CallAddress::of_segments(activation, method).ok()?;
217 let mut prefix = String::with_capacity(path.len());
218 for (i, s) in segments.iter().enumerate() {
219 if i > 0 {
220 prefix.push('.');
221 }
222 prefix.push_str(s);
223 if i > 0 && ambiguous.contains(&prefix) {
224 return None;
225 }
226 }
227 Some(DispatchedCall::new(at, grant.clone()))
228}
229
230pub fn named_twice(schema: &super::schema::PluginSchema) -> Vec<String> {
234 use super::schema::MethodRole;
235 let child = |r: &MethodRole| matches!(r, MethodRole::StaticChild | MethodRole::DynamicChild { .. } | MethodRole::Peer { .. });
236 let mut twice: Vec<String> = schema
237 .methods
238 .iter()
239 .filter(|m| matches!(m.role, MethodRole::Rpc) && schema.methods.iter().any(|c| c.name == m.name && child(&c.role)))
240 .map(|m| m.name.clone())
241 .collect();
242 twice.sort();
243 twice.dedup();
244 twice
245}
246
247impl From<Refusal> for PlexusError {
248 fn from(r: Refusal) -> Self {
249 match r {
250 Refusal::Unauthenticated => {
251 PlexusError::Unauthenticated("sign in first: this method is not public".into())
252 }
253 Refusal::MissingGrant { grant, scope, roles, held_on } => PlexusError::Forbidden {
254 reason: AuthzDenyReason::MissingGrant { grant, scope, roles, held_on },
255 },
256 Refusal::Ended { reason } => PlexusError::Unauthenticated(reason),
257 }
258 }
259}
260
261pub(crate) fn standing<'a>(gate: &Gate, auth: Option<&'a AuthContext>) -> (Option<&'a AuthContext>, Option<String>) {
267 match auth.map(|a| gate.alive(a)) {
268 Some(Err(reason)) => (None, Some(reason)),
269 _ => (auth, None),
270 }
271}
272
273pub(crate) fn say_ended(e: PlexusError, ended: Option<&str>) -> PlexusError {
276 match (e, ended) {
277 (PlexusError::Unauthenticated(_), Some(reason)) => PlexusError::Unauthenticated(reason.to_string()),
278 (e, _) => e,
279 }
280}
281
282pub(crate) fn target_values(params: &Value, param: &str) -> Result<Option<Vec<String>>, PlexusError> {
288 let Some(v) = params.get(param) else { return Ok(None) };
289 let one = |v: &Value| match v {
290 Value::String(s) => Some(s.clone()),
291 Value::Number(n) => Some(n.to_string()),
292 Value::Bool(b) => Some(b.to_string()),
293 _ => None,
294 };
295 let unreadable = || {
296 PlexusError::malformed_param(param, "names what this call acts on: a string, or a list of strings")
297 };
298 match v {
299 Value::Null => Ok(None),
300 Value::Array(items) => items.iter().map(|i| one(i).ok_or_else(unreadable)).collect::<Result<_, _>>().map(Some),
301 other => one(other).map(|s| Some(vec![s])).ok_or_else(unreadable),
302 }
303}
304
305fn params_shape(params: &Value) -> Result<(), PlexusError> {
310 match params {
311 Value::Object(_) | Value::Null => Ok(()),
312 _ => Err(PlexusError::invalid_params(
313 "params must be an object naming each parameter, e.g. {\"id\": \"…\"}: a gated method takes no bare value",
314 )),
315 }
316}
317
318fn said_at_everywhere(r: Refusal) -> Refusal {
323 match r {
324 Refusal::MissingGrant { grant, roles, held_on, .. } => {
325 Refusal::MissingGrant { grant, scope: plexus_auth_core::grants::ScopeRef::Everywhere, roles, held_on }
326 }
327 other => other,
328 }
329}
330
331pub(crate) fn door_shaped(everywhere: bool, target: Option<&str>, untyped_peer_slot: bool) -> bool {
338 match target {
339 Some(_) => false,
340 None => everywhere || untyped_peer_slot,
341 }
342}
343
344#[allow(clippy::too_many_arguments)]
348pub(crate) fn decide(
349 gate: &Gate,
350 service_ns: &str,
351 full_path: &str,
352 info: Option<&MethodGateInfo>,
353 params: &Value,
354 auth: Option<&AuthContext>,
355 signed_in_grants: &std::collections::BTreeSet<String>,
356 ambiguous: &std::collections::HashSet<String>,
357) -> Result<Admit, PlexusError> {
358 params_shape(params)?;
359 let (ns, method) = full_path.split_once('.').unwrap_or((full_path, ""));
360 let introspection = method == "schema"
361 || method.ends_with(".schema")
362 || (ns == service_ns && matches!(method, "hash" | "hashes" | "ir"));
363 if introspection {
364 return Ok(Admit::Open);
365 }
366 let grant = Grant::new(info.and_then(|i| i.grant.clone()).unwrap_or_else(|| full_path.to_string()));
367 if info.is_some_and(|i| i.door) {
372 return Ok(match dispatched(full_path, &grant, ambiguous) {
373 Some(call) => Admit::Reach(gate.check_everywhere_at(auth, &call).map_err(said_at_everywhere)?, Some(call), Some(Vec::new())),
374 None => Admit::Reach(gate.check_everywhere(auth, &grant)?, None, Some(Vec::new())),
375 });
376 }
377 if info.is_some_and(|i| i.everywhere) {
380 return Ok(Admit::Reach(gate.check_everywhere(auth, &grant)?, None, Some(Vec::new())));
381 }
382 if info.is_some_and(|i| i.public) {
383 return Ok(Admit::Reach(gate.reach_of_public(auth, &grant), None, None));
384 }
385 if signed_in_grants.contains(grant.as_str()) {
389 if auth.and_then(|a| a.principal()).is_none() {
390 return Err(Refusal::Unauthenticated.into());
391 }
392 return Ok(Admit::Reach(gate.reach_of_public(auth, &grant), None, None));
393 }
394 let targets = match info.and_then(|i| i.target.as_deref()) {
395 Some(param) => target_values(params, param)?,
396 None => None,
397 };
398 match targets {
399 None => Ok(Admit::Reach(gate.check(auth, &grant, None)?, None, Some(Vec::new()))),
400 Some(values) if values.is_empty() => Ok(Admit::Reach(gate.check(auth, &grant, None)?, None, Some(values))),
401 Some(values) => {
402 let mut reach = None;
403 for v in &values {
404 reach = Some(gate.check(auth, &grant, Some(v))?);
405 }
406 Ok(Admit::Reach(reach.expect("non-empty"), None, Some(values)))
409 }
410 }
411}
412
413pub fn require_everywhere(schema: &super::schema::PluginSchema, methods: &[&str]) -> Result<(), String> {
418 let unmarked: Vec<&str> = methods
419 .iter()
420 .copied()
421 .filter(|name| !schema.methods.iter().any(|m| m.name == *name && m.everywhere))
422 .collect();
423 if unmarked.is_empty() {
424 return Ok(());
425 }
426 Err(format!(
427 "{}: {} act on the whole service and must be marked `everywhere` in its schema; they are not — \
428 built with a plexus-macros that does not know the word (it needs 0.11.1 or later)",
429 schema.namespace,
430 unmarked.iter().map(|m| format!("{}.{m}", schema.namespace)).collect::<Vec<_>>().join(", "),
431 ))
432}
433
434#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
437pub struct ForbiddenItem {
438 pub grant: String,
439 pub scope: String,
440 #[serde(default)]
441 pub roles: Vec<String>,
442 #[serde(default)]
443 pub held_on: Vec<String>,
444 pub message: String,
445}
446
447impl ForbiddenItem {
448 pub fn from_item(item: &Value) -> Option<Self> {
450 if item.get("type")?.as_str()? != "error" || item.get("error_kind")?.as_str()? != "forbidden" {
451 return None;
452 }
453 item.get("grant")?;
454 serde_json::from_value(item.clone()).ok()
455 }
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
463 use plexus_auth_core::grants::{Membership, Memberships, Resolve, RoleTable, ScopeRef};
464 use serde_json::json;
465 use std::collections::{BTreeSet, HashSet};
466 use std::sync::Arc;
467
468 const OPERATOR: &str = "key:0101010101010101010101010101010101010101010101010101010101010101";
469 const KILN_ADMIN: &str = "key:0303030303030303030303030303030303030303030303030303030303030303";
470 const GARDENER: &str = "key:0202020202020202020202020202020202020202020202020202020202020202";
471
472 struct Held;
473 impl Memberships for Held {
474 fn held(&self, who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
475 let at = |role: &str, scope: &str| Membership { principal: who.clone(), role: plexus_auth_core::RoleName::new(role), scope: ScopeRef::parse(scope) };
476 match who.to_string().as_str() {
477 OPERATOR => vec![at("operator", "/ops")],
478 KILN_ADMIN => vec![at("admin", "KILN")],
479 GARDENER => vec![at("operator", "/ops.*")],
480 _ => vec![],
481 }
482 }
483 }
484 struct Kiln;
485 impl Resolve for Kiln {
486 fn chain(&self, t: &str) -> Option<Vec<ScopeRef>> {
487 Some(vec![ScopeRef::named(t.split('-').next().unwrap_or(t)), ScopeRef::Everywhere])
488 }
489 }
490
491 fn gate() -> Gate {
492 let roles = RoleTable::from_lists([("operator", ["ops.grow", "ops.get", "ops.misdeclared", "ops.tally", "ops.{peer}", "ops.{box}", "ops.{planet}.wipe", "ops.peer.shop.wipe"])]);
493 Gate::new(Arc::new(Held), Arc::new(roles), Arc::new(Kiln))
494 }
495
496 fn who(p: &str) -> AuthContext {
497 AuthContext::for_principal(&p.parse().unwrap(), "s", vec![], Value::Null)
498 }
499
500 fn info(grant: &str, everywhere: bool, target: Option<&str>, peer_slot: bool) -> MethodGateInfo {
501 MethodGateInfo {
502 grant: Some(grant.into()),
503 everywhere,
504 target: target.map(str::to_string),
505 door: door_shaped(everywhere, target, peer_slot),
506 ..Default::default()
507 }
508 }
509
510 fn decided(caller: &str, path: &str, info: &MethodGateInfo, params: Value) -> Result<bool, PlexusError> {
512 match decide(&gate(), "svc", path, Some(info), ¶ms, Some(&who(caller)), &BTreeSet::new(), &HashSet::new())? {
513 Admit::Reach(_, door, _) => Ok(door.is_some()),
514 Admit::Open => Ok(false),
515 }
516 }
517
518 #[test]
519 fn a_whole_activation_method_is_decided_at_its_door() {
520 let grow = info("ops.grow", true, None, false);
521 assert_eq!(decided(OPERATOR, "ops.grow", &grow, json!({})).unwrap(), true);
522 assert!(matches!(decided(KILN_ADMIN, "ops.grow", &grow, json!({})), Err(PlexusError::Forbidden { .. })), "KEEL-31");
523 }
524
525 #[test]
526 fn an_untyped_peer_slot_is_decided_at_the_peer_s_door() {
527 let peer = info("ops.{peer}", false, None, true);
528 assert_eq!(decided(OPERATOR, "ops.peer.shop.look", &peer, json!({})).ok(), None, "`/ops` is ops' own: no prefix rule");
529 assert!(matches!(decided(KILN_ADMIN, "ops.peer.shop.look", &peer, json!({})), Err(PlexusError::Forbidden { .. })), "KEEL-44");
530 }
531
532 #[test]
533 fn a_data_method_is_decided_on_its_target_never_at_a_door() {
534 let get = info("ops.get", false, Some("id"), false);
535 assert!(decided(OPERATOR, "ops.get", &get, json!({ "id": "KILN-3" })).is_err(), "an address holds no data");
536 assert_eq!(decided(KILN_ADMIN, "ops.get", &get, json!({ "id": "KILN-3" })).unwrap(), false);
537 let tally = info("ops.tally", false, None, false);
538 assert!(decided(OPERATOR, "ops.tally", &tally, json!({})).is_err(), "no target: held anywhere, on data");
539 assert_eq!(decided(KILN_ADMIN, "ops.tally", &tally, json!({})).unwrap(), false);
540 }
541
542 #[test]
545 fn a_misdeclared_data_method_is_not_reachable_through_the_door() {
546 let bad = info("ops.misdeclared", true, Some("id"), false);
547 assert!(!bad.door);
548 assert!(matches!(decided(OPERATOR, "ops.misdeclared", &bad, json!({ "id": "KILN-3" })), Err(PlexusError::Forbidden { .. })));
549 assert!(matches!(decided(KILN_ADMIN, "ops.misdeclared", &bad, json!({ "id": "KILN-3" })), Err(PlexusError::Forbidden { .. })));
550 }
551
552 #[test]
554 fn a_dynamic_child_slot_is_held_anywhere_as_before() {
555 let boxes = info("ops.{box}", false, None, false);
556 assert!(!boxes.door);
557 assert!(decided(OPERATOR, "ops.b1.look", &boxes, json!({})).is_err());
558 assert_eq!(decided(KILN_ADMIN, "ops.b1.look", &boxes, json!({})).unwrap(), false);
559 }
560
561 #[test]
562 fn a_call_is_dispatched_from_its_literal_path() {
563 let none = HashSet::new();
564 let g = Grant::new("ops.{peer}");
565 let call = dispatched("ops.peer.shop.items.list", &g, &none).unwrap();
566 assert_eq!((call.at().activation(), call.at().method(), call.grant()), ("ops.peer.shop.items", "list", &g));
567 for bad in ["ops", "ops..x", "ops.sh*p.x", "ops.sh p.x", "ops.{peer}.x", ""] {
568 assert!(dispatched(bad, &g, &none).is_none(), "{bad}");
569 }
570 let ambiguous: HashSet<String> = ["ops.peer".to_string()].into();
571 assert!(dispatched("ops.peer", &g, &ambiguous).is_none(), "a name both a method and a child");
572 assert!(dispatched("ops.peer.shop.look", &g, &ambiguous).is_none(), "and everything under it");
573 assert!(dispatched("ops.peers", &g, &ambiguous).is_some());
574 }
575
576 #[test]
577 fn a_name_given_twice_is_found() {
578 use crate::plexus::schema::{MethodRole, MethodSchema, PluginSchema};
579 let mut s = PluginSchema::leaf("dyn", "1", "d", vec![MethodSchema::new("peers", "d", "h")]);
580 s.methods.push(MethodSchema::new("peer", "d", "h"));
581 s.methods.push(MethodSchema::new("peer", "d", "h").with_role(MethodRole::Peer { list_method: None, search_method: None, interface: None }));
582 assert_eq!(named_twice(&s), ["peer"]);
583 }
584
585 #[test]
591 fn the_backstop_takes_only_the_methods_own_door() {
592 let ran = |caller: &str, path: &str, info: &MethodGateInfo, peer_slot: Option<&str>, grant: &str| -> bool {
593 let auth = who(caller);
594 let Ok(Admit::Reach(reach, Some(call), _)) = decide(&gate(), "svc", path, Some(info), &json!({}), Some(&auth), &BTreeSet::new(), &HashSet::new()) else {
595 panic!("{path}: not admitted at a door");
596 };
597 let ctx = crate::call::CallContext::admitted_by_gate(Some(&auth), reach).at_door(call, peer_slot);
598 futures::executor::block_on(crate::call::scope(ctx, async { crate::call::admits_everywhere(grant) })).is_ok()
599 };
600 let grow = info("ops.grow", true, None, false);
601 assert!(ran(OPERATOR, "ops.grow", &grow, None, "ops.grow"));
602 assert!(!ran(OPERATOR, "ops.grow", &grow, None, "x.grow"), "another activation's `grow`, in process");
603 assert!(!ran(OPERATOR, "ops.grow", &grow, None, "ops.tally"));
604 let wipe = info("ops.{planet}.wipe", true, None, false);
606 assert!(ran(GARDENER, "ops.mars.wipe", &wipe, None, "planet.wipe"));
607 assert!(!ran(GARDENER, "ops.mars.wipe", &wipe, None, "planet.look"));
608 let slot = info("ops.{peer}", false, None, true);
610 assert!(!ran(GARDENER, "ops.peer.shop.wipe", &slot, Some("ops.{peer}"), "shop.wipe"));
611 assert!(!ran(GARDENER, "ops.peer.shop.wipe", &slot, Some("ops.{peer}"), "leaf.wipe"));
612 let literal = MethodGateInfo { door: true, ..Default::default() };
615 assert!(ran(GARDENER, "ops.peer.shop.wipe", &literal, Some("ops.{peer}"), "shop.wipe"));
616 assert!(ran(GARDENER, "ops.peer.shop.wipe", &literal, Some("ops.{peer}"), "leaf.wipe"));
617 assert!(!ran(GARDENER, "ops.peer.shop.wipe", &literal, Some("ops.{peer}"), "leaf.look"));
618 assert!(!ran(GARDENER, "ops.peer.shop.wipe", &literal, None, "leaf.wipe"));
620 }
621}