alighieri 0.4.0

Alighieri — a lightweight, secure, asynchronous SOCKS5 proxy server with Dante-inspired configuration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
//! Username/password credential storage for RFC 1929 authentication.
//!
//! Credentials are loaded from a `userlist` file: one `username:password`
//! entry per line. Blank lines and `#` comments are ignored. Passwords may be
//! plaintext for backward compatibility or Argon2 PHC strings generated by the
//! `alighieri user add` command.
//!
//! ```text
//! # /etc/alighieri/users
//! # alighieri:user:argon2:616c696365:$argon2id$v=19$m=19456,t=2,p=1$...
//! legacy:plaintext-password
//! ```
//!
//! # Security note
//!
//! Plaintext entries are supported only for compatibility. Prefer Argon2id
//! hashes and keep the file readable only by the account that runs Alighieri
//! (e.g. `chmod 600`). Plaintext verification uses a constant-time comparison
//! to avoid leaking password content through timing side-channels.

use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};

use argon2::{Algorithm, Argon2, Params, Version};
use password_hash::{
    rand_core::{OsRng, RngCore},
    PasswordHash, PasswordHasher, PasswordVerifier, SaltString,
};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};

use crate::errors::{Error, Result};
use crate::util::constant_time_eq;

const ARGON2_DIRECTIVE_PREFIX: &str = "# alighieri:user:argon2:";
const DUMMY_ARGON2_HASH: &str = "$argon2id$v=19$m=19456,t=2,p=1$c29tZXJhbmRvbXNhbHQ$C7It2r7AayL9ud0k5lZByEYkYBm2MDc36XwDo7OZH34";
const MAX_CONCURRENT_PASSWORD_VERIFICATIONS: usize = 4;
/// Cap on concurrently running `auth.command` verifier processes, so a burst of
/// username handshakes cannot fork an unbounded number of children. External
/// verifiers are typically I/O-bound (LDAP/HTTP), so this is higher than the
/// CPU-bound `MAX_CONCURRENT_PASSWORD_VERIFICATIONS`; excess handshakes wait for
/// a slot and are denied if they cannot obtain one within the handshake timeout.
const MAX_CONCURRENT_AUTH_COMMANDS: usize = 64;
/// Upper bound on how long the detached reaper waits for a killed verifier child
/// to terminate before giving up. A SIGKILLed process dies almost immediately;
/// this only guards against one briefly stuck uninterruptibly, after which the
/// `Child` handle is dropped and tokio's orphan queue reaps anything slower.
const REAP_WAIT_TIMEOUT: Duration = Duration::from_secs(5);
const RFC1929_FIELD_MAX: usize = u8::MAX as usize;
const MAX_VERIFIED_CACHE_ENTRIES: usize = 1024;
/// Cache tags use a deliberately cheap Argon2 instance (microseconds): the
/// full-cost hash already ran once before anything is cached, and the
/// per-process random salt makes tags useless outside this process.
const CACHE_TAG_M_COST_KIB: u32 = 8;
const CACHE_TAG_LEN: usize = 32;

/// An in-memory username/password database.
#[derive(Debug, Clone)]
pub struct UserDb {
    users: HashMap<String, StoredCredential>,
    verified: Arc<VerifiedCache>,
}

