use std::{fmt, future::Future, pin::Pin, time::SystemTime};
use secrecy::{ExposeSecret as _, SecretString};
use sha2::{Digest as _, Sha256};
use subtle::ConstantTimeEq as _;
use crate::Address;
const TOKEN_BYTES: usize = 32;
pub type ConfirmationFuture<'operation, T> =
Pin<Box<dyn Future<Output = Result<T, ConfirmationError>> + Send + 'operation>>;
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct ChallengeId([u8; 32]);
impl fmt::Debug for ChallengeId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("ChallengeId([redacted])")
}
}
impl ChallengeId {
#[must_use]
pub const fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PendingConfirmation {
id: ChallengeId,
address: Address,
expires_at: SystemTime,
}
impl PendingConfirmation {
#[must_use]
pub const fn id(&self) -> &ChallengeId {
&self.id
}
#[must_use]
pub const fn address(&self) -> &Address {
&self.address
}
#[must_use]
pub const fn expires_at(&self) -> SystemTime {
self.expires_at
}
}
pub struct ChallengeMessage {
address: Address,
token: SecretString,
expires_at: SystemTime,
}
impl ChallengeMessage {
#[must_use]
pub const fn address(&self) -> &Address {
&self.address
}
#[must_use]
pub fn token(&self) -> &str {
self.token.expose_secret()
}
#[must_use]
pub const fn expires_at(&self) -> SystemTime {
self.expires_at
}
}
impl fmt::Debug for ChallengeMessage {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ChallengeMessage")
.field("address", &self.address)
.field("token", &"[redacted]")
.field("expires_at", &self.expires_at)
.finish()
}
}
pub trait ChallengeStore: Send + Sync {
fn put<'operation>(
&'operation self,
pending: PendingConfirmation,
) -> ConfirmationFuture<'operation, ()>;
fn consume<'operation>(
&'operation self,
id: &'operation ChallengeId,
now: SystemTime,
) -> ConfirmationFuture<'operation, Option<PendingConfirmation>>;
}
pub trait ChallengeSender: Send + Sync {
fn send<'operation>(
&'operation self,
message: &'operation ChallengeMessage,
) -> ConfirmationFuture<'operation, ()>;
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Confirmation {
address: Address,
confirmed_at: SystemTime,
}
impl Confirmation {
#[must_use]
pub const fn address(&self) -> &Address {
&self.address
}
#[must_use]
pub const fn confirmed_at(&self) -> SystemTime {
self.confirmed_at
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct ConfirmationService;
impl ConfirmationService {
pub async fn send<S, D>(
&self,
store: &S,
sender: &D,
address: Address,
expires_at: SystemTime,
) -> Result<(), ConfirmationError>
where
S: ChallengeStore + ?Sized,
D: ChallengeSender + ?Sized,
{
if expires_at <= SystemTime::now() {
return Err(ConfirmationError::InvalidExpiration);
}
let message = issue(address, expires_at)?;
let pending = PendingConfirmation {
id: token_id(message.token()),
address: message.address.clone(),
expires_at,
};
store.put(pending).await?;
sender.send(&message).await
}
pub async fn confirm<S>(
&self,
store: &S,
token: &str,
now: SystemTime,
) -> Result<Option<Confirmation>, ConfirmationError>
where
S: ChallengeStore + ?Sized,
{
if !valid_token(token) {
return Ok(None);
}
let expected = token_id(token);
let Some(pending) = store.consume(&expected, now).await? else {
return Ok(None);
};
if now >= pending.expires_at || !bool::from(expected.0.ct_eq(&pending.id.0)) {
return Ok(None);
}
Ok(Some(Confirmation {
address: pending.address,
confirmed_at: now,
}))
}
}
#[derive(Clone, Copy, Debug, thiserror::Error, Eq, PartialEq)]
#[non_exhaustive]
pub enum ConfirmationError {
#[error("confirmation expiration must be in the future")]
InvalidExpiration,
#[error("secure challenge randomness is unavailable")]
Entropy,
#[error("confirmation state operation failed")]
Storage,
#[error("confirmation message delivery failed")]
Delivery,
}
fn issue(address: Address, expires_at: SystemTime) -> Result<ChallengeMessage, ConfirmationError> {
let mut random = [0_u8; TOKEN_BYTES];
getrandom::fill(&mut random).map_err(|_| ConfirmationError::Entropy)?;
Ok(ChallengeMessage {
address,
token: SecretString::from(hex(&random)),
expires_at,
})
}
fn token_id(token: &str) -> ChallengeId {
ChallengeId(Sha256::digest(token.as_bytes()).into())
}
fn valid_token(token: &str) -> bool {
token.len() == TOKEN_BYTES * 2
&& token
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
fn hex(bytes: &[u8]) -> String {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut output = String::with_capacity(bytes.len() * 2);
for byte in bytes {
output.push(char::from(DIGITS[usize::from(byte >> 4)]));
output.push(char::from(DIGITS[usize::from(byte & 0x0f)]));
}
output
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use futures_executor::block_on;
use super::*;
#[derive(Default)]
struct MemoryStore(Mutex<Option<PendingConfirmation>>);
impl ChallengeStore for MemoryStore {
fn put<'a>(&'a self, pending: PendingConfirmation) -> ConfirmationFuture<'a, ()> {
Box::pin(async move {
*self.0.lock().unwrap() = Some(pending);
Ok(())
})
}
fn consume<'a>(
&'a self,
id: &'a ChallengeId,
now: SystemTime,
) -> ConfirmationFuture<'a, Option<PendingConfirmation>> {
Box::pin(async move {
let mut state = self.0.lock().unwrap();
let matches = state
.as_ref()
.is_some_and(|pending| pending.id == *id && pending.expires_at > now);
Ok(matches.then(|| state.take().unwrap()))
})
}
}
#[derive(Default)]
struct MemorySender(Mutex<Option<String>>);
impl ChallengeSender for MemorySender {
fn send<'a>(&'a self, message: &'a ChallengeMessage) -> ConfirmationFuture<'a, ()> {
Box::pin(async move {
*self.0.lock().unwrap() = Some(message.token().to_owned());
Ok(())
})
}
}
#[test]
fn token_is_single_use_and_debug_redacted() {
block_on(async {
let store = MemoryStore::default();
let sender = MemorySender::default();
let now = SystemTime::now();
let expires = now + std::time::Duration::from_secs(300);
ConfirmationService
.send(
&store,
&sender,
Address::parse("maya@example.com").unwrap(),
expires,
)
.await
.unwrap();
let token = sender.0.lock().unwrap().clone().unwrap();
assert!(!format!("{:?}", store.0.lock().unwrap()).contains(&token));
let confirmation = ConfirmationService
.confirm(&store, &token, now)
.await
.unwrap();
assert!(confirmation.is_some());
assert!(
ConfirmationService
.confirm(&store, &token, now)
.await
.unwrap()
.is_none()
);
});
}
#[test]
fn malformed_token_does_not_consume_state() {
block_on(async {
let store = MemoryStore::default();
assert!(
ConfirmationService
.confirm(&store, "not-a-token", SystemTime::now())
.await
.unwrap()
.is_none()
);
});
}
#[test]
fn expired_challenge_is_rejected_before_storage_or_delivery() {
let store = MemoryStore::default();
let sender = MemorySender::default();
let result = block_on(ConfirmationService.send(
&store,
&sender,
Address::parse("maya@example.com").unwrap(),
SystemTime::UNIX_EPOCH,
));
assert_eq!(result, Err(ConfirmationError::InvalidExpiration));
assert!(store.0.lock().unwrap().is_none());
assert!(sender.0.lock().unwrap().is_none());
}
}