use std::sync::Arc;
use std::time::Duration;
use adk_core::{Clock, SystemClock};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use http::header::HeaderValue;
use http::{HeaderMap, Method, Uri};
use super::keys::Ed25519SigningKey;
use super::message::{ComponentId, RequestHead, SignatureInput};
use super::structured::{BareItem, Dictionary, Item, ListEntry};
use super::{
SIGNATURE, SIGNATURE_AGENT, SIGNATURE_INPUT, WEB_BOT_AUTH_TAG, WebBotAuthError, combined_field,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SigningParams {
pub created: i64,
pub expires: i64,
pub nonce: Option<String>,
}
pub struct HttpSignatureSigner {
key: Arc<Ed25519SigningKey>,
signature_agent: String,
label: String,
agent_member: String,
components: Vec<ComponentId>,
lifetime: Duration,
nonce: bool,
clock: Arc<dyn Clock>,
}
impl std::fmt::Debug for HttpSignatureSigner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HttpSignatureSigner")
.field("key", &self.key)
.field("signature_agent", &self.signature_agent)
.field("label", &self.label)
.finish_non_exhaustive()
}
}
impl HttpSignatureSigner {
pub fn builder(
key: Arc<Ed25519SigningKey>,
signature_agent: impl Into<String>,
) -> HttpSignatureSignerBuilder {
HttpSignatureSignerBuilder {
key,
signature_agent: signature_agent.into(),
label: "sig1".to_string(),
agent_member: None,
components: vec![
ComponentId::new("@authority"),
ComponentId::new("@method"),
ComponentId::new("@path"),
ComponentId::new("@query"),
],
lifetime: Duration::from_secs(300),
nonce: true,
clock: Arc::new(SystemClock),
}
}
pub fn keyid(&self) -> &str {
self.key.thumbprint()
}
pub fn sign_request<B>(&self, request: &mut http::Request<B>) -> Result<(), WebBotAuthError> {
let method = request.method().clone();
let uri = request.uri().clone();
self.sign_head(&method, &uri, request.headers_mut())
}
pub fn sign_reqwest(&self, request: &mut reqwest::Request) -> Result<(), WebBotAuthError> {
let method = request.method().clone();
let uri: Uri = request.url().as_str().parse().map_err(|e| {
WebBotAuthError::SignatureBase { reason: format!("the request URL is not a URI: {e}") }
})?;
self.sign_head(&method, &uri, request.headers_mut())
}
pub fn sign_head(
&self,
method: &Method,
uri: &Uri,
headers: &mut HeaderMap,
) -> Result<(), WebBotAuthError> {
let created = self.clock.now().timestamp();
let lifetime = i64::try_from(self.lifetime.as_secs()).unwrap_or(i64::MAX);
let nonce = self.nonce.then(|| {
let mut bytes = [0u8; 32];
let _ = aws_lc_rs::rand::fill(&mut bytes);
STANDARD.encode(bytes)
});
self.sign_head_with(
method,
uri,
headers,
SigningParams { created, expires: created.saturating_add(lifetime), nonce },
)
}
pub fn sign_head_with(
&self,
method: &Method,
uri: &Uri,
headers: &mut HeaderMap,
params: SigningParams,
) -> Result<(), WebBotAuthError> {
let malformed = |field: &str, reason: String| WebBotAuthError::MalformedField {
field: field.to_string(),
reason,
};
let field = |headers: &HeaderMap, name: &str| -> Result<String, WebBotAuthError> {
Ok(combined_field(headers, name)?.unwrap_or_default())
};
let mut agents = Dictionary::parse(&field(headers, SIGNATURE_AGENT)?)
.map_err(|e| malformed(SIGNATURE_AGENT, e.to_string()))?;
agents.insert(
self.agent_member.clone(),
ListEntry::Item(Item::new(BareItem::String(self.signature_agent.clone()))),
);
set_field(headers, SIGNATURE_AGENT, &agents)?;
let mut components = self.components.clone();
components.push(ComponentId::signature_agent(self.agent_member.clone()));
let mut input = SignatureInput::new(components);
input.params.insert("created", BareItem::Integer(params.created));
input.params.insert("keyid", BareItem::String(self.key.thumbprint().to_string()));
input.params.insert("alg", BareItem::String("ed25519".into()));
input.params.insert("expires", BareItem::Integer(params.expires));
if let Some(nonce) = params.nonce {
input.params.insert("nonce", BareItem::String(nonce));
}
input.params.insert("tag", BareItem::String(WEB_BOT_AUTH_TAG.into()));
let base = RequestHead::new(method, uri, headers).signature_base(&input)?;
let signature = self.key.sign(base.as_bytes());
let mut inputs = Dictionary::parse(&field(headers, SIGNATURE_INPUT)?)
.map_err(|e| malformed(SIGNATURE_INPUT, e.to_string()))?;
let mut signatures = Dictionary::parse(&field(headers, SIGNATURE)?)
.map_err(|e| malformed(SIGNATURE, e.to_string()))?;
inputs.insert(self.label.clone(), ListEntry::InnerList(input.to_inner_list()));
signatures.insert(
self.label.clone(),
ListEntry::Item(Item::new(BareItem::ByteSequence(signature.to_vec()))),
);
set_field(headers, SIGNATURE_INPUT, &inputs)?;
set_field(headers, SIGNATURE, &signatures)
}
}
fn set_field(
headers: &mut HeaderMap,
name: &'static str,
value: &Dictionary,
) -> Result<(), WebBotAuthError> {
let invalid =
|reason: String| WebBotAuthError::MalformedField { field: name.to_string(), reason };
let serialized = value.serialize().map_err(|e| invalid(e.to_string()))?;
let value = HeaderValue::from_str(&serialized).map_err(|e| invalid(e.to_string()))?;
headers.insert(name, value);
Ok(())
}
pub struct HttpSignatureSignerBuilder {
key: Arc<Ed25519SigningKey>,
signature_agent: String,
label: String,
agent_member: Option<String>,
components: Vec<ComponentId>,
lifetime: Duration,
nonce: bool,
clock: Arc<dyn Clock>,
}
impl std::fmt::Debug for HttpSignatureSignerBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HttpSignatureSignerBuilder")
.field("signature_agent", &self.signature_agent)
.field("label", &self.label)
.finish_non_exhaustive()
}
}
impl HttpSignatureSignerBuilder {
pub fn label(mut self, label: impl Into<String>) -> Self {
self.label = label.into();
self
}
pub fn agent_member(mut self, member: impl Into<String>) -> Self {
self.agent_member = Some(member.into());
self
}
pub fn components(mut self, components: Vec<ComponentId>) -> Self {
self.components = components;
self
}
pub fn lifetime(mut self, lifetime: Duration) -> Self {
self.lifetime = lifetime;
self
}
pub fn nonce(mut self, nonce: bool) -> Self {
self.nonce = nonce;
self
}
pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
self.clock = clock;
self
}
pub fn build(self) -> Result<HttpSignatureSigner, WebBotAuthError> {
let invalid = |reason: String| WebBotAuthError::InvalidConfig { reason };
let url = reqwest::Url::parse(&self.signature_agent)
.map_err(|e| invalid(format!("Signature-Agent `{}`: {e}", self.signature_agent)))?;
if !matches!(url.scheme(), "https" | "http")
|| url.host_str().is_none()
|| url.path() != "/"
|| url.query().is_some()
|| url.fragment().is_some()
{
return Err(invalid(format!(
"Signature-Agent `{}` must be an origin such as https://bot.example",
self.signature_agent
)));
}
let agent_member = self.agent_member.unwrap_or_else(|| self.label.clone());
for key in [&self.label, &agent_member] {
let mut probe = Dictionary::new();
probe.insert(key.clone(), ListEntry::Item(Item::new(BareItem::Integer(1))));
probe.serialize().map_err(|_| {
invalid(format!("`{key}` is not a structured-field key (lowercase, digits, _-.*)"))
})?;
}
if !self.components.iter().any(|c| {
(c.name() == "@authority" || c.name() == "@target-uri") && c.params().is_empty()
}) {
return Err(invalid("the components must include @authority or @target-uri".into()));
}
let own_member = ComponentId::signature_agent(agent_member.clone());
if self.components.iter().any(|c| c.same_as(&own_member)) {
return Err(invalid(format!(
"the Signature-Agent member `{agent_member}` is covered automatically"
)));
}
Ok(HttpSignatureSigner {
key: self.key,
signature_agent: self.signature_agent,
label: self.label,
agent_member,
components: self.components,
lifetime: self.lifetime,
nonce: self.nonce,
clock: self.clock,
})
}
}