impl Default for UserDb {
    fn default() -> Self {
        UserDb {
            users: HashMap::new(),
            verified: Arc::new(VerifiedCache::new()),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum StoredCredential {
    Plain(String),
    Argon2(String),
}

impl UserDb {
    /// Creates an empty database.
    pub fn new() -> Self {
        UserDb::default()
    }

    /// Loads credentials from a userlist file.
    pub fn load(path: &Path) -> Result<UserDb> {
        let text = std::fs::read_to_string(path).map_err(|e| {
            Error::Config(format!("failed to read userlist {}: {e}", path.display()))
        })?;
        UserDb::parse(&text)
    }

    /// Parses credentials from the userlist text format.
    pub fn parse(text: &str) -> Result<UserDb> {
        let mut users = HashMap::new();
        for (i, line) in text.lines().enumerate() {
            let lineno = i + 1;
            let trimmed = line.trim();
            if let Some((user, credential)) = parse_argon2_directive(trimmed).map_err(|e| {
                Error::Config(format!("userlist line {lineno}: invalid Argon2 entry: {e}"))
            })? {
                if users.contains_key(&user) {
                    tracing::warn!(
                        line = lineno,
                        user = %user,
                        "duplicate userlist username; the later entry overrides the earlier one"
                    );
                }
                users.insert(user, credential);
                continue;
            }
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }
            let (user, pass) = trimmed.split_once(':').ok_or_else(|| {
                Error::Config(format!(
                    "userlist line {lineno}: expected 'username:password'"
                ))
            })?;
            let user = user.trim();
            if user.is_empty() {
                return Err(Error::Config(format!(
                    "userlist line {lineno}: empty username"
                )));
            }
            if users.contains_key(user) {
                tracing::warn!(
                    line = lineno,
                    user = %user,
                    "duplicate userlist username; the later entry overrides the earlier one"
                );
            }
            users.insert(user.to_string(), StoredCredential::Plain(pass.to_string()));
        }
        Ok(UserDb {
            users,
            ..UserDb::default()
        })
    }

    /// Builds a userlist line with an Argon2id hash for `password`.
    pub fn hash_user_line(username: &str, password: &str) -> Result<String> {
        validate_username(username)?;
        validate_password(password)?;
        let hash = hash_password(password)?;
        Ok(format!(
            "{ARGON2_DIRECTIVE_PREFIX}{}:{hash}",
            hex_encode(username.as_bytes())
        ))
    }

    /// Returns the username represented by a userlist line, if it is an entry.
    pub fn entry_username(line: &str) -> Option<String> {
        let trimmed = line.trim();
        if let Ok(Some(user)) = parse_argon2_directive_username(trimmed) {
            return Some(user);
        }
        if trimmed.is_empty() || trimmed.starts_with('#') {
            return None;
        }
        trimmed
            .split_once(':')
            .map(|(user, _)| user.trim().to_string())
            .filter(|user| !user.is_empty())
    }

    /// Returns the number of users in the database.
    pub fn len(&self) -> usize {
        self.users.len()
    }

    /// Returns `true` if the database is empty.
    pub fn is_empty(&self) -> bool {
        self.users.is_empty()
    }

    /// Verifies a username/password pair in (near) constant time.
    ///
    /// To avoid revealing whether a username exists via timing, an absent user
    /// is still compared against dummy plaintext and Argon2 values. Plaintext
    /// and Argon2 entries still have inherently different verification costs.
    pub fn verify(&self, username: &str, password: &str) -> bool {
        verify_stored(self.users.get(username), password)
    }

    /// Verifies credentials without blocking the async runtime on Argon2 work.
    ///
    /// When `cache_ttl` is set, a successful verification is remembered as a
    /// keyed tag (never the password itself) and repeat handshakes with the
    /// same credentials skip the full-cost hash until the entry expires or
    /// the user database is reloaded. Failures always take the full-cost
    /// path, so the cache does not cheapen brute force or username probing.
    pub async fn verify_async(
        &self,
        username: &str,
        password: &str,
        cache_ttl: Option<Duration>,
    ) -> bool {
        let cached = cache_ttl.and_then(|ttl| {
            let tag = self.verified.tag(username, password)?;
            Some((tag, ttl))
        });
        if let Some((tag, _)) = &cached {
            if self.verified.check(username, tag, Instant::now()) {
                return true;
            }
        }

        let stored = self.users.get(username).cloned();
        let password = password.to_string();
        let Ok(permit) = password_verify_semaphore().clone().acquire_owned().await else {
            return false;
        };
        let ok = tokio::task::spawn_blocking(move || {
            let _permit = permit;
            verify_stored(stored.as_ref(), &password)
        })
        .await
        .unwrap_or(false);

        if ok {
            if let Some((tag, ttl)) = cached {
                let now = Instant::now();
                if let Some(expires_at) = now.checked_add(ttl) {
                    self.verified.store(username, tag, expires_at, now);
                }
            }
        }
        ok
    }
}

/// The result of a username/password verification, so a backend timeout is
/// distinguishable from a wrong-credentials denial at the call site and both
/// auth backends produce consistent logs and error codes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthOutcome {
    /// Credentials accepted.
    Allowed,
    /// Credentials rejected.
    Denied,
    /// Verification did not finish within the allotted time.
    TimedOut,
}

/// Verifies credentials by invoking an external command (the `auth.command`
/// hook), so an operator can delegate to LDAP / OIDC / PAM / anything via a
/// script. The username and password are written to the command's **stdin**
/// (never argv or the environment, which can leak through `ps` or `/proc`); an
/// exit status of `0` allows the connection. Successful verifications are cached
/// exactly like the userlist path so the command is not re-run per handshake.
#[derive(Debug)]
pub struct CommandAuth {
    program: String,
    args: Vec<String>,
    verified: VerifiedCache,
    limiter: Arc<Semaphore>,
}

impl CommandAuth {
    /// Builds a verifier from a command line whose first token is the program
    /// and the remaining tokens are fixed arguments. `None` if `command` is
    /// empty.
    pub fn new(command: &[String]) -> Option<Self> {
        let (program, args) = command.split_first()?;
        Some(CommandAuth {
            program: program.clone(),
            args: args.to_vec(),
            verified: VerifiedCache::new(),
            limiter: Arc::new(Semaphore::new(MAX_CONCURRENT_AUTH_COMMANDS)),
        })
    }

