use core::fmt;
use std::error::Error;
use std::time::{Duration, SystemTime};
use keri_cesr::crypto::signer::Signer;
use keri_cesr::crypto::verifier::VerificationKey;
use crate::authentication::{AuthenticationError, RequestSigner, find_signature};
use crate::fields::{FieldText, SIGNATURE_HEADER_NAME, SignatureHeader};
use crate::header::{HeaderName, HeaderValue, Headers};
use crate::input::{
ED25519_ALGORITHM, InputLabel, RequestTarget, SIGNATURE_INPUT_HEADER_NAME, SIGNIFY_RESOURCE_HEADER_NAME,
SIGNIFY_TIMESTAMP_HEADER_NAME, SignatureComponent, SignatureInput, SignatureInputBuilder, SignatureInputHeader,
};
use crate::timestamp::SignifyTimestamp;
pub trait KeyLookup {
fn first_current_key(&self, controller: &str) -> Option<VerificationKey>;
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Freshness {
Ignore,
Window {
past: Duration,
future: Duration,
},
}
impl Default for Freshness {
fn default() -> Self {
Self::Window {
past: Duration::from_mins(5),
future: Duration::from_mins(1),
}
}
}
impl Freshness {
pub fn check(self, created: u64, now: SystemTime) -> Result<(), FreshnessError> {
let Self::Window { past, future } = self else {
return Ok(());
};
let now_seconds = now
.duration_since(SystemTime::UNIX_EPOCH)
.map_err(|_| FreshnessError::UnusableClock)?
.as_secs();
if created.saturating_add(past.as_secs()) < now_seconds {
return Err(FreshnessError::Stale {
created,
now: now_seconds,
allowed: past,
});
}
if created > now_seconds.saturating_add(future.as_secs()) {
return Err(FreshnessError::FromTheFuture {
created,
now: now_seconds,
allowed: future,
});
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum FreshnessError {
Stale {
created: u64,
now: u64,
allowed: Duration,
},
FromTheFuture {
created: u64,
now: u64,
allowed: Duration,
},
UnusableClock,
}
impl fmt::Display for FreshnessError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Stale { .. } => formatter.write_str("the signature is too old"),
Self::FromTheFuture { .. } => formatter.write_str("the signature is dated in the future"),
Self::UnusableClock => formatter.write_str("the clock reads before the epoch"),
}
}
}
impl Error for FreshnessError {}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VerifiedRequest {
controller: String,
input: SignatureInput,
}
impl VerifiedRequest {
#[must_use]
pub fn controller(&self) -> &str {
&self.controller
}
#[must_use]
pub const fn input(&self) -> &SignatureInput {
&self.input
}
}
#[derive(Clone, Debug)]
pub struct RequestVerifier<L> {
lookup: L,
freshness: Freshness,
}
impl<L: KeyLookup> RequestVerifier<L> {
#[must_use]
pub const fn new(lookup: L) -> Self {
Self {
lookup,
freshness: Freshness::Ignore,
}
}
#[must_use]
pub const fn with_freshness(mut self, freshness: Freshness) -> Self {
self.freshness = freshness;
self
}
pub fn verify(
&self,
target: &RequestTarget,
headers: &Headers,
now: SystemTime,
) -> Result<VerifiedRequest, RequestRejection> {
let required = |name: &'static str| headers.get(name).ok_or(RequestRejection::MissingHeader { name });
let input_value = required(SIGNATURE_INPUT_HEADER_NAME)?;
let signature_value = required(SIGNATURE_HEADER_NAME)?;
let controller = required(SIGNIFY_RESOURCE_HEADER_NAME)?;
let key = self
.lookup
.first_current_key(controller)
.ok_or(RequestRejection::UnknownController)?;
let label = InputLabel::signify();
let inputs = SignatureInputHeader::parse_received(input_value).map_err(RequestRejection::malformed)?;
let input = inputs.find(&label).ok_or(RequestRejection::NoSignifyInput)?;
let signature = SignatureHeader::parse(signature_value).map_err(RequestRejection::malformed)?;
let signature = find_signature(&signature, &label).map_err(RequestRejection::malformed)?;
let base = input
.received_base(target, headers)
.map_err(RequestRejection::malformed)?;
key.verify(signature, base.as_bytes())
.map_err(|_| RequestRejection::InvalidSignature)?;
self.freshness
.check(input.created(), now)
.map_err(|source| RequestRejection::Freshness { source })?;
Ok(VerifiedRequest {
controller: controller.to_owned(),
input: input.clone(),
})
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum RequestRejection {
MissingHeader {
name: &'static str,
},
UnknownController,
NoSignifyInput,
Malformed {
source: AuthenticationError,
},
InvalidSignature,
Freshness {
source: FreshnessError,
},
}
impl RequestRejection {
fn malformed(source: impl Into<AuthenticationError>) -> Self {
Self::Malformed { source: source.into() }
}
}
impl fmt::Display for RequestRejection {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("the request could not be authenticated")
}
}
impl Error for RequestRejection {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Malformed { source } => Some(source),
Self::Freshness { source } => Some(source),
Self::MissingHeader { .. } | Self::UnknownController | Self::NoSignifyInput | Self::InvalidSignature => {
None
}
}
}
}
pub struct ResponseSigner {
signer: RequestSigner,
identifier: FieldText,
}
impl ResponseSigner {
pub fn new(signer: Signer, identifier: &str) -> Result<Self, AuthenticationError> {
Ok(Self {
signer: RequestSigner::new(signer),
identifier: FieldText::new(identifier)?,
})
}
pub fn sign(
&self,
target: &RequestTarget,
timestamp: &SignifyTimestamp,
created: u64,
) -> Result<Headers, AuthenticationError> {
let resource = HeaderName::new(SIGNIFY_RESOURCE_HEADER_NAME.to_ascii_lowercase())?;
let moment = HeaderName::new(SIGNIFY_TIMESTAMP_HEADER_NAME.to_ascii_lowercase())?;
let components = vec![
SignatureComponent::Header(resource.clone()),
SignatureComponent::Method,
SignatureComponent::Path,
SignatureComponent::Header(moment.clone()),
];
let input = SignatureInputBuilder::new(InputLabel::signify(), components, created)
.key_identifier(self.identifier.clone())
.algorithm(FieldText::new(ED25519_ALGORITHM)?)
.build()?;
let mut headers = Headers::new();
headers.insert(resource, HeaderValue::new(self.identifier.as_str())?)?;
headers.insert(moment, timestamp.to_header_value()?)?;
self.signer.sign(&input, target, &headers)?.apply(&mut headers)?;
Ok(headers)
}
}
impl fmt::Debug for ResponseSigner {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("ResponseSigner")
.field("identifier", &self.identifier)
.finish_non_exhaustive()
}
}
#[must_use]
pub fn canonical_path(raw: &str) -> String {
let mut decoded = Vec::with_capacity(raw.len());
let mut rest = raw.as_bytes();
while let Some((&byte, tail)) = rest.split_first() {
if byte == b'%'
&& let [high, low, remainder @ ..] = tail
&& let (Some(high), Some(low)) = (char::from(*high).to_digit(16), char::from(*low).to_digit(16))
{
decoded.extend(u8::try_from(high.saturating_mul(16).saturating_add(low)));
rest = remainder;
} else {
decoded.push(byte);
rest = tail;
}
}
let mut quoted = String::with_capacity(raw.len());
for byte in String::from_utf8_lossy(&decoded).bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'_' | b'.' | b'-' | b'~') {
quoted.push(char::from(byte));
} else {
quoted.push('%');
quoted.extend([hex_digit(byte >> 4), hex_digit(byte & 0x0f)]);
}
}
quoted
}
fn hex_digit(value: u8) -> char {
char::from_digit(u32::from(value), 16).map_or('0', |digit| digit.to_ascii_uppercase())
}