Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(mcp): add expires_in to token callback (#6053)

Will Hutchinson806217cec9e9
diff --git a/Cargo.lock b/Cargo.lock
index 36e947cecc..0f52c6be31 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -9869,6 +9869,7 @@ dependencies = [
"serde_json",
"sha2 0.10.9",
"thiserror 2.0.18",
+ "tokio",
"tower 0.5.3",
"tower-http",
"tracing",
diff --git a/crates/fusionauth/src/oauth.rs b/crates/fusionauth/src/oauth.rs
index 74450fd07c..5a7e016784 100644
--- a/crates/fusionauth/src/oauth.rs
+++ b/crates/fusionauth/src/oauth.rs
@@ -46,6 +46,17 @@ struct AuthorizationCodeGrantCompleteResponse<'a> {
// TODO: add other fields if we start to need them
}
+/// Tokens returned by a successful OAuth2 grant.
+#[derive(Debug)]
+pub struct OAuth2Grant {
+ /// The access token.
+ pub access_token: String,
+ /// The refresh token.
+ pub refresh_token: String,
+ /// Seconds until the access token expires, as reported by FusionAuth.
+ pub expires_in: u64,
+}
+
/// Completes the authorization code grant
/// https://fusionauth.io/docs/lifecycle/authenticate-users/oauth/endpoints#complete-the-authorization-code-grant-request
/// Valid respones: 200, 400, 401, 500, 503
@@ -53,7 +64,7 @@ async fn complete(
client: &UnauthedClient,
base_url: &str,
request: impl Serialize,
-) -> Result<(String, String)> {
+) -> Result<OAuth2Grant> {
let body = serde_urlencoded::to_string(&request).map_err(|e| {
FusionAuthClientError::Generic(GenericErrorResponse {
message: e.to_string(),
@@ -91,7 +102,11 @@ async fn complete(
})
})?;
- Ok((body.access_token.into(), body.refresh_token.into()))
+ Ok(OAuth2Grant {
+ access_token: body.access_token.into(),
+ refresh_token: body.refresh_token.into(),
+ expires_in: body.expires_in,
+ })
}
_ => {
let body = res.text().await.map_err(|e| {
@@ -112,7 +127,7 @@ async fn complete(
impl FusionAuthClient {
/// Completes the OAuth2 authorization code grant flow.
#[tracing::instrument(skip(self), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]
- pub async fn complete_authorization_code_grant(&self, code: &str) -> Result<(String, String)> {
+ pub async fn complete_authorization_code_grant(&self, code: &str) -> Result<OAuth2Grant> {
complete(
&self.unauth_client,
&self.fusion_auth_base_url,
@@ -129,10 +144,7 @@ impl FusionAuthClient {
/// complete the OAuth2 Refresh token grant flow.
#[tracing::instrument(skip(self), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]
- pub async fn complete_refresh_token_grant(
- &self,
- refresh_token: &str,
- ) -> Result<(String, String)> {
+ pub async fn complete_refresh_token_grant(&self, refresh_token: &str) -> Result<OAuth2Grant> {
complete(
&self.unauth_client,
&self.fusion_auth_base_url,
diff --git a/services/authentication_service/src/api/oauth/oauth_redirect.rs b/services/authentication_service/src/api/oauth/oauth_redirect.rs
index 1f0d2130f5..bcd3f7a841 100644
--- a/services/authentication_service/src/api/oauth/oauth_redirect.rs
+++ b/services/authentication_service/src/api/oauth/oauth_redirect.rs
@@ -85,12 +85,16 @@ pub async fn handler(
// Obviously this is not ideal, but will work for now.
sleep(Duration::from_millis(500)).await;
- let (access_token, refresh_token) = match ctx
+ let fusionauth::oauth::OAuth2Grant {
+ access_token,
+ refresh_token,
+ ..
+ } = match ctx
.auth_client
.complete_authorization_code_grant(&code)
.await
{
- Ok(tokens) => tokens,
+ Ok(grant) => grant,
Err(e) => {
tracing::error!(
auth_handoff_failure = "code_grant_failed",
diff --git a/services/mcp_auth_proxy/Cargo.toml b/services/mcp_auth_proxy/Cargo.toml
index aade21bd7a..0a30b408c8 100644
--- a/services/mcp_auth_proxy/Cargo.toml
+++ b/services/mcp_auth_proxy/Cargo.toml
@@ -35,3 +35,6 @@ url = { workspace = true }
urlencoding = { workspace = true }
uuid = { workspace = true }
workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }
+
+[dev-dependencies]
+tokio = { workspace = true }
diff --git a/services/mcp_auth_proxy/src/domain/models.rs b/services/mcp_auth_proxy/src/domain/models.rs
index 04a7a67682..90b6e15f9b 100644
--- a/services/mcp_auth_proxy/src/domain/models.rs
+++ b/services/mcp_auth_proxy/src/domain/models.rs
@@ -1,5 +1,5 @@
use serde::{Deserialize, Serialize};
-use std::fmt;
+use std::{fmt, time::SystemTime};
/// Upstream OAuth access token.
#[derive(Clone, Deserialize, Eq, Hash, PartialEq, Serialize)]
@@ -85,6 +85,17 @@ impl fmt::Debug for RefreshToken {
}
}
+/// A token grant obtained from the upstream OAuth provider.
+#[derive(Debug)]
+pub struct UpstreamTokens {
+ /// The upstream access token.
+ pub access_token: AccessToken,
+ /// The upstream refresh token.
+ pub refresh_token: RefreshToken,
+ /// Seconds until `access_token` expires, as reported by the provider.
+ pub expires_in: u64,
+}
+
/// A pending OAuth authorization flow initiated by the client.
#[derive(Clone)]
pub struct PendingAuthorization {
@@ -108,6 +119,9 @@ pub struct IssuedAuthorizationCode {
/// The redirect URI from the authorization request, used for exact-match
/// validation during token exchange.
pub redirect_uri: String,
+ /// When `access_token` expires. `None` for codes issued before the broker
+ /// started tracking upstream token lifetimes.
+ pub access_token_expires_at: Option<SystemTime>,
}
/// OAuth authorize request from the MCP client.
@@ -181,4 +195,8 @@ pub struct TokenResponse {
pub refresh_token: RefreshToken,
/// OAuth token type.
pub token_type: &'static str,
+ /// Seconds until `access_token` expires, so clients can refresh before it
+ /// does. Omitted when the upstream lifetime is unknown.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub expires_in: Option<u64>,
}
diff --git a/services/mcp_auth_proxy/src/domain/ports.rs b/services/mcp_auth_proxy/src/domain/ports.rs
index 240d133e68..1651629628 100644
--- a/services/mcp_auth_proxy/src/domain/ports.rs
+++ b/services/mcp_auth_proxy/src/domain/ports.rs
@@ -2,11 +2,11 @@
use std::{future::Future, pin::Pin};
-use super::models::{AccessToken, RefreshToken};
+use super::models::{RefreshToken, UpstreamTokens};
-/// Boxed future returning an access/refresh token pair.
-pub type TokenPairFuture<'a> =
- Pin<Box<dyn Future<Output = anyhow::Result<(AccessToken, RefreshToken)>> + Send + 'a>>;
+/// Boxed future returning a token grant from the upstream provider.
+pub type UpstreamTokensFuture<'a> =
+ Pin<Box<dyn Future<Output = anyhow::Result<UpstreamTokens>> + Send + 'a>>;
/// Upstream OAuth provider used by the broker.
pub trait OAuthProvider: Send + Sync {
@@ -14,8 +14,11 @@ pub trait OAuthProvider: Send + Sync {
fn construct_authorize_url(&self, state: &str) -> anyhow::Result<String>;
/// Exchanges an upstream authorization code for tokens.
- fn exchange_authorization_code<'a>(&'a self, code: &'a str) -> TokenPairFuture<'a>;
+ fn exchange_authorization_code<'a>(&'a self, code: &'a str) -> UpstreamTokensFuture<'a>;
/// Refreshes an upstream access token using the refresh token grant.
- fn refresh_access_token<'a>(&'a self, refresh_token: &'a RefreshToken) -> TokenPairFuture<'a>;
+ fn refresh_access_token<'a>(
+ &'a self,
+ refresh_token: &'a RefreshToken,
+ ) -> UpstreamTokensFuture<'a>;
}
diff --git a/services/mcp_auth_proxy/src/domain/service.rs b/services/mcp_auth_proxy/src/domain/service.rs
index 42da0ce16e..c85ccbae0e 100644
--- a/services/mcp_auth_proxy/src/domain/service.rs
+++ b/services/mcp_auth_proxy/src/domain/service.rs
@@ -1,8 +1,15 @@
//! Service implementation for the MCP OAuth broker.
+#[cfg(test)]
+mod test;
+
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use sha2::{Digest, Sha256};
-use std::{future::Future, sync::Arc, time::Duration};
+use std::{
+ future::Future,
+ sync::Arc,
+ time::{Duration, SystemTime},
+};
use super::{
models::{
@@ -116,16 +123,17 @@ where
.refresh_token
.ok_or(TokenExchangeError::RefreshTokenRequired)?;
- let (access_token, new_refresh_token) = self
+ let tokens = self
.oauth_provider
.refresh_access_token(&refresh_token)
.await
.map_err(TokenExchangeError::RefreshFailed)?;
Ok(TokenResponse {
- access_token,
- refresh_token: new_refresh_token,
+ access_token: tokens.access_token,
+ refresh_token: tokens.refresh_token,
token_type: "Bearer",
+ expires_in: Some(tokens.expires_in),
})
}
@@ -168,6 +176,7 @@ where
access_token: issued.access_token,
refresh_token: issued.refresh_token,
token_type: "Bearer",
+ expires_in: issued.access_token_expires_at.map(seconds_until),
})
}
}
@@ -306,21 +315,29 @@ where
let code = params.code.ok_or(CompleteCallbackError::MissingCode)?;
- let (access_token, refresh_token) = self
+ let tokens = self
.oauth_provider
.exchange_authorization_code(&code)
.await
.map_err(CompleteCallbackError::AuthorizationCodeExchangeFailed)?;
+ // The client may sit on the broker code for up to `AUTHORIZATION_CODE_TTL`
+ // before redeeming it, so record when the upstream token actually expires
+ // and count down from that at token exchange rather than replaying a stale
+ // `expires_in`.
+ let access_token_expires_at =
+ SystemTime::now().checked_add(Duration::from_secs(tokens.expires_in));
+
let issued_code = uuid::Uuid::new_v4().to_string();
self.inflight_auth
.insert_issued(
&issued_code,
IssuedAuthorizationCode {
- access_token,
- refresh_token,
+ access_token: tokens.access_token,
+ refresh_token: tokens.refresh_token,
code_challenge: pending.code_challenge,
redirect_uri: pending.client_redirect_uri.clone(),
+ access_token_expires_at,
},
)
.await
@@ -353,6 +370,15 @@ where
}
}
+/// Seconds from now until `deadline`, saturating at zero for a deadline that
+/// has already passed.
+fn seconds_until(deadline: SystemTime) -> u64 {
+ deadline
+ .duration_since(SystemTime::now())
+ .map(|remaining| remaining.as_secs())
+ .unwrap_or(0)
+}
+
fn is_allowed_redirect_uri(uri: &str) -> bool {
let Ok(parsed) = url::Url::parse(uri) else {
return false;
diff --git a/services/mcp_auth_proxy/src/domain/service/test.rs b/services/mcp_auth_proxy/src/domain/service/test.rs
new file mode 100644
index 0000000000..0c16c7a73c
--- /dev/null
+++ b/services/mcp_auth_proxy/src/domain/service/test.rs
@@ -0,0 +1,286 @@
+use super::*;
+
+use std::{
+ collections::HashMap,
+ sync::Mutex,
+ time::{Duration, SystemTime},
+};
+
+use crate::domain::models::{AccessToken, RefreshToken, UpstreamTokens};
+
+/// Upstream access token lifetime FusionAuth reports for a one hour JWT.
+const UPSTREAM_EXPIRES_IN: u64 = 3600;
+const CODE_VERIFIER: &str = "test-code-verifier";
+const REDIRECT_URI: &str = "http://localhost:41234/callback";
+
+fn code_challenge_for(verifier: &str) -> String {
+ URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
+}
+
+#[derive(Default)]
+struct FakeInflightAuth {
+ pending: Mutex<HashMap<String, PendingAuthorization>>,
+ issued: Mutex<HashMap<String, IssuedAuthorizationCode>>,
+}
+
+impl FakeInflightAuth {
+ fn with_issued(code: &str, issued: IssuedAuthorizationCode) -> Self {
+ let store = Self::default();
+ store.issued.lock().unwrap().insert(code.to_owned(), issued);
+ store
+ }
+}
+
+impl InflightAuthStore for FakeInflightAuth {
+ async fn insert_pending(
+ &self,
+ session_id: &str,
+ pending: PendingAuthorization,
+ ) -> anyhow::Result<()> {
+ self.pending
+ .lock()
+ .unwrap()
+ .insert(session_id.to_owned(), pending);
+ Ok(())
+ }
+
+ async fn take_pending(&self, session_id: &str) -> anyhow::Result<Option<PendingAuthorization>> {
+ Ok(self.pending.lock().unwrap().remove(session_id))
+ }
+
+ async fn insert_issued(
+ &self,
+ code: &str,
+ issued: IssuedAuthorizationCode,
+ ) -> anyhow::Result<()> {
+ self.issued.lock().unwrap().insert(code.to_owned(), issued);
+ Ok(())
+ }
+
+ async fn take_issued(&self, code: &str) -> anyhow::Result<Option<IssuedAuthorizationCode>> {
+ Ok(self.issued.lock().unwrap().remove(code))
+ }
+
+ async fn cleanup_expired(&self) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
+
+struct FakeOAuthProvider {
+ expires_in: u64,
+}
+
+impl OAuthProvider for FakeOAuthProvider {
+ fn construct_authorize_url(&self, state: &str) -> anyhow::Result<String> {
+ Ok(format!(
+ "https://upstream.example.com/authorize?state={state}"
+ ))
+ }
+
+ fn exchange_authorization_code<'a>(
+ &'a self,
+ _code: &'a str,
+ ) -> crate::domain::ports::UpstreamTokensFuture<'a> {
+ Box::pin(async move {
+ Ok(UpstreamTokens {
+ access_token: AccessToken::from("upstream-access"),
+ refresh_token: RefreshToken::from("upstream-refresh"),
+ expires_in: self.expires_in,
+ })
+ })
+ }
+
+ fn refresh_access_token<'a>(
+ &'a self,
+ _refresh_token: &'a RefreshToken,
+ ) -> crate::domain::ports::UpstreamTokensFuture<'a> {
+ Box::pin(async move {
+ Ok(UpstreamTokens {
+ access_token: AccessToken::from("refreshed-access"),
+ refresh_token: RefreshToken::from("refreshed-refresh"),
+ expires_in: self.expires_in,
+ })
+ })
+ }
+}
+
+fn service(store: FakeInflightAuth) -> McpAuthProxyServiceImpl<FakeInflightAuth> {
+ McpAuthProxyServiceImpl::new(
+ "https://mcp.example.com".to_owned(),
+ Arc::new(store),
+ Arc::new(FakeOAuthProvider {
+ expires_in: UPSTREAM_EXPIRES_IN,
+ }),
+ )
+}
+
+fn issued_code(access_token_expires_at: Option<SystemTime>) -> IssuedAuthorizationCode {
+ IssuedAuthorizationCode {
+ access_token: AccessToken::from("upstream-access"),
+ refresh_token: RefreshToken::from("upstream-refresh"),
+ code_challenge: code_challenge_for(CODE_VERIFIER),
+ redirect_uri: REDIRECT_URI.to_owned(),
+ access_token_expires_at,
+ }
+}
+
+fn authorization_code_request(code: &str) -> TokenRequest {
+ TokenRequest {
+ grant_type: "authorization_code".to_owned(),
+ code: Some(code.to_owned()),
+ code_verifier: Some(CODE_VERIFIER.to_owned()),
+ refresh_token: None,
+ redirect_uri: Some(REDIRECT_URI.to_owned()),
+ client_id: None,
+ }
+}
+
+#[tokio::test]
+async fn authorization_code_exchange_returns_remaining_lifetime() {
+ // Issued five minutes ago, so the client should be told what is left rather
+ // than the full upstream lifetime.
+ let expires_at = SystemTime::now() + Duration::from_secs(UPSTREAM_EXPIRES_IN - 300);
+ let service = service(FakeInflightAuth::with_issued(
+ "broker-code",
+ issued_code(Some(expires_at)),
+ ));
+
+ let response = service
+ .exchange_token(authorization_code_request("broker-code"))
+ .await
+ .expect("token exchange should succeed");
+
+ let expires_in = response.expires_in.expect("expires_in should be present");
+ assert!(
+ (UPSTREAM_EXPIRES_IN - 302..=UPSTREAM_EXPIRES_IN - 300).contains(&expires_in),
+ "expected roughly {} seconds remaining, got {expires_in}",
+ UPSTREAM_EXPIRES_IN - 300
+ );
+}
+
+#[tokio::test]
+async fn authorization_code_exchange_serializes_expires_in() {
+ let service = service(FakeInflightAuth::with_issued(
+ "broker-code",
+ issued_code(Some(
+ SystemTime::now() + Duration::from_secs(UPSTREAM_EXPIRES_IN),
+ )),
+ ));
+
+ let response = service
+ .exchange_token(authorization_code_request("broker-code"))
+ .await
+ .expect("token exchange should succeed");
+
+ let json = serde_json::to_value(&response).expect("response should serialize");
+ assert_eq!(json["token_type"], "Bearer");
+ assert!(
+ json.get("expires_in").is_some_and(|v| v.is_u64()),
+ "expires_in should be serialized as a number, got {json}"
+ );
+}
+
+#[tokio::test]
+async fn authorization_code_exchange_omits_unknown_expiry() {
+ // Codes issued before the broker tracked upstream lifetimes have no expiry,
+ // and must not report a fabricated one.
+ let service = service(FakeInflightAuth::with_issued(
+ "broker-code",
+ issued_code(None),
+ ));
+
+ let response = service
+ .exchange_token(authorization_code_request("broker-code"))
+ .await
+ .expect("token exchange should succeed");
+
+ assert_eq!(response.expires_in, None);
+ let json = serde_json::to_value(&response).expect("response should serialize");
+ assert!(
+ json.get("expires_in").is_none(),
+ "expires_in should be omitted when unknown, got {json}"
+ );
+}
+
+#[tokio::test]
+async fn expired_access_token_reports_zero_rather_than_underflowing() {
+ let service = service(FakeInflightAuth::with_issued(
+ "broker-code",
+ issued_code(Some(SystemTime::now() - Duration::from_secs(60))),
+ ));
+
+ let response = service
+ .exchange_token(authorization_code_request("broker-code"))
+ .await
+ .expect("token exchange should succeed");
+
+ assert_eq!(response.expires_in, Some(0));
+}
+
+#[tokio::test]
+async fn refresh_grant_returns_upstream_lifetime() {
+ let service = service(FakeInflightAuth::default());
+
+ let response = service
+ .exchange_token(TokenRequest {
+ grant_type: "refresh_token".to_owned(),
+ code: None,
+ code_verifier: None,
+ refresh_token: Some(RefreshToken::from("upstream-refresh")),
+ redirect_uri: None,
+ client_id: None,
+ })
+ .await
+ .expect("refresh exchange should succeed");
+
+ assert_eq!(response.expires_in, Some(UPSTREAM_EXPIRES_IN));
+ assert_eq!(response.access_token.as_str(), "refreshed-access");
+}
+
+#[tokio::test]
+async fn callback_records_upstream_expiry_on_the_issued_code() {
+ let store = Arc::new(FakeInflightAuth::default());
+ let service = McpAuthProxyServiceImpl::new(
+ "https://mcp.example.com".to_owned(),
+ Arc::clone(&store),
+ Arc::new(FakeOAuthProvider {
+ expires_in: UPSTREAM_EXPIRES_IN,
+ }),
+ );
+
+ store
+ .insert_pending(
+ "session-id",
+ PendingAuthorization {
+ code_challenge: code_challenge_for(CODE_VERIFIER),
+ client_state: "client-state".to_owned(),
+ client_redirect_uri: REDIRECT_URI.to_owned(),
+ },
+ )
+ .await
+ .expect("pending insert should succeed");
+
+ service
+ .complete_callback(CallbackRequest {
+ code: Some("upstream-code".to_owned()),
+ state: Some("session-id".to_owned()),
+ error: None,
+ error_description: None,
+ })
+ .await
+ .expect("callback should succeed");
+
+ let issued = store.issued.lock().unwrap();
+ let (_, stored) = issued.iter().next().expect("a code should be issued");
+ let expires_at = stored
+ .access_token_expires_at
+ .expect("issued code should record the upstream expiry");
+ let remaining = expires_at
+ .duration_since(SystemTime::now())
+ .expect("expiry should be in the future")
+ .as_secs();
+ assert!(
+ (UPSTREAM_EXPIRES_IN - 2..=UPSTREAM_EXPIRES_IN).contains(&remaining),
+ "expected roughly {UPSTREAM_EXPIRES_IN} seconds remaining, got {remaining}"
+ );
+}
diff --git a/services/mcp_auth_proxy/src/outbound/fusionauth.rs b/services/mcp_auth_proxy/src/outbound/fusionauth.rs
index 0c2d5c1d29..7d95cc76ab 100644
--- a/services/mcp_auth_proxy/src/outbound/fusionauth.rs
+++ b/services/mcp_auth_proxy/src/outbound/fusionauth.rs
@@ -5,8 +5,8 @@ use std::sync::Arc;
use tracing::Instrument;
use crate::domain::{
- models::RefreshToken,
- ports::{OAuthProvider, TokenPairFuture},
+ models::{RefreshToken, UpstreamTokens},
+ ports::{OAuthProvider, UpstreamTokensFuture},
};
/// FusionAuth-backed OAuth provider for the MCP auth proxy.
@@ -43,33 +43,44 @@ impl OAuthProvider for FusionAuthOAuthProvider {
)
}
- fn exchange_authorization_code<'a>(&'a self, code: &'a str) -> TokenPairFuture<'a> {
+ fn exchange_authorization_code<'a>(&'a self, code: &'a str) -> UpstreamTokensFuture<'a> {
let span = tracing::debug_span!("FusionAuthOAuthProvider::exchange_authorization_code");
Box::pin(
async move {
- let (access_token, refresh_token) = self
+ let grant = self
.client
.complete_authorization_code_grant(code)
.await
.map_err(anyhow::Error::from)?;
- Ok((access_token.into(), refresh_token.into()))
+ Ok(UpstreamTokens {
+ access_token: grant.access_token.into(),
+ refresh_token: grant.refresh_token.into(),
+ expires_in: grant.expires_in,
+ })
}
.instrument(span),
)
}
- fn refresh_access_token<'a>(&'a self, refresh_token: &'a RefreshToken) -> TokenPairFuture<'a> {
+ fn refresh_access_token<'a>(
+ &'a self,
+ refresh_token: &'a RefreshToken,
+ ) -> UpstreamTokensFuture<'a> {
let span = tracing::debug_span!("FusionAuthOAuthProvider::refresh_access_token");
Box::pin(
async move {
- let (access_token, refresh_token) = self
+ let grant = self
.client
.complete_refresh_token_grant(refresh_token.as_str())
.await
.map_err(anyhow::Error::from)?;
- Ok((access_token.into(), refresh_token.into()))
+ Ok(UpstreamTokens {
+ access_token: grant.access_token.into(),
+ refresh_token: grant.refresh_token.into(),
+ expires_in: grant.expires_in,
+ })
}
.instrument(span),
)
diff --git a/services/mcp_auth_proxy/src/outbound/redis.rs b/services/mcp_auth_proxy/src/outbound/redis.rs
index 8c8e47b952..e81bfb8b1e 100644
--- a/services/mcp_auth_proxy/src/outbound/redis.rs
+++ b/services/mcp_auth_proxy/src/outbound/redis.rs
@@ -2,7 +2,10 @@
use anyhow::Context;
use redis::AsyncCommands;
-use std::future::Future;
+use std::{
+ future::Future,
+ time::{Duration, UNIX_EPOCH},
+};
use crate::domain::{
models::{IssuedAuthorizationCode, PendingAuthorization},
@@ -66,6 +69,10 @@ struct StoredIssuedAuthorizationCode {
refresh_token: crate::domain::models::RefreshToken,
code_challenge: String,
redirect_uri: String,
+ /// Unix seconds at which the upstream access token expires. Defaults to
+ /// `None` so codes written before this field existed still deserialize.
+ #[serde(default)]
+ access_token_expires_at_unix: Option<u64>,
}
impl From<IssuedAuthorizationCode> for StoredIssuedAuthorizationCode {
@@ -75,6 +82,12 @@ impl From<IssuedAuthorizationCode> for StoredIssuedAuthorizationCode {
refresh_token: value.refresh_token,
code_challenge: value.code_challenge,
redirect_uri: value.redirect_uri,
+ access_token_expires_at_unix: value.access_token_expires_at.and_then(|expires_at| {
+ expires_at
+ .duration_since(UNIX_EPOCH)
+ .ok()
+ .map(|since_epoch| since_epoch.as_secs())
+ }),
}
}
}
@@ -86,6 +99,9 @@ impl From<StoredIssuedAuthorizationCode> for IssuedAuthorizationCode {
refresh_token: value.refresh_token,
code_challenge: value.code_challenge,
redirect_uri: value.redirect_uri,
+ access_token_expires_at: value
+ .access_token_expires_at_unix
+ .map(|unix_seconds| UNIX_EPOCH + Duration::from_secs(unix_seconds)),
}
}
}