Skip to main content

plexus_core/plexus/
auth_params.rs

1//! MACRO-12 — the `auth` activation's parameters, as types.
2//!
3//! Every parameter of [`super::auth_activation`]'s methods is one of these
4//! instead of a bare `String`, and the activation is compiled with
5//! `#[plexus_macros::activation(typed_params)]`, so a bare string cannot come
6//! back. Each type:
7//!
8//! - is validated once, at the wire: `Deserialize` goes through
9//!   `TryFrom<String>`, so a bad value is `InvalidParams` naming the
10//!   parameter (`role: `a.b` is not a role name …`) before the method runs;
11//! - serializes as the same plain string it always was (`#[serde(transparent)]`),
12//!   so the JSON on the wire does not change by a byte;
13//! - is `$defs/<Name> { type: string }` behind a `$ref` in the schema (the
14//!   shape ACCESS-6 / ACCESS-43 found synapse and hub-codegen read);
15//! - has `Display`, `as_str()`, and no public field.
16//!
17//! The names are the parameters' own. They live in this module, not at
18//! `plexus_core::plexus::*`, because `MethodPath`, `RoleName` and
19//! `Principal` already name the identity layer's types there; reach them as
20//! `plexus_core::plexus::auth_params::RoleName` and so on.
21
22use std::fmt;
23
24use schemars::JsonSchema;
25use serde::{Deserialize, Deserializer, Serialize};
26
27use plexus_auth_core::grants::{Grant, ScopeRef};
28use plexus_auth_core::identity;
29
30/// The common shape: a transparent `String` newtype whose `Deserialize`
31/// goes through `TryFrom<String>`.
32macro_rules! string_param {
33    ($(#[$doc:meta])* $name:ident, $check:expr) => {
34        $(#[$doc])*
35        #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, JsonSchema)]
36        #[serde(transparent)]
37        pub struct $name(String);
38
39        impl $name {
40            /// The text, as it goes on the wire.
41            pub fn as_str(&self) -> &str {
42                &self.0
43            }
44
45            /// Consume into the text.
46            pub fn into_string(self) -> String {
47                self.0
48            }
49        }
50
51        impl TryFrom<String> for $name {
52            type Error = String;
53            fn try_from(text: String) -> Result<Self, String> {
54                let check: fn(&str) -> Result<(), String> = $check;
55                let trimmed = text.trim();
56                check(trimmed)?;
57                Ok(Self(trimmed.to_string()))
58            }
59        }
60
61        impl TryFrom<&str> for $name {
62            type Error = String;
63            fn try_from(text: &str) -> Result<Self, String> {
64                Self::try_from(text.to_string())
65            }
66        }
67
68        impl std::str::FromStr for $name {
69            type Err = String;
70            fn from_str(text: &str) -> Result<Self, String> {
71                Self::try_from(text.to_string())
72            }
73        }
74
75        impl<'de> Deserialize<'de> for $name {
76            fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
77                Self::try_from(String::deserialize(d)?).map_err(serde::de::Error::custom)
78            }
79        }
80
81        impl fmt::Display for $name {
82            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83                f.write_str(&self.0)
84            }
85        }
86
87        impl AsRef<str> for $name {
88            fn as_ref(&self) -> &str {
89                &self.0
90            }
91        }
92    };
93}
94
95/// The longest name any of these accepts. Generous: it bounds a hostile
96/// value, not a real one.
97const MAX: usize = 512;
98
99fn bounded(text: &str, what: &str) -> Result<(), String> {
100    if text.is_empty() {
101        return Err(format!("an empty {what}"));
102    }
103    if text.len() > MAX {
104        return Err(format!("{what} longer than {MAX} bytes"));
105    }
106    if text.chars().any(char::is_control) {
107        return Err(format!("`{}` holds a control character: not a {what}", text.escape_debug()));
108    }
109    Ok(())
110}
111
112fn word(text: &str, what: &str, shape: &str) -> Result<(), String> {
113    bounded(text, what)?;
114    if text.chars().any(char::is_whitespace) {
115        return Err(format!("`{text}` is not a {what} ({shape})"));
116    }
117    Ok(())
118}
119
120string_param!(
121    /// A method, as `<activation>.<method>` — `tickets.set_status`. Two
122    /// or more dot-separated segments, none empty, no whitespace.
123    MethodPath,
124    |t| {
125        word(t, "method path", "<activation>.<method>")?;
126        if !t.contains('.') || t.split('.').any(str::is_empty) {
127            return Err(format!("`{t}` is not a method path (<activation>.<method>)"));
128        }
129        Ok(())
130    }
131);
132
133string_param!(
134    /// A role's name — `editor`. One word: no `.` (that is a grant), no
135    /// `@` (that is a ceiling entry), no whitespace.
136    RoleName,
137    |t| {
138        word(t, "role name", "one word, no `.` or `@`")?;
139        if t.contains('.') || t.contains('@') {
140            return Err(format!("`{t}` is not a role name (one word, no `.` or `@`)"));
141        }
142        Ok(())
143    }
144);
145
146string_param!(
147    /// One entry of a role's grants: a grant (`tickets.get`) or a role
148    /// whose grants it includes (`viewer`). No `@`, no whitespace.
149    GrantName,
150    |t| {
151        word(t, "grant or role", "tickets.get, or a role")?;
152        if t.contains('@') || t.split('.').any(str::is_empty) {
153            return Err(format!("`{t}` is not a grant or a role (tickets.get, or a role)"));
154        }
155        Ok(())
156    }
157);
158
159string_param!(
160    /// Where a role is held: a scope name (`MENGER`) or `*`, everywhere.
161    /// What a name means is the service's; it is not blank.
162    ScopeName,
163    |t| bounded(t, "scope")
164);
165
166string_param!(
167    /// A sign-in provider's name, as `auth.providers` lists it
168    /// (`workos`, `plexus-idp`). One word.
169    ProviderName,
170    |t| word(t, "provider name", "one word, as auth.providers lists it")
171);
172
173string_param!(
174    /// A Plexus principal: `key:<hex>`, `oidc:<issuer>/<subject>`,
175    /// `idp:<subject>`, … — the identity layer's grammar, checked here;
176    /// [`Principal::principal`] is the parsed value.
177    Principal,
178    |t| {
179        bounded(t, "principal")?;
180        t.parse::<identity::Principal>().map(|_| ()).map_err(|e| format!("`{t}` is not a principal: {e}"))
181    }
182);
183
184impl MethodPath {
185    /// The method's grant (a method's grant is its path).
186    pub fn grant(&self) -> Grant {
187        Grant::new(self.0.clone())
188    }
189}
190
191impl RoleName {
192    /// The identity layer's role name.
193    pub fn role(&self) -> plexus_auth_core::RoleName {
194        plexus_auth_core::RoleName::new(self.0.clone())
195    }
196}
197
198impl GrantName {
199    /// A dotted entry is a grant; a bare one names a role.
200    pub fn is_grant(&self) -> bool {
201        self.0.contains('.')
202    }
203}
204
205impl ScopeName {
206    /// `*` → everywhere; anything else, that scope.
207    pub fn scope(&self) -> ScopeRef {
208        ScopeRef::parse(&self.0)
209    }
210}
211
212impl Principal {
213    /// The identity layer's principal. Infallible: the text was checked
214    /// with the same parse when this value was made.
215    pub fn principal(&self) -> identity::Principal {
216        self.0.parse().expect("a Principal param holds a parsed principal")
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use serde_json::json;
224
225    fn de<T: for<'de> Deserialize<'de>>(v: serde_json::Value) -> Result<T, String> {
226        serde_json::from_value(v).map_err(|e| e.to_string())
227    }
228
229    #[test]
230    fn the_json_is_unchanged() {
231        let m: MethodPath = de(json!("tickets.set_status")).unwrap();
232        assert_eq!(serde_json::to_value(&m).unwrap(), json!("tickets.set_status"));
233        assert_eq!(m.as_str(), "tickets.set_status");
234        assert_eq!(m.to_string(), "tickets.set_status");
235        let s: ScopeName = de(json!("*")).unwrap();
236        assert_eq!(serde_json::to_value(&s).unwrap(), json!("*"));
237        assert_eq!(s.scope(), ScopeRef::Everywhere);
238    }
239
240    #[test]
241    fn values_are_trimmed_once() {
242        let r: RoleName = de(json!("  editor ")).unwrap();
243        assert_eq!(r.as_str(), "editor");
244        let m: MethodPath = de(json!(" tickets.get ")).unwrap();
245        assert_eq!(m.as_str(), "tickets.get");
246    }
247
248    #[test]
249    fn a_method_path_is_dotted() {
250        assert!(de::<MethodPath>(json!("tickets")).unwrap_err().contains("is not a method path"));
251        assert!(de::<MethodPath>(json!("tickets.")).is_err());
252        assert!(de::<MethodPath>(json!(".get")).is_err());
253        assert!(de::<MethodPath>(json!("tickets get")).is_err());
254        assert!(de::<MethodPath>(json!("")).is_err());
255        assert!(de::<MethodPath>(json!("tickets.inputs.answer")).is_ok());
256    }
257
258    #[test]
259    fn a_role_name_is_one_word() {
260        for bad in ["", "a.b", "editor@MENGER", "two words", "   "] {
261            assert!(de::<RoleName>(json!(bad)).is_err(), "{bad:?}");
262        }
263        assert!(de::<RoleName>(json!("a.b")).unwrap_err().contains("`a.b` is not a role name"));
264        assert_eq!(de::<RoleName>(json!("viewer")).unwrap().role().as_str(), "viewer");
265    }
266
267    #[test]
268    fn a_grant_entry_is_a_grant_or_a_role() {
269        let g: GrantName = de(json!("tickets.get")).unwrap();
270        assert!(g.is_grant());
271        let r: GrantName = de(json!("viewer")).unwrap();
272        assert!(!r.is_grant());
273        for bad in ["", "tickets.get@MENGER", "tickets..get", "a b"] {
274            assert!(de::<GrantName>(json!(bad)).is_err(), "{bad:?}");
275        }
276    }
277
278    #[test]
279    fn a_principal_parses() {
280        let p: Principal = de(json!("idp:6f1c2a3b-4d5e-4f60-8a7b-9c0d1e2f3a4b")).unwrap();
281        assert_eq!(p.principal().to_string(), p.as_str());
282        assert!(de::<Principal>(json!("nobody")).unwrap_err().contains("`nobody` is not a principal"));
283    }
284
285    #[test]
286    fn scopes_and_providers() {
287        assert!(de::<ScopeName>(json!("")).is_err());
288        assert_eq!(de::<ScopeName>(json!("MENGER")).unwrap().scope(), ScopeRef::named("MENGER"));
289        assert!(de::<ProviderName>(json!("plexus-idp")).is_ok());
290        assert!(de::<ProviderName>(json!("two words")).is_err());
291    }
292
293    #[test]
294    fn the_schema_is_a_named_string() {
295        let s = serde_json::to_value(schemars::schema_for!(RoleName)).unwrap();
296        assert_eq!(s["type"], "string");
297        assert!(s["description"].as_str().unwrap().contains("role"));
298    }
299}