use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use id_effect::{Effect, fail, succeed, suspend};
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
use crate::error::AuthError;
use crate::principal::{AuthPrincipal, AuthScheme};
const ID_BYTES: usize = 8;
const SECRET_BYTES: usize = 32;
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn is_hex(s: &str, len: usize) -> bool {
s.len() == len
&& s
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
pub(crate) fn random_hex(len: usize) -> Result<String, AuthError> {
let mut bytes = vec![0_u8; len];
getrandom::fill(&mut bytes).map_err(|e| AuthError::Key(format!("random source: {e}")))?;
Ok(hex(&bytes))
}
fn digest(secret: &str) -> [u8; 32] {
Sha256::digest(secret.as_bytes()).into()
}
#[derive(Clone, PartialEq, Eq)]
pub struct ApiKey(String);
impl ApiKey {
pub fn generate(
prefix: &str,
principal: AuthPrincipal,
) -> Result<(Self, ApiKeyRecord), AuthError> {
check_prefix(prefix)?;
let id = random_hex(ID_BYTES)?;
let secret = random_hex(SECRET_BYTES)?;
let record = ApiKeyRecord {
id: id.clone(),
digest: digest(&secret),
principal,
};
Ok((Self(format!("{prefix}_{id}_{secret}")), record))
}
#[inline]
pub fn expose(&self) -> &str {
&self.0
}
}
impl fmt::Debug for ApiKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let shown = self.0.rsplit_once('_').map_or("", |(head, _)| head);
write!(f, "ApiKey({shown}_…)")
}
}
fn check_prefix(prefix: &str) -> Result<(), AuthError> {
let ok = !prefix.is_empty()
&& prefix
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit());
if ok {
Ok(())
} else {
Err(AuthError::Key(format!(
"API key prefix {prefix:?} must be lower-case letters and digits"
)))
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ApiKeyRecord {
id: String,
digest: [u8; 32],
principal: AuthPrincipal,
}
impl ApiKeyRecord {
pub fn from_parts(
id: impl Into<String>,
digest_hex: &str,
principal: AuthPrincipal,
) -> Result<Self, AuthError> {
let id = id.into();
if !is_hex(&id, ID_BYTES * 2) || !is_hex(digest_hex, 64) {
return Err(AuthError::Malformed("API key record".into()));
}
let mut digest = [0_u8; 32];
for (i, byte) in digest.iter_mut().enumerate() {
*byte = u8::from_str_radix(&digest_hex[i * 2..i * 2 + 2], 16)
.map_err(|_| AuthError::Malformed("API key record".into()))?;
}
Ok(Self {
id,
digest,
principal,
})
}
#[inline]
pub fn id(&self) -> &str {
&self.id
}
pub fn digest_hex(&self) -> String {
hex(&self.digest)
}
#[inline]
pub fn principal(&self) -> &AuthPrincipal {
&self.principal
}
}
pub trait ApiKeyStore: Send + Sync + 'static {
fn find(&self, id: &str) -> Effect<Option<ApiKeyRecord>, AuthError>;
fn find_now(&self, id: &str) -> Option<Result<Option<ApiKeyRecord>, AuthError>> {
let _ = id;
None
}
}
#[derive(Default)]
struct MemoryKeysState {
records: HashMap<String, ApiKeyRecord>,
fail: Option<String>,
}
#[derive(Clone, Default)]
pub struct MemoryApiKeyStore {
inner: Arc<Mutex<MemoryKeysState>>,
}
impl fmt::Debug for MemoryApiKeyStore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MemoryApiKeyStore")
.field("len", &self.state().records.len())
.finish()
}
}
impl MemoryApiKeyStore {
#[inline]
pub fn new() -> Self {
Self::default()
}
fn state(&self) -> MutexGuard<'_, MemoryKeysState> {
self.inner.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn insert(&self, record: ApiKeyRecord) {
self.state().records.insert(record.id.clone(), record);
}
pub fn revoke(&self, id: &str) -> bool {
self.state().records.remove(id).is_some()
}
pub fn fail_with(&self, message: Option<&str>) {
self.state().fail = message.map(str::to_owned);
}
fn lookup(&self, id: &str) -> Result<Option<ApiKeyRecord>, AuthError> {
let st = self.state();
match &st.fail {
Some(m) => Err(AuthError::Unavailable(m.clone())),
None => Ok(st.records.get(id).cloned()),
}
}
}
impl ApiKeyStore for MemoryApiKeyStore {
fn find(&self, id: &str) -> Effect<Option<ApiKeyRecord>, AuthError> {
let (this, id) = (self.clone(), id.to_owned());
suspend(move || match this.lookup(&id) {
Ok(found) => succeed(found),
Err(e) => fail(e),
})
}
fn find_now(&self, id: &str) -> Option<Result<Option<ApiKeyRecord>, AuthError>> {
Some(self.lookup(id))
}
}
#[derive(Clone)]
pub struct ApiKeys {
store: Arc<dyn ApiKeyStore>,
prefix: Arc<str>,
}
impl fmt::Debug for ApiKeys {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ApiKeys")
.field("prefix", &self.prefix)
.finish_non_exhaustive()
}
}
impl ApiKeys {
pub fn new(store: impl ApiKeyStore, prefix: impl Into<String>) -> Self {
Self {
store: Arc::new(store),
prefix: Arc::from(prefix.into()),
}
}
#[inline]
pub fn prefix(&self) -> &str {
&self.prefix
}
pub fn verify(&self, presented: &str) -> Effect<AuthPrincipal, AuthError> {
let Some((id, secret)) = self.split(presented) else {
return fail(not_a_key());
};
let presented_digest = digest(secret);
self
.store
.find(id)
.flat_map(move |found| match accept(found, &presented_digest) {
Ok(principal) => succeed(principal),
Err(e) => fail(e),
})
}
#[cfg(feature = "axum")]
pub(crate) fn verify_now(&self, presented: &str) -> Option<Result<AuthPrincipal, AuthError>> {
let Some((id, secret)) = self.split(presented) else {
return Some(Err(not_a_key()));
};
let found = self.store.find_now(id)?;
let presented_digest = digest(secret);
Some(found.and_then(|found| accept(found, &presented_digest)))
}
fn split<'k>(&self, key: &'k str) -> Option<(&'k str, &'k str)> {
let rest = key.strip_prefix(&*self.prefix)?.strip_prefix('_')?;
let (id, secret) = rest.split_once('_')?;
(is_hex(id, ID_BYTES * 2) && is_hex(secret, SECRET_BYTES * 2)).then_some((id, secret))
}
}
fn not_a_key() -> AuthError {
AuthError::Malformed("not an API key of this service".into())
}
fn accept(
found: Option<ApiKeyRecord>,
presented_digest: &[u8; 32],
) -> Result<AuthPrincipal, AuthError> {
match found {
Some(record) if bool::from(record.digest.ct_eq(presented_digest)) => {
Ok(record.principal.with_scheme(AuthScheme::ApiKey))
}
_ => Err(AuthError::InvalidCredentials),
}
}
#[cfg(test)]
mod tests {
use id_effect::{Cause, Exit};
use super::*;
fn run<A: Send + 'static>(eff: Effect<A, AuthError>) -> Result<A, AuthError> {
match eff.block_on() {
Exit::Success(a) => Ok(a),
Exit::Failure(Cause::Fail(e)) => Err(e),
Exit::Failure(c) => panic!("unexpected cause: {c:?}"),
}
}
#[test]
fn generated_keys_verify_and_records_never_hold_the_secret() {
let store = MemoryApiKeyStore::new();
let (key, record) = ApiKey::generate("ide", AuthPrincipal::new("svc").with_role("r")).unwrap();
assert!(key.expose().starts_with("ide_"));
assert_eq!(key.expose().len(), 4 + 16 + 1 + 64);
let secret = key.expose().rsplit_once('_').unwrap().1;
assert!(!record.digest_hex().contains(secret));
assert!(!format!("{record:?}").contains(secret));
assert!(!format!("{key:?}").contains(secret));
assert!(format!("{key:?}").contains(record.id()));
store.insert(record.clone());
let keys = ApiKeys::new(store.clone(), "ide");
assert_eq!(keys.prefix(), "ide");
let p = run(keys.verify(key.expose())).unwrap();
assert_eq!(
p,
record.principal().clone().with_scheme(AuthScheme::ApiKey)
);
assert!(format!("{keys:?}").contains("ide"));
assert!(format!("{store:?}").contains("len: 1"));
}
#[test]
fn wrong_secret_unknown_id_revoked_and_malformed() {
let store = MemoryApiKeyStore::new();
let (key, record) = ApiKey::generate("ide", AuthPrincipal::new("svc")).unwrap();
store.insert(record.clone());
let keys = ApiKeys::new(store.clone(), "ide");
let wrong = format!("ide_{}_{}", record.id(), "0".repeat(64));
assert_eq!(run(keys.verify(&wrong)), Err(AuthError::InvalidCredentials));
let unknown = format!("ide_{}_{}", "1".repeat(16), "0".repeat(64));
assert_eq!(
run(keys.verify(&unknown)),
Err(AuthError::InvalidCredentials)
);
for bad in [
"",
"ide",
"other_0000000000000000_00",
"ide_zz_00",
&format!("ide_{}", record.id()),
&format!("ide_{}_{}", record.id(), "A".repeat(64)),
] {
assert!(
matches!(run(keys.verify(bad)), Err(AuthError::Malformed(_))),
"{bad}"
);
}
assert!(store.revoke(record.id()));
assert!(!store.revoke(record.id()));
assert_eq!(
run(keys.verify(key.expose())),
Err(AuthError::InvalidCredentials)
);
store.insert(record);
store.fail_with(Some("db"));
assert_eq!(
run(keys.verify(key.expose())),
Err(AuthError::Unavailable("db".into()))
);
store.fail_with(None);
assert!(run(keys.verify(key.expose())).is_ok());
}
#[cfg(feature = "axum")]
#[test]
fn verify_now_answers_like_verify() {
let store = MemoryApiKeyStore::new();
let (key, record) = ApiKey::generate("ide", AuthPrincipal::new("svc")).unwrap();
store.insert(record.clone());
let keys = ApiKeys::new(store.clone(), "ide");
let check = |presented: &str| {
assert_eq!(
keys.verify_now(presented),
Some(run(keys.verify(presented))),
"{presented}"
);
};
let wrong = format!("ide_{}_{}", record.id(), "0".repeat(64));
let unknown = format!("ide_{}_{}", "1".repeat(16), "0".repeat(64));
for presented in [
key.expose(),
&wrong,
&unknown,
"",
"other_0000000000000000_00",
] {
check(presented);
}
store.fail_with(Some("db"));
check(key.expose());
struct Remote(MemoryApiKeyStore);
impl ApiKeyStore for Remote {
fn find(&self, id: &str) -> Effect<Option<ApiKeyRecord>, AuthError> {
self.0.find(id)
}
}
store.fail_with(None);
let remote = ApiKeys::new(Remote(store), "ide");
assert_eq!(remote.verify_now(key.expose()), None);
assert!(run(remote.verify(key.expose())).is_ok());
}
#[test]
fn records_round_trip_through_hex_and_prefixes_are_checked() {
let (_, record) = ApiKey::generate("k1", AuthPrincipal::new("svc")).unwrap();
let back = ApiKeyRecord::from_parts(
record.id(),
&record.digest_hex(),
record.principal().clone(),
)
.unwrap();
assert_eq!(back, record);
let p = || AuthPrincipal::new("x");
assert!(ApiKeyRecord::from_parts("short", &record.digest_hex(), p()).is_err());
assert!(ApiKeyRecord::from_parts(record.id(), "00", p()).is_err());
for bad in ["", "Ab", "a_b", "a-b"] {
assert!(matches!(ApiKey::generate(bad, p()), Err(AuthError::Key(_))));
}
}
}