mod hotp;
mod recovery;
mod secret;
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;
use std::fmt::Write as _;
use std::time::{SystemTime, UNIX_EPOCH};
use laravel::axum::extract::FromRequestParts;
use laravel::axum::http::request::Parts;
use laravel::config::cache::StoreConfig;
use laravel::config::{Config, Env, Section};
use laravel::container::Container;
use laravel::context::Context;
use laravel::foundation::ServiceProvider;
use laravel::rate_limit::{self, Limit, Quota, TooManyAttempts};
use qrcode::QrCode;
use qrcode::render::svg;
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
pub use crate::recovery::RecoveryCodes;
pub use crate::secret::{MIN_SECRET_BYTES, MIN_STORED_SECRET_BYTES, Secret};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Algorithm {
#[default]
Sha1,
Sha256,
Sha512,
}
impl std::str::FromStr for Algorithm {
type Err = Error;
fn from_str(name: &str) -> Result<Self, Error> {
match name.to_ascii_uppercase().as_str() {
"SHA1" => Ok(Self::Sha1),
"SHA256" => Ok(Self::Sha256),
"SHA512" => Ok(Self::Sha512),
_ => Err(Error::InvalidConfig("the algorithm must be SHA1, SHA256 or SHA512")),
}
}
}
impl Algorithm {
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Sha1 => "SHA1",
Self::Sha256 => "SHA256",
Self::Sha512 => "SHA512",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Section)]
pub struct TwoFactorConfig {
#[env("TWO_FACTOR_ISSUER")]
pub issuer: Option<String>,
#[env("TWO_FACTOR_DIGITS", default = 6)]
pub digits: u32,
#[env("TWO_FACTOR_PERIOD", default = 30)]
pub period: u64,
#[env("TWO_FACTOR_WINDOW", default = 1)]
pub window: u64,
#[env("TWO_FACTOR_ALGORITHM", default = Algorithm::Sha1)]
pub algorithm: Algorithm,
#[env("TWO_FACTOR_SECRET_BYTES", default = 20)]
pub secret_bytes: usize,
#[env("TWO_FACTOR_CACHE_STORE")]
pub cache_store: Option<String>,
}
impl TwoFactorConfig {
pub fn validate(&self) -> Result<(), Error> {
if self.issuer.as_deref().is_some_and(|issuer| issuer.contains(':')) {
return Err(Error::InvalidConfig("the issuer can't contain a colon"));
}
if !(6..=8).contains(&self.digits) {
return Err(Error::InvalidConfig("digits must be 6, 7 or 8"));
}
if !(1..=MAX_PERIOD).contains(&self.period) {
return Err(Error::InvalidConfig("the period must be 1 to 86400 seconds"));
}
if self.window > 10 {
return Err(Error::InvalidConfig("the window must be 10 periods or fewer"));
}
if self.secret_bytes < MIN_SECRET_BYTES {
return Err(Error::SecretTooShort);
}
Ok(())
}
}
pub const MAX_PERIOD: u64 = 86_400;
pub const ATTEMPTS_PER_MINUTE: u32 = 5;
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("the two-factor secret is too short: a new one needs 16 bytes, an existing one 10 (16 base32 characters)")]
SecretTooShort,
#[error(
"a two-factor secret must be base32: the letters A to Z and digits 2 to 7, as many as whole bytes encode to"
)]
InvalidSecret,
#[error("the operating system couldn't provide random bytes")]
Random,
#[error("invalid two-factor config: {0}")]
InvalidConfig(&'static str),
#[error("the two-factor URL is too long for a QR code")]
QrCode,
#[error("the two-factor account name can't contain a colon")]
InvalidAccount,
}
#[derive(Clone, Debug, Default)]
pub struct TwoFactor {
config: TwoFactorConfig,
}
impl TwoFactor {
pub fn new(config: TwoFactorConfig) -> Result<Self, Error> {
config.validate()?;
Ok(Self { config })
}
pub fn from_app() -> Result<Self, Error> {
let Some(config) = Context::current().map(|_| laravel::config()) else {
return Ok(Self::default());
};
Self::new(effective_config(&config))
}
#[must_use]
pub fn config(&self) -> &TwoFactorConfig {
&self.config
}
pub fn generate_secret(&self) -> Result<Secret, Error> {
Secret::generate(self.config.secret_bytes)
}
pub fn url(&self, secret: &Secret, account: &str) -> Result<String, Error> {
if account.contains(':') {
return Err(Error::InvalidAccount);
}
let label = match &self.config.issuer {
Some(issuer) => format!("{}:{}", encode(issuer), encode(account)),
None => encode(account),
};
let mut url = format!("otpauth://totp/{label}?secret={}", secret.to_base32());
if let Some(issuer) = &self.config.issuer {
let _ = write!(url, "&issuer={}", encode(issuer));
}
let _ = write!(
url,
"&algorithm={}&digits={}&period={}",
self.config.algorithm.as_str(),
self.config.digits,
self.config.period
);
Ok(url)
}
pub fn qr_code_svg(&self, secret: &Secret, account: &str) -> Result<String, Error> {
let code = QrCode::new(self.url(secret, account)?).map_err(|_| Error::QrCode)?;
Ok(code
.render::<svg::Color<'_>>()
.min_dimensions(192, 192)
.dark_color(svg::Color("#000000"))
.light_color(svg::Color("#ffffff"))
.build())
}
#[must_use]
pub fn code(&self, secret: &Secret) -> String {
self.code_at(secret, now())
}
#[must_use]
pub fn code_at(&self, secret: &Secret, time: u64) -> String {
hotp::code(secret, self.step(time), &self.config)
}
#[must_use]
pub fn verify(&self, secret: &Secret, code: &str) -> bool {
self.verify_at(secret, code, now()).is_some()
}
#[must_use]
pub fn verify_at(&self, secret: &Secret, code: &str, time: u64) -> Option<u64> {
let code: String = code.chars().filter(|c| !c.is_whitespace() && *c != '-').collect();
if code.len() != self.config.digits as usize || !code.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
let current = self.step(time);
let first = current.saturating_sub(self.config.window);
let last = current.saturating_add(self.config.window);
let mut found = Choice::from(0);
let mut matched = 0;
for step in first..=last {
let equal = hotp::code(secret, step, &self.config).as_bytes().ct_eq(code.as_bytes());
matched.conditional_assign(&step, equal);
found |= equal;
}
bool::from(found).then_some(matched)
}
pub async fn attempt(&self, key: &str) -> laravel::Result<Result<Quota, TooManyAttempts>> {
let config = laravel::config();
check_store(&config, &config.cache.default)?;
rate_limit::attempt(
&format!("two-factor:{key}:attempts"),
Limit::per_minute(ATTEMPTS_PER_MINUTE),
)
.await
}
pub async fn verify_once(&self, secret: &Secret, code: &str, key: &str) -> laravel::Result<bool> {
let config = laravel::config();
let name = self.config.cache_store.as_deref().unwrap_or(&config.cache.default);
check_store(&config, name)?;
let cache = laravel::cache::store(name)?;
let time = now();
let Some(step) = self.verify_at(secret, code, time) else {
return Ok(false);
};
let first = self.step(time).saturating_sub(self.config.window);
let seconds = self.config.period * (2 * self.config.window + 1);
let ttl = laravel::time::ToSpan::seconds(i64::try_from(seconds).unwrap_or(i64::MAX));
for earlier in first..step {
cache
.add(&format!("two-factor:{key}:step:{earlier}"), true, ttl)
.await?;
}
if !cache.add(&format!("two-factor:{key}:step:{step}"), true, ttl).await? {
return Ok(false);
}
let current = self.step(now());
Ok(current.saturating_sub(self.config.window) <= step && step <= current.saturating_add(self.config.window))
}
fn step(&self, time: u64) -> u64 {
time / self.config.period
}
}
impl<S: Send + Sync> FromRequestParts<S> for TwoFactor {
type Rejection = laravel::Error;
async fn from_request_parts(_parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
Ok(Self::from_app()?)
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct TwoFactorServiceProvider;
impl ServiceProvider for TwoFactorServiceProvider {
fn config(&self, config: &mut Config, env: &Env) {
config.discover(env!("CARGO_CRATE_NAME"), env);
}
async fn boot(&self, app: &Container) -> laravel::Result<()> {
let config = app.config();
let two_factor = effective_config(config);
two_factor.validate()?;
check_store(config, &config.cache.default)?;
if let Some(name) = &two_factor.cache_store {
if !config.cache.stores.contains_key(name) {
return Err(laravel::Error::msg(format!(
"two-factor's cache store `{name}` isn't defined"
)));
}
check_store(config, name)?;
}
Ok(())
}
}
fn check_store(config: &Config, name: &str) -> laravel::Result<()> {
match config.cache.stores.get(name) {
Some(StoreConfig::Discard) => Err(laravel::Error::msg(format!(
"two-factor needs a cache store that keeps values, and `{name}` is a discard store"
))),
Some(StoreConfig::Failover(_)) => Err(laravel::Error::msg(format!(
"two-factor needs one cache store it can trust, and `{name}` is a failover store; \
use one of its stores instead"
))),
_ => Ok(()),
}
}
fn effective_config(config: &Config) -> TwoFactorConfig {
let mut two_factor = config.get::<TwoFactorConfig>().cloned().unwrap_or_default();
if two_factor.issuer.is_none() && !config.app.name.is_empty() {
two_factor.issuer = Some(config.app.name.clone());
}
two_factor
}
fn now() -> u64 {
match Context::current() {
Some(_) => u64::try_from(laravel::now().timestamp().as_second()).unwrap_or(0),
None => SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_secs()),
}
}
fn encode(text: &str) -> String {
let mut encoded = String::with_capacity(text.len());
for byte in text.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
encoded.push(char::from(byte));
} else {
let _ = write!(encoded, "%{byte:02X}");
}
}
encoded
}