use std::collections::HashMap;
use serde::de::{Deserialize, Deserializer, Error as DeError};
use serde_json::{Map, Value};
use crate::{IdentityError, Result};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct IntrospectionAudience(pub Vec<String>);
impl IntrospectionAudience {
fn from_value(value: &Value) -> Result<Self> {
match value {
Value::Null => Ok(Self(Vec::new())),
Value::String(s) => Ok(Self(vec![s.clone()])),
Value::Array(items) => {
let mut out = Vec::with_capacity(items.len());
for item in items {
match item {
Value::String(s) => out.push(s.clone()),
_ => {
return Err(IdentityError::Deserialization(
"introspection \"aud\" invalid: array must contain only strings"
.to_string(),
));
}
}
}
Ok(Self(out))
}
_ => Err(IdentityError::Deserialization(
"introspection \"aud\" invalid: must be a string or array of strings".to_string(),
)),
}
}
pub fn contains(&self, s: &str) -> bool {
self.0.iter().any(|v| v == s)
}
pub fn values(&self) -> &[String] {
&self.0
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Introspection {
pub active: bool,
pub scope: Option<String>,
pub client_id: Option<String>,
pub username: Option<String>,
pub token_type: Option<String>,
pub exp: Option<i64>,
pub iat: Option<i64>,
pub nbf: Option<i64>,
pub sub: Option<String>,
pub aud: IntrospectionAudience,
pub iss: Option<String>,
pub jti: Option<String>,
pub extra: HashMap<String, Value>,
}
const STANDARD_MEMBERS: &[&str] = &[
"active",
"scope",
"client_id",
"username",
"token_type",
"exp",
"iat",
"nbf",
"sub",
"aud",
"iss",
"jti",
];
impl Introspection {
fn from_value(value: Value) -> Result<Self> {
let Value::Object(map) = value else {
return Err(IdentityError::Deserialization(
"introspection response is not a JSON object".to_string(),
));
};
Self::from_map(map)
}
fn from_map(map: Map<String, Value>) -> Result<Self> {
let active = match map.get("active") {
Some(Value::Bool(b)) => *b,
None | Some(Value::Null) => {
return Err(IdentityError::Deserialization(
"introspection response missing required \"active\" member (RFC 7662 §2.2)"
.to_string(),
));
}
Some(_) => {
return Err(IdentityError::Deserialization(
"introspection \"active\" member must be a boolean (RFC 7662 §2.2)".to_string(),
));
}
};
let scope = string_member(&map, "scope")?;
let client_id = string_member(&map, "client_id")?;
let username = string_member(&map, "username")?;
let token_type = string_member(&map, "token_type")?;
let sub = string_member(&map, "sub")?;
let iss = string_member(&map, "iss")?;
let jti = string_member(&map, "jti")?;
let exp = int_member(&map, "exp")?;
let iat = int_member(&map, "iat")?;
let nbf = int_member(&map, "nbf")?;
let aud = match map.get("aud") {
Some(v) => IntrospectionAudience::from_value(v)?,
None => IntrospectionAudience::default(),
};
let extra: HashMap<String, Value> = map
.into_iter()
.filter(|(k, _)| !STANDARD_MEMBERS.contains(&k.as_str()))
.collect();
Ok(Introspection {
active,
scope,
client_id,
username,
token_type,
exp,
iat,
nbf,
sub,
aud,
iss,
jti,
extra,
})
}
}
impl<'de> Deserialize<'de> for Introspection {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = Value::deserialize(deserializer)?;
Introspection::from_value(value).map_err(D::Error::custom)
}
}
fn string_member(map: &Map<String, Value>, name: &str) -> Result<Option<String>> {
match map.get(name) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(s.clone())),
Some(_) => Err(IdentityError::Deserialization(format!(
"introspection \"{name}\" invalid: must be a string"
))),
}
}
fn int_member(map: &Map<String, Value>, name: &str) -> Result<Option<i64>> {
match map.get(name) {
None | Some(Value::Null) => Ok(None),
Some(Value::Number(n)) => n.as_i64().map(Some).ok_or_else(|| {
IdentityError::Deserialization(format!(
"introspection \"{name}\" invalid: must be an integer number of seconds"
))
}),
Some(_) => Err(IdentityError::Deserialization(format!(
"introspection \"{name}\" invalid: must be a number"
))),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_active_response_with_extra() {
let json = r#"{
"active": true,
"scope": "read write dolphin",
"client_id": "l238j323ds-23ij4",
"username": "jdoe",
"token_type": "Bearer",
"exp": 1419356238,
"iat": 1419350238,
"nbf": 1419350238,
"sub": "Z5O3upPC88QrAjx00dis",
"aud": "https://protected.example.net/resource",
"iss": "https://issuer.example.com/",
"jti": "d3f5c9a1-2b7e-4c1a-9e8f-0a1b2c3d4e5f",
"extension_field": "twenty-seven"
}"#;
let ir: Introspection = serde_json::from_str(json).expect("parse");
assert!(ir.active);
assert_eq!(ir.scope.as_deref(), Some("read write dolphin"));
assert_eq!(ir.client_id.as_deref(), Some("l238j323ds-23ij4"));
assert_eq!(ir.username.as_deref(), Some("jdoe"));
assert_eq!(ir.token_type.as_deref(), Some("Bearer"));
assert_eq!(ir.exp, Some(1419356238));
assert_eq!(ir.iat, Some(1419350238));
assert_eq!(ir.nbf, Some(1419350238));
assert_eq!(ir.sub.as_deref(), Some("Z5O3upPC88QrAjx00dis"));
assert!(ir.aud.contains("https://protected.example.net/resource"));
assert_eq!(ir.iss.as_deref(), Some("https://issuer.example.com/"));
assert_eq!(
ir.jti.as_deref(),
Some("d3f5c9a1-2b7e-4c1a-9e8f-0a1b2c3d4e5f")
);
assert_eq!(
ir.extra.get("extension_field").and_then(Value::as_str),
Some("twenty-seven")
);
assert!(!ir.extra.contains_key("active"));
assert!(!ir.extra.contains_key("scope"));
}
#[test]
fn parses_active_minimal() {
let ir: Introspection = serde_json::from_str(r#"{"active": true}"#).expect("parse");
assert!(ir.active);
assert_eq!(ir.scope, None);
assert_eq!(ir.client_id, None);
assert!(ir.aud.values().is_empty());
assert!(ir.extra.is_empty());
}
#[test]
fn parses_inactive_response() {
let ir: Introspection = serde_json::from_str(r#"{"active": false}"#).expect("parse");
assert!(!ir.active);
assert_eq!(ir.username, None);
assert!(ir.extra.is_empty());
}
#[test]
fn rejects_missing_active() {
let err = serde_json::from_str::<Introspection>(r#"{"scope":"read"}"#)
.expect_err("missing active must fail");
assert!(err.to_string().contains("active"), "{err}");
}
#[test]
fn rejects_null_active() {
let err = serde_json::from_str::<Introspection>(r#"{"active":null}"#)
.expect_err("null active must fail");
assert!(err.to_string().contains("active"), "{err}");
}
#[test]
fn rejects_non_boolean_active() {
let err = serde_json::from_str::<Introspection>(r#"{"active":"true"}"#)
.expect_err("string active must fail");
assert!(err.to_string().contains("active"), "{err}");
}
#[test]
fn parses_audience_array() {
let ir: Introspection =
serde_json::from_str(r#"{"active":true,"aud":["a","b"]}"#).expect("parse");
assert_eq!(ir.aud.values(), ["a".to_string(), "b".to_string()]);
assert!(ir.aud.contains("b"));
}
#[test]
fn rejects_non_string_audience_element() {
let err = serde_json::from_str::<Introspection>(r#"{"active":true,"aud":["a",1]}"#)
.expect_err("numeric aud element must fail");
assert!(err.to_string().contains("aud"), "{err}");
}
#[test]
fn rejects_fractional_numeric_date() {
let err = serde_json::from_str::<Introspection>(r#"{"active":true,"exp":1419356238.5}"#)
.expect_err("fractional exp must fail, matching Go's int64 decode");
assert!(err.to_string().contains("exp"), "{err}");
}
}