use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerMetadata {
pub issuer: String,
pub authorization_endpoint: String,
pub token_endpoint: String,
pub revocation_endpoint: String,
pub registration_endpoint: String,
pub scopes_supported: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenResponse {
pub access_token: String,
pub token_type: String,
pub expires_in: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TokenSet {
pub access_token: String,
pub refresh_token: String,
pub expires_at: String,
pub scope: String,
pub client_id: String,
pub server_url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClientRegistration {
pub client_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_secret: Option<String>,
}
pub fn token_set_is_expired(t: &TokenSet) -> bool {
use chrono::{DateTime, Utc};
match DateTime::parse_from_rfc3339(&t.expires_at) {
Ok(expires_at) => {
Utc::now() > expires_at.with_timezone(&Utc) - chrono::Duration::seconds(30)
}
Err(_) => true,
}
}
pub fn is_valid_token_set(x: &serde_json::Value) -> bool {
serde_json::from_value::<TokenSet>(x.clone()).is_ok()
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::{Duration, Utc};
fn token_with_expiry(expires_at: &str) -> TokenSet {
TokenSet {
access_token: "at".into(),
refresh_token: "rt".into(),
expires_at: expires_at.into(),
scope: "ai".into(),
client_id: "cid".into(),
server_url: "https://acosmi.com".into(),
}
}
#[test]
fn expired_when_in_the_past() {
let past = (Utc::now() - Duration::hours(1)).to_rfc3339();
assert!(token_set_is_expired(&token_with_expiry(&past)));
}
#[test]
fn not_expired_when_well_in_the_future() {
let future = (Utc::now() + Duration::hours(1)).to_rfc3339();
assert!(!token_set_is_expired(&token_with_expiry(&future)));
}
#[test]
fn expired_within_30s_skew_window() {
let soon = (Utc::now() + Duration::seconds(10)).to_rfc3339();
assert!(token_set_is_expired(&token_with_expiry(&soon)));
}
#[test]
fn not_expired_just_outside_30s_skew_window() {
let later = (Utc::now() + Duration::seconds(60)).to_rfc3339();
assert!(!token_set_is_expired(&token_with_expiry(&later)));
}
#[test]
fn illegal_expires_at_treated_as_expired() {
assert!(token_set_is_expired(&token_with_expiry("")));
assert!(token_set_is_expired(&token_with_expiry("not-a-date")));
let z = "2099-01-01T00:00:00Z";
assert!(!token_set_is_expired(&token_with_expiry(z)));
}
}