use crate::error::OAuthError;
use serde::Deserialize;
#[derive(Clone, Debug)]
pub(crate) struct IntrospectionConfig {
pub(crate) url: String,
pub(crate) client_id: String,
pub(crate) client_secret: String,
}
#[derive(Debug, Deserialize)]
pub(crate) struct IntrospectionResponse {
pub(crate) active: bool,
#[serde(default)]
pub(crate) sub: Option<String>,
#[serde(default)]
pub(crate) aud: Option<Audience>,
#[serde(default)]
pub(crate) iss: Option<String>,
#[serde(default)]
pub(crate) scope: Option<String>,
#[serde(default)]
pub(crate) exp: Option<u64>,
}
#[derive(Debug, Deserialize)]
#[serde(untagged)]
pub(crate) enum Audience {
One(String),
Many(Vec<String>),
}
impl Audience {
pub(crate) fn contains(&self, expected: &str) -> bool {
match self {
Self::One(aud) => aud == expected,
Self::Many(auds) => auds.iter().any(|aud| aud == expected),
}
}
}
pub(crate) async fn call(
http: &reqwest::Client,
cfg: &IntrospectionConfig,
bearer: &str,
) -> Result<IntrospectionResponse, OAuthError> {
let resp = http
.post(&cfg.url)
.basic_auth(&cfg.client_id, Some(&cfg.client_secret))
.form(&[("token", bearer)])
.send()
.await
.map_err(|e| OAuthError::IntrospectionFailed(format!("request failed: {e}")))?;
if !resp.status().is_success() {
return Err(OAuthError::IntrospectionFailed(format!(
"status {}",
resp.status()
)));
}
resp.json::<IntrospectionResponse>()
.await
.map_err(|e| OAuthError::IntrospectionFailed(format!("body: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn audience_string_matches_only_the_exact_value() {
let aud = Audience::One("klieo-test".into());
assert!(aud.contains("klieo-test"));
assert!(!aud.contains("other-resource-server"));
}
#[test]
fn audience_array_matches_any_member() {
let aud = Audience::Many(vec!["a".into(), "klieo-test".into()]);
assert!(aud.contains("klieo-test"));
assert!(aud.contains("a"));
assert!(!aud.contains("not-present"));
}
#[test]
fn audience_empty_array_matches_nothing() {
let aud = Audience::Many(vec![]);
assert!(!aud.contains("klieo-test"));
}
}