use std::collections::HashSet;
use std::sync::Arc;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use sha2::{Digest, Sha256};
use tokio::sync::RwLock;
use crate::error::AxiamError;
use crate::time::{Duration, Instant};
const SUPPORTED_ALG: &str = "SHA-256";
pub const MIN_POLL_INTERVAL: Duration = Duration::from_secs(15);
pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_secs(30);
pub const MAX_ENTRIES: usize = 100_000;
#[derive(Debug, serde::Deserialize)]
struct FeedDocument {
alg: String,
#[serde(default)]
revoked: Vec<String>,
}
#[derive(Debug, Default)]
struct FeedState {
entries: Option<HashSet<String>>,
last_success: Option<Instant>,
last_attempt: Option<Instant>,
}
#[derive(Clone)]
pub struct RevocationFeed {
inner: Arc<FeedInner>,
}
struct FeedInner {
http_client: reqwest::Client,
feed_url: url::Url,
poll_interval: Duration,
state: RwLock<FeedState>,
fetch_lock: tokio::sync::Mutex<()>,
}
impl std::fmt::Debug for RevocationFeed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RevocationFeed")
.field("feed_url", &self.inner.feed_url.as_str())
.field("poll_interval", &self.inner.poll_interval)
.finish_non_exhaustive()
}
}
impl RevocationFeed {
pub fn new(http_client: reqwest::Client, base_url: &url::Url) -> Result<Self, AxiamError> {
let feed_url = base_url
.join("/oauth2/revocations")
.map_err(|e| AxiamError::Network {
message: format!("invalid revocation feed URL: {e}"),
source: None,
})?;
Ok(Self {
inner: Arc::new(FeedInner {
http_client,
feed_url,
poll_interval: DEFAULT_POLL_INTERVAL,
state: RwLock::new(FeedState::default()),
fetch_lock: tokio::sync::Mutex::new(()),
}),
})
}
#[must_use]
pub fn with_poll_interval(mut self, interval: Duration) -> Self {
let clamped = interval.max(MIN_POLL_INTERVAL);
let inner = Arc::get_mut(&mut self.inner);
match inner {
Some(inner) => inner.poll_interval = clamped,
None => {
let old = &self.inner;
self.inner = Arc::new(FeedInner {
http_client: old.http_client.clone(),
feed_url: old.feed_url.clone(),
poll_interval: clamped,
state: RwLock::new(FeedState::default()),
fetch_lock: tokio::sync::Mutex::new(()),
});
}
}
self
}
#[must_use]
pub fn entry_for(sid: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(sid.as_bytes());
URL_SAFE_NO_PAD.encode(hasher.finalize())
}
pub async fn is_revoked(&self, sid: &str) -> bool {
self.refresh_if_stale().await;
let state = self.inner.state.read().await;
state
.entries
.as_ref()
.is_some_and(|set| set.contains(&Self::entry_for(sid)))
}
pub async fn refresh(&self) {
let _guard = self.inner.fetch_lock.lock().await;
let fetched = self.fetch().await;
let mut state = self.inner.state.write().await;
state.last_attempt = Some(Instant::now());
if let Some(entries) = fetched {
state.entries = Some(entries);
state.last_success = Some(Instant::now());
}
}
async fn refresh_if_stale(&self) {
let due = {
let state = self.inner.state.read().await;
match state.last_attempt {
None => true,
Some(at) => at.elapsed() >= self.inner.poll_interval,
}
};
if due {
self.refresh().await;
}
}
async fn fetch(&self) -> Option<HashSet<String>> {
let response = self
.inner
.http_client
.get(self.inner.feed_url.clone())
.send()
.await
.ok()?;
if !response.status().is_success() {
return None;
}
let document: FeedDocument = response.json().await.ok()?;
if document.alg != SUPPORTED_ALG {
return None;
}
if document.revoked.len() > MAX_ENTRIES {
return None;
}
Some(document.revoked.into_iter().collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_entry_is_base64url_unpadded_sha256_of_the_claim_string() {
let entry = RevocationFeed::entry_for("6f3e0a5c-1b2d-4e8f-9a7b-0c1d2e3f4a5b");
assert_eq!(entry, "i9N2lYMTV4FhA0husWjGYCqJXXTb7_fMBuomhWjSsgQ");
assert_eq!(entry.len(), 43);
assert!(!entry.contains('+') && !entry.contains('/') && !entry.contains('='));
}
#[test]
fn the_entry_never_normalises_the_claim() {
assert_ne!(
RevocationFeed::entry_for("6F3E0A5C-1B2D-4E8F-9A7B-0C1D2E3F4A5B"),
RevocationFeed::entry_for("6f3e0a5c-1b2d-4e8f-9a7b-0c1d2e3f4a5b"),
);
}
#[test]
fn the_poll_interval_is_clamped_rather_than_refused() {
let client = reqwest::Client::new();
let base = url::Url::parse("https://iam.example.test").unwrap();
let feed = RevocationFeed::new(client, &base)
.unwrap()
.with_poll_interval(Duration::from_millis(1));
assert_eq!(feed.inner.poll_interval, MIN_POLL_INTERVAL);
}
#[test]
fn the_debug_never_renders_the_cached_set() {
let client = reqwest::Client::new();
let base = url::Url::parse("https://iam.example.test").unwrap();
let feed = RevocationFeed::new(client, &base).unwrap();
let rendered = format!("{feed:?}");
assert!(rendered.contains("oauth2/revocations"));
assert!(!rendered.contains("entries"));
}
}