    /// Verifies `username`/`password` by running the command. The command
    /// execution — acquiring a concurrency slot, spawning the verifier, delivering
    /// the credentials, and awaiting its verdict — is bounded by `timeout` (an
    /// overrun child is killed and reaped out of band); a cheap cache-tag
    /// derivation and lookup precede it. When `cache_ttl` is set, a success is
    /// cached so the command is not re-run for the same credentials until the
    /// entry expires. Failures always take the full path, so the cache cannot
    /// cheapen brute force.
    pub async fn verify_async(
        &self,
        username: &str,
        password: &str,
        cache_ttl: Option<Duration>,
        timeout: Duration,
    ) -> AuthOutcome {
        // Reject credentials containing a stdin line delimiter (LF or CR) or a
        // NUL up front — before any cache/tag work — so such pathological input
        // can neither reach the command nor desync the two-line stdin framing
        // below (a verifier that splits on CRLF would otherwise see a different
        // username/password boundary). RFC 1929 fields are arbitrary bytes, but
        // these values do not occur in practice, and the userlist path already
        // rejects CR/LF (`validate_username`); this matches it.
        if [username, password]
            .iter()
            .any(|s| s.contains(['\n', '\r', '\0']))
        {
            return AuthOutcome::Denied;
        }
        let cached = cache_ttl.and_then(|ttl| Some((self.verified.tag(username, password)?, ttl)));
        if let Some((tag, _)) = &cached {
            if self.verified.check(username, tag, Instant::now()) {
                return AuthOutcome::Allowed;
            }
        }
        // Bound the entire run — permit acquisition, spawn, credential delivery
        // and the wait for a verdict — by `timeout`. On expiry the in-flight
        // child is killed and reaped out of band by its guard, and the timeout is
        // surfaced distinctly so callers log it like the userlist path.
        let allowed = match tokio::time::timeout(timeout, self.run(username, password)).await {
            Ok(ok) => ok,
            Err(_) => {
                // The connection layer logs the timeout at WARN (with peer/user);
                // keep this program-specific detail at DEBUG so a timeout is not
                // logged twice at WARN.
                tracing::debug!(program = %self.program, "auth.command timed out");
                return AuthOutcome::TimedOut;
            }
        };
        if !allowed {
            return AuthOutcome::Denied;
        }
        if let Some((tag, ttl)) = cached {
            let now = Instant::now();
            if let Some(expires_at) = now.checked_add(ttl) {
                self.verified.store(username, tag, expires_at, now);
            }
        }
        AuthOutcome::Allowed
    }

    async fn run(&self, username: &str, password: &str) -> bool {
        // Cap concurrent verifier processes so a burst of handshakes cannot fork
        // an unbounded number of children. When saturated this awaits a free slot
        // until the surrounding `timeout` denies the attempt. The owned permit is
        // handed to the guard, which holds it until the child is fully reaped
        // (including the out-of-band reap after cancellation), so the slot is not
        // freed while a killed child is still terminating.
        let Ok(permit) = self.limiter.clone().acquire_owned().await else {
            return false; // The limiter is never closed; fail closed regardless.
        };
        // `verify_async` has already rejected credentials containing CR, LF, or
        // NUL, so the two-line stdin framing below is unambiguous.
        let child = match tokio::process::Command::new(&self.program)
            .args(&self.args)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .kill_on_drop(true)
            .spawn()
        {
            Ok(child) => child,
            Err(e) => {
                tracing::warn!(error = %e, program = %self.program, "auth.command failed to spawn");
                return false; // `permit` drops here, freeing the slot.
            }
        };
        // The guard kills and reaps the child on every exit from here — including
        // cancellation when the surrounding `timeout` fires mid-run — and holds
        // the permit until that reap completes.
        let mut guard = ChildReaper::new(child, permit);
        // Deliver the two credential lines as separate chunks, so stdin delivery
        // does not allocate one buffer holding both secrets. If delivery fails —
        // the verifier exited or closed stdin before reading them — the
        // credentials never arrived, so fail closed rather than trust a status
        // produced without them.
        let delivered = match guard.child().stdin.take() {
            Some(mut stdin) => {
                use tokio::io::AsyncWriteExt;
                stdin.write_all(username.as_bytes()).await.is_ok()
                    && stdin.write_all(b"\n").await.is_ok()
                    && stdin.write_all(password.as_bytes()).await.is_ok()
                    && stdin.write_all(b"\n").await.is_ok()
                // `stdin` is dropped here, closing the pipe so the command sees EOF.
            }
            None => false,
        };
        if !delivered {
            return false; // The guard reaps the child on drop.
        }
        let status = guard.child().wait().await;
        if status.is_ok() {
            // Reaped synchronously by `wait`; nothing left for `Drop` to do.
            guard.disarm();
        }
        // On a `wait` error the child may still be running, so leave the guard
        // armed to kill and reap it on drop.
        matches!(status, Ok(status) if status.success())
    }
}

/// Owns a spawned verifier child (and its concurrency permit) and guarantees the
/// child is killed and reaped even if the future is cancelled (e.g. the
/// verification timeout fires mid-run). Reaping runs in a detached task so it
/// neither blocks nor extends the caller; on the normal path the child is
/// awaited directly and the guard disarmed. The permit is held until the reap
/// completes, so the concurrency slot is not freed while the child is still
/// terminating. `kill_on_drop` backstops the kill if no runtime is available.
struct ChildReaper {
    child: Option<tokio::process::Child>,
    permit: Option<OwnedSemaphorePermit>,
}

impl ChildReaper {
    fn new(child: tokio::process::Child, permit: OwnedSemaphorePermit) -> Self {
        ChildReaper {
            child: Some(child),
            permit: Some(permit),
        }
    }

