use serde::Deserialize;
use crate::jwt::{jwt_account_id, jwt_exp};
use crate::store::{Cred, Secret};
pub const SKEW: u64 = 60;
pub fn is_expired(expires_at: u64, now: u64) -> bool {
now + SKEW >= expires_at
}
#[derive(Clone, PartialEq)]
pub struct Callback {
pub code: String,
pub state: String,
}
pub enum Grant<'a> {
AuthCode {
code: &'a str,
verifier: &'a str,
redirect_uri: &'a str,
state: Option<&'a str>,
},
Device {
device_code: &'a str,
},
Refresh {
refresh_token: &'a Secret,
},
}
#[derive(Clone, Debug, PartialEq)]
pub struct TokenResponse {
pub access_token: Secret,
pub refresh_token: Option<Secret>,
pub expires_at: u64,
pub scope: Option<String>,
pub account_id: Option<String>,
}
impl TokenResponse {
pub fn as_cred(
&self,
prior_refresh: &Secret,
prior_scope: &Option<String>,
prior_account_id: &Option<String>,
) -> Cred {
Cred::OAuth2 {
access_token: self.access_token.clone(),
refresh_token: self
.refresh_token
.clone()
.unwrap_or_else(|| prior_refresh.clone()),
expires_at: self.expires_at,
scope: self.scope.clone().or_else(|| prior_scope.clone()),
account_id: self.account_id.clone().or_else(|| prior_account_id.clone()),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum AuthError {
Pending,
SlowDown,
Fatal(String),
}
#[derive(Deserialize)]
struct RawToken {
access_token: Option<String>,
refresh_token: Option<String>,
expires_in: Option<u64>,
scope: Option<String>,
id_token: Option<String>,
error: Option<RawError>,
error_description: Option<String>,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum RawError {
Code(String),
Object {
#[serde(rename = "type")]
kind: Option<String>,
message: Option<String>,
},
}
const QUOTE: usize = 300;
fn clip(text: &str) -> String {
match text.char_indices().nth(QUOTE) {
Some((end, _)) => format!("{}…", &text[..end]),
None => text.to_owned(),
}
}
fn unreadable(bytes: &[u8]) -> String {
let text = String::from_utf8_lossy(bytes);
let keys = ["\"access_token\"", "\"refresh_token\"", "\"id_token\""];
if keys.iter().any(|key| text.contains(key)) {
return "unreadable token response (it carries a token, so it is not shown)".to_owned();
}
format!("unreadable token response: {}", clip(text.trim()))
}
pub fn parse_token_response(bytes: &[u8], now: u64) -> Result<TokenResponse, AuthError> {
let Ok(raw) = serde_json::from_slice::<RawToken>(bytes) else {
return Err(AuthError::Fatal(unreadable(bytes)));
};
if let Some(access) = raw.access_token {
let expires_at = match raw.expires_in {
Some(secs) => now.saturating_add(secs),
None => jwt_exp(&access).unwrap_or(now),
};
let account_id = raw.id_token.as_deref().and_then(jwt_account_id);
return Ok(TokenResponse {
access_token: Secret::new(access),
refresh_token: raw.refresh_token.map(Secret::new),
expires_at,
scope: raw.scope,
account_id,
});
}
let (code, detail) = match raw.error {
Some(RawError::Code(code)) => (Some(code), raw.error_description),
Some(RawError::Object { kind, message }) => (kind, message),
None => (None, None),
};
Err(match (code.as_deref(), detail) {
(Some("authorization_pending"), _) => AuthError::Pending,
(Some("slow_down"), _) => AuthError::SlowDown,
(Some(code), Some(detail)) => AuthError::Fatal(clip(&format!("{code}: {detail}"))),
(Some(code), None) => AuthError::Fatal(clip(code)),
(None, Some(detail)) => AuthError::Fatal(clip(&detail)),
(None, None) => AuthError::Fatal(unreadable(bytes)),
})
}