plexus_core/plexus/
auth_params.rs1use 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
30macro_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 pub fn as_str(&self) -> &str {
42 &self.0
43 }
44
45 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
95const 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 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 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 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 ScopeName,
163 |t| bounded(t, "scope")
164);
165
166string_param!(
167 ProviderName,
170 |t| word(t, "provider name", "one word, as auth.providers lists it")
171);
172
173string_param!(
174 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 pub fn grant(&self) -> Grant {
187 Grant::new(self.0.clone())
188 }
189}
190
191impl RoleName {
192 pub fn role(&self) -> plexus_auth_core::RoleName {
194 plexus_auth_core::RoleName::new(self.0.clone())
195 }
196}
197
198impl GrantName {
199 pub fn is_grant(&self) -> bool {
201 self.0.contains('.')
202 }
203}
204
205impl ScopeName {
206 pub fn scope(&self) -> ScopeRef {
208 ScopeRef::parse(&self.0)
209 }
210}
211
212impl Principal {
213 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}