use std::fmt;
use url::Url;
use crate::error::{Error, Result};
pub(crate) const REDACTED: &str = "[REDACTED]";
pub struct AuthRequest<'a> {
pub method: &'a str,
pub url: &'a Url,
pub body: Option<&'a [u8]>,
pub(crate) headers: Vec<(String, String)>,
}
impl AuthRequest<'_> {
pub fn set_header(&mut self, name: impl Into<String>, value: impl Into<String>) {
self.headers.push((name.into(), value.into()));
}
}
pub trait Authenticator: Send + Sync + 'static {
fn kind(&self) -> &str;
fn authenticate(&self, request: &mut AuthRequest<'_>) -> Result<()>;
fn redact(&self, text: &str) -> String;
fn adjust_clock(&self, _server_time_ms: i64) -> Option<bool> {
None
}
fn sign_websocket_challenge(
&self,
_connection_id: &str,
_challenge: &str,
) -> Option<(String, String)> {
None
}
}
#[derive(Clone)]
pub struct ApiKeyAuthenticator {
key: String,
secret: String,
}
impl ApiKeyAuthenticator {
pub fn new(api_key: impl Into<String>, api_secret: impl Into<String>) -> Result<Self> {
let (key, secret) = (api_key.into(), api_secret.into());
if key.trim().is_empty() {
return Err(Error::config("api_key must be a non-empty string"));
}
if secret.trim().is_empty() {
return Err(Error::config("api_secret must be a non-empty string"));
}
if [&key, &secret].iter().any(|s| s.contains(['\r', '\n'])) {
return Err(Error::config(
"api_key and api_secret must not contain line breaks",
));
}
Ok(ApiKeyAuthenticator { key, secret })
}
pub fn key_hint(&self) -> String {
let head: String = self.key.chars().take(6).collect();
format!("{head}…")
}
}
impl Authenticator for ApiKeyAuthenticator {
fn kind(&self) -> &str {
"api-key"
}
fn authenticate(&self, request: &mut AuthRequest<'_>) -> Result<()> {
request.set_header("X-API-Key", self.key.clone());
request.set_header("X-API-Secret", self.secret.clone());
Ok(())
}
fn redact(&self, text: &str) -> String {
let mut out = text.to_string();
for s in [&self.secret, &self.key] {
if !s.is_empty() {
out = out.replace(s.as_str(), REDACTED);
}
}
out
}
}
impl fmt::Display for ApiKeyAuthenticator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"ApiKeyAuthenticator({}, secret={REDACTED})",
self.key_hint()
)
}
}
impl fmt::Debug for ApiKeyAuthenticator {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}