use plexus_auth_core::grants::{CallAddress, DispatchedCall, Gate, Grant, Reach, Refusal};
use serde_json::Value;
use super::auth::AuthContext;
use super::plexus::{AuthzDenyReason, PlexusError};
use super::scope_gate::MethodGateInfo;
pub fn current_reach() -> Result<Reach, PlexusError> {
let ctx = crate::call::context()?;
ctx.reach().cloned().ok_or_else(|| crate::call::CallError::ThroughHop.into())
}
pub async fn with_reach<F: std::future::Future>(reach: Reach, fut: F) -> Result<F::Output, PlexusError> {
let ctx = crate::call::context()?;
let current = ctx.reach().ok_or(crate::call::CallError::ThroughHop)?;
if let Err(why) = narrows(current, &reach) {
return Err(PlexusError::Unauthenticated(why.into()));
}
Ok(crate::call::scope(ctx.with_reach(reach), fut).await)
}
fn narrows(current: &Reach, reach: &Reach) -> Result<(), &'static str> {
let within = current.is_everywhere() || reach.held_on().iter().all(|s| current.held_on().contains(s));
if !within {
return Err("with_reach narrows a call's reach; it holds a scope the call does not");
}
if reach.holds_activation() && !current.holds_activation() {
return Err("with_reach narrows a call's reach; it holds the activation, and the call does not");
}
if is_door(reach) && reach.grant() != current.grant() {
return Err("with_reach narrows a call's reach; it is the door of another grant than the call's");
}
Ok(())
}
pub(crate) fn is_door(reach: &Reach) -> bool {
reach.holds_activation() && !reach.is_everywhere()
}
pub(crate) fn door_is_own(call: &DispatchedCall) -> bool {
let path = call.at().path();
let grant = call.grant().as_str();
path.split('.').count() == grant.split('.').count()
&& path.split('.').zip(grant.split('.')).all(|(p, g)| p == g || is_slot_segment(g))
}
pub(crate) fn door_shape(call: &DispatchedCall, peer_slot: Option<&str>) -> String {
let grant = call.grant().as_str();
let Some(slot) = peer_slot else { return grant.to_string() };
let at = slot.split('.').count();
grant
.split('.')
.enumerate()
.map(|(i, s)| if i == at { "{peer}" } else { s })
.collect::<Vec<_>>()
.join(".")
}
pub(crate) fn is_slot_segment(segment: &str) -> bool {
segment.len() > 2 && segment.starts_with('{') && segment.ends_with('}')
}
pub(crate) enum Admit {
Reach(Reach, Option<DispatchedCall>, Option<Vec<String>>),
Open,
}
pub(crate) fn dispatched(path: &str, grant: &Grant, ambiguous: &std::collections::HashSet<String>) -> Option<DispatchedCall> {
let segments: Vec<&str> = path.split('.').collect();
let (method, activation) = segments.split_last()?;
let at = CallAddress::of_segments(activation, method).ok()?;
let mut prefix = String::with_capacity(path.len());
for (i, s) in segments.iter().enumerate() {
if i > 0 {
prefix.push('.');
}
prefix.push_str(s);
if i > 0 && ambiguous.contains(&prefix) {
return None;
}
}
Some(DispatchedCall::new(at, grant.clone()))
}
pub fn named_twice(schema: &super::schema::PluginSchema) -> Vec<String> {
use super::schema::MethodRole;
let child = |r: &MethodRole| matches!(r, MethodRole::StaticChild | MethodRole::DynamicChild { .. } | MethodRole::Peer { .. });
let mut twice: Vec<String> = schema
.methods
.iter()
.filter(|m| matches!(m.role, MethodRole::Rpc) && schema.methods.iter().any(|c| c.name == m.name && child(&c.role)))
.map(|m| m.name.clone())
.collect();
twice.sort();
twice.dedup();
twice
}
impl From<Refusal> for PlexusError {
fn from(r: Refusal) -> Self {
match r {
Refusal::Unauthenticated => {
PlexusError::Unauthenticated("sign in first: this method is not public".into())
}
Refusal::MissingGrant { grant, scope, roles, held_on } => PlexusError::Forbidden {
reason: AuthzDenyReason::MissingGrant { grant, scope, roles, held_on },
},
Refusal::Ended { reason } => PlexusError::Unauthenticated(reason),
}
}
}
pub(crate) fn standing<'a>(gate: &Gate, auth: Option<&'a AuthContext>) -> (Option<&'a AuthContext>, Option<String>) {
match auth.map(|a| gate.alive(a)) {
Some(Err(reason)) => (None, Some(reason)),
_ => (auth, None),
}
}
pub(crate) fn say_ended(e: PlexusError, ended: Option<&str>) -> PlexusError {
match (e, ended) {
(PlexusError::Unauthenticated(_), Some(reason)) => PlexusError::Unauthenticated(reason.to_string()),
(e, _) => e,
}
}
pub(crate) fn target_values(params: &Value, param: &str) -> Result<Option<Vec<String>>, PlexusError> {
let Some(v) = params.get(param) else { return Ok(None) };
let one = |v: &Value| match v {
Value::String(s) => Some(s.clone()),
Value::Number(n) => Some(n.to_string()),
Value::Bool(b) => Some(b.to_string()),
_ => None,
};
let unreadable = || {
PlexusError::malformed_param(param, "names what this call acts on: a string, or a list of strings")
};
match v {
Value::Null => Ok(None),
Value::Array(items) => items.iter().map(|i| one(i).ok_or_else(unreadable)).collect::<Result<_, _>>().map(Some),
other => one(other).map(|s| Some(vec![s])).ok_or_else(unreadable),
}
}
fn params_shape(params: &Value) -> Result<(), PlexusError> {
match params {
Value::Object(_) | Value::Null => Ok(()),
_ => Err(PlexusError::invalid_params(
"params must be an object naming each parameter, e.g. {\"id\": \"…\"}: a gated method takes no bare value",
)),
}
}
fn said_at_everywhere(r: Refusal) -> Refusal {
match r {
Refusal::MissingGrant { grant, roles, held_on, .. } => {
Refusal::MissingGrant { grant, scope: plexus_auth_core::grants::ScopeRef::Everywhere, roles, held_on }
}
other => other,
}
}
pub(crate) fn door_shaped(everywhere: bool, target: Option<&str>, untyped_peer_slot: bool) -> bool {
match target {
Some(_) => false,
None => everywhere || untyped_peer_slot,
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn decide(
gate: &Gate,
service_ns: &str,
full_path: &str,
info: Option<&MethodGateInfo>,
params: &Value,
auth: Option<&AuthContext>,
signed_in_grants: &std::collections::BTreeSet<String>,
ambiguous: &std::collections::HashSet<String>,
) -> Result<Admit, PlexusError> {
params_shape(params)?;
let (ns, method) = full_path.split_once('.').unwrap_or((full_path, ""));
let introspection = method == "schema"
|| method.ends_with(".schema")
|| (ns == service_ns && matches!(method, "hash" | "hashes" | "ir"));
if introspection {
return Ok(Admit::Open);
}
let grant = Grant::new(info.and_then(|i| i.grant.clone()).unwrap_or_else(|| full_path.to_string()));
if info.is_some_and(|i| i.door) {
return Ok(match dispatched(full_path, &grant, ambiguous) {
Some(call) => Admit::Reach(gate.check_everywhere_at(auth, &call).map_err(said_at_everywhere)?, Some(call), Some(Vec::new())),
None => Admit::Reach(gate.check_everywhere(auth, &grant)?, None, Some(Vec::new())),
});
}
if info.is_some_and(|i| i.everywhere) {
return Ok(Admit::Reach(gate.check_everywhere(auth, &grant)?, None, Some(Vec::new())));
}
if info.is_some_and(|i| i.public) {
return Ok(Admit::Reach(gate.reach_of_public(auth, &grant), None, None));
}
if signed_in_grants.contains(grant.as_str()) {
if auth.and_then(|a| a.principal()).is_none() {
return Err(Refusal::Unauthenticated.into());
}
return Ok(Admit::Reach(gate.reach_of_public(auth, &grant), None, None));
}
let targets = match info.and_then(|i| i.target.as_deref()) {
Some(param) => target_values(params, param)?,
None => None,
};
match targets {
None => Ok(Admit::Reach(gate.check(auth, &grant, None)?, None, Some(Vec::new()))),
Some(values) if values.is_empty() => Ok(Admit::Reach(gate.check(auth, &grant, None)?, None, Some(values))),
Some(values) => {
let mut reach = None;
for v in &values {
reach = Some(gate.check(auth, &grant, Some(v))?);
}
Ok(Admit::Reach(reach.expect("non-empty"), None, Some(values)))
}
}
}
pub fn require_everywhere(schema: &super::schema::PluginSchema, methods: &[&str]) -> Result<(), String> {
let unmarked: Vec<&str> = methods
.iter()
.copied()
.filter(|name| !schema.methods.iter().any(|m| m.name == *name && m.everywhere))
.collect();
if unmarked.is_empty() {
return Ok(());
}
Err(format!(
"{}: {} act on the whole service and must be marked `everywhere` in its schema; they are not — \
built with a plexus-macros that does not know the word (it needs 0.11.1 or later)",
schema.namespace,
unmarked.iter().map(|m| format!("{}.{m}", schema.namespace)).collect::<Vec<_>>().join(", "),
))
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ForbiddenItem {
pub grant: String,
pub scope: String,
#[serde(default)]
pub roles: Vec<String>,
#[serde(default)]
pub held_on: Vec<String>,
pub message: String,
}
impl ForbiddenItem {
pub fn from_item(item: &Value) -> Option<Self> {
if item.get("type")?.as_str()? != "error" || item.get("error_kind")?.as_str()? != "forbidden" {
return None;
}
item.get("grant")?;
serde_json::from_value(item.clone()).ok()
}
}
#[cfg(test)]
mod tests {
use super::*;
use plexus_auth_core::grants::{Membership, Memberships, Resolve, RoleTable, ScopeRef};
use serde_json::json;
use std::collections::{BTreeSet, HashSet};
use std::sync::Arc;
const OPERATOR: &str = "key:0101010101010101010101010101010101010101010101010101010101010101";
const KILN_ADMIN: &str = "key:0303030303030303030303030303030303030303030303030303030303030303";
const GARDENER: &str = "key:0202020202020202020202020202020202020202020202020202020202020202";
struct Held;
impl Memberships for Held {
fn held(&self, who: &plexus_auth_core::identity::Principal) -> Vec<Membership> {
let at = |role: &str, scope: &str| Membership { principal: who.clone(), role: plexus_auth_core::RoleName::new(role), scope: ScopeRef::parse(scope) };
match who.to_string().as_str() {
OPERATOR => vec![at("operator", "/ops")],
KILN_ADMIN => vec![at("admin", "KILN")],
GARDENER => vec![at("operator", "/ops.*")],
_ => vec![],
}
}
}
struct Kiln;
impl Resolve for Kiln {
fn chain(&self, t: &str) -> Option<Vec<ScopeRef>> {
Some(vec![ScopeRef::named(t.split('-').next().unwrap_or(t)), ScopeRef::Everywhere])
}
}
fn gate() -> Gate {
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"])]);
Gate::new(Arc::new(Held), Arc::new(roles), Arc::new(Kiln))
}
fn who(p: &str) -> AuthContext {
AuthContext::for_principal(&p.parse().unwrap(), "s", vec![], Value::Null)
}
fn info(grant: &str, everywhere: bool, target: Option<&str>, peer_slot: bool) -> MethodGateInfo {
MethodGateInfo {
grant: Some(grant.into()),
everywhere,
target: target.map(str::to_string),
door: door_shaped(everywhere, target, peer_slot),
..Default::default()
}
}
fn decided(caller: &str, path: &str, info: &MethodGateInfo, params: Value) -> Result<bool, PlexusError> {
match decide(&gate(), "svc", path, Some(info), ¶ms, Some(&who(caller)), &BTreeSet::new(), &HashSet::new())? {
Admit::Reach(_, door, _) => Ok(door.is_some()),
Admit::Open => Ok(false),
}
}
#[test]
fn a_whole_activation_method_is_decided_at_its_door() {
let grow = info("ops.grow", true, None, false);
assert_eq!(decided(OPERATOR, "ops.grow", &grow, json!({})).unwrap(), true);
assert!(matches!(decided(KILN_ADMIN, "ops.grow", &grow, json!({})), Err(PlexusError::Forbidden { .. })), "KEEL-31");
}
#[test]
fn an_untyped_peer_slot_is_decided_at_the_peer_s_door() {
let peer = info("ops.{peer}", false, None, true);
assert_eq!(decided(OPERATOR, "ops.peer.shop.look", &peer, json!({})).ok(), None, "`/ops` is ops' own: no prefix rule");
assert!(matches!(decided(KILN_ADMIN, "ops.peer.shop.look", &peer, json!({})), Err(PlexusError::Forbidden { .. })), "KEEL-44");
}
#[test]
fn a_data_method_is_decided_on_its_target_never_at_a_door() {
let get = info("ops.get", false, Some("id"), false);
assert!(decided(OPERATOR, "ops.get", &get, json!({ "id": "KILN-3" })).is_err(), "an address holds no data");
assert_eq!(decided(KILN_ADMIN, "ops.get", &get, json!({ "id": "KILN-3" })).unwrap(), false);
let tally = info("ops.tally", false, None, false);
assert!(decided(OPERATOR, "ops.tally", &tally, json!({})).is_err(), "no target: held anywhere, on data");
assert_eq!(decided(KILN_ADMIN, "ops.tally", &tally, json!({})).unwrap(), false);
}
#[test]
fn a_misdeclared_data_method_is_not_reachable_through_the_door() {
let bad = info("ops.misdeclared", true, Some("id"), false);
assert!(!bad.door);
assert!(matches!(decided(OPERATOR, "ops.misdeclared", &bad, json!({ "id": "KILN-3" })), Err(PlexusError::Forbidden { .. })));
assert!(matches!(decided(KILN_ADMIN, "ops.misdeclared", &bad, json!({ "id": "KILN-3" })), Err(PlexusError::Forbidden { .. })));
}
#[test]
fn a_dynamic_child_slot_is_held_anywhere_as_before() {
let boxes = info("ops.{box}", false, None, false);
assert!(!boxes.door);
assert!(decided(OPERATOR, "ops.b1.look", &boxes, json!({})).is_err());
assert_eq!(decided(KILN_ADMIN, "ops.b1.look", &boxes, json!({})).unwrap(), false);
}
#[test]
fn a_call_is_dispatched_from_its_literal_path() {
let none = HashSet::new();
let g = Grant::new("ops.{peer}");
let call = dispatched("ops.peer.shop.items.list", &g, &none).unwrap();
assert_eq!((call.at().activation(), call.at().method(), call.grant()), ("ops.peer.shop.items", "list", &g));
for bad in ["ops", "ops..x", "ops.sh*p.x", "ops.sh p.x", "ops.{peer}.x", ""] {
assert!(dispatched(bad, &g, &none).is_none(), "{bad}");
}
let ambiguous: HashSet<String> = ["ops.peer".to_string()].into();
assert!(dispatched("ops.peer", &g, &ambiguous).is_none(), "a name both a method and a child");
assert!(dispatched("ops.peer.shop.look", &g, &ambiguous).is_none(), "and everything under it");
assert!(dispatched("ops.peers", &g, &ambiguous).is_some());
}
#[test]
fn a_name_given_twice_is_found() {
use crate::plexus::schema::{MethodRole, MethodSchema, PluginSchema};
let mut s = PluginSchema::leaf("dyn", "1", "d", vec![MethodSchema::new("peers", "d", "h")]);
s.methods.push(MethodSchema::new("peer", "d", "h"));
s.methods.push(MethodSchema::new("peer", "d", "h").with_role(MethodRole::Peer { list_method: None, search_method: None, interface: None }));
assert_eq!(named_twice(&s), ["peer"]);
}
#[test]
fn the_backstop_takes_only_the_methods_own_door() {
let ran = |caller: &str, path: &str, info: &MethodGateInfo, peer_slot: Option<&str>, grant: &str| -> bool {
let auth = who(caller);
let Ok(Admit::Reach(reach, Some(call), _)) = decide(&gate(), "svc", path, Some(info), &json!({}), Some(&auth), &BTreeSet::new(), &HashSet::new()) else {
panic!("{path}: not admitted at a door");
};
let ctx = crate::call::CallContext::admitted_by_gate(Some(&auth), reach).at_door(call, peer_slot);
futures::executor::block_on(crate::call::scope(ctx, async { crate::call::admits_everywhere(grant) })).is_ok()
};
let grow = info("ops.grow", true, None, false);
assert!(ran(OPERATOR, "ops.grow", &grow, None, "ops.grow"));
assert!(!ran(OPERATOR, "ops.grow", &grow, None, "x.grow"), "another activation's `grow`, in process");
assert!(!ran(OPERATOR, "ops.grow", &grow, None, "ops.tally"));
let wipe = info("ops.{planet}.wipe", true, None, false);
assert!(ran(GARDENER, "ops.mars.wipe", &wipe, None, "planet.wipe"));
assert!(!ran(GARDENER, "ops.mars.wipe", &wipe, None, "planet.look"));
let slot = info("ops.{peer}", false, None, true);
assert!(!ran(GARDENER, "ops.peer.shop.wipe", &slot, Some("ops.{peer}"), "shop.wipe"));
assert!(!ran(GARDENER, "ops.peer.shop.wipe", &slot, Some("ops.{peer}"), "leaf.wipe"));
let literal = MethodGateInfo { door: true, ..Default::default() };
assert!(ran(GARDENER, "ops.peer.shop.wipe", &literal, Some("ops.{peer}"), "shop.wipe"));
assert!(ran(GARDENER, "ops.peer.shop.wipe", &literal, Some("ops.{peer}"), "leaf.wipe"));
assert!(!ran(GARDENER, "ops.peer.shop.wipe", &literal, Some("ops.{peer}"), "leaf.look"));
assert!(!ran(GARDENER, "ops.peer.shop.wipe", &literal, None, "leaf.wipe"));
}
}