    fn child(&mut self) -> &mut tokio::process::Child {
        self.child.as_mut().expect("child present until disarmed")
    }

    /// Releases the child and its permit once the child has already been reaped,
    /// making `Drop` a no-op.
    fn disarm(&mut self) {
        self.child = None;
        self.permit = None;
    }
}

impl Drop for ChildReaper {
    fn drop(&mut self) {
        if let Some(mut child) = self.child.take() {
            let permit = self.permit.take();
            let _ = child.start_kill();
            if let Ok(handle) = tokio::runtime::Handle::try_current() {
                handle.spawn(async move {
                    // Reap the killed child, but bounded: a process briefly stuck
                    // uninterruptibly must not hang this task forever — that would
                    // also pin the `Child` handle and stop `kill_on_drop` from ever
                    // running. On timeout `child` drops here, so `kill_on_drop`
                    // plus tokio's orphan queue take over the reap.
                    let _ = tokio::time::timeout(REAP_WAIT_TIMEOUT, child.wait()).await;
                    // Release the concurrency slot only now the child is reaped.
                    drop(permit);
                });
            }
            // With no runtime, `child` and `permit` drop now; `kill_on_drop` plus
            // the orphan queue reap the child.
        }
    }
}

/// Remembers recently verified credentials so repeat handshakes skip the
/// expensive password hash. Entries hold a keyed tag derived with a cheap
/// Argon2 instance and a per-process random salt — never the password itself
/// — and the whole cache is dropped with the `UserDb` on reload.
struct VerifiedCache {
    salt: [u8; 16],
    entries: Mutex<HashMap<String, VerifiedEntry>>,
}

struct VerifiedEntry {
    tag: [u8; CACHE_TAG_LEN],
    expires_at: Instant,
}

impl VerifiedCache {
    fn new() -> Self {
        let mut salt = [0u8; 16];
        OsRng.fill_bytes(&mut salt);
        VerifiedCache {
            salt,
            entries: Mutex::new(HashMap::new()),
        }
    }

    /// Derives the cache tag for a credential pair. The NUL separator keeps
    /// pairs with shifted boundaries (e.g. `ab`/`c` vs `a`/`bc`) distinct.
    fn tag(&self, username: &str, password: &str) -> Option<[u8; CACHE_TAG_LEN]> {
        let params = Params::new(CACHE_TAG_M_COST_KIB, 1, 1, Some(CACHE_TAG_LEN)).ok()?;
        let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
        let mut material = Vec::with_capacity(username.len() + 1 + password.len());
        material.extend_from_slice(username.as_bytes());
        material.push(0);
        material.extend_from_slice(password.as_bytes());
        let mut tag = [0u8; CACHE_TAG_LEN];
        argon
            .hash_password_into(&material, &self.salt, &mut tag)
            .ok()?;
        Some(tag)
    }

    fn check(&self, username: &str, tag: &[u8; CACHE_TAG_LEN], now: Instant) -> bool {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        let Some(entry) = entries.get(username) else {
            return false;
        };
        if entry.expires_at <= now {
            entries.remove(username);
            return false;
        }
        constant_time_eq(&entry.tag, tag)
    }

