1use std::collections::BTreeMap;
21use std::fmt;
22use std::sync::Arc;
23
24use coqui_access::guatiao::library::ProviderError;
25use coqui_access::{Claims, Directory, Lookup, Person, error};
26use coqui_builder::Describe;
27
28use crate::pins::{PinCheck, PinSet, PinSource};
29
30pub const MAX_CANDIDATES: usize = 16;
32
33const BYS: [&str; 4] = ["name", "email", "id", "filter"];
36
37#[derive(Debug, Clone, PartialEq, Eq, Describe)]
45#[map(deny_unknown_fields)]
46#[non_exhaustive]
47pub struct MatchRule {
48 pub by: String,
51 pub template: String,
56 pub pins: Option<String>,
59 pub domain: Option<String>,
63}
64
65impl MatchRule {
66 pub fn new(by: impl Into<String>, template: impl Into<String>) -> Self {
68 Self {
69 by: by.into(),
70 template: template.into(),
71 pins: None,
72 domain: None,
73 }
74 }
75
76 #[must_use]
78 pub fn domain(mut self, domain: impl Into<String>) -> Self {
79 self.domain = Some(domain.into());
80 self
81 }
82
83 #[must_use]
85 pub fn pins(mut self, source: impl Into<String>) -> Self {
86 self.pins = Some(source.into());
87 self
88 }
89}
90
91pub fn default_rules() -> Vec<MatchRule> {
95 vec![
96 MatchRule::new("name", "{san.upn}"),
97 MatchRule::new("email", "{san.email}"),
98 ]
99}
100
101#[derive(Debug, Clone, PartialEq, Eq, Describe)]
103#[map(deny_unknown_fields)]
104#[non_exhaustive]
105pub struct MatcherConfig {
106 #[map(default = default_rules())]
108 pub rule: Vec<MatchRule>,
109}
110
111impl Default for MatcherConfig {
112 fn default() -> Self {
113 Self {
114 rule: default_rules(),
115 }
116 }
117}
118
119#[derive(Debug, Clone, PartialEq, Eq)]
121#[non_exhaustive]
122pub struct MatcherError(String);
123
124impl fmt::Display for MatcherError {
125 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
126 formatter.write_str(&self.0)
127 }
128}
129
130impl core::error::Error for MatcherError {}
131
132impl From<MatcherError> for ProviderError {
133 fn from(failure: MatcherError) -> Self {
134 error::bad_value(&failure.0)
135 }
136}
137
138fn fail(index: usize, message: &str) -> MatcherError {
139 MatcherError(format!("rule {index}: {message}"))
140}
141
142#[derive(Debug, Clone, PartialEq, Eq)]
144#[non_exhaustive]
145pub enum Match {
146 Found(Person),
148 NotFound,
150 Ambiguous,
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
156#[non_exhaustive]
157pub struct Matched {
158 pub result: Match,
160 pub notes: Vec<String>,
163}
164
165#[derive(Clone, Copy, PartialEq, Eq)]
166enum Filter {
167 Lower,
168 Upper,
169 Local,
170 Domain,
171}
172
173impl Filter {
174 fn apply(self, value: &str) -> Option<String> {
175 match self {
176 Self::Lower => Some(value.to_lowercase()),
177 Self::Upper => Some(value.to_uppercase()),
178 _ if value.matches('@').count() > 1 => None,
180 Self::Local => Some(
181 value
182 .rsplit_once('@')
183 .map_or(value, |(local, _)| local)
184 .to_owned(),
185 ),
186 Self::Domain => value.rsplit_once('@').map(|(_, domain)| domain.to_owned()),
187 }
188 }
189}
190
191enum Piece {
192 Text(String),
193 Field { name: String, filters: Vec<Filter> },
194}
195
196fn parse(index: usize, template: &str) -> Result<Vec<Piece>, MatcherError> {
197 let mut pieces = Vec::new();
198 let mut text = String::new();
199 let mut chars = template.chars().peekable();
200 while let Some(character) = chars.next() {
201 match character {
202 '{' if chars.peek() == Some(&'{') => {
203 chars.next();
204 text.push('{');
205 }
206 '}' if chars.peek() == Some(&'}') => {
207 chars.next();
208 text.push('}');
209 }
210 '}' => return Err(fail(index, "the template has an unmatched }")),
211 '{' => {
212 let mut inner = String::new();
213 loop {
214 match chars.next() {
215 Some('}') => break,
216 Some('{') | None => {
217 return Err(fail(index, "the template has an unmatched {"));
218 }
219 Some(other) => inner.push(other),
220 }
221 }
222 let mut parts = inner.split('|');
223 let name = parts.next().unwrap_or_default();
224 let valid = !name.is_empty()
225 && name.bytes().all(|byte| {
226 byte.is_ascii_lowercase()
227 || byte.is_ascii_digit()
228 || matches!(byte, b'.' | b'_' | b'-')
229 });
230 if !valid {
231 return Err(fail(index, "a claim name is empty or not lowercase words"));
232 }
233 let mut filters = Vec::new();
234 for word in parts {
235 filters.push(match word {
236 "lower" => Filter::Lower,
237 "upper" => Filter::Upper,
238 "local" => Filter::Local,
239 "domain" => Filter::Domain,
240 _ => {
241 return Err(fail(
242 index,
243 "a filter is not lower, upper, local or domain",
244 ));
245 }
246 });
247 }
248 if !text.is_empty() {
249 pieces.push(Piece::Text(std::mem::take(&mut text)));
250 }
251 pieces.push(Piece::Field {
252 name: name.to_owned(),
253 filters,
254 });
255 }
256 other => text.push(other),
257 }
258 }
259 if !text.is_empty() {
260 pieces.push(Piece::Text(text));
261 }
262 Ok(pieces)
263}
264
265fn one_group(shape: &str) -> bool {
268 let mut depth = 0_i32;
269 let mut chars = shape.chars().peekable();
270 if chars.peek() != Some(&'(') {
271 return false;
272 }
273 let mut first = true;
274 for character in chars {
275 if !first && depth == 0 {
276 return false;
277 }
278 first = false;
279 match character {
280 '(' => depth += 1,
281 ')' => depth -= 1,
282 _ => {}
283 }
284 if depth < 0 {
285 return false;
286 }
287 }
288 depth == 0
289}
290
291struct Compiled {
292 by: &'static str,
293 filter: bool,
294 pieces: Vec<Piece>,
295 pins: Option<String>,
296 domain: Option<String>,
298}
299
300fn in_realm(value: &str, domain: &str) -> bool {
302 value.matches('@').count() == 1
303 && value
304 .rsplit_once('@')
305 .is_some_and(|(local, found)| !local.is_empty() && found.eq_ignore_ascii_case(domain))
306}
307
308impl Compiled {
309 fn new(index: usize, rule: &MatchRule) -> Result<Self, MatcherError> {
310 let Some(by) = BYS.iter().find(|word| **word == rule.by) else {
311 return Err(fail(index, "by is not name, email, id or filter"));
312 };
313 let pieces = parse(index, &rule.template)?;
314 if !pieces
315 .iter()
316 .any(|piece| matches!(piece, Piece::Field { .. }))
317 {
318 return Err(fail(
319 index,
320 "the template names no claim, so it would look up the same account for everyone",
321 ));
322 }
323 let strips = pieces.iter().any(|piece| {
324 matches!(piece, Piece::Field { filters, .. } if filters.contains(&Filter::Local))
325 });
326 let domain = match rule.domain.as_deref() {
327 None => None,
328 Some(domain) => {
329 if domain.is_empty()
330 || domain.contains('@')
331 || domain.chars().any(|c| c.is_control() || c.is_whitespace())
332 {
333 return Err(fail(index, "the domain is not a domain name"));
334 }
335 if !strips {
336 return Err(fail(
337 index,
338 "a domain applies to a template that uses local",
339 ));
340 }
341 Some(domain.to_ascii_lowercase())
342 }
343 };
344 if strips && domain.is_none() && rule.pins.is_none() {
345 return Err(fail(
346 index,
347 "local strips the realm from a name: say which with domain, or require pins",
348 ));
349 }
350 let filter = *by == "filter";
351 if filter {
352 let shape: String = pieces
353 .iter()
354 .map(|piece| match piece {
355 Piece::Text(text) => text.as_str(),
356 Piece::Field { .. } => "x",
357 })
358 .collect();
359 if !one_group(&shape) {
360 return Err(fail(index, "a filter is one balanced parenthesised group"));
361 }
362 }
363 Ok(Self {
364 by,
365 filter,
366 pieces,
367 pins: rule.pins.clone(),
368 domain,
369 })
370 }
371
372 fn candidates(&self, claims: &Claims) -> Result<Vec<Lookup>, ProviderError> {
374 let mut options: Vec<Vec<String>> = Vec::new();
376 for piece in &self.pieces {
377 match piece {
378 Piece::Text(text) => options.push(vec![text.clone()]),
379 Piece::Field { name, filters } => {
380 let mut values: Vec<String> = Vec::new();
381 for value in claims.get(name) {
382 if let Some(domain) = &self.domain
383 && filters.contains(&Filter::Local)
384 && !in_realm(value, domain)
385 {
386 continue;
387 }
388 let mut value = Some(value.clone());
389 for filter in filters {
390 value = value.and_then(|value| filter.apply(&value));
391 }
392 if let Some(value) = value.filter(|value| !value.is_empty()) {
393 let value = if self.filter {
394 escape_filter_value(&value)
395 } else {
396 value
397 };
398 if !values.contains(&value) {
399 values.push(value);
400 }
401 }
402 }
403 if values.is_empty() {
404 return Ok(Vec::new());
405 }
406 options.push(values);
407 }
408 }
409 }
410 let mut rendered = vec![String::new()];
411 for choices in &options {
412 if rendered.len().saturating_mul(choices.len()) > MAX_CANDIDATES {
413 return Err(error::bad_value(
414 "the claims render more lookups than a rule may ask for",
415 ));
416 }
417 rendered = rendered
418 .iter()
419 .flat_map(|head| choices.iter().map(move |tail| format!("{head}{tail}")))
420 .collect();
421 }
422 Ok(rendered
423 .into_iter()
424 .map(|value| Lookup {
425 by: self.by.to_owned(),
426 value,
427 claims: None,
428 })
429 .collect())
430 }
431}
432
433pub struct MatcherBuilder {
435 config: MatcherConfig,
436 sources: BTreeMap<String, Arc<dyn PinSource>>,
437}
438
439impl fmt::Debug for MatcherBuilder {
440 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
441 formatter
442 .debug_struct("MatcherBuilder")
443 .field("rules", &self.config.rule.len())
444 .field("sources", &self.sources.len())
445 .finish()
446 }
447}
448
449impl MatcherBuilder {
450 #[must_use]
452 pub fn pin_source(mut self, name: impl Into<String>, source: Arc<dyn PinSource>) -> Self {
453 self.sources.insert(name.into(), source);
454 self
455 }
456
457 pub fn build(self) -> Result<Matcher, MatcherError> {
463 let mut rules = Vec::with_capacity(self.config.rule.len());
464 for (index, rule) in self.config.rule.iter().enumerate() {
465 let compiled = Compiled::new(index, rule)?;
466 if let Some(name) = &compiled.pins
467 && !self.sources.contains_key(name)
468 {
469 return Err(fail(
470 index,
471 "the rule names a pin source that was not given",
472 ));
473 }
474 rules.push(compiled);
475 }
476 Ok(Matcher {
477 rules,
478 sources: self.sources,
479 })
480 }
481}
482
483pub struct Matcher {
485 rules: Vec<Compiled>,
486 sources: BTreeMap<String, Arc<dyn PinSource>>,
487}
488
489impl fmt::Debug for Matcher {
490 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
491 formatter
492 .debug_struct("Matcher")
493 .field("rules", &self.rules.len())
494 .field("sources", &self.sources.len())
495 .finish()
496 }
497}
498
499impl Default for Matcher {
501 fn default() -> Self {
502 Self::new(MatcherConfig::default()).expect("the default rules are valid")
503 }
504}
505
506impl Matcher {
507 pub fn builder(config: MatcherConfig) -> MatcherBuilder {
509 MatcherBuilder {
510 config,
511 sources: BTreeMap::new(),
512 }
513 }
514
515 pub fn new(config: MatcherConfig) -> Result<Self, MatcherError> {
526 Self::builder(config).build()
527 }
528
529 pub fn resolve(
540 &self,
541 lookup: &Lookup,
542 directory: &dyn Directory,
543 ) -> Result<Matched, ProviderError> {
544 let mut notes = Vec::new();
545 let result = self.walk(lookup, directory, &mut notes)?;
546 Ok(Matched { result, notes })
547 }
548
549 fn walk(
550 &self,
551 lookup: &Lookup,
552 directory: &dyn Directory,
553 notes: &mut Vec<String>,
554 ) -> Result<Match, ProviderError> {
555 let claims = match (&lookup.claims, lookup.by.as_str()) {
556 (Some(claims), "claims") => claims,
557 (None, "claims") => return Ok(Match::NotFound),
558 (_, "filter") => return Ok(Match::NotFound),
561 _ => {
562 return Ok(match asked(directory, lookup.clone())? {
563 Asked::One(person) => Match::Found(person),
564 Asked::None => Match::NotFound,
565 Asked::Several => Match::Ambiguous,
566 });
567 }
568 };
569 let pins = PinSet::from_claims(claims);
570 for rule in &self.rules {
571 let mut found: Vec<Person> = Vec::new();
572 for candidate in rule.candidates(claims)? {
573 match asked(directory, candidate)? {
574 Asked::None => {}
575 Asked::Several => return Ok(Match::Ambiguous),
576 Asked::One(person) => {
577 if !found.iter().any(|known| known.id == person.id) {
578 found.push(person);
579 }
580 }
581 }
582 }
583 match found.len() {
584 0 => continue,
585 1 => {}
586 _ => return Ok(Match::Ambiguous),
587 }
588 let person = found.remove(0);
589 let Some(name) = &rule.pins else {
590 return Ok(Match::Found(person));
591 };
592 let Some(source) = self.sources.get(name) else {
593 continue;
594 };
595 if pins.is_empty() {
596 continue;
597 }
598 match source.check(&person, &pins)? {
599 PinCheck::Holds => return Ok(Match::Found(person)),
600 PinCheck::Refused(reason) => notes.push(reason),
601 _ => {}
602 }
603 }
604 Ok(Match::NotFound)
605 }
606}
607
608enum Asked {
609 None,
610 One(Person),
611 Several,
612}
613
614fn asked(directory: &dyn Directory, lookup: Lookup) -> Result<Asked, ProviderError> {
616 match directory.lookup(lookup) {
617 Ok(Some(person)) => Ok(Asked::One(person)),
618 Ok(None) => Ok(Asked::None),
619 Err(failure) if error::is_ambiguous(&failure) => Ok(Asked::Several),
620 Err(failure) => Err(failure),
621 }
622}
623
624pub fn escape_filter_value(value: &str) -> String {
629 let mut output = String::with_capacity(value.len());
630 for byte in value.bytes() {
631 if byte.is_ascii_graphic() && !matches!(byte, b'*' | b'(' | b')' | b'\\') || byte == b' ' {
632 output.push(char::from(byte));
633 } else {
634 output.push('\\');
635 output.push_str(&format!("{byte:02x}"));
636 }
637 }
638 output
639}