use plexus_auth_core::grants::{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)?;
let within = current.is_everywhere() || reach.held_on().iter().all(|s| current.held_on().contains(s));
if !within {
return Err(PlexusError::Unauthenticated(
"with_reach narrows a call's reach; it holds a scope the call does not".into(),
));
}
Ok(crate::call::scope(ctx.with_reach(reach), fut).await)
}
pub(crate) enum Admit {
Reach(Reach),
Open,
}
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",
)),
}
}
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>,
) -> 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.everywhere) {
return Ok(Admit::Reach(gate.check_everywhere(auth, &grant)?));
}
if info.is_some_and(|i| i.public) {
return Ok(Admit::Reach(gate.reach_of_public(auth, &grant)));
}
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)));
}
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)?)),
Some(values) if values.is_empty() => Ok(Admit::Reach(gate.check(auth, &grant, None)?)),
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")))
}
}
}
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()
}
}