    fn store(&self, username: &str, tag: [u8; CACHE_TAG_LEN], expires_at: Instant, now: Instant) {
        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
        if entries.len() >= MAX_VERIFIED_CACHE_ENTRIES && !entries.contains_key(username) {
            entries.retain(|_, entry| entry.expires_at > now);
        }
        if entries.len() >= MAX_VERIFIED_CACHE_ENTRIES && !entries.contains_key(username) {
            let oldest = entries
                .iter()
                .min_by_key(|(_, entry)| entry.expires_at)
                .map(|(user, _)| user.clone());
            if let Some(oldest) = oldest {
                entries.remove(&oldest);
            }
        }
        entries.insert(username.to_string(), VerifiedEntry { tag, expires_at });
    }
}

impl std::fmt::Debug for VerifiedCache {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("VerifiedCache").finish_non_exhaustive()
    }
}

fn password_verify_semaphore() -> &'static Arc<Semaphore> {
    static SEMAPHORE: OnceLock<Arc<Semaphore>> = OnceLock::new();
    SEMAPHORE.get_or_init(|| Arc::new(Semaphore::new(MAX_CONCURRENT_PASSWORD_VERIFICATIONS)))
}

fn verify_stored(stored: Option<&StoredCredential>, password: &str) -> bool {
    match stored {
        Some(StoredCredential::Plain(stored)) => {
            let ok = constant_time_eq(stored.as_bytes(), password.as_bytes());
            let _ = dummy_argon2_credential().verify(password);
            ok
        }
        Some(stored) => stored.verify(password),
        None => {
            let _ = constant_time_eq(password.as_bytes(), password.as_bytes());
            let _ = dummy_argon2_credential().verify(password);
            false
        }
    }
}

impl StoredCredential {
    fn parse_argon2(phc: &str) -> std::result::Result<Self, String> {
        let parsed = PasswordHash::new(phc).map_err(|e| e.to_string())?;
        if parsed.algorithm.as_str() != "argon2id" {
            return Err("expected argon2id PHC hash".into());
        }
        if parsed.hash.is_none() {
            return Err("missing hash output".into());
        }
        Ok(StoredCredential::Argon2(phc.to_string()))
    }

    fn verify(&self, password: &str) -> bool {
        match self {
            StoredCredential::Plain(stored) => {
                constant_time_eq(stored.as_bytes(), password.as_bytes())
            }
            StoredCredential::Argon2(stored) => PasswordHash::new(stored)
                .ok()
                .and_then(|hash| {
                    Argon2::default()
                        .verify_password(password.as_bytes(), &hash)
                        .ok()
                })
                .is_some(),
        }
    }
}

fn dummy_argon2_credential() -> &'static StoredCredential {
    static DUMMY: OnceLock<StoredCredential> = OnceLock::new();
    DUMMY.get_or_init(|| {
        StoredCredential::parse_argon2(DUMMY_ARGON2_HASH).expect("dummy Argon2 hash is valid")
    })
}

fn hash_password(password: &str) -> Result<String> {
    let salt = SaltString::generate(&mut OsRng);
    Argon2::default()
        .hash_password(password.as_bytes(), &salt)
        .map(|hash| hash.to_string())
        .map_err(|e| Error::Config(format!("failed to hash password: {e}")))
}

fn parse_argon2_directive(
    trimmed: &str,
) -> std::result::Result<Option<(String, StoredCredential)>, String> {
    let Some((username, phc)) = parse_argon2_directive_parts(trimmed)? else {
        return Ok(None);
    };
    let credential = StoredCredential::parse_argon2(phc)?;
    Ok(Some((username, credential)))
}

fn parse_argon2_directive_username(trimmed: &str) -> std::result::Result<Option<String>, String> {
    Ok(parse_argon2_directive_parts(trimmed)?.map(|(username, _)| username))
}

fn parse_argon2_directive_parts(
    trimmed: &str,
) -> std::result::Result<Option<(String, &str)>, String> {
    let Some(rest) = trimmed.strip_prefix(ARGON2_DIRECTIVE_PREFIX) else {
        return Ok(None);
    };
    let (encoded_user, phc) = rest
        .split_once(':')
        .ok_or_else(|| "expected encoded username and PHC hash".to_string())?;
    let username = hex_decode_utf8(encoded_user)?;
    validate_username(&username).map_err(|e| e.to_string())?;
    Ok(Some((username, phc)))
}

fn hex_encode(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut encoded = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        encoded.push(HEX[(byte >> 4) as usize] as char);
        encoded.push(HEX[(byte & 0x0f) as usize] as char);
    }
    encoded
}

