1use 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
45pub const MAX_CREDENTIAL_LEN: usize = 256;
47
48#[derive(Clone)]
52pub struct Credential(SecretString);
53
54impl Credential {
55 pub fn new(secret: impl Into<String>) -> Self {
57 Credential(SecretString::from(secret.into()))
58 }
59
60 pub fn expose(&self) -> &str {
62 self.0.expose_secret()
63 }
64
65 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
77pub fn fingerprint(secret: &str) -> [u8; 32] {
79 Sha256::digest(secret.as_bytes()).into()
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum CredentialCheck {
86 Valid,
88 Invalid(Option<String>),
91 Unavailable(String),
94}
95
96pub type CheckFuture<'a> = Pin<Box<dyn Future<Output = CredentialCheck> + Send + 'a>>;
98
99pub trait CredentialVerifier: Send + Sync + 'static {
132 fn label(&self) -> &str;
136 fn help(&self) -> &str {
138 ""
139 }
140 fn prepare<'a>(&self, entered: &'a str) -> &'a str {
143 entered.trim()
144 }
145 fn plausible(&self, credential: &str) -> bool {
150 plausible(credential)
151 }
152 fn check<'a>(&'a self, credential: &'a str) -> CheckFuture<'a>;
154 fn carried(&self) -> bool {
158 true
159 }
160 fn accepts_bearer(&self) -> bool {
163 self.carried()
164 }
165 fn subject(&self, credential: &str) -> Option<String> {
172 let _ = credential;
173 None
174 }
175 fn generation(&self) -> &[u8] {
179 &[]
180 }
181 fn upstream(&self) -> Option<&dyn crate::upstream::UpstreamSignIn> {
186 None
187 }
188}
189
190pub fn plausible(s: &str) -> bool {
193 !s.is_empty() && s.len() <= MAX_CREDENTIAL_LEN && s.bytes().all(|b| b.is_ascii_graphic())
194}
195
196pub const MAX_PASSWORD_LEN: usize = 1024;
198
199pub struct PasswordVerifier {
204 password: SecretString,
205 generation: [u8; 32],
206}
207
208impl PasswordVerifier {
209 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#[derive(Debug, thiserror::Error, PartialEq, Eq)]
264#[non_exhaustive]
265pub enum SealError {
266 #[error("sealing failed")]
268 Seal,
269 #[error("the sealed credential is invalid")]
271 Open,
272}
273
274pub 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 pub fn new(signing_key: &[u8]) -> Self {
290 Self::for_purpose(signing_key, SEAL_INFO, SEAL_AAD)
291 }
292
293 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 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 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
345pub(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 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 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
405pub(crate) struct CheckRunner {
414 permits: Semaphore,
415 timeout: Duration,
416 wait: Duration,
417 running: Mutex<HashMap<[u8; 32], watch::Receiver<Option<CredentialCheck>>>>,
418}
419
420pub(crate) enum Ticket {
422 Lead(Lead),
424 Follow(watch::Receiver<Option<CredentialCheck>>),
426}
427
428pub(crate) struct Lead {
430 fingerprint: [u8; 32],
431 tx: watch::Sender<Option<CredentialCheck>>,
432}
433
434impl CheckRunner {
435 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 pub fn join(&self, fingerprint: [u8; 32]) -> Ticket {
449 let mut running = self.running.lock().unwrap_or_else(|e| e.into_inner());
450 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 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 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 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 #[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}