Skip to main content

mcp_server_core/
credential.rs

1//! Who may sign in, and the credentials people bring with them.
2//!
3//! A [`CredentialVerifier`] decides what the sign-in page asks for and checks it. There are two
4//! shapes, told apart by [`CredentialVerifier::carried`]:
5//!
6//! - **A password** that only proves who may sign in, such as the owner's password
7//!   ([`PasswordVerifier`]). Tools act with the server's own upstream configuration, and nothing
8//!   about the password is kept in tokens.
9//! - **The person's own credential for the upstream service** the tools call, such as an API key,
10//!   so one server can serve many people. The server stores no credential: it is checked once
11//!   upstream when the person signs in, then sealed (encrypted and authenticated with a key derived
12//!   from `OAUTH_SIGNING_KEY`, see [`Sealer`]) into their OAuth tokens, and opened again on every
13//!   request, where tools find it as a [`Credential`] in the request extensions. A client that can
14//!   send a header may instead send the credential itself as its bearer token; that is checked
15//!   upstream too, and the verdict is cached briefly under the credential's SHA-256, never the
16//!   credential.
17//!
18//! Reading the caller's credential in an rmcp tool:
19//!
20//! ```
21//! use mcp_server_core::axum::http::request::Parts;
22//! use mcp_server_core::credential::Credential;
23//!
24//! fn api_key(parts: &Parts) -> Option<&str> {
25//!     parts.extensions.get::<Credential>().map(Credential::expose)
26//! }
27//! ```
28//!
29//! The `Parts` come from rmcp's `Extension<Parts>` tool argument.
30
31use base64::Engine as _;
32use base64::engine::general_purpose::URL_SAFE_NO_PAD;
33use ring::aead::{Aad, CHACHA20_POLY1305, LessSafeKey, NONCE_LEN, Nonce, UnboundKey};
34use ring::hkdf;
35use ring::rand::{SecureRandom, SystemRandom};
36use secrecy::{ExposeSecret, SecretString};
37use sha2::{Digest, Sha256};
38use std::collections::HashMap;
39use std::future::Future;
40use std::pin::Pin;
41use std::sync::Mutex;
42use std::time::{Duration, Instant};
43use tokio::sync::{Semaphore, watch};
44
45/// Longest credential accepted by [`plausible`], as a bound on what is sent upstream and sealed.
46pub const MAX_CREDENTIAL_LEN: usize = 256;
47
48/// The caller's credential, placed in the request extensions by the bearer guard when the
49/// verifier's credentials are [carried](CredentialVerifier::carried). Its `Debug` output never
50/// shows the secret.
51#[derive(Clone)]
52pub struct Credential(SecretString);
53
54impl Credential {
55    /// Wraps a secret.
56    pub fn new(secret: impl Into<String>) -> Self {
57        Credential(SecretString::from(secret.into()))
58    }
59
60    /// The secret itself, to send upstream. Never log it.
61    pub fn expose(&self) -> &str {
62        self.0.expose_secret()
63    }
64
65    /// SHA-256 of the credential: safe to keep as a map key or compare, never to log.
66    pub fn fingerprint(&self) -> [u8; 32] {
67        fingerprint(self.expose())
68    }
69}
70
71impl std::fmt::Debug for Credential {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        f.write_str("Credential(..)")
74    }
75}
76
77/// SHA-256 of `secret`, used to key caches and sessions without keeping the secret.
78pub fn fingerprint(secret: &str) -> [u8; 32] {
79    Sha256::digest(secret.as_bytes()).into()
80}
81
82/// A verifier's verdict on a credential.
83#[derive(Debug, Clone, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum CredentialCheck {
86    /// Accepted.
87    Valid,
88    /// Rejected, with a reason to show the person when there is a more useful one than "not
89    /// accepted". Counts as a failed attempt for the sign-in limits.
90    Invalid(Option<String>),
91    /// Could not be checked now (upstream down, rate limited): say why. It does not count as a
92    /// failed attempt.
93    Unavailable(String),
94}
95
96/// The future returned by [`CredentialVerifier::check`].
97pub type CheckFuture<'a> = Pin<Box<dyn Future<Output = CredentialCheck> + Send + 'a>>;
98
99/// Decides what people sign in with and checks it. The server asks it when someone submits the
100/// sign-in page and, when [`accepts_bearer`](Self::accepts_bearer), for bearer tokens that are
101/// not this server's own OAuth tokens.
102///
103/// Checks run with a timeout, at most a few at once, and only once at a time per credential:
104/// concurrent requests with the same credential share one check.
105///
106/// ```
107/// use mcp_server_core::credential::{CheckFuture, CredentialCheck, CredentialVerifier};
108///
109/// /// Accepts keys the upstream API accepts.
110/// struct ApiKeys;
111///
112/// impl CredentialVerifier for ApiKeys {
113///     fn label(&self) -> &str {
114///         "Example API key"
115///     }
116///     fn help(&self) -> &str {
117///         "Create one under Settings, API keys at example.com."
118///     }
119///     fn check<'a>(&'a self, key: &'a str) -> CheckFuture<'a> {
120///         Box::pin(async move {
121///             // Make one cheap authenticated request upstream with `key` here.
122///             if key.starts_with("ex_") {
123///                 CredentialCheck::Valid
124///             } else {
125///                 CredentialCheck::Invalid(None)
126///             }
127///         })
128///     }
129/// }
130/// ```
131pub trait CredentialVerifier: Send + Sync + 'static {
132    /// The credential's name in lower case, as it reads in a sentence and on the sign-in page,
133    /// e.g. "password" or "Companies House API key". It also tells verifiers apart in the
134    /// sign-in version, so changing it signs everyone out.
135    fn label(&self) -> &str;
136    /// One sentence of help under the field, plain text: what it is and where to get one.
137    fn help(&self) -> &str {
138        ""
139    }
140    /// Turns what was typed on the sign-in page into the credential to check. Defaults to
141    /// trimming surrounding whitespace, which pasted keys often carry; a password keeps it.
142    fn prepare<'a>(&self, entered: &'a str) -> &'a str {
143        entered.trim()
144    }
145    /// Whether `credential` has the shape of one, checked before anything else. Defaults to
146    /// [`plausible`]; narrow it when the upstream service's credentials have a known form, so
147    /// other tokens are refused locally instead of being forwarded. Implausible input is refused
148    /// without counting as a failed attempt.
149    fn plausible(&self, credential: &str) -> bool {
150        plausible(credential)
151    }
152    /// Checks `credential`.
153    fn check<'a>(&'a self, credential: &'a str) -> CheckFuture<'a>;
154    /// Whether the credential is the person's own key to the upstream service: sealed into their
155    /// tokens and handed to tools as a [`Credential`]. `false` for a password that only proves
156    /// who may sign in. Defaults to `true`.
157    fn carried(&self) -> bool {
158        true
159    }
160    /// Whether a client may send the credential itself as its bearer token instead of signing in
161    /// with OAuth. Defaults to [`carried`](Self::carried).
162    fn accepts_bearer(&self) -> bool {
163        self.carried()
164    }
165    /// Who signed in with `credential`: the `sub` of their tokens, the audit log's subject and a
166    /// [`Caller`](crate::caller::Caller)'s subject. It must not reveal the credential, and is
167    /// readable by anyone who sees a token or a log line. Defaults to `None`, which lets the
168    /// server name them: `key:` and 16 hex digits of a hash of the credential keyed by
169    /// `OAUTH_SIGNING_KEY` when credentials are carried (one subject per person), and `owner`
170    /// otherwise.
171    fn subject(&self, credential: &str) -> Option<String> {
172        let _ = credential;
173        None
174    }
175    /// Bytes that change whenever every earlier sign-in should end, such as a hash of the
176    /// password, or a new upstream service or environment. Tokens carry a keyed hash of them and
177    /// of [`label`](Self::label), so a change to either signs everyone out. Defaults to none.
178    fn generation(&self) -> &[u8] {
179        &[]
180    }
181    /// The upstream OAuth provider people sign in through instead of typing a credential, if
182    /// any: the sign-in page then sends them to the provider, and the credential it grants is
183    /// sealed into their tokens. Defaults to `None`. [`UpstreamVerifier`](crate::upstream::UpstreamVerifier)
184    /// builds a verifier around one; see [`crate::upstream`].
185    fn upstream(&self) -> Option<&dyn crate::upstream::UpstreamSignIn> {
186        None
187    }
188}
189
190/// Whether `s` has the shape of a credential: non-empty, at most [`MAX_CREDENTIAL_LEN`] bytes,
191/// visible ASCII without spaces.
192pub fn plausible(s: &str) -> bool {
193    !s.is_empty() && s.len() <= MAX_CREDENTIAL_LEN && s.bytes().all(|b| b.is_ascii_graphic())
194}
195
196/// Longest password [`PasswordVerifier`] considers.
197pub const MAX_PASSWORD_LEN: usize = 1024;
198
199/// One password that proves the person signing in is the server's owner, compared in constant
200/// time. It is not [carried](CredentialVerifier::carried): tools use the server's own upstream
201/// configuration. This is what [`SignIn::OwnerPassword`](crate::app::SignIn::OwnerPassword)
202/// builds from `OAUTH_ADMIN_PASSWORD`.
203pub struct PasswordVerifier {
204    password: SecretString,
205    generation: [u8; 32],
206}
207
208impl PasswordVerifier {
209    /// Accepts exactly `password`. Changing it signs everyone out.
210    pub fn new(password: SecretString) -> Self {
211        let generation = Sha256::new()
212            .chain_update(b"mcp-server-core owner password\0")
213            .chain_update(password.expose_secret().as_bytes())
214            .finalize()
215            .into();
216        PasswordVerifier {
217            password,
218            generation,
219        }
220    }
221}
222
223impl std::fmt::Debug for PasswordVerifier {
224    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
225        f.write_str("PasswordVerifier(..)")
226    }
227}
228
229impl CredentialVerifier for PasswordVerifier {
230    fn label(&self) -> &str {
231        "password"
232    }
233
234    fn prepare<'a>(&self, entered: &'a str) -> &'a str {
235        entered
236    }
237
238    fn plausible(&self, credential: &str) -> bool {
239        !credential.is_empty() && credential.len() <= MAX_PASSWORD_LEN
240    }
241
242    fn check<'a>(&'a self, credential: &'a str) -> CheckFuture<'a> {
243        let ok = crate::pkce::ct_eq(credential, self.password.expose_secret());
244        Box::pin(async move {
245            if ok {
246                CredentialCheck::Valid
247            } else {
248                CredentialCheck::Invalid(None)
249            }
250        })
251    }
252
253    fn carried(&self) -> bool {
254        false
255    }
256
257    fn generation(&self) -> &[u8] {
258        &self.generation
259    }
260}
261
262/// Why a credential could not be sealed or opened.
263#[derive(Debug, thiserror::Error, PartialEq, Eq)]
264#[non_exhaustive]
265pub enum SealError {
266    /// The random nonce or the encryption failed.
267    #[error("sealing failed")]
268    Seal,
269    /// Not a credential sealed under this key.
270    #[error("the sealed credential is invalid")]
271    Open,
272}
273
274/// Seals credentials into tokens with ChaCha20-Poly1305 under a key derived (HKDF-SHA256) from
275/// the OAuth signing key, so rotating `OAUTH_SIGNING_KEY` also invalidates every sealed
276/// credential.
277pub struct Sealer {
278    key: LessSafeKey,
279    rng: SystemRandom,
280    aad: &'static [u8],
281}
282
283const SEAL_SALT: &[u8] = b"mcp-server-core credential sealing";
284const SEAL_INFO: &[u8] = b"v1";
285const SEAL_AAD: &[u8] = b"mcp-server-core credential v1";
286
287impl Sealer {
288    /// A sealer whose key is derived from `signing_key`.
289    pub fn new(signing_key: &[u8]) -> Self {
290        Self::for_purpose(signing_key, SEAL_INFO, SEAL_AAD)
291    }
292
293    /// A sealer for something other than credentials, under its own key (HKDF `info`) and
294    /// associated data, so what it seals can never be opened as a credential or the reverse.
295    pub(crate) fn for_purpose(signing_key: &[u8], info: &[u8], aad: &'static [u8]) -> Self {
296        let prk = hkdf::Salt::new(hkdf::HKDF_SHA256, SEAL_SALT).extract(signing_key);
297        let info = [info];
298        let okm = prk
299            .expand(&info, &CHACHA20_POLY1305)
300            .expect("32 bytes is a valid HKDF-SHA256 output length");
301        Sealer {
302            key: LessSafeKey::new(UnboundKey::from(okm)),
303            rng: SystemRandom::new(),
304            aad,
305        }
306    }
307
308    /// `base64url(nonce || ciphertext || tag)` of `credential`, with a random nonce.
309    pub fn seal(&self, credential: &str) -> Result<String, SealError> {
310        let mut nonce = [0u8; NONCE_LEN];
311        self.rng.fill(&mut nonce).map_err(|_| SealError::Seal)?;
312        let mut data = credential.as_bytes().to_vec();
313        self.key
314            .seal_in_place_append_tag(
315                Nonce::assume_unique_for_key(nonce),
316                Aad::from(self.aad),
317                &mut data,
318            )
319            .map_err(|_| SealError::Seal)?;
320        let mut out = nonce.to_vec();
321        out.extend_from_slice(&data);
322        Ok(URL_SAFE_NO_PAD.encode(out))
323    }
324
325    /// The credential sealed in `sealed`, if it was sealed under this key and not altered.
326    pub fn open(&self, sealed: &str) -> Result<Credential, SealError> {
327        let raw = URL_SAFE_NO_PAD
328            .decode(sealed)
329            .map_err(|_| SealError::Open)?;
330        if raw.len() < NONCE_LEN {
331            return Err(SealError::Open);
332        }
333        let (nonce, rest) = raw.split_at(NONCE_LEN);
334        let nonce = Nonce::try_assume_unique_for_key(nonce).map_err(|_| SealError::Open)?;
335        let mut data = rest.to_vec();
336        let plain = self
337            .key
338            .open_in_place(nonce, Aad::from(self.aad), &mut data)
339            .map_err(|_| SealError::Open)?;
340        let text = std::str::from_utf8(plain).map_err(|_| SealError::Open)?;
341        Ok(Credential::new(text))
342    }
343}
344
345/// Recent verdicts on bearer credentials, keyed by fingerprint. Valid ones are remembered longer
346/// than rejected ones, so a fixed key is not rechecked upstream on every request.
347pub(crate) struct CheckCache {
348    entries: Mutex<HashMap<[u8; 32], (Instant, bool)>>,
349    valid_for: Duration,
350    invalid_for: Duration,
351    max_entries: usize,
352}
353
354impl CheckCache {
355    pub fn new(valid_for: Duration, invalid_for: Duration, max_entries: usize) -> Self {
356        CheckCache {
357            entries: Mutex::new(HashMap::new()),
358            valid_for,
359            invalid_for,
360            max_entries,
361        }
362    }
363
364    /// The cached verdict, if one has not expired.
365    pub fn get(&self, fingerprint: &[u8; 32]) -> Option<bool> {
366        let now = Instant::now();
367        let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
368        entries
369            .get(fingerprint)
370            .filter(|(expires, _)| *expires > now)
371            .map(|(_, valid)| *valid)
372    }
373
374    pub fn put(&self, fingerprint: [u8; 32], valid: bool) {
375        let now = Instant::now();
376        let ttl = if valid {
377            self.valid_for
378        } else {
379            self.invalid_for
380        };
381        let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
382        if entries.len() >= self.max_entries && !entries.contains_key(&fingerprint) {
383            entries.retain(|_, (expires, _)| *expires > now);
384            // Rejected keys go first, so a burst of junk never pushes out keys that work.
385            if entries.len() >= self.max_entries {
386                entries.retain(|_, (_, valid)| *valid);
387            }
388            if entries.len() >= self.max_entries {
389                if !valid {
390                    return;
391                }
392                if let Some(oldest) = entries
393                    .iter()
394                    .min_by_key(|(_, (expires, _))| *expires)
395                    .map(|(k, _)| *k)
396                {
397                    entries.remove(&oldest);
398                }
399            }
400        }
401        entries.insert(fingerprint, (now + ttl, valid));
402    }
403}
404
405/// Runs upstream credential checks: one check at a time per credential, at most `max_running`
406/// at once, each bounded by `timeout`. A check that finds every slot taken waits up to `wait`
407/// for one before giving up as busy.
408///
409/// The first request for a credential [`join`](Self::join)s as the [`Lead`] and runs the check;
410/// requests arriving while it runs follow it and get its verdict. Only a lead ever calls the
411/// upstream service, so the caller decides once, when the request arrives, whether it is the
412/// attempt that counts.
413pub(crate) struct CheckRunner {
414    permits: Semaphore,
415    timeout: Duration,
416    wait: Duration,
417    running: Mutex<HashMap<[u8; 32], watch::Receiver<Option<CredentialCheck>>>>,
418}
419
420/// How a request takes part in a credential check.
421pub(crate) enum Ticket {
422    /// Run the check ([`CheckRunner::lead`]) or end it ([`CheckRunner::finish`]).
423    Lead(Lead),
424    /// Wait for the lead's verdict ([`CheckRunner::follow`]).
425    Follow(watch::Receiver<Option<CredentialCheck>>),
426}
427
428/// The request responsible for one credential's check.
429pub(crate) struct Lead {
430    fingerprint: [u8; 32],
431    tx: watch::Sender<Option<CredentialCheck>>,
432}
433
434impl CheckRunner {
435    /// At most `max_running` checks at once, each bounded by `timeout`; a check waits up to
436    /// `wait` for a free slot.
437    pub fn new(max_running: usize, timeout: Duration, wait: Duration) -> Self {
438        CheckRunner {
439            permits: Semaphore::new(max_running),
440            timeout,
441            wait,
442            running: Mutex::new(HashMap::new()),
443        }
444    }
445
446    /// Joins the check of the credential with this fingerprint: as its lead when none is
447    /// running, otherwise as a follower.
448    pub fn join(&self, fingerprint: [u8; 32]) -> Ticket {
449        let mut running = self.running.lock().unwrap_or_else(|e| e.into_inner());
450        // A lead that went away without finishing leaves a closed channel: start afresh.
451        if let Some(rx) = running.get(&fingerprint)
452            && rx.has_changed().is_ok()
453        {
454            return Ticket::Follow(rx.clone());
455        }
456        let (tx, rx) = watch::channel(None);
457        running.insert(fingerprint, rx);
458        Ticket::Lead(Lead { fingerprint, tx })
459    }
460
461    /// Runs the upstream check for `lead` and hands the verdict to its followers.
462    pub async fn lead(
463        &self,
464        lead: Lead,
465        verifier: &dyn CredentialVerifier,
466        credential: &str,
467    ) -> CredentialCheck {
468        let verdict = match tokio::time::timeout(self.wait, self.permits.acquire()).await {
469            Ok(Ok(_permit)) => {
470                match tokio::time::timeout(self.timeout, verifier.check(credential)).await {
471                    Ok(verdict) => verdict,
472                    Err(_) => CredentialCheck::Unavailable("the check timed out".into()),
473                }
474            }
475            _ => CredentialCheck::Unavailable(
476                "the server is checking too many credentials at once".into(),
477            ),
478        };
479        self.finish(lead, verdict.clone());
480        verdict
481    }
482
483    /// Ends `lead` with `verdict` without checking upstream, for example when its client is
484    /// refused for too many attempts. Followers get `verdict`.
485    pub fn finish(&self, lead: Lead, verdict: CredentialCheck) {
486        let mut running = self.running.lock().unwrap_or_else(|e| e.into_inner());
487        if running
488            .get(&lead.fingerprint)
489            .is_some_and(|rx| rx.same_channel(&lead.tx.subscribe()))
490        {
491            running.remove(&lead.fingerprint);
492        }
493        lead.tx.send_replace(Some(verdict));
494    }
495
496    /// The verdict of the check a follower joined.
497    pub async fn follow(mut rx: watch::Receiver<Option<CredentialCheck>>) -> CredentialCheck {
498        match rx.wait_for(Option::is_some).await {
499            Ok(v) => v.clone().unwrap_or_else(|| unreachable!("waited for Some")),
500            Err(_) => CredentialCheck::Unavailable("the check was abandoned".into()),
501        }
502    }
503
504    /// Joins and runs or follows the check of `credential`.
505    #[cfg(test)]
506    pub async fn check(
507        &self,
508        verifier: &dyn CredentialVerifier,
509        credential: &str,
510    ) -> CredentialCheck {
511        match self.join(fingerprint(credential)) {
512            Ticket::Lead(lead) => self.lead(lead, verifier, credential).await,
513            Ticket::Follow(rx) => Self::follow(rx).await,
514        }
515    }
516
517    #[cfg(test)]
518    fn is_running(&self, fingerprint: &[u8; 32]) -> bool {
519        self.running
520            .lock()
521            .unwrap_or_else(|e| e.into_inner())
522            .contains_key(fingerprint)
523    }
524}
525
526#[cfg(test)]
527mod tests {
528    use super::*;
529
530    const KEY: &[u8] = b"0123456789abcdef0123456789abcdef";
531
532    #[test]
533    fn sealed_credentials_open_with_the_same_signing_key_only() {
534        let a = Sealer::new(KEY);
535        let sealed = a.seal("my-api-key").unwrap();
536        assert!(!sealed.contains("my-api-key"));
537        assert_eq!(a.open(&sealed).unwrap().expose(), "my-api-key");
538        let b = Sealer::new(b"another signing key of 32 bytes!");
539        assert_eq!(b.open(&sealed).unwrap_err(), SealError::Open);
540    }
541
542    #[test]
543    fn sealing_uses_a_fresh_nonce() {
544        let s = Sealer::new(KEY);
545        assert_ne!(s.seal("k").unwrap(), s.seal("k").unwrap());
546    }
547
548    #[test]
549    fn tampered_or_malformed_seals_do_not_open() {
550        let s = Sealer::new(KEY);
551        let sealed = s.seal("my-api-key").unwrap();
552        let mut raw = URL_SAFE_NO_PAD.decode(&sealed).unwrap();
553        let last = raw.len() - 1;
554        raw[last] ^= 1;
555        assert!(s.open(&URL_SAFE_NO_PAD.encode(raw)).is_err());
556        for bad in [
557            "",
558            "not base64!",
559            "AAAA",
560            &URL_SAFE_NO_PAD.encode([0u8; 12]),
561        ] {
562            assert!(s.open(bad).is_err(), "{bad:?}");
563        }
564    }
565
566    #[test]
567    fn credentials_never_print() {
568        let c = Credential::new("secret-value");
569        assert_eq!(format!("{c:?}"), "Credential(..)");
570        assert_eq!(c.fingerprint(), fingerprint("secret-value"));
571        assert_ne!(c.fingerprint(), fingerprint("secret-valuf"));
572    }
573
574    #[tokio::test]
575    async fn the_owner_password_is_compared_exactly_and_never_carried() {
576        let v = PasswordVerifier::new("correct horse battery staple ".to_string().into());
577        assert!(!v.carried());
578        assert!(!v.accepts_bearer());
579        assert_eq!(
580            v.prepare(" a b "),
581            " a b ",
582            "passwords keep their whitespace"
583        );
584        assert!(v.plausible("with spaces and ünïcode"));
585        assert!(!v.plausible(""));
586        assert!(!v.plausible(&"x".repeat(MAX_PASSWORD_LEN + 1)));
587        assert_eq!(
588            v.check("correct horse battery staple ").await,
589            CredentialCheck::Valid
590        );
591        for wrong in [
592            "correct horse battery staple",
593            "",
594            "Correct horse battery staple ",
595        ] {
596            assert_eq!(
597                v.check(wrong).await,
598                CredentialCheck::Invalid(None),
599                "{wrong:?}"
600            );
601        }
602        assert_eq!(format!("{v:?}"), "PasswordVerifier(..)");
603    }
604
605    #[test]
606    fn upstream_credentials_are_carried_and_trimmed_by_default() {
607        struct Key;
608        impl CredentialVerifier for Key {
609            fn label(&self) -> &str {
610                "key"
611            }
612            fn check<'a>(&'a self, _: &'a str) -> CheckFuture<'a> {
613                Box::pin(async { CredentialCheck::Valid })
614            }
615        }
616        assert!(Key.carried());
617        assert!(Key.accepts_bearer());
618        assert_eq!(Key.help(), "");
619        assert_eq!(Key.prepare("  k-1 \n"), "k-1");
620    }
621
622    #[test]
623    fn plausible_credentials() {
624        assert!(plausible("0f1e2d3c-4b5a-4968-8776-a5b4c3d2e1f0"));
625        for bad in [
626            "",
627            "has space",
628            "tab\tkey",
629            "ключ",
630            &"x".repeat(MAX_CREDENTIAL_LEN + 1),
631        ] {
632            assert!(!plausible(bad), "{bad:?}");
633        }
634    }
635
636    #[test]
637    fn a_full_cache_drops_rejected_keys_before_working_ones() {
638        let c = CheckCache::new(Duration::from_secs(600), Duration::from_secs(60), 3);
639        c.put([1; 32], true);
640        c.put([2; 32], false);
641        c.put([3; 32], false);
642        c.put([4; 32], false);
643        assert_eq!(
644            c.get(&[1; 32]),
645            Some(true),
646            "junk never pushes out a working key"
647        );
648        c.put([5; 32], true);
649        c.put([6; 32], true);
650        c.put([7; 32], true);
651        assert!(c.entries.lock().unwrap().len() <= 3);
652        assert_eq!(c.get(&[7; 32]), Some(true));
653        c.put([8; 32], false);
654        assert_eq!(
655            c.get(&[8; 32]),
656            None,
657            "a full cache of working keys keeps them"
658        );
659        assert_eq!(c.get(&[7; 32]), Some(true));
660    }
661
662    struct Slow {
663        checks: std::sync::atomic::AtomicUsize,
664        delay: Duration,
665    }
666
667    impl CredentialVerifier for Slow {
668        fn label(&self) -> &'static str {
669            "key"
670        }
671        fn help(&self) -> &'static str {
672            ""
673        }
674        fn check<'a>(&'a self, credential: &'a str) -> CheckFuture<'a> {
675            self.checks
676                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
677            let ok = credential == "good";
678            let delay = self.delay;
679            Box::pin(async move {
680                tokio::time::sleep(delay).await;
681                if ok {
682                    CredentialCheck::Valid
683                } else {
684                    CredentialCheck::Invalid(None)
685                }
686            })
687        }
688    }
689
690    fn slow(ms: u64) -> Slow {
691        Slow {
692            checks: Default::default(),
693            delay: Duration::from_millis(ms),
694        }
695    }
696
697    #[tokio::test]
698    async fn concurrent_checks_of_one_credential_share_one_upstream_call() {
699        let runner = CheckRunner::new(4, Duration::from_secs(5), Duration::ZERO);
700        let v = slow(50);
701        let all = futures_join(&runner, &v, &["good"; 8]).await;
702        assert!(all.iter().all(|c| *c == CredentialCheck::Valid));
703        assert_eq!(v.checks.load(std::sync::atomic::Ordering::SeqCst), 1);
704        assert!(!runner.is_running(&fingerprint("good")));
705    }
706
707    #[tokio::test]
708    async fn running_checks_are_capped_and_timed_out() {
709        let runner = CheckRunner::new(2, Duration::from_millis(100), Duration::ZERO);
710        let v = slow(300);
711        let all = futures_join(&runner, &v, &["a", "b", "c"]).await;
712        assert_eq!(v.checks.load(std::sync::atomic::Ordering::SeqCst), 2);
713        assert!(
714            all.iter()
715                .all(|c| matches!(c, CredentialCheck::Unavailable(_))),
716            "{all:?}"
717        );
718    }
719
720    #[tokio::test]
721    async fn followers_of_a_refused_lead_never_check_upstream() {
722        let runner = CheckRunner::new(4, Duration::from_secs(5), Duration::ZERO);
723        let v = slow(10);
724        let Ticket::Lead(lead) = runner.join(fingerprint("good")) else {
725            panic!("the first request leads");
726        };
727        let Ticket::Follow(rx) = runner.join(fingerprint("good")) else {
728            panic!("the second follows");
729        };
730        runner.finish(lead, CredentialCheck::Unavailable("refused".into()));
731        assert_eq!(
732            CheckRunner::follow(rx).await,
733            CredentialCheck::Unavailable("refused".into())
734        );
735        assert_eq!(v.checks.load(std::sync::atomic::Ordering::SeqCst), 0);
736        assert!(matches!(runner.join(fingerprint("good")), Ticket::Lead(_)));
737    }
738
739    #[tokio::test]
740    async fn a_lead_that_disappears_does_not_block_the_credential() {
741        let runner = CheckRunner::new(4, Duration::from_secs(5), Duration::ZERO);
742        let Ticket::Lead(lead) = runner.join(fingerprint("k")) else {
743            panic!();
744        };
745        let Ticket::Follow(rx) = runner.join(fingerprint("k")) else {
746            panic!();
747        };
748        drop(lead);
749        assert!(matches!(
750            CheckRunner::follow(rx).await,
751            CredentialCheck::Unavailable(_)
752        ));
753        assert!(matches!(runner.join(fingerprint("k")), Ticket::Lead(_)));
754    }
755
756    #[test]
757    fn subjects_and_generations_default_sensibly() {
758        struct Key;
759        impl CredentialVerifier for Key {
760            fn label(&self) -> &str {
761                "key"
762            }
763            fn check<'a>(&'a self, _: &'a str) -> CheckFuture<'a> {
764                Box::pin(async { CredentialCheck::Valid })
765            }
766        }
767        assert_eq!(Key.subject("secret-key-1"), None, "the server names them");
768        assert!(Key.generation().is_empty());
769        let owner = PasswordVerifier::new("a long password".to_string().into());
770        assert_eq!(owner.subject("a long password"), None);
771        let other = PasswordVerifier::new("another password".to_string().into());
772        assert_ne!(owner.generation(), other.generation());
773        assert_eq!(owner.generation().len(), 32);
774    }
775
776    #[tokio::test]
777    async fn a_check_waits_briefly_for_a_free_slot() {
778        let runner = CheckRunner::new(1, Duration::from_secs(5), Duration::from_secs(2));
779        let v = slow(50);
780        let all = futures_join(&runner, &v, &["good", "good-too", "good"]).await;
781        assert_eq!(v.checks.load(std::sync::atomic::Ordering::SeqCst), 2);
782        assert_eq!(all[0], CredentialCheck::Valid);
783        assert_eq!(all[2], CredentialCheck::Valid);
784        assert_eq!(
785            all[1],
786            CredentialCheck::Invalid(None),
787            "ran after waiting, not busy"
788        );
789    }
790
791    async fn futures_join(runner: &CheckRunner, v: &Slow, creds: &[&str]) -> Vec<CredentialCheck> {
792        let futs = creds.iter().map(|c| runner.check(v, c));
793        let mut out = Vec::new();
794        let handles: Vec<_> = futs.collect();
795        for verdict in join_all(handles).await {
796            out.push(verdict);
797        }
798        out
799    }
800
801    async fn join_all<F: Future>(futs: Vec<F>) -> Vec<F::Output> {
802        let mut pinned: Vec<Pin<Box<F>>> = futs.into_iter().map(Box::pin).collect();
803        let mut done: Vec<Option<F::Output>> = (0..pinned.len()).map(|_| None).collect();
804        std::future::poll_fn(|cx| {
805            let mut pending = false;
806            for (i, f) in pinned.iter_mut().enumerate() {
807                if done[i].is_none() {
808                    match f.as_mut().poll(cx) {
809                        std::task::Poll::Ready(v) => done[i] = Some(v),
810                        std::task::Poll::Pending => pending = true,
811                    }
812                }
813            }
814            if pending {
815                std::task::Poll::Pending
816            } else {
817                std::task::Poll::Ready(())
818            }
819        })
820        .await;
821        done.into_iter().map(|d| d.unwrap()).collect()
822    }
823
824    #[test]
825    fn the_cache_expires_and_stays_bounded() {
826        let c = CheckCache::new(Duration::from_secs(60), Duration::ZERO, 2);
827        c.put([1; 32], true);
828        c.put([2; 32], false);
829        assert_eq!(c.get(&[1; 32]), Some(true));
830        assert_eq!(c.get(&[2; 32]), None, "a zero ttl expires at once");
831        c.put([3; 32], true);
832        c.put([4; 32], true);
833        assert!(c.entries.lock().unwrap().len() <= 2);
834        assert_eq!(c.get(&[4; 32]), Some(true));
835    }
836}