fn hex_decode_utf8(encoded: &str) -> std::result::Result<String, String> {
    if !encoded.len().is_multiple_of(2) {
        return Err("encoded username must have an even number of hex digits".into());
    }
    let mut bytes = Vec::with_capacity(encoded.len() / 2);
    for pair in encoded.as_bytes().chunks_exact(2) {
        let high = hex_value(pair[0])?;
        let low = hex_value(pair[1])?;
        bytes.push((high << 4) | low);
    }
    String::from_utf8(bytes).map_err(|e| e.to_string())
}

fn hex_value(byte: u8) -> std::result::Result<u8, String> {
    match byte {
        b'0'..=b'9' => Ok(byte - b'0'),
        b'a'..=b'f' => Ok(byte - b'a' + 10),
        b'A'..=b'F' => Ok(byte - b'A' + 10),
        _ => Err("encoded username contains a non-hex digit".into()),
    }
}

fn validate_username(username: &str) -> Result<()> {
    if username.trim().is_empty() {
        return Err(Error::Config("username must not be empty".into()));
    }
    if username != username.trim() {
        return Err(Error::Config(
            "username must not contain leading or trailing whitespace".into(),
        ));
    }
    if username.contains(':') || username.contains('\n') || username.contains('\r') {
        return Err(Error::Config(
            "username must not contain ':', CR, or LF".into(),
        ));
    }
    if username.len() > RFC1929_FIELD_MAX {
        return Err(Error::Config(
            "username must not exceed 255 bytes for SOCKS5 username/password authentication".into(),
        ));
    }
    Ok(())
}

