Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(mcp): add OAuth token and grant revocation (#8977)
Wolf Mermelstein8fb4864c9831
diff --git a/crates/fusionauth/src/jwt.rs b/crates/fusionauth/src/jwt.rsindex 1699916755..4a198b8dac 100644--- a/crates/fusionauth/src/jwt.rs+++ b/crates/fusionauth/src/jwt.rs@@ -1,6 +1,9 @@use crate::{FusionAuthClient, Result};mod refresh;+mod revoke;+#[cfg(test)]+mod test;impl FusionAuthClient {/// Refreshes a JWT token using the provided access and refresh tokens.@@ -18,4 +21,11 @@ impl FusionAuthClient {).await}++ /// Revokes a refresh token so it can no longer be exchanged.+ #[tracing::instrument(skip_all, err, fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]+ pub async fn revoke_refresh_token(&self, refresh_token: &str) -> Result<()> {+ revoke::revoke_refresh_token(&self.auth_client, &self.fusion_auth_base_url, refresh_token)+ .await+ }}diff --git a/crates/fusionauth/src/jwt/revoke.rs b/crates/fusionauth/src/jwt/revoke.rsnew file mode 100644index 0000000000..4b96a2a8d3--- /dev/null+++ b/crates/fusionauth/src/jwt/revoke.rs@@ -0,0 +1,49 @@+use crate::{+ AuthedClient, Result,+ error::{FusionAuthClientError, GenericErrorResponse},+};++/// Revokes a single refresh token. A token FusionAuth does not know (already+/// revoked or expired) counts as revoked, so callers can retry.+/// The token goes in a form-encoded body, which FusionAuth accepts in place of+/// the `token` query parameter, so it stays out of URLs and request logs.+/// FusionAuth does not read a JSON body here.+/// https://fusionauth.io/docs/apis/jwt/revoke-refresh-tokens+/// Valid responses: 200, 400, 401, 404, 500, 503+pub(crate) async fn revoke_refresh_token(+ client: &AuthedClient,+ base_url: &str,+ refresh_token: &str,+) -> Result<()> {+ let res = client+ .client()+ .delete(format!("{base_url}/api/jwt/refresh"))+ .form(&[("token", refresh_token)])+ .send()+ .await+ .map_err(|e| {+ FusionAuthClientError::Generic(GenericErrorResponse {+ message: e.to_string(),+ })+ })?;++ match res.status() {+ reqwest::StatusCode::OK | reqwest::StatusCode::NOT_FOUND => {+ tracing::trace!("refresh token revoked");+ Ok(())+ }+ status => {+ let body = res.text().await.map_err(|e| {+ FusionAuthClientError::Generic(GenericErrorResponse {+ message: e.to_string(),+ })+ })?;++ tracing::error!(body=%body, %status, "unexpected response from fusionauth");++ Err(FusionAuthClientError::Generic(GenericErrorResponse {+ message: body,+ }))+ }+ }+}diff --git a/crates/fusionauth/src/jwt/test.rs b/crates/fusionauth/src/jwt/test.rsnew file mode 100644index 0000000000..268697b0c3--- /dev/null+++ b/crates/fusionauth/src/jwt/test.rs@@ -0,0 +1,67 @@+use wiremock::matchers::{body_string, header, method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++use crate::FusionAuthClient;++fn client(base_url: String) -> FusionAuthClient {+ FusionAuthClient::new(+ "api-key".into(),+ "application-id".into(),+ "client-secret".into(),+ base_url,+ "http://localhost:28011/oauth/redirect".into(),+ "google-client-id".into(),+ "google-client-secret".into(),+ )+}++#[tokio::test]+async fn revoke_refresh_token_sends_the_token_form_encoded() {+ let server = MockServer::start().await;+ Mock::given(method("DELETE"))+ .and(path("/api/jwt/refresh"))+ .and(header("authorization", "api-key"))+ .and(header("content-type", "application/x-www-form-urlencoded"))+ .and(body_string("token=refresh-token"))+ .respond_with(ResponseTemplate::new(200))+ .expect(1)+ .mount(&server)+ .await;++ client(server.uri())+ .revoke_refresh_token("refresh-token")+ .await+ .expect("revocation should succeed");+}++#[tokio::test]+async fn revoke_refresh_token_treats_an_unknown_token_as_revoked() {+ let server = MockServer::start().await;+ Mock::given(method("DELETE"))+ .and(path("/api/jwt/refresh"))+ .respond_with(ResponseTemplate::new(404))+ .expect(1)+ .mount(&server)+ .await;++ client(server.uri())+ .revoke_refresh_token("already-revoked")+ .await+ .expect("an unknown token is already revoked");+}++#[tokio::test]+async fn revoke_refresh_token_reports_a_server_error() {+ let server = MockServer::start().await;+ Mock::given(method("DELETE"))+ .and(path("/api/jwt/refresh"))+ .respond_with(ResponseTemplate::new(503).set_body_string("unavailable"))+ .expect(1)+ .mount(&server)+ .await;++ client(server.uri())+ .revoke_refresh_token("refresh-token")+ .await+ .expect_err("a server error must not count as a revocation");+}diff --git a/services/mcp_auth_proxy/AGENTS.md b/services/mcp_auth_proxy/AGENTS.mdindex b538ccf499..5141efb0e0 100644--- a/services/mcp_auth_proxy/AGENTS.md+++ b/services/mcp_auth_proxy/AGENTS.md@@ -11,7 +11,8 @@ in front of FusionAuth, which doesn't support DCR itself.- `README.md`: the security model — which redirect URIs are usable, and whichclient a grant belongs to. Read before touching `/register`, `/authorize`,- or `/token` logic.+ or `/token` logic, and its "Disconnecting a client" section before touching+ `/revoke`.- `src/domain/service.rs` + `src/domain/service/test.rs`: the broker's corelogic (registration, authorize, token/refresh).- `src/domain/redirect_uri.rs`: the redirect URI usability policy from the README.@@ -23,8 +24,9 @@ in front of FusionAuth, which doesn't support DCR itself.## Scope-- Owns: DCR-compliant client registration, authorization-code issuance, and- refresh-token rotation/binding, all proxied in front of FusionAuth.+- Owns: DCR-compliant client registration, authorization-code issuance,+ refresh-token rotation/binding, and RFC 7009 revocation, all proxied in+ front of FusionAuth.- Not here: the MCP tool surface itself → `services/agent_harness_service/src/public_mcp.rs`.## Recipes@@ -53,6 +55,9 @@ and other library consumers. Both retain OAuth metadata, CORS, and bearer auth.- Refresh tokens are bound by SHA-256 digest with rotate-before-drop ordering;don't weaken that to avoid a race, and remember pre-binding-era refreshtokens have no binding (clients reauthorize once).+- A binding carries the grant id of its token family; rotation must copy it+ and refresh must check the revoked-grant marker, or `/revoke` stops covering+ rotated tokens. Bindings stored as a bare client id are their own family.## Relateddiff --git a/services/mcp_auth_proxy/README.md b/services/mcp_auth_proxy/README.mdindex 74a3cb34a0..51babe9699 100644--- a/services/mcp_auth_proxy/README.md+++ b/services/mcp_auth_proxy/README.md@@ -56,3 +56,36 @@ Refresh tokens issued before this scheme existed have no binding, so the clientsholding them authorize once more. Rate limiting of `/register` belongs at theedge; the broker bounds each registration's size but not how many a caller maycreate.++## Disconnecting a client++`/revoke` implements RFC 7009 and is advertised as `revocation_endpoint` in+the authorization server metadata. A client disconnecting from Macro posts its+refresh token there as a form:++```+POST /revoke+Content-Type: application/x-www-form-urlencoded++token=<refresh token>&token_type_hint=refresh_token&client_id=<client id>+```++`client_id` is required (`401 invalid_client` without it) and is the client+authentication RFC 7009 asks for: these are public clients, so the request must+come from the client the refresh token is bound to. Another client's+`client_id` gets `400 invalid_grant` and leaves the grant untouched.++A revocation revokes the whole grant, not just the presented token. Every+refresh token rotated out of one authorization code shares the grant id on its+binding, and the broker records the grant as revoked for as long as any binding+can outlive it, so no token from the family is refreshed again. It also revokes+the token in FusionAuth and drops its binding. Each step is idempotent and the+binding goes last, so a client that sees a `503` can retry. A token the broker+does not hold (never issued, expired, or already revoked) gets `200`, as RFC+7009 section 2.2 requires.++Access tokens are FusionAuth JWTs and are not revocable: presenting one gets+`400 unsupported_token_type`. Revocation does not cut them short, so an access+token issued before the revocation stays valid until it expires. Every token+response carries `expires_in`, which is that remaining window; FusionAuth signs+them for one hour (`ttlSeconds` in `infra/stacks/fusionauth-instance`).diff --git a/services/mcp_auth_proxy/src/domain/models.rs b/services/mcp_auth_proxy/src/domain/models.rsindex 44344337ab..e55eabbfd9 100644--- a/services/mcp_auth_proxy/src/domain/models.rs+++ b/services/mcp_auth_proxy/src/domain/models.rs@@ -178,9 +178,8 @@ 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>,+ /// When `access_token` expires.+ pub access_token_expires_at: SystemTime,}/// OAuth authorize request from the MCP client.@@ -258,7 +257,34 @@ pub struct TokenResponse {/// 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>,+ /// does. Revocation does not cut an access token short, so this is also the+ /// longest it stays usable after its grant is revoked.+ pub expires_in: u64,+}++/// The client and grant an outstanding refresh token belongs to.+#[derive(Clone, Debug, Eq, PartialEq)]+pub struct RefreshTokenBinding {+ /// The client that obtained the refresh token.+ pub client_id: String,+ /// The authorization this refresh token descends from. Every token rotated+ /// out of one authorization code shares it, so revoking it revokes the+ /// whole family.+ pub grant_id: String,+}++/// RFC 7009 token revocation request from the MCP client.+///+/// `token_type_hint` is accepted and ignored: RFC 7009 makes it optional, and+/// the broker looks the token up the same way whatever its type.+#[derive(Deserialize)]+pub struct RevocationRequest {+ /// The token to revoke.+ #[serde(default)]+ pub token: Option<RefreshToken>,+ /// The client revoking the token. Public clients hold no credential, so+ /// this is the client authentication RFC 7009 requires, and it must match+ /// the client the token was issued to.+ #[serde(default)]+ pub client_id: Option<String>,}diff --git a/services/mcp_auth_proxy/src/domain/ports.rs b/services/mcp_auth_proxy/src/domain/ports.rsindex 29abfb3384..052b92d76c 100644--- a/services/mcp_auth_proxy/src/domain/ports.rs+++ b/services/mcp_auth_proxy/src/domain/ports.rs@@ -2,7 +2,7 @@use std::{future::Future, pin::Pin};-use super::models::{RefreshToken, RegisteredClient, UpstreamTokens};+use super::models::{RefreshToken, RefreshTokenBinding, RegisteredClient, UpstreamTokens};/// Boxed future returning a token grant from the upstream provider.pub type UpstreamTokensFuture<'a> =@@ -15,9 +15,16 @@ pub type StoreWriteFuture<'a> = Pin<Box<dyn Future<Output = anyhow::Result<()>>pub type RegisteredClientFuture<'a> =Pin<Box<dyn Future<Output = anyhow::Result<Option<RegisteredClient>>> + Send + 'a>>;-/// Boxed future returning a client id, if one is bound.-pub type BoundClientIdFuture<'a> =- Pin<Box<dyn Future<Output = anyhow::Result<Option<String>>> + Send + 'a>>;+/// Boxed future returning a refresh token binding, if one exists.+pub type RefreshTokenBindingFuture<'a> =+ Pin<Box<dyn Future<Output = anyhow::Result<Option<RefreshTokenBinding>>> + Send + 'a>>;++/// Boxed future returning whether a grant has been revoked.+pub type GrantRevokedFuture<'a> = Pin<Box<dyn Future<Output = anyhow::Result<bool>> + Send + 'a>>;++/// Boxed future returning nothing once the upstream provider has acted.+pub type UpstreamRevocationFuture<'a> =+ Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'a>>;/// Store of clients created through dynamic client registration.///@@ -36,24 +43,32 @@ pub trait ClientRegistrationStore: Send + Sync {fn find_client<'a>(&'a self, client_id: &'a str) -> RegisteredClientFuture<'a>;}-/// Store recording which client each outstanding refresh token was issued to.+/// Store recording which client and grant each outstanding refresh token was+/// issued to, and which grants have been revoked.////// Refresh tokens are keyed by digest rather than by their own value so the/// store never holds a usable credential.pub trait RefreshTokenBindingStore: Send + Sync {- /// Binds a refresh token digest to the client that obtained it, replacing- /// any existing binding for that digest.+ /// Binds a refresh token digest to the client and grant it belongs to,+ /// replacing any existing binding for that digest.fn bind<'a>(&'a self,refresh_token_digest: &'a str,- client_id: &'a str,+ binding: &'a RefreshTokenBinding,) -> StoreWriteFuture<'a>;- /// Returns the client a refresh token digest is bound to, if any.- fn bound_client<'a>(&'a self, refresh_token_digest: &'a str) -> BoundClientIdFuture<'a>;+ /// Returns the binding for a refresh token digest, if any.+ fn binding<'a>(&'a self, refresh_token_digest: &'a str) -> RefreshTokenBindingFuture<'a>;/// Drops the binding for a refresh token digest.fn unbind<'a>(&'a self, refresh_token_digest: &'a str) -> StoreWriteFuture<'a>;++ /// Records that a grant is revoked, so no refresh token in its family is+ /// honored again. Must outlive every binding that names the grant.+ fn revoke_grant<'a>(&'a self, grant_id: &'a str) -> StoreWriteFuture<'a>;++ /// Returns whether a grant has been revoked.+ fn is_grant_revoked<'a>(&'a self, grant_id: &'a str) -> GrantRevokedFuture<'a>;}/// Upstream OAuth provider used by the broker.@@ -69,4 +84,11 @@ pub trait OAuthProvider: Send + Sync {&'a self,refresh_token: &'a RefreshToken,) -> UpstreamTokensFuture<'a>;++ /// Revokes an upstream refresh token. Succeeds when the provider no longer+ /// knows the token, so a revocation can be retried.+ fn revoke_refresh_token<'a>(+ &'a self,+ refresh_token: &'a RefreshToken,+ ) -> UpstreamRevocationFuture<'a>;}diff --git a/services/mcp_auth_proxy/src/domain/service.rs b/services/mcp_auth_proxy/src/domain/service.rsindex fc84e8609a..a691531221 100644--- a/services/mcp_auth_proxy/src/domain/service.rs+++ b/services/mcp_auth_proxy/src/domain/service.rs@@ -14,8 +14,8 @@ use std::{use super::{models::{AuthorizeRequest, CallbackRequest, ClientRegistrationRequest, ClientRegistrationResponse,- IssuedAuthorizationCode, PendingAuthorization, RefreshToken, RegisteredClient,- TokenRequest, TokenResponse,+ IssuedAuthorizationCode, PendingAuthorization, RefreshToken, RefreshTokenBinding,+ RegisteredClient, RevocationRequest, TokenRequest, TokenResponse,},ports::{ClientRegistrationStore, OAuthProvider, RefreshTokenBindingStore},redirect_uri::RedirectUriPolicy,@@ -31,6 +31,10 @@ pub const CLIENT_REGISTRATION_TTL: Duration = Duration::from_secs(90 * 24 * 60 */// refresh tokens on a 30-day sliding window and each broker refresh re-binds,/// so a binding outlives every refresh token that can still be redeemed.pub const REFRESH_TOKEN_BINDING_TTL: Duration = Duration::from_secs(30 * 24 * 60 * 60);+/// How long a grant revocation is remembered. A binding is re-armed for at+/// most `REFRESH_TOKEN_BINDING_TTL` from its last write, so a revocation kept+/// as long outlives every binding in the family it revokes.+pub const REVOKED_GRANT_TTL: Duration = REFRESH_TOKEN_BINDING_TTL;/// Redirect URIs accepted per registration. Enough for a client that offers/// several callbacks, low enough that open registration cannot be used to@@ -65,6 +69,11 @@ pub trait McpAuthProxyService: Clone + Send + Sync + 'static {&self,params: TokenRequest,) -> impl Future<Output = Result<TokenResponse, TokenExchangeError>> + Send;+ /// Revokes the refresh token family a token belongs to (RFC 7009).+ fn revoke_token(+ &self,+ params: RevocationRequest,+ ) -> impl Future<Output = Result<(), RevokeTokenError>> + Send;/// Removes expired broker state when required by the backing store.fn cleanup_expired(&self) -> impl Future<Output = anyhow::Result<()>> + Send;}@@ -197,14 +206,14 @@ where.ok_or(TokenExchangeError::RefreshTokenRequired)?;let presented_digest = refresh_token_digest(&refresh_token);- let bound_client_id = self+ let binding = self.refresh_token_bindings- .bound_client(&presented_digest)+ .binding(&presented_digest).await.map_err(TokenExchangeError::RefreshTokenBindingStore)?.ok_or(TokenExchangeError::UnboundRefreshToken)?;- if bound_client_id != client_id {+ if binding.client_id != client_id {tracing::warn!(%client_id,"refresh token presented by a client it was not issued to"@@ -212,6 +221,18 @@ wherereturn Err(TokenExchangeError::ClientMismatch);}+ // A revocation that raced a refresh can leave a binding behind for the+ // token that refresh rotated to; the grant marker refuses it anyway.+ if self+ .refresh_token_bindings+ .is_grant_revoked(&binding.grant_id)+ .await+ .map_err(TokenExchangeError::RefreshTokenBindingStore)?+ {+ tracing::warn!(%client_id, grant_id = %binding.grant_id, "refresh token from a revoked grant");+ return Err(TokenExchangeError::RevokedGrant);+ }+let tokens = self.oauth_provider.refresh_access_token(&refresh_token)@@ -225,7 +246,7 @@ where// costs them the session outright. So log and hand the token over.let rebound = self.refresh_token_bindings- .bind(&rotated_digest, &client_id)+ .bind(&rotated_digest, &binding).await.inspect_err(|error| {tracing::error!(error=?error, %client_id, "failed to bind rotated refresh token");@@ -249,7 +270,7 @@ whereaccess_token: tokens.access_token,refresh_token: tokens.refresh_token,token_type: "Bearer",- expires_in: Some(tokens.expires_in),+ expires_in: tokens.expires_in,})}@@ -307,7 +328,10 @@ whereself.refresh_token_bindings.bind(&refresh_token_digest(&issued.refresh_token),- &issued.client_id,+ &RefreshTokenBinding {+ client_id: issued.client_id,+ grant_id: uuid::Uuid::new_v4().to_string(),+ },).await.map_err(TokenExchangeError::RefreshTokenBindingStore)?;@@ -316,7 +340,7 @@ whereaccess_token: issued.access_token,refresh_token: issued.refresh_token,token_type: "Bearer",- expires_in: issued.access_token_expires_at.map(seconds_until),+ expires_in: seconds_until(issued.access_token_expires_at),})}}@@ -334,6 +358,8 @@ where"authorization_endpoint": format!("{base}/authorize"),"token_endpoint": format!("{base}/token"),"registration_endpoint": format!("{base}/register"),+ "revocation_endpoint": format!("{base}/revoke"),+ "revocation_endpoint_auth_methods_supported": ["none"],"response_types_supported": ["code"],"grant_types_supported": ["authorization_code", "refresh_token"],"code_challenge_methods_supported": ["S256"],@@ -512,8 +538,14 @@ where// 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 access_token_expires_at = SystemTime::now()+ .checked_add(Duration::from_secs(tokens.expires_in))+ .ok_or_else(|| {+ CompleteCallbackError::AuthorizationCodeExchangeFailed(anyhow::anyhow!(+ "upstream expires_in {} is out of range",+ tokens.expires_in+ ))+ })?;let issued_code = uuid::Uuid::new_v4().to_string();self.inflight_auth@@ -553,6 +585,57 @@ where}}+ /// Revokes the refresh token family a token belongs to.+ ///+ /// Every step is idempotent and the binding is dropped last, so a client+ /// that gets an error can retry and finish the revocation. A token the+ /// broker does not know (never issued, expired, or already revoked) is not+ /// an error, as RFC 7009 section 2.2 requires.+ #[tracing::instrument(skip_all, err, fields(client_id = params.client_id.as_deref(), grant_id))]+ async fn revoke_token(&self, params: RevocationRequest) -> Result<(), RevokeTokenError> {+ let client_id = params.client_id.ok_or(RevokeTokenError::ClientIdRequired)?;+ let token = params.token.ok_or(RevokeTokenError::TokenRequired)?;++ let digest = refresh_token_digest(&token);+ let Some(binding) = self+ .refresh_token_bindings+ .binding(&digest)+ .await+ .map_err(RevokeTokenError::RefreshTokenBindingStore)?+ else {+ // Access tokens are FusionAuth JWTs, which the broker cannot+ // revoke; say so rather than reporting a revocation that did not+ // happen. Refresh tokens are opaque, so a JWT is never one.+ if token.as_str().split('.').count() == 3 {+ return Err(RevokeTokenError::UnsupportedTokenType);+ }+ tracing::info!("revocation of a token the broker does not hold");+ return Ok(());+ };+ tracing::Span::current().record("grant_id", binding.grant_id.as_str());++ if binding.client_id != client_id {+ tracing::warn!("revocation by a client the token was not issued to");+ return Err(RevokeTokenError::ClientMismatch);+ }++ self.refresh_token_bindings+ .revoke_grant(&binding.grant_id)+ .await+ .map_err(RevokeTokenError::RefreshTokenBindingStore)?;+ self.oauth_provider+ .revoke_refresh_token(&token)+ .await+ .map_err(RevokeTokenError::UpstreamRevocationFailed)?;+ self.refresh_token_bindings+ .unbind(&digest)+ .await+ .map_err(RevokeTokenError::RefreshTokenBindingStore)?;++ tracing::info!("refresh token grant revoked");+ Ok(())+ }+/// Removes expired pending sessions and broker-issued codes.async fn cleanup_expired(&self) -> anyhow::Result<()> {self.inflight_auth.cleanup_expired().await@@ -696,6 +779,9 @@ pub enum TokenExchangeError {/// tell which client it belongs to.#[error("refresh token is not bound to a client")]UnboundRefreshToken,+ /// The refresh token belongs to a grant that has been revoked.+ #[error("refresh token has been revoked")]+ RevokedGrant,/// Inflight auth state could not be loaded or updated.#[error("failed to access inflight auth state")]InflightStore(anyhow::Error),@@ -706,3 +792,26 @@ pub enum TokenExchangeError {#[error("refresh token exchange failed")]RefreshFailed(anyhow::Error),}++/// Errors returned when revoking a token.+#[derive(Debug, thiserror::Error)]+pub enum RevokeTokenError {+ /// The client_id was absent, so the revoking client is unidentified.+ #[error("client_id required")]+ ClientIdRequired,+ /// The token parameter was absent.+ #[error("token required")]+ TokenRequired,+ /// The token is an access token, which the broker cannot revoke.+ #[error("access tokens cannot be revoked")]+ UnsupportedTokenType,+ /// The token was issued to a different client than the one revoking it.+ #[error("token was not issued to this client")]+ ClientMismatch,+ /// Refresh token bindings could not be read or written.+ #[error("failed to access refresh token bindings")]+ RefreshTokenBindingStore(anyhow::Error),+ /// The upstream provider did not revoke the refresh token.+ #[error("upstream refresh token revocation failed")]+ UpstreamRevocationFailed(anyhow::Error),+}diff --git a/services/mcp_auth_proxy/src/domain/service/test.rs b/services/mcp_auth_proxy/src/domain/service/test.rsindex da0b9ede93..5c8ca72fc8 100644--- a/services/mcp_auth_proxy/src/domain/service/test.rs+++ b/services/mcp_auth_proxy/src/domain/service/test.rs@@ -427,6 +427,218 @@ async fn rotated_refresh_token_is_rebound_and_the_old_one_is_refused() {assert!(rotated.is_ok(), "the rotated token must be usable");}+// --- Revocation ------------------------------------------------------++/// Takes `client_id` through authorize, callback, and code exchange, returning+/// the refresh token it ends up holding.+async fn obtain_refresh_token(harness: &Harness, client_id: &str) -> RefreshToken {+ let code = harness+ .complete_flow_to_code(client_id, TRUSTED_REDIRECT_URI, VICTIM_CODE_VERIFIER)+ .await;+ harness+ .service+ .exchange_token(authorization_code_request(&code, client_id))+ .await+ .expect("code exchange should succeed")+ .refresh_token+}++fn refresh_request(refresh_token: RefreshToken, client_id: &str) -> TokenRequest {+ TokenRequest {+ grant_type: "refresh_token".to_owned(),+ code: None,+ code_verifier: None,+ refresh_token: Some(refresh_token),+ redirect_uri: None,+ client_id: Some(client_id.to_owned()),+ }+}++#[tokio::test]+async fn revoked_refresh_token_cannot_mint_access_tokens() {+ let harness = Harness::new();+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;+ let refresh_token = obtain_refresh_token(&harness, &client_id).await;++ harness+ .service+ .revoke_token(RevocationRequest {+ token: Some(refresh_token.clone()),+ client_id: Some(client_id.clone()),+ })+ .await+ .expect("the owning client should be able to revoke");++ assert!(+ harness.provider.revoked(UPSTREAM_REFRESH_TOKEN),+ "the upstream refresh token must be revoked too"+ );+ let error = harness+ .service+ .exchange_token(refresh_request(refresh_token, &client_id))+ .await+ .expect_err("a revoked refresh token must not mint an access token");+ assert!(matches!(error, TokenExchangeError::UnboundRefreshToken));+}++#[tokio::test]+async fn revoking_twice_succeeds() {+ let harness = Harness::new();+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;+ let refresh_token = obtain_refresh_token(&harness, &client_id).await;++ for _ in 0..2 {+ harness+ .service+ .revoke_token(RevocationRequest {+ token: Some(refresh_token.clone()),+ client_id: Some(client_id.clone()),+ })+ .await+ .expect("revocation must be idempotent");+ }+}++/// An expired refresh token's binding has lapsed, so to the broker it is the+/// same as one it never issued; RFC 7009 answers both with success.+#[tokio::test]+async fn revoking_an_unknown_or_expired_refresh_token_succeeds() {+ let harness = Harness::new();+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;++ harness+ .service+ .revoke_token(RevocationRequest {+ token: Some(RefreshToken::from("never-issued-or-expired")),+ client_id: Some(client_id),+ })+ .await+ .expect("an unknown token is not an error");++ assert!(+ !harness.provider.revoked("never-issued-or-expired"),+ "the broker must not forward a token it does not hold"+ );+}++#[tokio::test]+async fn another_client_cannot_revoke_the_grant() {+ let harness = Harness::new();+ let owner_client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;+ let other_client_id = harness.register(&[LOOPBACK_REDIRECT_URI]).await;+ let refresh_token = obtain_refresh_token(&harness, &owner_client_id).await;++ let error = harness+ .service+ .revoke_token(RevocationRequest {+ token: Some(refresh_token.clone()),+ client_id: Some(other_client_id),+ })+ .await+ .expect_err("a client must not revoke another client's grant");+ assert!(matches!(error, RevokeTokenError::ClientMismatch));++ assert!(!harness.provider.revoked(UPSTREAM_REFRESH_TOKEN));+ harness+ .service+ .exchange_token(refresh_request(refresh_token, &owner_client_id))+ .await+ .expect("the owner's grant must survive the refused revocation");+}++#[tokio::test]+async fn revocation_requires_a_client_id() {+ let harness = Harness::new();+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;+ let refresh_token = obtain_refresh_token(&harness, &client_id).await;++ let error = harness+ .service+ .revoke_token(RevocationRequest {+ token: Some(refresh_token.clone()),+ client_id: None,+ })+ .await+ .expect_err("an unidentified client must not revoke anything");+ assert!(matches!(error, RevokeTokenError::ClientIdRequired));++ harness+ .service+ .exchange_token(refresh_request(refresh_token, &client_id))+ .await+ .expect("the grant must survive the refused revocation");+}++#[tokio::test]+async fn revoking_an_access_token_is_reported_as_unsupported() {+ let harness = Harness::new();+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;++ let error = harness+ .service+ .revoke_token(RevocationRequest {+ token: Some(RefreshToken::from(+ "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyIn0.c2lnbmF0dXJl",+ )),+ client_id: Some(client_id),+ })+ .await+ .expect_err("the broker cannot revoke a JWT access token");+ assert!(matches!(error, RevokeTokenError::UnsupportedTokenType));+}++/// A refresh that races a revocation can leave a binding behind for a token+/// rotated out of the revoked grant. The grant marker must refuse it.+#[tokio::test]+async fn revocation_refuses_every_token_in_the_family() {+ let harness = Harness::new();+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;+ let refresh_token = obtain_refresh_token(&harness, &client_id).await;+ let binding = harness+ .registry+ .binding(&refresh_token_digest(&refresh_token))+ .await+ .expect("lookup should succeed")+ .expect("the issued token should be bound");+ harness+ .registry+ .bind(+ &refresh_token_digest(&RefreshToken::from("rotated-refresh-token")),+ &binding,+ )+ .await+ .expect("seeding the rotated binding should succeed");++ harness+ .service+ .revoke_token(RevocationRequest {+ token: Some(refresh_token),+ client_id: Some(client_id.clone()),+ })+ .await+ .expect("the owning client should be able to revoke");++ let error = harness+ .service+ .exchange_token(refresh_request(+ RefreshToken::from("rotated-refresh-token"),+ &client_id,+ ))+ .await+ .expect_err("a token from the revoked family must not mint an access token");+ assert!(matches!(error, TokenExchangeError::RevokedGrant));+}++#[test]+fn authorization_server_metadata_advertises_revocation() {+ let json = Harness::new().service.authorization_server_metadata();+ assert_eq!(json["revocation_endpoint"], "https://mcp.macro.com/revoke");+ assert_eq!(+ json["revocation_endpoint_auth_methods_supported"],+ serde_json::json!(["none"])+ );+}+// --- Redirect construction -------------------------------------------#[tokio::test]@@ -471,7 +683,7 @@ async fn seed_issued_code(harness: &Harness,code: &str,client_id: &str,- access_token_expires_at: Option<SystemTime>,+ access_token_expires_at: SystemTime,) {harness.inflight@@ -508,7 +720,7 @@ async fn authorization_code_exchange_returns_remaining_lifetime() {let harness = Harness::new();let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;let expires_at = SystemTime::now() + Duration::from_secs(UPSTREAM_EXPIRES_IN - 300);- seed_issued_code(&harness, "broker-code", &client_id, Some(expires_at)).await;+ seed_issued_code(&harness, "broker-code", &client_id, expires_at).await;let response = harness.service@@ -516,7 +728,7 @@ async fn authorization_code_exchange_returns_remaining_lifetime() {.await.expect("token exchange should succeed");- let expires_in = response.expires_in.expect("expires_in should be present");+ let expires_in = response.expires_in;assert!((UPSTREAM_EXPIRES_IN - 302..=UPSTREAM_EXPIRES_IN - 300).contains(&expires_in),"expected roughly {} seconds remaining, got {expires_in}",@@ -532,7 +744,7 @@ async fn authorization_code_exchange_serializes_expires_in() {&harness,"broker-code",&client_id,- Some(SystemTime::now() + Duration::from_secs(UPSTREAM_EXPIRES_IN)),+ SystemTime::now() + Duration::from_secs(UPSTREAM_EXPIRES_IN),).await;@@ -550,28 +762,6 @@ async fn authorization_code_exchange_serializes_expires_in() {);}-#[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 harness = Harness::new();- let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;- seed_issued_code(&harness, "broker-code", &client_id, None).await;-- let response = harness- .service- .exchange_token(authorization_code_request("broker-code", &client_id))- .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 harness = Harness::new();@@ -580,7 +770,7 @@ async fn expired_access_token_reports_zero_rather_than_underflowing() {&harness,"broker-code",&client_id,- Some(SystemTime::now() - Duration::from_secs(60)),+ SystemTime::now() - Duration::from_secs(60),).await;@@ -590,7 +780,7 @@ async fn expired_access_token_reports_zero_rather_than_underflowing() {.await.expect("token exchange should succeed");- assert_eq!(response.expires_in, Some(0));+ assert_eq!(response.expires_in, 0);}#[tokio::test]@@ -620,7 +810,7 @@ async fn refresh_grant_returns_upstream_lifetime() {.await.expect("refresh exchange should succeed");- assert_eq!(refreshed.expires_in, Some(UPSTREAM_EXPIRES_IN));+ assert_eq!(refreshed.expires_in, UPSTREAM_EXPIRES_IN);assert_eq!(refreshed.access_token.as_str(), REFRESHED_ACCESS_TOKEN);}@@ -653,7 +843,6 @@ async fn callback_records_upstream_expiry_on_the_issued_code() {let remaining = harness.inflight.only_issued_expiry()- .expect("issued code should record the upstream expiry").duration_since(SystemTime::now()).expect("expiry should be in the future").as_secs();diff --git a/services/mcp_auth_proxy/src/inbound/axum_router.rs b/services/mcp_auth_proxy/src/inbound/axum_router.rsindex 472ef27a04..f97cb8500d 100644--- a/services/mcp_auth_proxy/src/inbound/axum_router.rs+++ b/services/mcp_auth_proxy/src/inbound/axum_router.rs@@ -17,10 +17,13 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;use tower_http::cors::{AllowOrigin, CorsLayer};use crate::domain::{- models::{AuthorizeRequest, CallbackRequest, ClientRegistrationRequest, TokenRequest},+ models::{+ AuthorizeRequest, CallbackRequest, ClientRegistrationRequest, RevocationRequest,+ TokenRequest,+ },service::{CompleteCallbackError, InflightAuthStore, McpAuthProxyService, McpAuthProxyServiceImpl,- RegisterClientError, StartAuthorizationError, TokenExchangeError,+ RegisterClientError, RevokeTokenError, StartAuthorizationError, TokenExchangeError,},};@@ -240,6 +243,11 @@ async fn token<I: InflightAuthStore + 'static>("refresh token is not bound to a client",).into_response(),+ Err(TokenExchangeError::RevokedGrant) => (+ axum::http::StatusCode::BAD_REQUEST,+ "refresh token has been revoked",+ )+ .into_response(),Err(TokenExchangeError::InflightStore(error)) => {tracing::error!(error=?error, "failed to access inflight auth state");(@@ -267,8 +275,61 @@ async fn token<I: InflightAuthStore + 'static>(}}+/// RFC 7009 revocation endpoint. Errors use the RFC 6749 section 5.2 JSON+/// shape that RFC 7009 section 2.2.1 refers to.+async fn revoke<I: InflightAuthStore + 'static>(+ State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,+ axum::Form(params): axum::Form<RevocationRequest>,+) -> Response {+ let (status, error, description) = match auth_proxy.revoke_token(params).await {+ Ok(()) => return axum::http::StatusCode::OK.into_response(),+ Err(RevokeTokenError::ClientIdRequired) => (+ axum::http::StatusCode::UNAUTHORIZED,+ "invalid_client",+ "client_id required",+ ),+ Err(RevokeTokenError::TokenRequired) => (+ axum::http::StatusCode::BAD_REQUEST,+ "invalid_request",+ "token required",+ ),+ Err(RevokeTokenError::UnsupportedTokenType) => (+ axum::http::StatusCode::BAD_REQUEST,+ "unsupported_token_type",+ "access tokens cannot be revoked; revoke the refresh token instead",+ ),+ Err(RevokeTokenError::ClientMismatch) => (+ axum::http::StatusCode::BAD_REQUEST,+ "invalid_grant",+ "token was not issued to this client",+ ),+ Err(RevokeTokenError::RefreshTokenBindingStore(error)) => {+ tracing::error!(error=?error, "failed to access refresh token bindings");+ (+ axum::http::StatusCode::SERVICE_UNAVAILABLE,+ "server_error",+ "failed to access refresh token bindings",+ )+ }+ Err(RevokeTokenError::UpstreamRevocationFailed(error)) => {+ tracing::error!(error=?error, "upstream refresh token revocation failed");+ (+ axum::http::StatusCode::SERVICE_UNAVAILABLE,+ "server_error",+ "upstream refresh token revocation failed",+ )+ }+ };+ (+ status,+ Json(serde_json::json!({ "error": error, "error_description": description })),+ )+ .into_response()+}+/// Builds the unauthenticated OAuth broker routes: discovery metadata,-/// dynamic client registration, authorize, upstream callback, and token.+/// dynamic client registration, authorize, upstream callback, token, and+/// revocation.pub fn oauth_router<I>(auth_proxy: McpAuthProxyServiceImpl<I>) -> RouterwhereI: InflightAuthStore + 'static,@@ -298,6 +359,7 @@ fn oauth_routes<I: InflightAuthStore + 'static>(auth_proxy: McpAuthProxyServiceI.route("/register", routing::post(register)).route("/oauth/callback", routing::get(oauth_callback)).route("/token", routing::post(token))+ .route("/revoke", routing::post(revoke)).with_state(auth_proxy)}diff --git a/services/mcp_auth_proxy/src/inbound/axum_router/test.rs b/services/mcp_auth_proxy/src/inbound/axum_router/test.rsindex f35beecd72..107f0d7b43 100644--- a/services/mcp_auth_proxy/src/inbound/axum_router/test.rs+++ b/services/mcp_auth_proxy/src/inbound/axum_router/test.rs@@ -10,7 +10,8 @@ use tower::ServiceExt;use super::{health, mcp_router, mount_at_root_and_prefix, oauth_router};use crate::test_support::{ATTACKER_CODE_VERIFIER, ATTACKER_REDIRECT_URI, Harness, TRUSTED_REDIRECT_URI,- UPSTREAM_ACCESS_TOKEN, VICTIM_CODE_VERIFIER, code_challenge_for, query_param,+ UPSTREAM_ACCESS_TOKEN, UPSTREAM_REFRESH_TOKEN, VICTIM_CODE_VERIFIER, code_challenge_for,+ query_param,};use axum::{Router, routing::get};use macro_auth::middleware::decode_jwt::JwtValidationArgs;@@ -247,6 +248,81 @@ async fn token_endpoint_refuses_a_code_presented_by_another_client() {assert_eq!(retried.body, "invalid or expired code");}+fn revoke_request(form: &str) -> Request<Body> {+ Request::builder()+ .method("POST")+ .uri("/revoke")+ .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")+ .body(Body::from(form.to_owned()))+ .expect("request should build")+}++/// The disconnect flow over HTTP: another client is refused with an RFC 6749+/// error body, the owner revokes, the revoked token no longer refreshes, and+/// revoking again still succeeds.+#[tokio::test]+async fn client_disconnects_by_revoking_its_refresh_token() {+ let harness = Harness::new();+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;+ let code = harness+ .complete_flow_to_code(&client_id, TRUSTED_REDIRECT_URI, VICTIM_CODE_VERIFIER)+ .await;+ let exchange = send(+ &harness,+ token_request(&format!(+ "grant_type=authorization_code&code={code}&code_verifier={VICTIM_CODE_VERIFIER}\+ &redirect_uri={}&client_id={client_id}",+ urlencoding::encode(TRUSTED_REDIRECT_URI)+ )),+ )+ .await;+ assert_eq!(exchange.status, StatusCode::OK);+ assert!(+ exchange.json()["expires_in"].is_u64(),+ "expires_in must always be present"+ );++ let anonymous = send(+ &harness,+ revoke_request(&format!("token={UPSTREAM_REFRESH_TOKEN}")),+ )+ .await;+ assert_eq!(anonymous.status, StatusCode::UNAUTHORIZED);+ assert_eq!(anonymous.json()["error"], "invalid_client");++ let other_client = send(+ &harness,+ revoke_request(&format!(+ "token={UPSTREAM_REFRESH_TOKEN}&token_type_hint=refresh_token&client_id=some-other-client"+ )),+ )+ .await;+ assert_eq!(other_client.status, StatusCode::BAD_REQUEST);+ assert_eq!(other_client.json()["error"], "invalid_grant");++ for _ in 0..2 {+ let revoked = send(+ &harness,+ revoke_request(&format!(+ "token={UPSTREAM_REFRESH_TOKEN}&token_type_hint=refresh_token&client_id={client_id}"+ )),+ )+ .await;+ assert_eq!(revoked.status, StatusCode::OK);+ assert_eq!(revoked.body, "");+ }++ let refresh = send(+ &harness,+ token_request(&format!(+ "grant_type=refresh_token&refresh_token={UPSTREAM_REFRESH_TOKEN}&client_id={client_id}"+ )),+ )+ .await;+ assert_eq!(refresh.status, StatusCode::BAD_REQUEST);+ assert_eq!(refresh.body, "refresh token is not bound to a client");+}+async fn ok() -> &'static str {"ok"}diff --git a/services/mcp_auth_proxy/src/lib.rs b/services/mcp_auth_proxy/src/lib.rsindex e38c4b3d37..a63721b982 100644--- a/services/mcp_auth_proxy/src/lib.rs+++ b/services/mcp_auth_proxy/src/lib.rs@@ -12,6 +12,7 @@//! 5. issue a short-lived broker code for the MCP client loopback callback//! 6. exchange that code at `/token` after redirect URI and PKCE validation//! 7. support refresh-token exchanges against the upstream provider+//! 8. revoke a client's refresh-token family at `/revoke` (RFC 7009)//!//! Module layout://! - `domain`: auth proxy state, models, ports, and service logicdiff --git a/services/mcp_auth_proxy/src/outbound/fusionauth.rs b/services/mcp_auth_proxy/src/outbound/fusionauth.rsindex 7d95cc76ab..d8d16d5071 100644--- a/services/mcp_auth_proxy/src/outbound/fusionauth.rs+++ b/services/mcp_auth_proxy/src/outbound/fusionauth.rs@@ -6,7 +6,7 @@ use tracing::Instrument;use crate::domain::{models::{RefreshToken, UpstreamTokens},- ports::{OAuthProvider, UpstreamTokensFuture},+ ports::{OAuthProvider, UpstreamRevocationFuture, UpstreamTokensFuture},};/// FusionAuth-backed OAuth provider for the MCP auth proxy.@@ -85,4 +85,20 @@ impl OAuthProvider for FusionAuthOAuthProvider {.instrument(span),)}++ fn revoke_refresh_token<'a>(+ &'a self,+ refresh_token: &'a RefreshToken,+ ) -> UpstreamRevocationFuture<'a> {+ let span = tracing::debug_span!("FusionAuthOAuthProvider::revoke_refresh_token");+ Box::pin(+ async move {+ self.client+ .revoke_refresh_token(refresh_token.as_str())+ .await+ .map_err(anyhow::Error::from)+ }+ .instrument(span),+ )+ }}diff --git a/services/mcp_auth_proxy/src/outbound/redis.rs b/services/mcp_auth_proxy/src/outbound/redis.rsindex d769811340..4326635ad9 100644--- a/services/mcp_auth_proxy/src/outbound/redis.rs+++ b/services/mcp_auth_proxy/src/outbound/redis.rs@@ -11,14 +11,16 @@ use std::{};use crate::domain::{- models::{IssuedAuthorizationCode, PendingAuthorization, RegisteredClient},+ models::{+ IssuedAuthorizationCode, PendingAuthorization, RefreshTokenBinding, RegisteredClient,+ },ports::{- BoundClientIdFuture, ClientRegistrationStore, RefreshTokenBindingStore,- RegisteredClientFuture, StoreWriteFuture,+ ClientRegistrationStore, GrantRevokedFuture, RefreshTokenBindingFuture,+ RefreshTokenBindingStore, RegisteredClientFuture, StoreWriteFuture,},service::{AUTHORIZATION_CODE_TTL, CLIENT_REGISTRATION_TTL, InflightAuthStore, PENDING_AUTH_TTL,- REFRESH_TOKEN_BINDING_TTL,+ REFRESH_TOKEN_BINDING_TTL, REVOKED_GRANT_TTL,},};@@ -26,6 +28,7 @@ const PENDING_KEY_PREFIX: &str = "mcp_auth_proxy:pending:";const ISSUED_KEY_PREFIX: &str = "mcp_auth_proxy:issued:";const CLIENT_KEY_PREFIX: &str = "mcp_auth_proxy:client:";const REFRESH_BINDING_KEY_PREFIX: &str = "mcp_auth_proxy:refresh_binding:";+const REVOKED_GRANT_KEY_PREFIX: &str = "mcp_auth_proxy:revoked_grant:";/// Redis-backed implementation of the in-flight OAuth state store.#[derive(Clone)]@@ -68,6 +71,37 @@ impl RedisClientRegistry {fn refresh_binding_key(refresh_token_digest: &str) -> String {format!("{REFRESH_BINDING_KEY_PREFIX}{refresh_token_digest}")}++ fn revoked_grant_key(grant_id: &str) -> String {+ format!("{REVOKED_GRANT_KEY_PREFIX}{grant_id}")+ }+}++#[derive(serde::Serialize, serde::Deserialize)]+struct StoredRefreshTokenBinding {+ client_id: String,+ grant_id: String,+}++/// Reads a stored binding. Bindings written before grants were tracked hold+/// the bare client id; each becomes a family of its own, named by its digest,+/// and keeps that grant id as it rotates.+fn parse_refresh_token_binding(+ refresh_token_digest: &str,+ value: String,+) -> anyhow::Result<RefreshTokenBinding> {+ if !value.starts_with('{') {+ return Ok(RefreshTokenBinding {+ client_id: value,+ grant_id: refresh_token_digest.to_owned(),+ });+ }+ let stored: StoredRefreshTokenBinding =+ serde_json::from_str(&value).context("failed to deserialize refresh token binding")?;+ Ok(RefreshTokenBinding {+ client_id: stored.client_id,+ grant_id: stored.grant_id,+ })}#[derive(serde::Serialize, serde::Deserialize)]@@ -154,18 +188,23 @@ impl RefreshTokenBindingStore for RedisClientRegistry {fn bind<'a>(&'a self,refresh_token_digest: &'a str,- client_id: &'a str,+ binding: &'a RefreshTokenBinding,) -> StoreWriteFuture<'a> {let redis_client = self.client.clone();let key = Self::refresh_binding_key(refresh_token_digest);Box::pin(async move {+ let value = serde_json::to_string(&StoredRefreshTokenBinding {+ client_id: binding.client_id.clone(),+ grant_id: binding.grant_id.clone(),+ })+ .context("failed to serialize refresh token binding")?;let mut conn = redis_client.get_multiplexed_async_connection().await.context("unable to connect to redis")?;- conn.set_ex::<String, &str, ()>(+ conn.set_ex::<String, String, ()>(key.clone(),- client_id,+ value,REFRESH_TOKEN_BINDING_TTL.as_secs(),).await@@ -174,7 +213,7 @@ impl RefreshTokenBindingStore for RedisClientRegistry {})}- fn bound_client<'a>(&'a self, refresh_token_digest: &'a str) -> BoundClientIdFuture<'a> {+ fn binding<'a>(&'a self, refresh_token_digest: &'a str) -> RefreshTokenBindingFuture<'a> {let redis_client = self.client.clone();let key = Self::refresh_binding_key(refresh_token_digest);Box::pin(async move {@@ -182,11 +221,13 @@ impl RefreshTokenBindingStore for RedisClientRegistry {.get_multiplexed_async_connection().await.context("unable to connect to redis")?;- let client_id: Option<String> = conn+ let value: Option<String> = conn.get(&key).await.with_context(|| format!("failed to fetch refresh token binding for key {key}"))?;- Ok(client_id)+ value+ .map(|value| parse_refresh_token_binding(refresh_token_digest, value))+ .transpose()})}@@ -204,6 +245,37 @@ impl RefreshTokenBindingStore for RedisClientRegistry {Ok(())})}++ fn revoke_grant<'a>(&'a self, grant_id: &'a str) -> StoreWriteFuture<'a> {+ let redis_client = self.client.clone();+ let key = Self::revoked_grant_key(grant_id);+ Box::pin(async move {+ let mut conn = redis_client+ .get_multiplexed_async_connection()+ .await+ .context("unable to connect to redis")?;+ conn.set_ex::<String, u8, ()>(key.clone(), 1, REVOKED_GRANT_TTL.as_secs())+ .await+ .with_context(|| format!("failed to persist grant revocation for key {key}"))?;+ Ok(())+ })+ }++ fn is_grant_revoked<'a>(&'a self, grant_id: &'a str) -> GrantRevokedFuture<'a> {+ let redis_client = self.client.clone();+ let key = Self::revoked_grant_key(grant_id);+ Box::pin(async move {+ let mut conn = redis_client+ .get_multiplexed_async_connection()+ .await+ .context("unable to connect to redis")?;+ let revoked: bool = conn+ .exists(&key)+ .await+ .with_context(|| format!("failed to read grant revocation for key {key}"))?;+ Ok(revoked)+ })+ }}#[derive(serde::Serialize, serde::Deserialize)]@@ -243,10 +315,8 @@ 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>,+ /// Unix seconds at which the upstream access token expires.+ access_token_expires_at_unix: u64,}impl From<IssuedAuthorizationCode> for StoredIssuedAuthorizationCode {@@ -257,12 +327,11 @@ 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())- }),+ access_token_expires_at_unix: value+ .access_token_expires_at+ .duration_since(UNIX_EPOCH)+ .map(|since_epoch| since_epoch.as_secs())+ .unwrap_or(0),}}}@@ -275,9 +344,8 @@ 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)),+ access_token_expires_at: UNIX_EPOCH+ + Duration::from_secs(value.access_token_expires_at_unix),}}}diff --git a/services/mcp_auth_proxy/src/outbound/redis/test.rs b/services/mcp_auth_proxy/src/outbound/redis/test.rsindex 109283b7d5..4186ae0d3e 100644--- a/services/mcp_auth_proxy/src/outbound/redis/test.rs+++ b/services/mcp_auth_proxy/src/outbound/redis/test.rs@@ -110,11 +110,14 @@ async fn looking_up_a_client_re_arms_its_ttl() {async fn refresh_token_binding_round_trips() {let registry = RedisClientRegistry::new(client());let digest = unique("digest");- let client_id = unique("client-binding");+ let binding = RefreshTokenBinding {+ client_id: unique("client-binding"),+ grant_id: unique("grant"),+ };assert!(registry- .bound_client(&digest)+ .binding(&digest).await.expect("lookup should succeed").is_none(),@@ -122,15 +125,15 @@ async fn refresh_token_binding_round_trips() {);registry- .bind(&digest, &client_id)+ .bind(&digest, &binding).await.expect("bind should succeed");assert_eq!(registry- .bound_client(&digest)+ .binding(&digest).await.expect("lookup should succeed"),- Some(client_id)+ Some(binding));registry@@ -139,7 +142,7 @@ async fn refresh_token_binding_round_trips() {.expect("unbind should succeed");assert!(registry- .bound_client(&digest)+ .binding(&digest).await.expect("lookup should succeed").is_none(),@@ -147,6 +150,49 @@ async fn refresh_token_binding_round_trips() {);}+#[tokio::test]+#[ignore = "requires a local Redis"]+async fn grant_revocation_round_trips() {+ let registry = RedisClientRegistry::new(client());+ let grant_id = unique("grant");++ assert!(+ !registry+ .is_grant_revoked(&grant_id)+ .await+ .expect("lookup should succeed")+ );+ registry+ .revoke_grant(&grant_id)+ .await+ .expect("revocation should succeed");+ assert!(+ registry+ .is_grant_revoked(&grant_id)+ .await+ .expect("lookup should succeed")+ );+}++/// Bindings written before grants were tracked hold the bare client id. They+/// must keep working, each as a family named by its own digest.+#[test]+fn binding_without_a_grant_becomes_its_own_family() {+ let binding = parse_refresh_token_binding(+ "legacy-digest",+ "0b8f3c1e-6a59-4bd5-9b0e-3f8d4c2a1e77".to_owned(),+ )+ .expect("a bare client id should parse");++ assert_eq!(+ binding,+ RefreshTokenBinding {+ client_id: "0b8f3c1e-6a59-4bd5-9b0e-3f8d4c2a1e77".to_owned(),+ grant_id: "legacy-digest".to_owned(),+ }+ );+}+/// Handshake state carries the client id now, so the stored form has to survive/// a round trip with it.#[tokio::test]@@ -195,7 +241,7 @@ async fn handshake_state_round_trips_with_its_client_id() {refresh_token: RefreshToken::from("refresh"),code_challenge: "challenge".to_owned(),redirect_uri: "https://claude.ai/api/mcp/auth_callback".to_owned(),- access_token_expires_at: Some(expires_at),+ access_token_expires_at: expires_at,},).await@@ -208,7 +254,7 @@ async fn handshake_state_round_trips_with_its_client_id() {.expect("the issued code should be readable");assert_eq!(issued.client_id, "client-abc");assert_eq!(issued.access_token.as_str(), "access");- assert_eq!(issued.access_token_expires_at, Some(expires_at));+ assert_eq!(issued.access_token_expires_at, expires_at);assert!(inflight.take_issued(&code)diff --git a/services/mcp_auth_proxy/src/test_support.rs b/services/mcp_auth_proxy/src/test_support.rsindex 6f69045de2..e0832d0f78 100644--- a/services/mcp_auth_proxy/src/test_support.rs+++ b/services/mcp_auth_proxy/src/test_support.rs@@ -2,7 +2,7 @@//! tests.use std::{- collections::HashMap,+ collections::{HashMap, HashSet},sync::{Arc, Mutex},time::SystemTime,};@@ -13,12 +13,13 @@ use sha2::{Digest, Sha256};use crate::domain::{models::{AccessToken, AuthorizeRequest, CallbackRequest, ClientRegistrationRequest,- IssuedAuthorizationCode, PendingAuthorization, RefreshToken, RegisteredClient,- UpstreamTokens,+ IssuedAuthorizationCode, PendingAuthorization, RefreshToken, RefreshTokenBinding,+ RegisteredClient, UpstreamTokens,},ports::{- BoundClientIdFuture, ClientRegistrationStore, OAuthProvider, RefreshTokenBindingStore,- RegisteredClientFuture, StoreWriteFuture, UpstreamTokensFuture,+ ClientRegistrationStore, GrantRevokedFuture, OAuthProvider, RefreshTokenBindingFuture,+ RefreshTokenBindingStore, RegisteredClientFuture, StoreWriteFuture,+ UpstreamRevocationFuture, UpstreamTokensFuture,},redirect_uri::RedirectUriPolicy,service::{@@ -79,7 +80,7 @@ impl FakeInflightAuth {/// Returns the recorded upstream expiry of the only issued code, panicking/// unless there is exactly one.- pub fn only_issued_expiry(&self) -> Option<SystemTime> {+ pub fn only_issued_expiry(&self) -> SystemTime {let issued = self.issued.lock().expect("issued lock");assert_eq!(issued.len(), 1, "expected exactly one issued code");issued@@ -136,7 +137,8 @@ impl InflightAuthStore for FakeInflightAuth {#[derive(Default)]pub struct FakeClientRegistry {clients: Mutex<HashMap<String, RegisteredClient>>,- refresh_bindings: Mutex<HashMap<String, String>>,+ refresh_bindings: Mutex<HashMap<String, RefreshTokenBinding>>,+ revoked_grants: Mutex<HashSet<String>>,}impl ClientRegistrationStore for FakeClientRegistry {@@ -166,18 +168,18 @@ impl RefreshTokenBindingStore for FakeClientRegistry {fn bind<'a>(&'a self,refresh_token_digest: &'a str,- client_id: &'a str,+ binding: &'a RefreshTokenBinding,) -> StoreWriteFuture<'a> {Box::pin(async move {self.refresh_bindings.lock().expect("bindings lock")- .insert(refresh_token_digest.to_owned(), client_id.to_owned());+ .insert(refresh_token_digest.to_owned(), binding.clone());Ok(())})}- fn bound_client<'a>(&'a self, refresh_token_digest: &'a str) -> BoundClientIdFuture<'a> {+ fn binding<'a>(&'a self, refresh_token_digest: &'a str) -> RefreshTokenBindingFuture<'a> {Box::pin(async move {Ok(self.refresh_bindings@@ -197,11 +199,32 @@ impl RefreshTokenBindingStore for FakeClientRegistry {Ok(())})}++ fn revoke_grant<'a>(&'a self, grant_id: &'a str) -> StoreWriteFuture<'a> {+ Box::pin(async move {+ self.revoked_grants+ .lock()+ .expect("revoked grants lock")+ .insert(grant_id.to_owned());+ Ok(())+ })+ }++ fn is_grant_revoked<'a>(&'a self, grant_id: &'a str) -> GrantRevokedFuture<'a> {+ Box::pin(async move {+ Ok(self+ .revoked_grants+ .lock()+ .expect("revoked grants lock")+ .contains(grant_id))+ })+ }}/// Upstream provider that hands back fixed tokens, standing in for FusionAuth.pub struct FakeOAuthProvider {rotated_refresh_token: Option<String>,+ revoked_refresh_tokens: Mutex<HashSet<String>>,}impl FakeOAuthProvider {@@ -210,13 +233,23 @@ impl FakeOAuthProvider {pub fn new() -> Self {Self {rotated_refresh_token: None,+ revoked_refresh_tokens: Mutex::default(),}}+ /// Returns whether the provider was asked to revoke `refresh_token`.+ pub fn revoked(&self, refresh_token: &str) -> bool {+ self.revoked_refresh_tokens+ .lock()+ .expect("revoked refresh tokens lock")+ .contains(refresh_token)+ }+/// A provider whose refresh grant issues a new refresh token.pub fn rotating(rotated_refresh_token: &str) -> Self {Self {rotated_refresh_token: Some(rotated_refresh_token.to_owned()),+ revoked_refresh_tokens: Mutex::default(),}}}@@ -241,6 +274,14 @@ impl OAuthProvider for FakeOAuthProvider {refresh_token: &'a RefreshToken,) -> UpstreamTokensFuture<'a> {Box::pin(async move {+ if self+ .revoked_refresh_tokens+ .lock()+ .expect("revoked refresh tokens lock")+ .contains(refresh_token.as_str())+ {+ anyhow::bail!("refresh token was revoked upstream");+ }let next = self.rotated_refresh_token.clone()@@ -252,6 +293,19 @@ impl OAuthProvider for FakeOAuthProvider {})})}++ fn revoke_refresh_token<'a>(+ &'a self,+ refresh_token: &'a RefreshToken,+ ) -> UpstreamRevocationFuture<'a> {+ Box::pin(async move {+ self.revoked_refresh_tokens+ .lock()+ .expect("revoked refresh tokens lock")+ .insert(refresh_token.as_str().to_owned());+ Ok(())+ })+ }}/// A broker service wired to in-memory stores, trusting only `claude.ai` for@@ -263,6 +317,8 @@ pub struct Harness {pub inflight: Arc<FakeInflightAuth>,/// The client registry the service was built with.pub registry: Arc<FakeClientRegistry>,+ /// The upstream provider the service was built with.+ pub provider: Arc<FakeOAuthProvider>,}impl Harness {@@ -275,19 +331,21 @@ impl Harness {pub fn with_provider(provider: FakeOAuthProvider) -> Self {let inflight = Arc::new(FakeInflightAuth::default());let registry = Arc::new(FakeClientRegistry::default());+ let provider = Arc::new(provider);let service = McpAuthProxyServiceImpl::new(McpAuthProxyServiceDeps {public_url: "https://mcp.macro.com".to_owned(),redirect_uri_policy: RedirectUriPolicy::new(["claude.ai"]),inflight_auth: Arc::clone(&inflight),client_registrations: Arc::clone(®istry) as Arc<dyn ClientRegistrationStore>,refresh_token_bindings: Arc::clone(®istry) as Arc<dyn RefreshTokenBindingStore>,- oauth_provider: Arc::new(provider),+ oauth_provider: Arc::clone(&provider) as Arc<dyn OAuthProvider>,});Self {service,inflight,registry,+ provider,}}