1#![doc = include_str!("../README.md")]
7#![forbid(unsafe_code)]
8#![warn(missing_debug_implementations)]
9#![warn(missing_docs)]
10
11use std::borrow::Cow;
12use std::collections::BTreeSet;
13use std::fmt;
14use std::sync::Arc;
15
16use coqui_access::guatiao::library::ProviderError;
17use coqui_access::guatiao::{FromValue, Schema, ToValue};
18use coqui_access::{
19 AccountInfo, AccountPut, Accounts, Attempt, Authenticator, Description, Directory, Limit,
20 Lookup, Person, PutOutcome, Verdict, error, takes,
21};
22use coqui_access_kit::{
23 Argon2Params, DEFAULT_MAX_PASSWORD_BYTES, Keyed, MemoryTable, PasswordHasher, RecordLimits,
24 Reloading, SourceError, Table, check_keys, is_password_hash, secret, unix_now,
25};
26
27pub const DEFAULT_MAX_ACCOUNTS: usize = 10_000;
29
30#[derive(Clone, PartialEq, Eq, FromValue, Schema, ToValue)]
35#[map(crate = ::coqui_access::guatiao, deny_unknown_fields)]
36#[non_exhaustive]
37pub struct AccountRecord {
38 pub id: String,
40 pub name: String,
42 pub password_hash: String,
44 pub display_name: Option<String>,
46 pub email: Option<String>,
48 #[map(default, skip_serializing_if = Vec::is_empty)]
50 pub groups: Vec<String>,
51 #[map(default, skip_serializing_if = core::ops::Not::not)]
53 pub disabled: bool,
54 pub made_unix: Option<i64>,
56}
57
58impl AccountRecord {
59 pub fn new(
61 id: impl Into<String>,
62 name: impl Into<String>,
63 password_hash: impl Into<String>,
64 ) -> Self {
65 Self {
66 id: id.into(),
67 name: name.into(),
68 password_hash: password_hash.into(),
69 display_name: None,
70 email: None,
71 groups: Vec::new(),
72 disabled: false,
73 made_unix: None,
74 }
75 }
76
77 #[must_use]
79 pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<String>>) -> Self {
80 self.groups = groups.into_iter().map(Into::into).collect();
81 self
82 }
83
84 #[must_use]
86 pub fn display_name(mut self, display_name: impl Into<String>) -> Self {
87 self.display_name = Some(display_name.into());
88 self
89 }
90
91 #[must_use]
93 pub fn email(mut self, email: impl Into<String>) -> Self {
94 self.email = Some(email.into());
95 self
96 }
97
98 #[must_use]
100 pub fn disabled(mut self, disabled: bool) -> Self {
101 self.disabled = disabled;
102 self
103 }
104}
105
106impl Keyed for AccountRecord {
107 fn key(&self) -> Cow<'_, str> {
108 Cow::Borrowed(&self.name)
109 }
110}
111
112impl fmt::Debug for AccountRecord {
113 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
114 formatter
115 .debug_struct("AccountRecord")
116 .field("id", &"[REDACTED]")
117 .field("name", &"[REDACTED]")
118 .field("password_hash", &"[REDACTED]")
119 .field(
120 "display_name",
121 &self.display_name.as_ref().map(|_| "[REDACTED]"),
122 )
123 .field("email", &self.email.as_ref().map(|_| "[REDACTED]"))
124 .field("groups", &self.groups.len())
125 .field("disabled", &self.disabled)
126 .finish()
127 }
128}
129
130pub struct PasswordAccountsBuilder {
132 table: Option<Arc<dyn Table<AccountRecord>>>,
133 max_accounts: usize,
134 argon2: Argon2Params,
135 limits: RecordLimits,
136 max_password_bytes: Limit,
137}
138
139impl fmt::Debug for PasswordAccountsBuilder {
140 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
141 formatter
142 .debug_struct("PasswordAccountsBuilder")
143 .field("max_accounts", &self.max_accounts)
144 .finish_non_exhaustive()
145 }
146}
147
148impl PasswordAccountsBuilder {
149 #[must_use]
151 pub fn table(mut self, table: Arc<dyn Table<AccountRecord>>) -> Self {
152 self.table = Some(table);
153 self
154 }
155
156 #[must_use]
158 pub fn max_accounts(mut self, max: usize) -> Self {
159 self.max_accounts = max;
160 self
161 }
162
163 #[must_use]
165 pub fn record_limits(mut self, limits: RecordLimits) -> Self {
166 self.limits = limits;
167 self
168 }
169
170 #[must_use]
172 pub fn max_password_bytes(mut self, most: Limit) -> Self {
173 self.max_password_bytes = most;
174 self
175 }
176
177 #[must_use]
181 pub fn argon2(mut self, params: Argon2Params) -> Self {
182 self.argon2 = params;
183 self
184 }
185
186 pub fn build(self) -> Result<PasswordAccounts, SourceError> {
193 let table = self
194 .table
195 .unwrap_or_else(|| Arc::new(MemoryTable::<AccountRecord>::new()));
196 let (max, limits) = (self.max_accounts, self.limits);
197 Ok(PasswordAccounts {
198 accounts: Reloading::new(table, move |records| validate(records, max, &limits))?,
199 hasher: PasswordHasher::new(self.argon2)
200 .map_err(SourceError::invalid)?
201 .max_password_bytes(self.max_password_bytes),
202 limits,
203 })
204 }
205}
206
207#[derive(Debug)]
234pub struct PasswordAccounts {
235 accounts: Reloading<AccountRecord>,
236 hasher: PasswordHasher,
237 limits: RecordLimits,
238}
239
240impl PasswordAccounts {
241 pub fn builder() -> PasswordAccountsBuilder {
244 PasswordAccountsBuilder {
245 table: None,
246 max_accounts: DEFAULT_MAX_ACCOUNTS,
247 argon2: Argon2Params::default(),
248 limits: RecordLimits::DEFAULT,
249 max_password_bytes: DEFAULT_MAX_PASSWORD_BYTES,
250 }
251 }
252}
253
254impl Authenticator for PasswordAccounts {
255 fn authenticate(&self, attempt: Attempt) -> Result<Verdict, ProviderError> {
256 let (Some(name), Some(password)) = (attempt.name, attempt.secret) else {
257 return Ok(Verdict::Unknown);
258 };
259 let account = self
260 .accounts
261 .read(|records| records.iter().find(|account| account.name == name).cloned())
262 .map_err(|reason| reason.reading("account table"))?;
263 let verified = self.hasher.verify(
264 account
265 .as_ref()
266 .map(|account| account.password_hash.as_str()),
267 &password,
268 );
269 Ok(match account {
270 Some(account) if verified && !account.disabled => Verdict::Valid(Lookup {
271 by: "id".to_owned(),
272 value: account.id,
273 ..Lookup::default()
274 }),
275 Some(_) => Verdict::Invalid,
276 None => Verdict::Unknown,
277 })
278 }
279
280 fn describe(&self) -> Result<Description, ProviderError> {
281 Ok(Description {
282 name: Some("Password accounts".to_owned()),
283 takes: Some(takes::PASSWORD.to_owned()),
284 })
285 }
286}
287
288impl Directory for PasswordAccounts {
289 fn lookup(&self, lookup: Lookup) -> Result<Option<Person>, ProviderError> {
290 self.accounts
291 .read(|records| {
292 records
293 .iter()
294 .find(|account| {
295 !account.disabled
296 && match lookup.by.as_str() {
297 "id" => account.id == lookup.value,
298 "name" => account.name == lookup.value,
299 "email" => account.email.as_deref() == Some(&lookup.value),
300 _ => false,
301 }
302 })
303 .map(|account| Person {
304 id: account.id.clone(),
305 name: account.name.clone(),
306 display_name: account.display_name.clone(),
307 email: account.email.clone(),
308 groups: account.groups.clone(),
309 attributes: Default::default(),
310 })
311 })
312 .map_err(|reason| reason.reading("account table"))
313 }
314}
315
316impl Accounts for PasswordAccounts {
317 fn accounts(&self) -> Result<Vec<AccountInfo>, ProviderError> {
318 self.accounts
319 .read(|records| {
320 records
321 .iter()
322 .map(|account| AccountInfo {
323 id: account.id.clone(),
324 name: account.name.clone(),
325 groups: account.groups.clone(),
326 disabled: Some(account.disabled),
327 made_unix: account.made_unix,
328 expires_unix: None,
329 ..AccountInfo::default()
330 })
331 .collect()
332 })
333 .map_err(|reason| reason.reading("account table"))
334 }
335
336 fn put(&self, account: AccountPut) -> Result<PutOutcome, ProviderError> {
339 if !self.limits.allows_field(&account.name) {
340 return Err(error::bad_value("an account has a name"));
341 }
342 if account.reset || account.unlock {
343 return Err(error::unsupported(
344 "this provider keeps no reset mark or failure count",
345 ));
346 }
347 if account.expires_unix.is_some() {
348 return Err(error::bad_value("password accounts do not expire"));
349 }
350 let password = account
351 .secret
352 .as_deref()
353 .map(|password| self.hasher.hash(password))
354 .transpose()
355 .map_err(|reason| error::bad_value(&reason))?;
356 self.accounts
357 .put_with(|records| {
358 let mut entry = match records.iter().find(|entry| entry.name == account.name) {
359 Some(entry) => entry.clone(),
360 None => {
361 let Some(password) = &password else {
362 return Err(SourceError::invalid("a new account needs a password"));
363 };
364 let mut entry = AccountRecord::new(
365 secret::identifier().map_err(SourceError::unavailable)?,
366 account.name.clone(),
367 password.clone(),
368 );
369 entry.made_unix = Some(unix_now());
370 entry
371 }
372 };
373 if let Some(password) = password {
374 entry.password_hash = password;
375 }
376 if let Some(groups) = account.groups {
377 entry.groups = groups;
378 }
379 if let Some(disabled) = account.disabled {
380 entry.disabled = disabled;
381 }
382 Ok((entry, ()))
383 })
384 .map(|()| PutOutcome::default())
385 .map_err(|reason| reason.writing("account table"))
386 }
387
388 fn remove(&self, name: String) -> Result<(), ProviderError> {
389 self.accounts
390 .remove(&name)
391 .map_err(|reason| reason.writing("account table"))
392 .and_then(|removed| {
393 removed
394 .then_some(())
395 .ok_or_else(|| error::not_found("there is no such account"))
396 })
397 }
398}
399
400fn validate(
401 accounts: &[AccountRecord],
402 max: usize,
403 limits: &RecordLimits,
404) -> Result<(), SourceError> {
405 check_keys(accounts, max)?;
406 let mut ids = BTreeSet::new();
407 for account in accounts {
408 if !limits.allows_field(&account.id)
409 || !limits.allows_field(&account.name)
410 || account.name.trim().is_empty()
411 || account.password_hash.len() > 1024
412 || !is_password_hash(&account.password_hash)
413 || !ids.insert(&account.id)
414 || !limits.allows_groups(&account.groups)
415 || account
416 .display_name
417 .as_ref()
418 .is_some_and(|value| !limits.allows_display_name(value))
419 || account
420 .email
421 .as_ref()
422 .is_some_and(|value| !limits.allows_email(value))
423 {
424 return Err(SourceError::invalid(
425 "an account entry is invalid or duplicated",
426 ));
427 }
428 }
429 Ok(())
430}
431
432#[cfg(test)]
433mod tests {
434 use super::*;
435
436 fn cheap() -> Argon2Params {
437 Argon2Params::new(64, 1, 1).unwrap()
438 }
439
440 fn hash_of(password: &str) -> Result<String, String> {
441 PasswordHasher::new(cheap())?.hash(password)
442 }
443
444 fn attempt(name: &str, password: &str) -> Attempt {
445 Attempt {
446 name: Some(name.to_owned()),
447 secret: Some(password.to_owned()),
448 ..Attempt::default()
449 }
450 }
451
452 fn named(name: &str) -> AccountPut {
453 AccountPut {
454 name: name.to_owned(),
455 ..AccountPut::default()
456 }
457 }
458
459 fn with_accounts(
460 records: impl IntoIterator<Item = AccountRecord>,
461 ) -> (Arc<MemoryTable<AccountRecord>>, PasswordAccounts) {
462 let table = Arc::new(MemoryTable::from_records(records));
463 let accounts = PasswordAccounts::builder()
464 .table(table.clone())
465 .argon2(cheap())
466 .build()
467 .unwrap();
468 (table, accounts)
469 }
470
471 #[test]
472 fn a_reset_or_an_unlock_is_refused_as_unsupported() {
473 let (_, accounts) = with_accounts([AccountRecord::new(
474 "person-a",
475 "alice",
476 hash_of("x").unwrap(),
477 )]);
478 for put in [
479 AccountPut {
480 reset: true,
481 ..named("alice")
482 },
483 AccountPut {
484 unlock: true,
485 ..named("alice")
486 },
487 ] {
488 let refused = accounts.put(put).unwrap_err();
489 assert_eq!(
490 refused.status,
491 coqui_access::guatiao::Status::GUATIAO_ERR_UNSUPPORTED
492 );
493 }
494 }
495
496 #[test]
497 fn authenticates_and_resolves_accounts_without_exposing_password_hashes() {
498 let password_hash = hash_of("correct horse battery staple").unwrap();
499 let (_, accounts) =
500 with_accounts([
501 AccountRecord::new("person-a", "alice", password_hash.clone()).groups(["field"]),
502 ]);
503 let Verdict::Valid(lookup) = accounts
504 .authenticate(attempt("alice", "correct horse battery staple"))
505 .unwrap()
506 else {
507 panic!("password should be valid");
508 };
509 assert_eq!(lookup.by, "id");
510 let person = accounts.lookup(lookup).unwrap().unwrap();
511 assert_eq!(person.id, "person-a");
512 assert_eq!(person.groups, vec!["field".to_owned()]);
513 assert!(!format!("{accounts:?}").contains(&password_hash));
514 }
515
516 #[test]
517 fn wrong_unknown_and_disabled_credentials_do_not_authenticate() {
518 let password_hash = hash_of("password").unwrap();
519 let (_, accounts) =
520 with_accounts([AccountRecord::new("person-a", "a", password_hash).disabled(true)]);
521 assert!(
522 accounts
523 .lookup(Lookup {
524 by: "id".to_owned(),
525 value: "person-a".to_owned(),
526 ..Lookup::default()
527 })
528 .unwrap()
529 .is_none()
530 );
531 assert_eq!(
534 accounts.authenticate(attempt("a", "password")).unwrap(),
535 Verdict::Invalid
536 );
537 assert_eq!(
538 accounts
539 .authenticate(attempt("missing", "password"))
540 .unwrap(),
541 Verdict::Unknown
542 );
543 assert_eq!(
544 accounts.authenticate(Attempt::default()).unwrap(),
545 Verdict::Unknown
546 );
547 }
548
549 #[test]
550 fn an_unknown_name_costs_a_hash_check_like_a_wrong_password() {
551 let (_, accounts) = with_accounts([]);
552 assert!(!accounts.hasher.verify(None, "anything"));
553 assert_eq!(
554 accounts
555 .authenticate(attempt("nobody", "anything"))
556 .unwrap(),
557 Verdict::Unknown
558 );
559 }
560
561 #[test]
562 fn a_name_it_holds_with_the_wrong_password_is_invalid() {
563 let (_, accounts) = with_accounts([AccountRecord::new(
564 "person-a",
565 "alice",
566 hash_of("right").unwrap(),
567 )]);
568 assert_eq!(
569 accounts.authenticate(attempt("alice", "wrong")).unwrap(),
570 Verdict::Invalid
571 );
572 }
573
574 #[test]
575 fn invalid_duplicated_and_oversized_tables_are_refused() {
576 let hash = hash_of("pw").unwrap();
577 let build = |records: Vec<AccountRecord>, max: usize| {
578 PasswordAccounts::builder()
579 .table(Arc::new(MemoryTable::from_records(records)))
580 .max_accounts(max)
581 .build()
582 };
583 assert!(build(vec![AccountRecord::new("1", "a", "not a hash")], 10).is_err());
584 assert!(
585 build(
586 vec![
587 AccountRecord::new("1", "a", hash.clone()),
588 AccountRecord::new("1", "b", hash.clone()),
589 ],
590 10
591 )
592 .is_err(),
593 "an id is not shared"
594 );
595 assert!(
596 build(
597 vec![
598 AccountRecord::new("1", "a", hash.clone()),
599 AccountRecord::new("2", "b", hash.clone()),
600 ],
601 1
602 )
603 .is_err()
604 );
605 assert!(build(vec![AccountRecord::new("1", "a", hash)], 1).is_ok());
606 }
607
608 #[test]
609 fn accounts_are_made_changed_and_removed_through_the_kind() {
610 let (table, accounts) = with_accounts([]);
611 assert!(
612 accounts.put(named("alice")).is_err(),
613 "a new account needs a password"
614 );
615 accounts
616 .put(AccountPut {
617 secret: Some("pw one".to_owned()),
618 groups: Some(vec!["staff".to_owned()]),
619 ..named("alice")
620 })
621 .unwrap();
622 assert!(matches!(
623 accounts.authenticate(attempt("alice", "pw one")).unwrap(),
624 Verdict::Valid(_)
625 ));
626 accounts
628 .put(AccountPut {
629 groups: Some(vec!["admin".to_owned()]),
630 ..named("alice")
631 })
632 .unwrap();
633 assert!(matches!(
634 accounts.authenticate(attempt("alice", "pw one")).unwrap(),
635 Verdict::Valid(_)
636 ));
637 accounts
638 .put(AccountPut {
639 secret: Some("pw two".to_owned()),
640 ..named("alice")
641 })
642 .unwrap();
643 assert_eq!(
644 accounts.authenticate(attempt("alice", "pw one")).unwrap(),
645 Verdict::Invalid
646 );
647 let listed = accounts.accounts().unwrap();
648 assert_eq!(listed.len(), 1);
649 assert_eq!(listed[0].groups, ["admin"]);
650 let kept = table.load().unwrap().records;
651 assert!(
652 kept[0]
653 .password_hash
654 .starts_with("$argon2id$v=19$m=64,t=1,p=1$")
655 );
656 assert!(
657 accounts
658 .put(AccountPut {
659 expires_unix: Some(1),
660 ..named("alice")
661 })
662 .is_err()
663 );
664 accounts.remove("alice".to_owned()).unwrap();
665 assert!(accounts.remove("alice".to_owned()).is_err());
666 }
667
668 #[test]
669 fn a_write_through_another_handle_is_seen_without_rebuilding() {
670 let (table, accounts) = with_accounts([]);
671 let other = PasswordAccounts::builder()
672 .table(table)
673 .argon2(cheap())
674 .build()
675 .unwrap();
676 other
677 .put(AccountPut {
678 secret: Some("x".to_owned()),
679 ..named("bob")
680 })
681 .unwrap();
682 assert_eq!(accounts.accounts().unwrap().len(), 1);
683 }
684
685 #[test]
686 fn a_read_only_table_refuses_changes_but_authenticates() {
687 struct Fixed(Vec<AccountRecord>);
688 impl Table<AccountRecord> for Fixed {
689 fn load(&self) -> Result<coqui_access_kit::Snapshot<AccountRecord>, SourceError> {
690 Ok(coqui_access_kit::Snapshot::new(
691 coqui_access_kit::Revision::default(),
692 self.0.clone(),
693 ))
694 }
695 }
696 let hash = hash_of("pw").unwrap();
697 let accounts = PasswordAccounts::builder()
698 .table(Arc::new(Fixed(vec![AccountRecord::new("1", "a", hash)])))
699 .build()
700 .unwrap();
701 assert!(matches!(
702 accounts.authenticate(attempt("a", "pw")).unwrap(),
703 Verdict::Valid(_)
704 ));
705 assert!(
706 accounts
707 .put(AccountPut {
708 secret: Some("new".to_owned()),
709 ..named("b")
710 })
711 .is_err()
712 );
713 assert!(accounts.remove("a".to_owned()).is_err());
714 }
715}