fn validate_password(password: &str) -> Result<()> {
    if password.len() > RFC1929_FIELD_MAX {
        return Err(Error::Config(
            "password must not exceed 255 bytes for SOCKS5 username/password authentication".into(),
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_basic_userlist() {
        let db = UserDb::parse("alice:s3cr3t\nbob:hunter2\n").unwrap();
        assert_eq!(db.len(), 2);
        assert!(db.verify("alice", "s3cr3t"));
        assert!(db.verify("bob", "hunter2"));
    }

    #[test]
    fn parse_duplicate_username_keeps_last_entry() {
        // A duplicate username is not an error (a hard failure would break
        // userlists that load today), but the later entry wins; the parser logs
        // a warning so the shadowing is not silent.
        let db = UserDb::parse("alice:first\nalice:second\n").unwrap();
        assert_eq!(db.len(), 1);
        assert!(db.verify("alice", "second"));
        assert!(!db.verify("alice", "first"));
    }

    #[test]
    fn argon2_hash_user_line_verifies() {
        let line = UserDb::hash_user_line("alice", "s3cr3t").unwrap();
        assert!(line.starts_with("# alighieri:user:argon2:616c696365:$argon2id$"));
        let db = UserDb::parse(&line).unwrap();
        assert!(db.verify("alice", "s3cr3t"));
        assert!(!db.verify("alice", "wrong"));
    }

    #[test]
    fn invalid_argon2_hash_is_rejected() {
        let err = UserDb::parse("# alighieri:user:argon2:616c696365:$argon2id$not-a-valid-phc")
            .unwrap_err();
        assert!(err.to_string().contains("invalid Argon2 entry"));
    }

    #[test]
    fn non_argon2id_hash_is_rejected() {
        let err = UserDb::parse(
            "# alighieri:user:argon2:616c696365:$argon2i$v=19$m=19456,t=2,p=1$c29tZXJhbmRvbXNhbHQ$C7It2r7AayL9ud0k5lZByEYkYBm2MDc36XwDo7OZH34",
        )
        .unwrap_err();
        assert!(err.to_string().contains("argon2id"));
    }

    #[test]
    fn plaintext_argon2_prefix_without_marker_remains_plaintext() {
        let db = UserDb::parse("alice:$argon2-secret").unwrap();
        assert!(db.verify("alice", "$argon2-secret"));
    }

    #[test]
    fn plaintext_argon2_marker_without_phc_remains_plaintext() {
        let db = UserDb::parse("alice:argon2:not-a-phc").unwrap();
        assert!(db.verify("alice", "argon2:not-a-phc"));
    }

    #[test]
    fn plaintext_argon2_phc_looking_password_remains_plaintext() {
        let password = "argon2:$argon2id$v=19$m=19456,t=2,p=1$c29tZXJhbmRvbXNhbHQ$C7It2r7AayL9ud0k5lZByEYkYBm2MDc36XwDo7OZH34";
        let db = UserDb::parse(&format!("alice:{password}")).unwrap();
        assert!(db.verify("alice", password));
    }

    #[test]
    fn entry_username_handles_plain_and_argon2_entries() {
        let line = UserDb::hash_user_line("alice", "s3cr3t").unwrap();
        assert_eq!(UserDb::entry_username(&line).as_deref(), Some("alice"));
        assert_eq!(
            UserDb::entry_username("# alighieri:user:argon2:616c696365:$argon2id$not-a-valid-phc")
                .as_deref(),
            Some("alice")
        );
        assert_eq!(UserDb::entry_username("bob:pw").as_deref(), Some("bob"));
        assert_eq!(
            UserDb::entry_username("alice :pw").as_deref(),
            Some("alice")
        );
        assert_eq!(UserDb::entry_username("# just a comment"), None);
    }

    #[test]
    fn reject_wrong_password() {
        let db = UserDb::parse("alice:s3cr3t").unwrap();
        assert!(!db.verify("alice", "wrong"));
    }

    #[test]
    fn reject_unknown_user() {
        let db = UserDb::parse("alice:s3cr3t").unwrap();
        assert!(!db.verify("eve", "whatever"));
    }

    #[test]
    fn ignores_comments_and_blanks() {
        let db = UserDb::parse("# users\n\nalice:pw\n\n# end\n").unwrap();
        assert_eq!(db.len(), 1);
        assert!(db.verify("alice", "pw"));
    }

    #[test]
    fn password_with_colon() {
        let db = UserDb::parse("alice:a:b:c").unwrap();
        assert!(db.verify("alice", "a:b:c"));
    }

    #[test]
    fn missing_colon_is_error() {
        let err = UserDb::parse("aliceNoColon").unwrap_err();
        assert!(err.to_string().contains("expected 'username:password'"));
    }

    #[test]
    fn empty_username_is_error() {
        let err = UserDb::parse(":pw").unwrap_err();
        assert!(err.to_string().contains("empty username"));
    }

    #[test]
    fn hash_user_line_rejects_bad_username() {
        let err = UserDb::hash_user_line("bad:name", "pw").unwrap_err();
        assert!(err.to_string().contains("must not contain"));
    }

    #[test]
    fn hash_user_line_rejects_surrounding_whitespace() {
        let err = UserDb::hash_user_line(" alice", "pw").unwrap_err();
        assert!(err.to_string().contains("whitespace"));
    }

    #[test]
    fn hash_user_line_rejects_protocol_length_overflow() {
        let long_username = "a".repeat(256);
        let err = UserDb::hash_user_line(&long_username, "pw").unwrap_err();
        assert!(err.to_string().contains("255 bytes"));

        let long_password = "p".repeat(256);
        let err = UserDb::hash_user_line("alice", &long_password).unwrap_err();
        assert!(err.to_string().contains("255 bytes"));
    }

    #[tokio::test]
    async fn async_verify_matches_sync_verifier() {
        let line = UserDb::hash_user_line("alice", "s3cr3t").unwrap();
        let db = UserDb::parse(&line).unwrap();

        assert!(db.verify_async("alice", "s3cr3t", None).await);
        assert!(!db.verify_async("alice", "wrong", None).await);
        assert!(!db.verify_async("eve", "s3cr3t", None).await);
    }

    #[tokio::test]
    async fn async_verify_caches_successful_credentials() {
        let line = UserDb::hash_user_line("alice", "s3cr3t").unwrap();
        let db = UserDb::parse(&line).unwrap();
        let ttl = Some(Duration::from_secs(60));

        assert!(db.verify_async("alice", "s3cr3t", ttl).await);

        let tag = db.verified.tag("alice", "s3cr3t").unwrap();
        assert!(db.verified.check("alice", &tag, Instant::now()));
        // A wrong password misses the cache and still fails the full check.
        assert!(!db.verify_async("alice", "wrong", ttl).await);
        assert!(db.verify_async("alice", "s3cr3t", ttl).await);
    }

    #[tokio::test]
    async fn async_verify_does_not_cache_when_disabled() {
        let db = UserDb::parse("alice:s3cr3t").unwrap();

        assert!(db.verify_async("alice", "s3cr3t", None).await);

        let tag = db.verified.tag("alice", "s3cr3t").unwrap();
        assert!(!db.verified.check("alice", &tag, Instant::now()));
    }

    #[tokio::test]
    async fn async_verify_short_circuits_on_cached_tag() {
        // Seeding the cache for a user absent from the database proves the
        // hit path returns without consulting the stored credentials. Within
        // one UserDb the user set is immutable, so this cannot happen outside
        // tests; reloads build a fresh UserDb and a fresh cache.
        let db = UserDb::new();
        let now = Instant::now();
        let tag = db.verified.tag("ghost", "pw").unwrap();
        db.verified
            .store("ghost", tag, now + Duration::from_secs(60), now);

        assert!(
            db.verify_async("ghost", "pw", Some(Duration::from_secs(60)))
                .await
        );
        assert!(!db.verify_async("ghost", "pw", None).await);
    }

    #[test]
    fn verified_cache_entries_expire() {
        let cache = VerifiedCache::new();
        let tag = cache.tag("alice", "pw").unwrap();
        let now = Instant::now();
        cache.store("alice", tag, now + Duration::from_secs(10), now);

        assert!(cache.check("alice", &tag, now));
        assert!(!cache.check("alice", &tag, now + Duration::from_secs(10)));
    }

    #[test]
    fn verified_cache_rejects_other_credentials() {
        let cache = VerifiedCache::new();
        let tag = cache.tag("alice", "pw").unwrap();
        let other = cache.tag("alice", "other").unwrap();
        let now = Instant::now();
        cache.store("alice", tag, now + Duration::from_secs(10), now);

        assert!(!cache.check("alice", &other, now));
        assert!(!cache.check("bob", &tag, now));
    }

    #[test]
    fn verified_cache_is_bounded() {
        let cache = VerifiedCache::new();
        let now = Instant::now();
        for i in 0..=MAX_VERIFIED_CACHE_ENTRIES {
            let user = format!("user{i}");
            let tag = cache.tag(&user, "pw").unwrap();
            cache.store(&user, tag, now + Duration::from_secs(60 + i as u64), now);
        }

        let entries = cache.entries.lock().unwrap();
        assert_eq!(entries.len(), MAX_VERIFIED_CACHE_ENTRIES);
        // The soonest-to-expire entry was evicted to make room.
        assert!(!entries.contains_key("user0"));
    }

    #[test]
    fn command_auth_new_rejects_empty_command() {
        assert!(CommandAuth::new(&[]).is_none());
    }

    #[cfg(unix)]
    fn sh_auth(script: &str) -> CommandAuth {
        CommandAuth::new(&["/bin/sh".to_string(), "-c".to_string(), script.to_string()]).unwrap()
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn command_auth_allows_only_on_exit_zero() {
        // Reads the username then the password from stdin; allows alice/secret.
        let auth = sh_auth("read u; read p; [ \"$u\" = alice ] && [ \"$p\" = secret ]");
        let t = Duration::from_secs(5);
        assert_eq!(
            auth.verify_async("alice", "secret", None, t).await,
            AuthOutcome::Allowed
        );
        assert_eq!(
            auth.verify_async("alice", "wrong", None, t).await,
            AuthOutcome::Denied
        );
        assert_eq!(
            auth.verify_async("bob", "secret", None, t).await,
            AuthOutcome::Denied
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn command_auth_rejects_embedded_delimiters() {
        // A command that always succeeds; a CR, LF, or NUL in either field must
        // still be rejected before it runs, to keep the two-line stdin framing
        // unambiguous (a verifier splitting on CRLF would otherwise mis-parse).
        let auth = sh_auth("exit 0");
        for (user, pass) in [
            ("alice", "sec\nret"), // LF in password
            ("alice", "sec\rret"), // CR in password
            ("al\rice", "secret"), // CR in username
            ("al\nice", "secret"), // LF in username
            ("alice", "sec\0ret"), // NUL in password
            ("al\0ice", "secret"), // NUL in username
        ] {
            assert_eq!(
                auth.verify_async(user, pass, None, Duration::from_secs(5))
                    .await,
                AuthOutcome::Denied,
                "credentials with an embedded delimiter must be denied: {user:?}/{pass:?}"
            );
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn command_auth_times_out() {
        // A verifier that never exits is bounded by CommandAuth's own deadline,
        // which kills the child (reaping it out of band) and reports the timeout
        // distinctly so the caller can log it like the userlist path.
        let auth = sh_auth("sleep 5");
        assert_eq!(
            auth.verify_async("alice", "secret", None, Duration::from_millis(100))
                .await,
            AuthOutcome::TimedOut
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn command_auth_caches_success() {
        // The script allows only on its first run (it creates a marker, then
        // fails when the marker exists). A cached second call must still succeed,
        // proving the command was not re-run.
        let dir = tempfile::tempdir().unwrap();
        let marker = dir.path().join("ran");
        // Drain stdin first, as a real verifier consuming the credentials does,
        // then allow only on the first run.
        let auth = sh_auth(&format!(
            "cat >/dev/null; [ ! -e '{m}' ] && touch '{m}'",
            m = marker.display()
        ));
        let ttl = Some(Duration::from_secs(60));
        let t = Duration::from_secs(5);
        assert_eq!(
            auth.verify_async("alice", "secret", ttl, t).await,
            AuthOutcome::Allowed,
            "first run"
        );
        assert_eq!(
            auth.verify_async("alice", "secret", ttl, t).await,
            AuthOutcome::Allowed,
            "second call should hit the cache"
        );
    }
}