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.

fix(mcp_auth_proxy): validate redirect URIs against registered clients (#6084)

Eric Hayesc12138fc7921
diff --git a/services/mcp_auth_proxy/README.md b/services/mcp_auth_proxy/README.md
index 75df9fc2d9..8a532fafef 100644
--- a/services/mcp_auth_proxy/README.md
+++ b/services/mcp_auth_proxy/README.md
@@ -1,6 +1,58 @@
The `mcp_service` acts as proxy to the auth server.
-I believe this is needed because FusionAuth doesn't support DCR
+I believe this is needed because FusionAuth doesn't support DCR
(Official Docs)[https://modelcontextprotocol.io/docs/tutorials/security/authorization]
(Useful fusionauth article)[https://fusionauth.io/articles/ai/mcp-connecting-software-ai]
+
+## Which redirect URIs are usable
+
+Dynamic client registration is open, because MCP clients require it. That means
+the registered redirect URIs of a client prove nothing about who registered it:
+anyone can register a client whose callback they control. So a client's
+registration is not the only check on where a code may go — a deployment-level
+policy decides which destinations are usable at all, and a registration can only
+narrow that set further.
+
+A redirect URI is usable when it is either:
+
+- `http` on a loopback host (`localhost`, `127.0.0.1`, `[::1]`), on any port.
+ RFC 8252 section 7.3. A code sent here reaches a listener on the resource
+ owner's own machine, so it cannot leave the user who authorized it.
+- `https` on a host listed in `MCP_ALLOWED_REDIRECT_HOSTS`, matched exactly.
+ When that variable is unset the list falls back to
+ `DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS` in `services/mcp_service/src/config.rs`,
+ which holds the browser-based MCP clients Macro supports. Subdomains of a
+ listed host are not themselves trusted.
+
+A redirect URI carrying a fragment or credentials in its authority is refused
+regardless of host.
+
+Both endpoints that take a redirect URI apply the policy: `/register` refuses to
+store one it does not permit, and `/authorize` re-applies the policy before
+comparing against the registration, so narrowing the host list takes effect for
+clients that registered under a wider one.
+
+## Which client a grant belongs to
+
+Public clients hold no credential, so `client_id` is the only client identity
+the broker ever receives. It is not a secret and does not authenticate anyone.
+It is still checked everywhere, because a grant that is not tied to a client can
+be redeemed by anything that gets hold of it:
+
+- `/authorize` requires a `client_id` with a live registration, and requires the
+ request's `redirect_uri` to appear in that registration exactly.
+- `/token` requires a `client_id` on both grants. An authorization code is only
+ redeemable by the client it was issued to, and a refresh token only by the
+ client that obtained it.
+
+Refresh tokens are bound to their client by SHA-256 digest, so the binding store
+never holds a token that could be replayed if read. The binding rotates on every
+refresh: the new token is bound before the superseded one is dropped, so a
+replay of a token the broker has already rotated past finds no binding and is
+refused.
+
+Refresh tokens issued before this scheme existed have no binding, so the clients
+holding them authorize once more. Rate limiting of `/register` belongs at the
+edge; the broker bounds each registration's size but not how many a caller may
+create.
diff --git a/services/mcp_auth_proxy/src/domain.rs b/services/mcp_auth_proxy/src/domain.rs
index 2540aa7a65..e6e4903fc6 100644
--- a/services/mcp_auth_proxy/src/domain.rs
+++ b/services/mcp_auth_proxy/src/domain.rs
@@ -2,7 +2,9 @@
/// Domain models for broker-managed OAuth state and request payloads.
pub mod models;
-/// Domain port traits for upstream OAuth providers.
+/// Domain port traits for upstream OAuth providers and broker state stores.
pub mod ports;
+/// Policy for the redirect URIs the broker will deliver codes to.
+pub mod redirect_uri;
/// Domain service for the MCP OAuth broker.
pub mod service;
diff --git a/services/mcp_auth_proxy/src/domain/models.rs b/services/mcp_auth_proxy/src/domain/models.rs
index 90b6e15f9b..44344337ab 100644
--- a/services/mcp_auth_proxy/src/domain/models.rs
+++ b/services/mcp_auth_proxy/src/domain/models.rs
@@ -96,9 +96,65 @@ pub struct UpstreamTokens {
pub expires_in: u64,
}
+/// An MCP client created through dynamic client registration.
+#[derive(Clone, Debug)]
+pub struct RegisteredClient {
+ /// Broker-assigned client identifier.
+ pub client_id: String,
+ /// Human-readable name submitted at registration.
+ pub client_name: String,
+ /// The redirect URIs submitted at registration. Nothing outside this set
+ /// may receive an authorization code for this client.
+ pub redirect_uris: Vec<String>,
+}
+
+impl RegisteredClient {
+ /// Returns whether `uri` is one of this client's registered redirect URIs.
+ ///
+ /// Compared as an exact string, as RFC 6749 section 3.1.2.3 requires for
+ /// redirect URIs that are not loopback addresses. Loopback ports vary per
+ /// launch, but MCP clients re-register per port, so exact comparison holds
+ /// for them too.
+ pub fn permits_redirect_uri(&self, uri: &str) -> bool {
+ self.redirect_uris
+ .iter()
+ .any(|registered| registered == uri)
+ }
+}
+
+/// A dynamic client registration request from an MCP client.
+#[derive(Debug, Deserialize)]
+pub struct ClientRegistrationRequest {
+ /// Human-readable client name.
+ #[serde(default)]
+ pub client_name: Option<String>,
+ /// The redirect URIs the client will use.
+ #[serde(default)]
+ pub redirect_uris: Vec<String>,
+}
+
+/// The registration response returned to an MCP client.
+#[derive(Debug, Serialize)]
+pub struct ClientRegistrationResponse {
+ /// Broker-assigned client identifier.
+ pub client_id: String,
+ /// Human-readable client name.
+ pub client_name: String,
+ /// The registered redirect URIs.
+ pub redirect_uris: Vec<String>,
+ /// Grant types this client may use.
+ pub grant_types: [&'static str; 2],
+ /// Response types this client may use.
+ pub response_types: [&'static str; 1],
+ /// Public clients hold no credential.
+ pub token_endpoint_auth_method: &'static str,
+}
+
/// A pending OAuth authorization flow initiated by the client.
#[derive(Clone)]
pub struct PendingAuthorization {
+ /// The registered client that started the flow.
+ pub client_id: String,
/// PKCE S256 code challenge from the client.
pub code_challenge: String,
/// The client's original `state` parameter.
@@ -110,6 +166,9 @@ pub struct PendingAuthorization {
/// An authorization code issued by this broker and backed by an upstream token.
#[derive(Clone)]
pub struct IssuedAuthorizationCode {
+ /// The registered client this code was issued to. Only that client may
+ /// redeem it.
+ pub client_id: String,
/// The access token obtained from the upstream provider.
pub access_token: AccessToken,
/// The refresh token obtained from the upstream provider.
@@ -130,7 +189,6 @@ pub struct AuthorizeRequest {
/// Expected to be `code`.
pub response_type: String,
/// Dynamically registered client id.
- #[allow(dead_code)]
pub client_id: String,
/// Loopback callback URI owned by the MCP client.
pub redirect_uri: String,
@@ -180,14 +238,18 @@ pub struct TokenRequest {
/// Redirect URI from the original authorization request.
#[serde(default)]
pub redirect_uri: Option<String>,
- /// Optional client id.
+ /// The client redeeming the code or refresh token. Required: public clients
+ /// hold no credential, so this is the only client identity the broker gets,
+ /// and it must match the client the grant was issued to.
#[serde(default)]
- #[allow(dead_code)]
pub client_id: Option<String>,
}
/// OAuth token response returned to the MCP client.
-#[derive(Serialize)]
+///
+/// The token fields redact themselves when formatted, so `Debug` here does not
+/// expose a credential.
+#[derive(Debug, Serialize)]
pub struct TokenResponse {
/// Bearer access token.
pub access_token: AccessToken,
diff --git a/services/mcp_auth_proxy/src/domain/ports.rs b/services/mcp_auth_proxy/src/domain/ports.rs
index 1651629628..29abfb3384 100644
--- a/services/mcp_auth_proxy/src/domain/ports.rs
+++ b/services/mcp_auth_proxy/src/domain/ports.rs
@@ -2,12 +2,60 @@
use std::{future::Future, pin::Pin};
-use super::models::{RefreshToken, UpstreamTokens};
+use super::models::{RefreshToken, RegisteredClient, UpstreamTokens};
/// Boxed future returning a token grant from the upstream provider.
pub type UpstreamTokensFuture<'a> =
Pin<Box<dyn Future<Output = anyhow::Result<UpstreamTokens>> + Send + 'a>>;
+/// Boxed future returning nothing on success.
+pub type StoreWriteFuture<'a> = Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send + 'a>>;
+
+/// Boxed future returning a registered client, if one exists.
+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>>;
+
+/// Store of clients created through dynamic client registration.
+///
+/// Registrations outlive a single handshake: a client registers once and then
+/// authorizes repeatedly, so this is separate from the in-flight handshake
+/// state and each entry must survive well beyond an authorization code.
+pub trait ClientRegistrationStore: Send + Sync {
+ /// Persists a newly registered client.
+ fn insert_client<'a>(&'a self, client: &'a RegisteredClient) -> StoreWriteFuture<'a>;
+
+ /// Loads a registered client by id, returning `None` when the id is
+ /// unknown or its registration has lapsed.
+ ///
+ /// Implementations may treat a successful lookup as use of the
+ /// registration and extend its lifetime accordingly.
+ fn find_client<'a>(&'a self, client_id: &'a str) -> RegisteredClientFuture<'a>;
+}
+
+/// Store recording which client each outstanding refresh token was issued to.
+///
+/// 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.
+ fn bind<'a>(
+ &'a self,
+ refresh_token_digest: &'a str,
+ client_id: &'a str,
+ ) -> 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>;
+
+ /// Drops the binding for a refresh token digest.
+ fn unbind<'a>(&'a self, refresh_token_digest: &'a str) -> StoreWriteFuture<'a>;
+}
+
/// Upstream OAuth provider used by the broker.
pub trait OAuthProvider: Send + Sync {
/// Builds the upstream authorize URL for a broker session.
diff --git a/services/mcp_auth_proxy/src/domain/redirect_uri.rs b/services/mcp_auth_proxy/src/domain/redirect_uri.rs
new file mode 100644
index 0000000000..e23badc1a9
--- /dev/null
+++ b/services/mcp_auth_proxy/src/domain/redirect_uri.rs
@@ -0,0 +1,78 @@
+//! Policy governing which redirect URIs the broker will deliver a code to.
+
+use std::collections::BTreeSet;
+
+/// Hosts accepted for `http` redirect URIs, per RFC 8252 section 7.3. A code
+/// sent to one of these is delivered to a listener on the resource owner's own
+/// machine, so it never leaves the user who authorized it.
+const LOOPBACK_HOSTS: [&str; 3] = ["localhost", "127.0.0.1", "[::1]"];
+
+/// The set of destinations the broker is willing to hand an authorization code
+/// to.
+///
+/// Dynamic client registration is open, so any caller can register a client and
+/// choose its redirect URIs. Comparing a request against its own registration
+/// therefore proves nothing on its own: an attacker registers a client pointing
+/// at a callback they control and both sides of the comparison are theirs. This
+/// policy is the check that does not depend on the requester — an `https`
+/// redirect URI is only usable on a host the deployment trusts, and an `http`
+/// one only on a loopback address.
+#[derive(Clone, Debug)]
+pub struct RedirectUriPolicy {
+ allowed_https_hosts: BTreeSet<String>,
+}
+
+impl RedirectUriPolicy {
+ /// Builds a policy trusting `https` redirect URIs on the given hosts.
+ ///
+ /// Hosts are matched exactly after lowercasing; subdomains of a trusted
+ /// host are not themselves trusted.
+ pub fn new<I, S>(allowed_https_hosts: I) -> Self
+ where
+ I: IntoIterator<Item = S>,
+ S: AsRef<str>,
+ {
+ Self {
+ allowed_https_hosts: allowed_https_hosts
+ .into_iter()
+ .map(|host| host.as_ref().trim().to_ascii_lowercase())
+ .filter(|host| !host.is_empty())
+ .collect(),
+ }
+ }
+
+ /// Returns whether the broker may redirect to `uri`.
+ pub fn permits(&self, uri: &str) -> bool {
+ let Ok(parsed) = url::Url::parse(uri) else {
+ return false;
+ };
+
+ // RFC 6749 section 3.1.2 forbids a fragment on a redirection endpoint,
+ // and credentials in the authority would change who the URI resolves
+ // to without changing its host.
+ if parsed.fragment().is_some()
+ || !parsed.username().is_empty()
+ || parsed.password().is_some()
+ {
+ return false;
+ }
+
+ let Some(host) = parsed.host_str() else {
+ return false;
+ };
+
+ match parsed.scheme() {
+ "http" => LOOPBACK_HOSTS.contains(&host),
+ "https" => self.allowed_https_hosts.contains(host),
+ _ => false,
+ }
+ }
+
+ /// Returns the trusted `https` hosts, for logging at startup.
+ pub fn allowed_https_hosts(&self) -> impl Iterator<Item = &str> {
+ self.allowed_https_hosts.iter().map(String::as_str)
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/services/mcp_auth_proxy/src/domain/redirect_uri/test.rs b/services/mcp_auth_proxy/src/domain/redirect_uri/test.rs
new file mode 100644
index 0000000000..ff9f550ea9
--- /dev/null
+++ b/services/mcp_auth_proxy/src/domain/redirect_uri/test.rs
@@ -0,0 +1,74 @@
+use super::*;
+
+fn policy() -> RedirectUriPolicy {
+ RedirectUriPolicy::new(["claude.ai", "cursor.com"])
+}
+
+#[test]
+fn permits_trusted_https_host() {
+ assert!(policy().permits("https://claude.ai/api/mcp/auth_callback"));
+}
+
+#[test]
+fn permits_trusted_https_host_regardless_of_case() {
+ assert!(policy().permits("https://Claude.AI/api/mcp/auth_callback"));
+}
+
+#[test]
+fn rejects_untrusted_https_host() {
+ assert!(!policy().permits("https://attacker.example/callback"));
+}
+
+#[test]
+fn rejects_subdomain_of_trusted_host() {
+ assert!(!policy().permits("https://mcp.claude.ai/callback"));
+}
+
+#[test]
+fn rejects_trusted_host_used_as_a_subdomain_label() {
+ assert!(!policy().permits("https://claude.ai.attacker.example/callback"));
+}
+
+#[test]
+fn rejects_trusted_host_in_userinfo() {
+ assert!(!policy().permits("https://[email protected]/callback"));
+}
+
+#[test]
+fn rejects_fragment_on_redirect_uri() {
+ assert!(!policy().permits("https://claude.ai/callback#fragment"));
+}
+
+#[test]
+fn permits_loopback_http_on_any_port() {
+ let policy = policy();
+ assert!(policy.permits("http://127.0.0.1:51000/oauth/callback"));
+ assert!(policy.permits("http://localhost:8123/callback"));
+ assert!(policy.permits("http://[::1]:9000/callback"));
+}
+
+#[test]
+fn rejects_non_loopback_http() {
+ assert!(!policy().permits("http://claude.ai/callback"));
+ assert!(!policy().permits("http://attacker.example/callback"));
+}
+
+#[test]
+fn rejects_non_http_schemes() {
+ let policy = policy();
+ assert!(!policy.permits("javascript:alert(1)"));
+ assert!(!policy.permits("data:text/html,hi"));
+ assert!(!policy.permits("com.attacker.app:/callback"));
+}
+
+#[test]
+fn rejects_unparseable_uri() {
+ assert!(!policy().permits("not a uri"));
+}
+
+#[test]
+fn empty_allowlist_permits_only_loopback() {
+ let policy = RedirectUriPolicy::new(Vec::<String>::new());
+ assert!(policy.permits("http://127.0.0.1:51000/oauth/callback"));
+ assert!(!policy.permits("https://claude.ai/api/mcp/auth_callback"));
+}
diff --git a/services/mcp_auth_proxy/src/domain/service.rs b/services/mcp_auth_proxy/src/domain/service.rs
index b0d60d0a71..fc84e8609a 100644
--- a/services/mcp_auth_proxy/src/domain/service.rs
+++ b/services/mcp_auth_proxy/src/domain/service.rs
@@ -13,14 +13,31 @@ use std::{
use super::{
models::{
- AuthorizeRequest, CallbackRequest, IssuedAuthorizationCode, PendingAuthorization,
+ AuthorizeRequest, CallbackRequest, ClientRegistrationRequest, ClientRegistrationResponse,
+ IssuedAuthorizationCode, PendingAuthorization, RefreshToken, RegisteredClient,
TokenRequest, TokenResponse,
},
- ports::OAuthProvider,
+ ports::{ClientRegistrationStore, OAuthProvider, RefreshTokenBindingStore},
+ redirect_uri::RedirectUriPolicy,
};
pub(crate) const PENDING_AUTH_TTL: Duration = Duration::from_secs(10 * 60);
pub(crate) const AUTHORIZATION_CODE_TTL: Duration = Duration::from_secs(5 * 60);
+/// How long a dynamic client registration survives without being used. Every
+/// successful lookup extends it, so a client that keeps authorizing keeps its
+/// registration and one that stops is eventually collected.
+pub const CLIENT_REGISTRATION_TTL: Duration = Duration::from_secs(90 * 24 * 60 * 60);
+/// How long a refresh token stays bound to its client. FusionAuth issues
+/// 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);
+
+/// Redirect URIs accepted per registration. Enough for a client that offers
+/// several callbacks, low enough that open registration cannot be used to
+/// store unbounded data.
+const MAX_REDIRECT_URIS_PER_CLIENT: usize = 8;
+/// Longest redirect URI accepted at registration.
+const MAX_REDIRECT_URI_LEN: usize = 512;
/// Domain interface for the MCP OAuth broker.
pub trait McpAuthProxyService: Clone + Send + Sync + 'static {
@@ -29,7 +46,10 @@ pub trait McpAuthProxyService: Clone + Send + Sync + 'static {
/// Returns protected-resource metadata for MCP clients.
fn protected_resource_metadata(&self) -> serde_json::Value;
/// Registers a public MCP client dynamically.
- fn register_client(&self, body: serde_json::Value) -> serde_json::Value;
+ fn register_client(
+ &self,
+ request: ClientRegistrationRequest,
+ ) -> impl Future<Output = Result<ClientRegistrationResponse, RegisterClientError>> + Send;
/// Starts an OAuth authorization flow and returns the upstream authorize URL.
fn start_authorization(
&self,
@@ -81,6 +101,22 @@ pub trait InflightAuthStore: Send + Sync {
fn cleanup_expired(&self) -> impl Future<Output = anyhow::Result<()>> + Send;
}
+/// Dependencies and policy required to build the broker service.
+pub struct McpAuthProxyServiceDeps<I> {
+ /// Public base URL the broker is served from.
+ pub public_url: String,
+ /// The redirect URI destinations this deployment trusts.
+ pub redirect_uri_policy: RedirectUriPolicy,
+ /// Store for short-lived handshake state.
+ pub inflight_auth: Arc<I>,
+ /// Store for dynamically registered clients.
+ pub client_registrations: Arc<dyn ClientRegistrationStore>,
+ /// Store binding refresh tokens to the clients that obtained them.
+ pub refresh_token_bindings: Arc<dyn RefreshTokenBindingStore>,
+ /// Upstream OAuth provider the broker fronts.
+ pub oauth_provider: Arc<dyn OAuthProvider>,
+}
+
/// Streamable HTTP resource URL advertised in protected-resource metadata.
///
/// MCP clients require a `resource` field. When `MCP_PUBLIC_URL` is an origin
@@ -98,7 +134,10 @@ fn mcp_resource_url(public_url: &str) -> String {
/// Domain service backing the MCP OAuth broker.
pub struct McpAuthProxyServiceImpl<I> {
inflight_auth: Arc<I>,
+ client_registrations: Arc<dyn ClientRegistrationStore>,
+ refresh_token_bindings: Arc<dyn RefreshTokenBindingStore>,
oauth_provider: Arc<dyn OAuthProvider>,
+ redirect_uri_policy: RedirectUriPolicy,
public_url: String,
}
@@ -106,7 +145,10 @@ impl<I> Clone for McpAuthProxyServiceImpl<I> {
fn clone(&self) -> Self {
Self {
inflight_auth: Arc::clone(&self.inflight_auth),
+ client_registrations: Arc::clone(&self.client_registrations),
+ refresh_token_bindings: Arc::clone(&self.refresh_token_bindings),
oauth_provider: Arc::clone(&self.oauth_provider),
+ redirect_uri_policy: self.redirect_uri_policy.clone(),
public_url: self.public_url.clone(),
}
}
@@ -117,32 +159,92 @@ where
I: InflightAuthStore + 'static,
{
/// Creates a new auth proxy service backed by an upstream OAuth provider.
- pub fn new(
- public_url: String,
- inflight_auth: Arc<I>,
- oauth_provider: Arc<dyn OAuthProvider>,
- ) -> Self {
+ pub fn new(deps: McpAuthProxyServiceDeps<I>) -> Self {
+ let McpAuthProxyServiceDeps {
+ public_url,
+ redirect_uri_policy,
+ inflight_auth,
+ client_registrations,
+ refresh_token_bindings,
+ oauth_provider,
+ } = deps;
+
Self {
inflight_auth,
+ client_registrations,
+ refresh_token_bindings,
oauth_provider,
+ redirect_uri_policy,
public_url,
}
}
+ /// Refreshes an upstream token for the client the refresh token belongs to.
+ ///
+ /// A public client has no credential to present, so the binding recorded
+ /// when the token was issued is what ties the grant to a client. Rotating
+ /// the binding on every refresh means a replayed token whose binding has
+ /// already moved on finds nothing and is refused.
async fn refresh_token_exchange(
&self,
params: TokenRequest,
) -> Result<TokenResponse, TokenExchangeError> {
+ let client_id = params
+ .client_id
+ .ok_or(TokenExchangeError::ClientIdRequired)?;
let refresh_token = params
.refresh_token
.ok_or(TokenExchangeError::RefreshTokenRequired)?;
+ let presented_digest = refresh_token_digest(&refresh_token);
+ let bound_client_id = self
+ .refresh_token_bindings
+ .bound_client(&presented_digest)
+ .await
+ .map_err(TokenExchangeError::RefreshTokenBindingStore)?
+ .ok_or(TokenExchangeError::UnboundRefreshToken)?;
+
+ if bound_client_id != client_id {
+ tracing::warn!(
+ %client_id,
+ "refresh token presented by a client it was not issued to"
+ );
+ return Err(TokenExchangeError::ClientMismatch);
+ }
+
let tokens = self
.oauth_provider
.refresh_access_token(&refresh_token)
.await
.map_err(TokenExchangeError::RefreshFailed)?;
+ let rotated_digest = refresh_token_digest(&tokens.refresh_token);
+ // The upstream token is already issued at this point. A binding write
+ // that fails costs the client its next refresh, which it recovers from
+ // by authorizing again; discarding a token the user just approved
+ // costs them the session outright. So log and hand the token over.
+ let rebound = self
+ .refresh_token_bindings
+ .bind(&rotated_digest, &client_id)
+ .await
+ .inspect_err(|error| {
+ tracing::error!(error=?error, %client_id, "failed to bind rotated refresh token");
+ })
+ .is_ok();
+
+ if rebound && rotated_digest != presented_digest {
+ self.refresh_token_bindings
+ .unbind(&presented_digest)
+ .await
+ .unwrap_or_else(|error| {
+ tracing::error!(
+ error=?error,
+ %client_id,
+ "failed to drop superseded refresh token binding"
+ );
+ });
+ }
+
Ok(TokenResponse {
access_token: tokens.access_token,
refresh_token: tokens.refresh_token,
@@ -155,6 +257,13 @@ where
&self,
params: TokenRequest,
) -> Result<TokenResponse, TokenExchangeError> {
+ // Read the client id before consuming the code, so a malformed request
+ // does not spend a code that is still good.
+ let client_id = params
+ .client_id
+ .as_deref()
+ .ok_or(TokenExchangeError::ClientIdRequired)?;
+
let issued = self
.inflight_auth
.take_issued(
@@ -167,6 +276,15 @@ where
.map_err(TokenExchangeError::InflightStore)?
.ok_or(TokenExchangeError::InvalidOrExpiredCode)?;
+ if client_id != issued.client_id {
+ tracing::warn!(
+ presented_client_id = %client_id,
+ issued_client_id = %issued.client_id,
+ "authorization code redeemed by a client it was not issued to"
+ );
+ return Err(TokenExchangeError::ClientMismatch);
+ }
+
match &params.redirect_uri {
Some(uri) if *uri != issued.redirect_uri => {
return Err(TokenExchangeError::RedirectUriMismatch);
@@ -186,6 +304,14 @@ where
None => return Err(TokenExchangeError::CodeVerifierRequired),
}
+ self.refresh_token_bindings
+ .bind(
+ &refresh_token_digest(&issued.refresh_token),
+ &issued.client_id,
+ )
+ .await
+ .map_err(TokenExchangeError::RefreshTokenBindingStore)?;
+
Ok(TokenResponse {
access_token: issued.access_token,
refresh_token: issued.refresh_token,
@@ -226,22 +352,54 @@ where
}
/// Handles dynamic client registration for public MCP clients.
- fn register_client(&self, body: serde_json::Value) -> serde_json::Value {
- let client_id = uuid::Uuid::new_v4().to_string();
- let client_name = body
- .get("client_name")
- .and_then(|v| v.as_str())
- .unwrap_or("mcp-client");
+ ///
+ /// Registration is open, as MCP clients require, but it is not
+ /// unconstrained: every submitted redirect URI must satisfy the
+ /// deployment's redirect URI policy, and the accepted set is persisted so
+ /// later authorize requests have something to be checked against.
+ async fn register_client(
+ &self,
+ request: ClientRegistrationRequest,
+ ) -> Result<ClientRegistrationResponse, RegisterClientError> {
+ if request.redirect_uris.is_empty() {
+ return Err(RegisterClientError::RedirectUrisRequired);
+ }
+ if request.redirect_uris.len() > MAX_REDIRECT_URIS_PER_CLIENT {
+ return Err(RegisterClientError::TooManyRedirectUris);
+ }
+ for uri in &request.redirect_uris {
+ if uri.len() > MAX_REDIRECT_URI_LEN || !self.redirect_uri_policy.permits(uri) {
+ return Err(RegisterClientError::UnsupportedRedirectUri { uri: uri.clone() });
+ }
+ }
- tracing::info!(%client_id, %client_name, "dynamic client registration");
+ let client = RegisteredClient {
+ client_id: uuid::Uuid::new_v4().to_string(),
+ client_name: request
+ .client_name
+ .unwrap_or_else(|| "mcp-client".to_owned()),
+ redirect_uris: request.redirect_uris,
+ };
- serde_json::json!({
- "client_id": client_id,
- "client_name": client_name,
- "redirect_uris": body.get("redirect_uris").cloned().unwrap_or(serde_json::json!([])),
- "grant_types": ["authorization_code", "refresh_token"],
- "response_types": ["code"],
- "token_endpoint_auth_method": "none",
+ self.client_registrations
+ .insert_client(&client)
+ .await
+ .map_err(RegisterClientError::ClientRegistrationStore)?;
+
+ tracing::info!(
+ client_id = %client.client_id,
+ client_name = %client.client_name,
+ redirect_uris = ?client.redirect_uris,
+ "dynamic client registration"
+ );
+
+ Ok(ClientRegistrationResponse {
+ client_id: client.client_id,
+ client_name: client.client_name,
+ redirect_uris: client.redirect_uris,
+ grant_types: ["authorization_code", "refresh_token"],
+ response_types: ["code"],
+ token_endpoint_auth_method: "none",
})
}
@@ -258,18 +416,36 @@ where
if params.code_challenge_method != "S256" {
return Err(StartAuthorizationError::UnsupportedCodeChallengeMethod);
}
- if !is_allowed_redirect_uri(&params.redirect_uri) {
+ // Applied ahead of the registered set so a registration made
+ // before the policy was narrowed cannot still be used.
+ if !service.redirect_uri_policy.permits(&params.redirect_uri) {
return Err(StartAuthorizationError::InvalidRedirectUri);
}
+ let client = service
+ .client_registrations
+ .find_client(&params.client_id)
+ .await
+ .map_err(StartAuthorizationError::ClientRegistrationStore)?
+ .ok_or(StartAuthorizationError::UnknownClient)?;
+
+ if !client.permits_redirect_uri(&params.redirect_uri) {
+ tracing::warn!(
+ client_id = %params.client_id,
+ "authorize request used a redirect_uri the client did not register"
+ );
+ return Err(StartAuthorizationError::UnregisteredRedirectUri);
+ }
+
let session_id = uuid::Uuid::new_v4().to_string();
- tracing::info!(%session_id, "starting OAuth authorize flow");
+ tracing::info!(%session_id, client_id = %client.client_id, "starting OAuth authorize flow");
service
.inflight_auth
.insert_pending(
&session_id,
PendingAuthorization {
+ client_id: client.client_id,
code_challenge: params.code_challenge,
client_state: params.state,
client_redirect_uri: params.redirect_uri,
@@ -313,19 +489,15 @@ where
description = ?params.error_description,
"upstream oauth returned error"
);
- let mut redirect = format!(
- "{}?error={}&state={}",
- pending.client_redirect_uri,
- urlencoding::encode(&error),
- urlencoding::encode(&pending.client_state),
- );
+ let mut params_to_append =
+ vec![("error", error), ("state", pending.client_state.clone())];
if let Some(desc) = params.error_description {
- redirect.push_str(&format!(
- "&error_description={}",
- urlencoding::encode(&desc)
- ));
+ params_to_append.push(("error_description", desc));
}
- return Ok(redirect);
+ return Ok(append_query_params(
+ &pending.client_redirect_uri,
+ &params_to_append,
+ ));
}
let code = params.code.ok_or(CompleteCallbackError::MissingCode)?;
@@ -348,6 +520,7 @@ where
.insert_issued(
&issued_code,
IssuedAuthorizationCode {
+ client_id: pending.client_id,
access_token: tokens.access_token,
refresh_token: tokens.refresh_token,
code_challenge: pending.code_challenge,
@@ -358,11 +531,12 @@ where
.await
.map_err(CompleteCallbackError::InflightStore)?;
- Ok(format!(
- "{}?code={}&state={}",
- pending.client_redirect_uri,
- urlencoding::encode(&issued_code),
- urlencoding::encode(&pending.client_state),
+ Ok(append_query_params(
+ &pending.client_redirect_uri,
+ &[
+ ("code", issued_code),
+ ("state", pending.client_state.clone()),
+ ],
))
}
@@ -394,20 +568,46 @@ fn seconds_until(deadline: SystemTime) -> u64 {
.unwrap_or(0)
}
-fn is_allowed_redirect_uri(uri: &str) -> bool {
- let Ok(parsed) = url::Url::parse(uri) else {
- return false;
- };
-
- if parsed.scheme() == "https" {
- return true;
- }
+/// Digest used to key a refresh token binding, so the store never holds a
+/// token that could be replayed if it were read.
+fn refresh_token_digest(refresh_token: &RefreshToken) -> String {
+ let digest = Sha256::digest(refresh_token.as_str().as_bytes());
+ URL_SAFE_NO_PAD.encode(digest)
+}
- if parsed.scheme() == "http" {
- return matches!(parsed.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"));
+/// Appends query parameters to a redirect URI, keeping any query the client
+/// registered on it.
+fn append_query_params(uri: &str, params: &[(&str, String)]) -> String {
+ let mut redirect = uri.to_owned();
+ let mut separator = if uri.contains('?') { '&' } else { '?' };
+ for (key, value) in params {
+ redirect.push(separator);
+ redirect.push_str(key);
+ redirect.push('=');
+ redirect.push_str(&urlencoding::encode(value));
+ separator = '&';
}
+ redirect
+}
- false
+/// Errors returned when registering a client.
+#[derive(Debug, thiserror::Error)]
+pub enum RegisterClientError {
+ /// A client with no redirect URI could never complete a flow.
+ #[error("at least one redirect_uri is required")]
+ RedirectUrisRequired,
+ /// More redirect URIs than the broker will store for one client.
+ #[error("too many redirect_uris")]
+ TooManyRedirectUris,
+ /// A submitted redirect URI is not a destination this deployment trusts.
+ #[error("redirect_uri is not an allowed destination")]
+ UnsupportedRedirectUri {
+ /// The rejected URI, for logging.
+ uri: String,
+ },
+ /// The registration could not be persisted.
+ #[error("failed to persist client registration")]
+ ClientRegistrationStore(anyhow::Error),
}
/// Errors returned when starting authorization.
@@ -419,9 +619,18 @@ pub enum StartAuthorizationError {
/// Only S256 PKCE is supported.
#[error("unsupported code_challenge_method")]
UnsupportedCodeChallengeMethod,
- /// Only https or loopback http redirect URIs are allowed.
- #[error("redirect_uri must be https or a loopback address")]
+ /// The redirect URI is not a destination this deployment trusts.
+ #[error("redirect_uri is not an allowed destination")]
InvalidRedirectUri,
+ /// The redirect URI is not one this client registered.
+ #[error("redirect_uri was not registered for this client")]
+ UnregisteredRedirectUri,
+ /// The client_id has no live registration.
+ #[error("unknown client_id")]
+ UnknownClient,
+ /// Client registrations could not be read.
+ #[error("failed to read client registrations")]
+ ClientRegistrationStore(anyhow::Error),
/// Inflight auth state could not be persisted.
#[error("failed to persist inflight auth state")]
InflightStore(anyhow::Error),
@@ -477,9 +686,22 @@ pub enum TokenExchangeError {
/// Refresh token is required for refresh_token grants.
#[error("refresh_token required")]
RefreshTokenRequired,
+ /// The client_id was absent from the token request.
+ #[error("client_id required")]
+ ClientIdRequired,
+ /// The grant was issued to a different client than the one presenting it.
+ #[error("grant was not issued to this client")]
+ ClientMismatch,
+ /// The refresh token has no recorded client binding, so the broker cannot
+ /// tell which client it belongs to.
+ #[error("refresh token is not bound to a client")]
+ UnboundRefreshToken,
/// Inflight auth state could not be loaded or updated.
#[error("failed to access inflight auth state")]
InflightStore(anyhow::Error),
+ /// Refresh token bindings could not be read or written.
+ #[error("failed to access refresh token bindings")]
+ RefreshTokenBindingStore(anyhow::Error),
/// Upstream refresh failed.
#[error("refresh token exchange failed")]
RefreshFailed(anyhow::Error),
diff --git a/services/mcp_auth_proxy/src/domain/service/test.rs b/services/mcp_auth_proxy/src/domain/service/test.rs
index 901c73e984..da0b9ede93 100644
--- a/services/mcp_auth_proxy/src/domain/service/test.rs
+++ b/services/mcp_auth_proxy/src/domain/service/test.rs
@@ -1,169 +1,503 @@
-use super::*;
+use std::time::{Duration, SystemTime};
-use std::{
- collections::HashMap,
- sync::Mutex,
- time::{Duration, SystemTime},
+use super::*;
+use crate::{
+ domain::models::{AccessToken, ClientRegistrationRequest},
+ test_support::{
+ ATTACKER_CODE_VERIFIER, ATTACKER_REDIRECT_URI, FakeOAuthProvider, Harness,
+ LOOPBACK_REDIRECT_URI, REFRESHED_ACCESS_TOKEN, TRUSTED_REDIRECT_URI, UPSTREAM_ACCESS_TOKEN,
+ UPSTREAM_EXPIRES_IN, UPSTREAM_REFRESH_TOKEN, VICTIM_CODE_VERIFIER, code_challenge_for,
+ },
};
-use crate::domain::models::{AccessToken, RefreshToken, UpstreamTokens};
+// --- Registration -------------------------------------------------------
-/// 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";
+#[tokio::test]
+async fn registration_persists_the_submitted_redirect_uris() {
+ let harness = Harness::new();
+ let client_id = harness.register(&[LOOPBACK_REDIRECT_URI]).await;
-fn code_challenge_for(verifier: &str) -> String {
- URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
+ let stored = harness
+ .registry
+ .find_client(&client_id)
+ .await
+ .expect("lookup should succeed")
+ .expect("client should be persisted");
+
+ assert_eq!(stored.redirect_uris, vec![LOOPBACK_REDIRECT_URI]);
}
-#[derive(Default)]
-struct FakeInflightAuth {
- pending: Mutex<HashMap<String, PendingAuthorization>>,
- issued: Mutex<HashMap<String, IssuedAuthorizationCode>>,
+#[tokio::test]
+async fn registration_rejects_an_untrusted_https_redirect_uri() {
+ let harness = Harness::new();
+
+ let error = harness
+ .service
+ .register_client(ClientRegistrationRequest {
+ client_name: None,
+ redirect_uris: vec![ATTACKER_REDIRECT_URI.to_owned()],
+ })
+ .await
+ .expect_err("an untrusted host must not be registrable");
+
+ assert!(matches!(
+ error,
+ RegisterClientError::UnsupportedRedirectUri { .. }
+ ));
}
-impl FakeInflightAuth {
- fn with_issued(code: &str, issued: IssuedAuthorizationCode) -> Self {
- let store = Self::default();
- store.issued.lock().unwrap().insert(code.to_owned(), issued);
- store
- }
+#[tokio::test]
+async fn registration_rejects_an_empty_redirect_uri_list() {
+ let harness = Harness::new();
+
+ let error = harness
+ .service
+ .register_client(ClientRegistrationRequest {
+ client_name: None,
+ redirect_uris: Vec::new(),
+ })
+ .await
+ .expect_err("a client with no redirect_uri must be rejected");
+
+ assert!(matches!(error, RegisterClientError::RedirectUrisRequired));
}
-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(())
- }
+// --- Authorization ------------------------------------------------------
- async fn take_pending(&self, session_id: &str) -> anyhow::Result<Option<PendingAuthorization>> {
- Ok(self.pending.lock().unwrap().remove(session_id))
- }
+#[tokio::test]
+async fn authorize_rejects_an_unknown_client_id() {
+ let harness = Harness::new();
+
+ let error = harness
+ .service
+ .start_authorization(harness.authorize_request(
+ "never-registered",
+ LOOPBACK_REDIRECT_URI,
+ &code_challenge_for(VICTIM_CODE_VERIFIER),
+ ))
+ .await
+ .expect_err("an unregistered client_id must be rejected");
- async fn insert_issued(
- &self,
- code: &str,
- issued: IssuedAuthorizationCode,
- ) -> anyhow::Result<()> {
- self.issued.lock().unwrap().insert(code.to_owned(), issued);
- Ok(())
- }
+ assert!(matches!(error, StartAuthorizationError::UnknownClient));
+}
- async fn take_issued(&self, code: &str) -> anyhow::Result<Option<IssuedAuthorizationCode>> {
- Ok(self.issued.lock().unwrap().remove(code))
- }
+#[tokio::test]
+async fn authorize_rejects_a_redirect_uri_the_client_did_not_register() {
+ let harness = Harness::new();
+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
+
+ let error = harness
+ .service
+ .start_authorization(harness.authorize_request(
+ &client_id,
+ "https://claude.ai/some/other/path",
+ &code_challenge_for(VICTIM_CODE_VERIFIER),
+ ))
+ .await
+ .expect_err("a redirect_uri outside the registration must be rejected");
- async fn cleanup_expired(&self) -> anyhow::Result<()> {
- Ok(())
- }
+ assert!(matches!(
+ error,
+ StartAuthorizationError::UnregisteredRedirectUri
+ ));
}
-struct FakeOAuthProvider {
- expires_in: u64,
+#[tokio::test]
+async fn authorize_rejects_an_attacker_controlled_redirect_uri() {
+ let harness = Harness::new();
+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
+
+ let error = harness
+ .service
+ .start_authorization(harness.authorize_request(
+ &client_id,
+ ATTACKER_REDIRECT_URI,
+ &code_challenge_for(ATTACKER_CODE_VERIFIER),
+ ))
+ .await
+ .expect_err("an untrusted host must be rejected at authorize");
+
+ assert!(matches!(error, StartAuthorizationError::InvalidRedirectUri));
}
-impl OAuthProvider for FakeOAuthProvider {
- fn construct_authorize_url(&self, state: &str) -> anyhow::Result<String> {
- Ok(format!(
- "https://upstream.example.com/authorize?state={state}"
+/// The reported attack: an attacker registers a client, crafts an authorize
+/// link carrying a redirect URI and PKCE challenge of their own, and gets a
+/// victim to follow it. Every check the broker makes at token exchange
+/// compares the attacker's values against the attacker's values, so the flow
+/// has to fail before a code is ever issued.
+#[tokio::test]
+async fn authorization_code_interception_fails_at_authorize() {
+ let harness = Harness::new();
+
+ let attacker_registration = harness
+ .service
+ .register_client(ClientRegistrationRequest {
+ client_name: Some("totally-legitimate-client".to_owned()),
+ redirect_uris: vec![ATTACKER_REDIRECT_URI.to_owned()],
+ })
+ .await;
+ assert!(
+ attacker_registration.is_err(),
+ "the attacker must not be able to register their callback"
+ );
+
+ // Registration refused, so the attacker reuses a real client's id and
+ // supplies their own callback on the authorize request instead.
+ let victim_client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
+ let error = harness
+ .service
+ .start_authorization(harness.authorize_request(
+ &victim_client_id,
+ ATTACKER_REDIRECT_URI,
+ &code_challenge_for(ATTACKER_CODE_VERIFIER),
))
- }
+ .await
+ .expect_err("the crafted authorize request must fail");
- 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,
- })
+ assert!(matches!(error, StartAuthorizationError::InvalidRedirectUri));
+ assert!(
+ !harness.inflight.has_pending(),
+ "no handshake state may be created for a rejected authorize request"
+ );
+}
+
+// --- Token exchange ----------------------------------------------------
+
+#[tokio::test]
+async fn authorization_code_grant_returns_upstream_tokens() {
+ 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 response = harness
+ .service
+ .exchange_token(TokenRequest {
+ grant_type: "authorization_code".to_owned(),
+ code: Some(code),
+ code_verifier: Some(VICTIM_CODE_VERIFIER.to_owned()),
+ refresh_token: None,
+ redirect_uri: Some(TRUSTED_REDIRECT_URI.to_owned()),
+ client_id: Some(client_id),
})
- }
+ .await
+ .expect("the legitimate client should get its tokens");
- 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,
- })
+ assert_eq!(response.access_token.as_str(), UPSTREAM_ACCESS_TOKEN);
+ assert_eq!(response.refresh_token.as_str(), UPSTREAM_REFRESH_TOKEN);
+}
+
+#[tokio::test]
+async fn authorization_code_grant_requires_a_client_id() {
+ 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 error = harness
+ .service
+ .exchange_token(TokenRequest {
+ grant_type: "authorization_code".to_owned(),
+ code: Some(code.clone()),
+ code_verifier: Some(VICTIM_CODE_VERIFIER.to_owned()),
+ refresh_token: None,
+ redirect_uri: Some(TRUSTED_REDIRECT_URI.to_owned()),
+ client_id: None,
})
- }
+ .await
+ .expect_err("a token request without client_id must be rejected");
+
+ assert!(matches!(error, TokenExchangeError::ClientIdRequired));
+ assert!(
+ harness.inflight.holds_issued_code(&code),
+ "a request rejected before validation must not spend the code"
+ );
}
-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,
- }),
- )
+#[tokio::test]
+async fn authorization_code_grant_rejects_a_different_client() {
+ let harness = Harness::new();
+ let victim_client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
+ let other_client_id = harness.register(&[LOOPBACK_REDIRECT_URI]).await;
+ let code = harness
+ .complete_flow_to_code(
+ &victim_client_id,
+ TRUSTED_REDIRECT_URI,
+ VICTIM_CODE_VERIFIER,
+ )
+ .await;
+
+ let error = harness
+ .service
+ .exchange_token(TokenRequest {
+ grant_type: "authorization_code".to_owned(),
+ code: Some(code),
+ code_verifier: Some(VICTIM_CODE_VERIFIER.to_owned()),
+ refresh_token: None,
+ redirect_uri: Some(TRUSTED_REDIRECT_URI.to_owned()),
+ client_id: Some(other_client_id),
+ })
+ .await
+ .expect_err("a code must only be redeemable by the client it was issued to");
+
+ assert!(matches!(error, TokenExchangeError::ClientMismatch));
}
-#[test]
-fn protected_resource_metadata_includes_required_resource_url() {
- let json = service(FakeInflightAuth::default()).protected_resource_metadata();
- assert_eq!(
- json,
- serde_json::json!({
- "resource": "https://mcp.example.com/mcp",
- "authorization_server": "https://mcp.example.com",
- "authorization_servers": ["https://mcp.example.com"],
+// --- Refresh grant ----------------------------------------------------
+
+#[tokio::test]
+async fn refresh_grant_succeeds_for_the_client_the_token_was_issued_to() {
+ 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 issued = harness
+ .service
+ .exchange_token(TokenRequest {
+ grant_type: "authorization_code".to_owned(),
+ code: Some(code),
+ code_verifier: Some(VICTIM_CODE_VERIFIER.to_owned()),
+ refresh_token: None,
+ redirect_uri: Some(TRUSTED_REDIRECT_URI.to_owned()),
+ client_id: Some(client_id.clone()),
})
- );
+ .await
+ .expect("code exchange should succeed");
+
+ let refreshed = harness
+ .service
+ .exchange_token(TokenRequest {
+ grant_type: "refresh_token".to_owned(),
+ code: None,
+ code_verifier: None,
+ refresh_token: Some(issued.refresh_token),
+ redirect_uri: None,
+ client_id: Some(client_id),
+ })
+ .await
+ .expect("the bound client should be able to refresh");
+
+ assert_eq!(refreshed.access_token.as_str(), REFRESHED_ACCESS_TOKEN);
}
-#[test]
-fn protected_resource_metadata_does_not_double_the_mcp_path() {
- let service = McpAuthProxyServiceImpl::new(
- "https://gateway.macro.com/mcp".to_owned(),
- Arc::new(FakeInflightAuth::default()),
- Arc::new(FakeOAuthProvider {
- expires_in: UPSTREAM_EXPIRES_IN,
- }),
- );
- assert_eq!(
- service.protected_resource_metadata(),
- serde_json::json!({
- "resource": "https://gateway.macro.com/mcp",
- "authorization_server": "https://gateway.macro.com/mcp",
- "authorization_servers": ["https://gateway.macro.com/mcp"],
+#[tokio::test]
+async fn refresh_grant_rejects_an_unbound_refresh_token() {
+ let harness = Harness::new();
+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
+
+ let error = harness
+ .service
+ .exchange_token(TokenRequest {
+ grant_type: "refresh_token".to_owned(),
+ code: None,
+ code_verifier: None,
+ refresh_token: Some(RefreshToken::from(UPSTREAM_REFRESH_TOKEN)),
+ redirect_uri: None,
+ client_id: Some(client_id),
+ })
+ .await
+ .expect_err("a refresh token the broker never issued must be rejected");
+
+ assert!(matches!(error, TokenExchangeError::UnboundRefreshToken));
+}
+
+#[tokio::test]
+async fn refresh_grant_rejects_a_client_the_token_was_not_issued_to() {
+ 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 code = harness
+ .complete_flow_to_code(&owner_client_id, TRUSTED_REDIRECT_URI, VICTIM_CODE_VERIFIER)
+ .await;
+
+ let issued = harness
+ .service
+ .exchange_token(TokenRequest {
+ grant_type: "authorization_code".to_owned(),
+ code: Some(code),
+ code_verifier: Some(VICTIM_CODE_VERIFIER.to_owned()),
+ refresh_token: None,
+ redirect_uri: Some(TRUSTED_REDIRECT_URI.to_owned()),
+ client_id: Some(owner_client_id),
})
+ .await
+ .expect("code exchange should succeed");
+
+ let error = harness
+ .service
+ .exchange_token(TokenRequest {
+ grant_type: "refresh_token".to_owned(),
+ code: None,
+ code_verifier: None,
+ refresh_token: Some(issued.refresh_token),
+ redirect_uri: None,
+ client_id: Some(other_client_id),
+ })
+ .await
+ .expect_err("another client must not be able to use this refresh token");
+
+ assert!(matches!(error, TokenExchangeError::ClientMismatch));
+}
+
+#[tokio::test]
+async fn refresh_grant_requires_a_client_id() {
+ let harness = Harness::new();
+
+ let error = harness
+ .service
+ .exchange_token(TokenRequest {
+ grant_type: "refresh_token".to_owned(),
+ code: None,
+ code_verifier: None,
+ refresh_token: Some(RefreshToken::from(UPSTREAM_REFRESH_TOKEN)),
+ redirect_uri: None,
+ client_id: None,
+ })
+ .await
+ .expect_err("a refresh without client_id must be rejected");
+
+ assert!(matches!(error, TokenExchangeError::ClientIdRequired));
+}
+
+#[tokio::test]
+async fn rotated_refresh_token_is_rebound_and_the_old_one_is_refused() {
+ let harness = Harness::with_provider(FakeOAuthProvider::rotating("rotated-refresh-token"));
+ 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 issued = harness
+ .service
+ .exchange_token(TokenRequest {
+ grant_type: "authorization_code".to_owned(),
+ code: Some(code),
+ code_verifier: Some(VICTIM_CODE_VERIFIER.to_owned()),
+ refresh_token: None,
+ redirect_uri: Some(TRUSTED_REDIRECT_URI.to_owned()),
+ client_id: Some(client_id.clone()),
+ })
+ .await
+ .expect("code exchange should succeed");
+ let original_refresh_token = issued.refresh_token.clone();
+
+ let refreshed = harness
+ .service
+ .exchange_token(TokenRequest {
+ grant_type: "refresh_token".to_owned(),
+ code: None,
+ code_verifier: None,
+ refresh_token: Some(original_refresh_token.clone()),
+ redirect_uri: None,
+ client_id: Some(client_id.clone()),
+ })
+ .await
+ .expect("the bound client should be able to refresh");
+ assert_eq!(refreshed.refresh_token.as_str(), "rotated-refresh-token");
+
+ let replay = harness
+ .service
+ .exchange_token(TokenRequest {
+ grant_type: "refresh_token".to_owned(),
+ code: None,
+ code_verifier: None,
+ refresh_token: Some(original_refresh_token),
+ redirect_uri: None,
+ client_id: Some(client_id.clone()),
+ })
+ .await
+ .expect_err("the superseded refresh token must not work again");
+ assert!(matches!(replay, TokenExchangeError::UnboundRefreshToken));
+
+ let rotated = harness
+ .service
+ .exchange_token(TokenRequest {
+ grant_type: "refresh_token".to_owned(),
+ code: None,
+ code_verifier: None,
+ refresh_token: Some(refreshed.refresh_token),
+ redirect_uri: None,
+ client_id: Some(client_id),
+ })
+ .await;
+ assert!(rotated.is_ok(), "the rotated token must be usable");
+}
+
+// --- Redirect construction -------------------------------------------
+
+#[tokio::test]
+async fn callback_redirect_preserves_a_query_on_the_registered_redirect_uri() {
+ let harness = Harness::new();
+ let redirect_uri = "https://claude.ai/api/mcp/auth_callback?tenant=macro";
+ let client_id = harness.register(&[redirect_uri]).await;
+
+ harness
+ .service
+ .start_authorization(harness.authorize_request(
+ &client_id,
+ redirect_uri,
+ &code_challenge_for(VICTIM_CODE_VERIFIER),
+ ))
+ .await
+ .expect("authorize should succeed");
+
+ let redirect = harness
+ .service
+ .complete_callback(CallbackRequest {
+ code: Some("upstream-code".to_owned()),
+ state: Some(harness.inflight.only_pending_session_id()),
+ error: None,
+ error_description: None,
+ })
+ .await
+ .expect("callback should succeed");
+
+ assert!(
+ redirect.starts_with("https://claude.ai/api/mcp/auth_callback?tenant=macro&code="),
+ "unexpected redirect: {redirect}"
);
+ assert!(redirect.contains("&state=client-state"));
}
-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,
- }
+// --- Upstream token lifetime ------------------------------------------
+
+/// Seeds a broker code for `client_id` expiring at `access_token_expires_at`,
+/// bypassing the handshake so the expiry under test is exact.
+async fn seed_issued_code(
+ harness: &Harness,
+ code: &str,
+ client_id: &str,
+ access_token_expires_at: Option<SystemTime>,
+) {
+ harness
+ .inflight
+ .insert_issued(
+ code,
+ IssuedAuthorizationCode {
+ client_id: client_id.to_owned(),
+ access_token: AccessToken::from(UPSTREAM_ACCESS_TOKEN),
+ refresh_token: RefreshToken::from(UPSTREAM_REFRESH_TOKEN),
+ code_challenge: code_challenge_for(VICTIM_CODE_VERIFIER),
+ redirect_uri: TRUSTED_REDIRECT_URI.to_owned(),
+ access_token_expires_at,
+ },
+ )
+ .await
+ .expect("seeding an issued code should succeed");
}
-fn authorization_code_request(code: &str) -> TokenRequest {
+fn authorization_code_request(code: &str, client_id: &str) -> TokenRequest {
TokenRequest {
grant_type: "authorization_code".to_owned(),
code: Some(code.to_owned()),
- code_verifier: Some(CODE_VERIFIER.to_owned()),
+ code_verifier: Some(VICTIM_CODE_VERIFIER.to_owned()),
refresh_token: None,
- redirect_uri: Some(REDIRECT_URI.to_owned()),
- client_id: None,
+ redirect_uri: Some(TRUSTED_REDIRECT_URI.to_owned()),
+ client_id: Some(client_id.to_owned()),
}
}
@@ -171,14 +505,14 @@ fn authorization_code_request(code: &str) -> TokenRequest {
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 harness = Harness::new();
+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
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)),
- ));
+ seed_issued_code(&harness, "broker-code", &client_id, Some(expires_at)).await;
- let response = service
- .exchange_token(authorization_code_request("broker-code"))
+ let response = harness
+ .service
+ .exchange_token(authorization_code_request("broker-code", &client_id))
.await
.expect("token exchange should succeed");
@@ -192,15 +526,19 @@ async fn authorization_code_exchange_returns_remaining_lifetime() {
#[tokio::test]
async fn authorization_code_exchange_serializes_expires_in() {
- let service = service(FakeInflightAuth::with_issued(
+ let harness = Harness::new();
+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
+ seed_issued_code(
+ &harness,
"broker-code",
- issued_code(Some(
- SystemTime::now() + Duration::from_secs(UPSTREAM_EXPIRES_IN),
- )),
- ));
+ &client_id,
+ Some(SystemTime::now() + Duration::from_secs(UPSTREAM_EXPIRES_IN)),
+ )
+ .await;
- let response = service
- .exchange_token(authorization_code_request("broker-code"))
+ let response = harness
+ .service
+ .exchange_token(authorization_code_request("broker-code", &client_id))
.await
.expect("token exchange should succeed");
@@ -216,13 +554,13 @@ async fn authorization_code_exchange_serializes_expires_in() {
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 harness = Harness::new();
+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
+ seed_issued_code(&harness, "broker-code", &client_id, None).await;
- let response = service
- .exchange_token(authorization_code_request("broker-code"))
+ let response = harness
+ .service
+ .exchange_token(authorization_code_request("broker-code", &client_id))
.await
.expect("token exchange should succeed");
@@ -236,13 +574,19 @@ async fn authorization_code_exchange_omits_unknown_expiry() {
#[tokio::test]
async fn expired_access_token_reports_zero_rather_than_underflowing() {
- let service = service(FakeInflightAuth::with_issued(
+ let harness = Harness::new();
+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
+ seed_issued_code(
+ &harness,
"broker-code",
- issued_code(Some(SystemTime::now() - Duration::from_secs(60))),
- ));
+ &client_id,
+ Some(SystemTime::now() - Duration::from_secs(60)),
+ )
+ .await;
- let response = service
- .exchange_token(authorization_code_request("broker-code"))
+ let response = harness
+ .service
+ .exchange_token(authorization_code_request("broker-code", &client_id))
.await
.expect("token exchange should succeed");
@@ -251,63 +595,65 @@ async fn expired_access_token_reports_zero_rather_than_underflowing() {
#[tokio::test]
async fn refresh_grant_returns_upstream_lifetime() {
- let service = service(FakeInflightAuth::default());
+ 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 issued = harness
+ .service
+ .exchange_token(authorization_code_request(&code, &client_id))
+ .await
+ .expect("code exchange should succeed");
- let response = service
+ let refreshed = harness
+ .service
.exchange_token(TokenRequest {
grant_type: "refresh_token".to_owned(),
code: None,
code_verifier: None,
- refresh_token: Some(RefreshToken::from("upstream-refresh")),
+ refresh_token: Some(issued.refresh_token),
redirect_uri: None,
- client_id: None,
+ client_id: Some(client_id),
})
.await
.expect("refresh exchange should succeed");
- assert_eq!(response.expires_in, Some(UPSTREAM_EXPIRES_IN));
- assert_eq!(response.access_token.as_str(), "refreshed-access");
+ assert_eq!(refreshed.expires_in, Some(UPSTREAM_EXPIRES_IN));
+ assert_eq!(refreshed.access_token.as_str(), REFRESHED_ACCESS_TOKEN);
}
#[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(),
- },
- )
+ let harness = Harness::new();
+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
+
+ harness
+ .service
+ .start_authorization(harness.authorize_request(
+ &client_id,
+ TRUSTED_REDIRECT_URI,
+ &code_challenge_for(VICTIM_CODE_VERIFIER),
+ ))
.await
- .expect("pending insert should succeed");
+ .expect("authorize should succeed");
- service
+ harness
+ .service
.complete_callback(CallbackRequest {
code: Some("upstream-code".to_owned()),
- state: Some("session-id".to_owned()),
+ state: Some(harness.inflight.only_pending_session_id()),
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
+ 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();
@@ -316,3 +662,30 @@ async fn callback_records_upstream_expiry_on_the_issued_code() {
"expected roughly {UPSTREAM_EXPIRES_IN} seconds remaining, got {remaining}"
);
}
+
+#[test]
+fn protected_resource_metadata_includes_required_resource_url() {
+ let json = Harness::new().service.protected_resource_metadata();
+ assert_eq!(
+ json,
+ serde_json::json!({
+ "resource": "https://mcp.macro.com/mcp",
+ "authorization_server": "https://mcp.macro.com",
+ "authorization_servers": ["https://mcp.macro.com"],
+ })
+ );
+}
+
+#[test]
+fn protected_resource_metadata_does_not_double_the_mcp_path() {
+ let mut service = Harness::new().service;
+ service.public_url = "https://gateway.macro.com/mcp".to_owned();
+ assert_eq!(
+ service.protected_resource_metadata(),
+ serde_json::json!({
+ "resource": "https://gateway.macro.com/mcp",
+ "authorization_server": "https://gateway.macro.com/mcp",
+ "authorization_servers": ["https://gateway.macro.com/mcp"],
+ })
+ );
+}
diff --git a/services/mcp_auth_proxy/src/inbound/axum_router.rs b/services/mcp_auth_proxy/src/inbound/axum_router.rs
index 4226a22aff..6ba16dc265 100644
--- a/services/mcp_auth_proxy/src/inbound/axum_router.rs
+++ b/services/mcp_auth_proxy/src/inbound/axum_router.rs
@@ -17,10 +17,10 @@ use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use tower_http::cors::{AllowOrigin, CorsLayer};
use crate::domain::{
- models::{AuthorizeRequest, CallbackRequest, TokenRequest},
+ models::{AuthorizeRequest, CallbackRequest, ClientRegistrationRequest, TokenRequest},
service::{
CompleteCallbackError, InflightAuthStore, McpAuthProxyService, McpAuthProxyServiceImpl,
- StartAuthorizationError, TokenExchangeError,
+ RegisterClientError, StartAuthorizationError, TokenExchangeError,
},
};
@@ -43,9 +43,42 @@ async fn protected_resource_metadata<I: InflightAuthStore + 'static>(
async fn register<I: InflightAuthStore + 'static>(
State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,
- axum::Json(body): axum::Json<serde_json::Value>,
-) -> Json<serde_json::Value> {
- Json(auth_proxy.register_client(body))
+ axum::Json(body): axum::Json<ClientRegistrationRequest>,
+) -> Response {
+ match auth_proxy.register_client(body).await {
+ // RFC 7591 section 3.2.1 only says SHOULD for 201, and clients already
+ // work against the 200 this endpoint has always returned.
+ Ok(registration) => Json(registration).into_response(),
+ Err(RegisterClientError::RedirectUrisRequired) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "at least one redirect_uri is required",
+ )
+ .into_response(),
+ Err(RegisterClientError::TooManyRedirectUris) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "too many redirect_uris",
+ )
+ .into_response(),
+ Err(RegisterClientError::UnsupportedRedirectUri { uri }) => {
+ tracing::warn!(
+ rejected_redirect_uri = %uri,
+ "client registration used a redirect_uri this deployment does not trust"
+ );
+ (
+ axum::http::StatusCode::BAD_REQUEST,
+ "redirect_uri must be a loopback address or a trusted MCP client host",
+ )
+ .into_response()
+ }
+ Err(RegisterClientError::ClientRegistrationStore(error)) => {
+ tracing::error!(error=?error, "failed to persist client registration");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to persist client registration",
+ )
+ .into_response()
+ }
+ }
}
async fn authorize<I: InflightAuthStore + 'static>(
@@ -66,9 +99,25 @@ async fn authorize<I: InflightAuthStore + 'static>(
.into_response(),
Err(StartAuthorizationError::InvalidRedirectUri) => (
axum::http::StatusCode::BAD_REQUEST,
- "redirect_uri must be https or a loopback address",
+ "redirect_uri must be a loopback address or a trusted MCP client host",
)
.into_response(),
+ Err(StartAuthorizationError::UnregisteredRedirectUri) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "redirect_uri was not registered for this client",
+ )
+ .into_response(),
+ Err(StartAuthorizationError::UnknownClient) => {
+ (axum::http::StatusCode::BAD_REQUEST, "unknown client_id").into_response()
+ }
+ Err(StartAuthorizationError::ClientRegistrationStore(error)) => {
+ tracing::error!(error=?error, "failed to read client registrations");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to read client registrations",
+ )
+ .into_response()
+ }
Err(StartAuthorizationError::InflightStore(error)) => {
tracing::error!(error=?error, "failed to persist inflight auth state");
(
@@ -174,6 +223,19 @@ async fn token<I: InflightAuthStore + 'static>(
"refresh_token required",
)
.into_response(),
+ Err(TokenExchangeError::ClientIdRequired) => {
+ (axum::http::StatusCode::BAD_REQUEST, "client_id required").into_response()
+ }
+ Err(TokenExchangeError::ClientMismatch) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "grant was not issued to this client",
+ )
+ .into_response(),
+ Err(TokenExchangeError::UnboundRefreshToken) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "refresh token is not bound to a client",
+ )
+ .into_response(),
Err(TokenExchangeError::InflightStore(error)) => {
tracing::error!(error=?error, "failed to access inflight auth state");
(
@@ -182,6 +244,14 @@ async fn token<I: InflightAuthStore + 'static>(
)
.into_response()
}
+ Err(TokenExchangeError::RefreshTokenBindingStore(error)) => {
+ tracing::error!(error=?error, "failed to access refresh token bindings");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to access refresh token bindings",
+ )
+ .into_response()
+ }
Err(TokenExchangeError::RefreshFailed(error)) => {
tracing::error!(error=?error, "upstream refresh token exchange failed");
(
@@ -193,24 +263,13 @@ async fn token<I: InflightAuthStore + 'static>(
}
}
-/// Builds the complete MCP router: unauthenticated OAuth broker routes plus
-/// the Bearer-protected `/mcp` service route.
-pub fn mcp_router<I, S>(
- auth_proxy: McpAuthProxyServiceImpl<I>,
- jwt_args: JwtValidationArgs,
- mcp_service: S,
-) -> Router
+/// Builds the unauthenticated OAuth broker routes: discovery metadata,
+/// dynamic client registration, authorize, upstream callback, and token.
+pub fn oauth_router<I>(auth_proxy: McpAuthProxyServiceImpl<I>) -> Router
where
- I: InflightAuthStore + Clone + Send + Sync + 'static,
- S: tower::Service<axum::http::Request<axum::body::Body>, Error = std::convert::Infallible>
- + Clone
- + Send
- + Sync
- + 'static,
- S::Response: axum::response::IntoResponse,
- S::Future: Send + 'static,
+ I: InflightAuthStore + 'static,
{
- let oauth_routes = Router::new()
+ Router::new()
.route("/health", routing::get(health))
.route(
"/.well-known/oauth-protected-resource",
@@ -232,8 +291,26 @@ where
.route("/register", routing::post(register))
.route("/oauth/callback", routing::get(oauth_callback))
.route("/token", routing::post(token))
- .with_state(auth_proxy);
+ .with_state(auth_proxy)
+}
+/// Builds the complete MCP router: unauthenticated OAuth broker routes plus
+/// the Bearer-protected `/mcp` service route.
+pub fn mcp_router<I, S>(
+ auth_proxy: McpAuthProxyServiceImpl<I>,
+ jwt_args: JwtValidationArgs,
+ mcp_service: S,
+) -> Router
+where
+ I: InflightAuthStore + 'static,
+ S: tower::Service<axum::http::Request<axum::body::Body>, Error = std::convert::Infallible>
+ + Clone
+ + Send
+ + Sync
+ + 'static,
+ S::Response: axum::response::IntoResponse,
+ S::Future: Send + 'static,
+{
let mcp_route =
Router::new()
.nest_service("/mcp", mcp_service)
@@ -242,7 +319,7 @@ where
super::middleware::validate_bearer,
));
- mount_at_root_and_prefix(oauth_routes.merge(mcp_route)).layer(mcp_cors_layer())
+ mount_at_root_and_prefix(oauth_router(auth_proxy).merge(mcp_route)).layer(mcp_cors_layer())
}
fn mount_at_root_and_prefix(inner: Router) -> Router {
diff --git a/services/mcp_auth_proxy/src/inbound/axum_router/test.rs b/services/mcp_auth_proxy/src/inbound/axum_router/test.rs
index 4a9c9d8305..9a183aaa6e 100644
--- a/services/mcp_auth_proxy/src/inbound/axum_router/test.rs
+++ b/services/mcp_auth_proxy/src/inbound/axum_router/test.rs
@@ -1,22 +1,249 @@
-use std::sync::Arc;
-
-use super::{health, mcp_router, mount_at_root_and_prefix};
-use crate::domain::{
- models::{
- AccessToken, IssuedAuthorizationCode, PendingAuthorization, RefreshToken, UpstreamTokens,
- },
- ports::OAuthProvider,
- service::{InflightAuthStore, McpAuthProxyServiceImpl},
-};
+//! Drives the reported attack and the legitimate flow over the real router, so
+//! the checks are exercised through the same HTTP surface an attacker uses.
+
use axum::{
- Router,
body::Body,
- http::{Request, StatusCode},
- routing::get,
+ http::{Request, StatusCode, header},
};
-use macro_auth::middleware::decode_jwt::JwtValidationArgs;
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,
+};
+use axum::{Router, routing::get};
+use macro_auth::middleware::decode_jwt::JwtValidationArgs;
+
+const BODY_LIMIT: usize = 64 * 1024;
+
+struct Response {
+ status: StatusCode,
+ location: Option<String>,
+ body: String,
+}
+
+impl Response {
+ fn json(&self) -> serde_json::Value {
+ serde_json::from_str(&self.body).expect("response body should be JSON")
+ }
+}
+
+async fn send(harness: &Harness, request: Request<Body>) -> Response {
+ let response = oauth_router(harness.service.clone())
+ .oneshot(request)
+ .await
+ .expect("router should respond");
+
+ let status = response.status();
+ let location = response
+ .headers()
+ .get(header::LOCATION)
+ .map(|value| value.to_str().expect("Location is text").to_owned());
+ let bytes = axum::body::to_bytes(response.into_body(), BODY_LIMIT)
+ .await
+ .expect("body should be readable");
+
+ Response {
+ status,
+ location,
+ body: String::from_utf8(bytes.to_vec()).expect("body should be UTF-8"),
+ }
+}
+
+fn register_request(redirect_uri: &str) -> Request<Body> {
+ Request::builder()
+ .method("POST")
+ .uri("/register")
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(Body::from(format!(
+ r#"{{"client_name":"test-client","redirect_uris":["{redirect_uri}"]}}"#
+ )))
+ .expect("request should build")
+}
+
+fn authorize_request(client_id: &str, redirect_uri: &str, code_verifier: &str) -> Request<Body> {
+ let redirect_uri = urlencoding::encode(redirect_uri);
+ let code_challenge = code_challenge_for(code_verifier);
+ Request::builder()
+ .method("GET")
+ .uri(format!(
+ "/authorize?response_type=code&client_id={client_id}&redirect_uri={redirect_uri}\
+ &state=client-state&code_challenge={code_challenge}&code_challenge_method=S256"
+ ))
+ .body(Body::empty())
+ .expect("request should build")
+}
+
+fn token_request(form: &str) -> Request<Body> {
+ Request::builder()
+ .method("POST")
+ .uri("/token")
+ .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
+ .body(Body::from(form.to_owned()))
+ .expect("request should build")
+}
+
+fn callback_request(session_id: &str) -> Request<Body> {
+ Request::builder()
+ .method("GET")
+ .uri(format!(
+ "/oauth/callback?code=upstream-code&state={session_id}"
+ ))
+ .body(Body::empty())
+ .expect("request should build")
+}
+
+/// The attack from the report, over HTTP: the attacker cannot register their
+/// own callback, and cannot smuggle it onto an authorize request belonging to a
+/// client that is registered. No code reaches them, so there is nothing to
+/// exchange.
+#[tokio::test]
+async fn attacker_cannot_have_a_code_delivered_to_their_own_callback() {
+ let harness = Harness::new();
+
+ let registration = send(&harness, register_request(ATTACKER_REDIRECT_URI)).await;
+ assert_eq!(registration.status, StatusCode::BAD_REQUEST);
+ assert_eq!(
+ registration.body,
+ "redirect_uri must be a loopback address or a trusted MCP client host"
+ );
+
+ let victim_registration = send(&harness, register_request(TRUSTED_REDIRECT_URI)).await;
+ assert_eq!(victim_registration.status, StatusCode::OK);
+ let client_id = victim_registration.json()["client_id"]
+ .as_str()
+ .expect("registration returns a client_id")
+ .to_owned();
+
+ let crafted = send(
+ &harness,
+ authorize_request(&client_id, ATTACKER_REDIRECT_URI, ATTACKER_CODE_VERIFIER),
+ )
+ .await;
+
+ assert_eq!(crafted.status, StatusCode::BAD_REQUEST);
+ assert_eq!(
+ crafted.location, None,
+ "a rejected authorize request must not redirect anywhere"
+ );
+ assert!(
+ !harness.inflight.has_pending(),
+ "a rejected authorize request must not create handshake state"
+ );
+}
+
+#[tokio::test]
+async fn authorize_rejects_an_unregistered_client_id() {
+ let harness = Harness::new();
+
+ let response = send(
+ &harness,
+ authorize_request(
+ "not-a-registered-client",
+ TRUSTED_REDIRECT_URI,
+ VICTIM_CODE_VERIFIER,
+ ),
+ )
+ .await;
+
+ assert_eq!(response.status, StatusCode::BAD_REQUEST);
+ assert_eq!(response.body, "unknown client_id");
+}
+
+/// The flow a real MCP client drives, from registration through to a bearer
+/// token, so the added checks are shown not to break it.
+#[tokio::test]
+async fn registered_client_completes_the_whole_flow() {
+ let harness = Harness::new();
+
+ let registration = send(&harness, register_request(TRUSTED_REDIRECT_URI)).await;
+ assert_eq!(registration.status, StatusCode::OK);
+ let registration_body = registration.json();
+ let client_id = registration_body["client_id"]
+ .as_str()
+ .expect("registration returns a client_id")
+ .to_owned();
+ assert_eq!(
+ registration_body["redirect_uris"][0].as_str(),
+ Some(TRUSTED_REDIRECT_URI)
+ );
+
+ let authorize = send(
+ &harness,
+ authorize_request(&client_id, TRUSTED_REDIRECT_URI, VICTIM_CODE_VERIFIER),
+ )
+ .await;
+ assert_eq!(authorize.status, StatusCode::TEMPORARY_REDIRECT);
+ let upstream = authorize.location.expect("authorize redirects upstream");
+ assert!(
+ upstream.starts_with("https://upstream.example/authorize"),
+ "unexpected upstream redirect: {upstream}"
+ );
+
+ let session_id = harness.inflight.only_pending_session_id();
+ let callback = send(&harness, callback_request(&session_id)).await;
+ assert_eq!(callback.status, StatusCode::TEMPORARY_REDIRECT);
+ let client_redirect = callback.location.expect("callback redirects to the client");
+ assert!(
+ client_redirect.starts_with(TRUSTED_REDIRECT_URI),
+ "code was delivered somewhere unexpected: {client_redirect}"
+ );
+ let code = query_param(&client_redirect, "code").expect("redirect carries a code");
+
+ 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);
+ let tokens = exchange.json();
+ assert_eq!(
+ tokens["access_token"].as_str(),
+ Some(UPSTREAM_ACCESS_TOKEN),
+ "the legitimate client should receive the upstream access token"
+ );
+ assert_eq!(tokens["token_type"].as_str(), Some("Bearer"));
+}
+
+/// A code that reached one client is refused to any other, and the attempt
+/// spends it, so a mismatched redemption cannot be retried.
+#[tokio::test]
+async fn token_endpoint_refuses_a_code_presented_by_another_client() {
+ 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 encoded_redirect_uri = urlencoding::encode(TRUSTED_REDIRECT_URI).into_owned();
+
+ let stolen = send(
+ &harness,
+ token_request(&format!(
+ "grant_type=authorization_code&code={code}&code_verifier={ATTACKER_CODE_VERIFIER}\
+ &redirect_uri={encoded_redirect_uri}&client_id=some-other-client"
+ )),
+ )
+ .await;
+ assert_eq!(stolen.status, StatusCode::BAD_REQUEST);
+ assert_eq!(stolen.body, "grant was not issued to this client");
+
+ let retried = send(
+ &harness,
+ token_request(&format!(
+ "grant_type=authorization_code&code={code}&code_verifier={VICTIM_CODE_VERIFIER}\
+ &redirect_uri={encoded_redirect_uri}&client_id={client_id}"
+ )),
+ )
+ .await;
+ assert_eq!(retried.status, StatusCode::BAD_REQUEST);
+ assert_eq!(retried.body, "invalid or expired code");
+}
+
async fn ok() -> &'static str {
"ok"
}
@@ -45,85 +272,9 @@ async fn get_status(app: Router, path: &str) -> StatusCode {
.status()
}
-#[derive(Clone, Default)]
-struct NoopInflightAuth;
-
-impl InflightAuthStore for NoopInflightAuth {
- async fn insert_pending(
- &self,
- _session_id: &str,
- _pending: PendingAuthorization,
- ) -> anyhow::Result<()> {
- Ok(())
- }
-
- async fn take_pending(
- &self,
- _session_id: &str,
- ) -> anyhow::Result<Option<PendingAuthorization>> {
- Ok(None)
- }
-
- async fn insert_issued(
- &self,
- _code: &str,
- _issued: IssuedAuthorizationCode,
- ) -> anyhow::Result<()> {
- Ok(())
- }
-
- async fn take_issued(&self, _code: &str) -> anyhow::Result<Option<IssuedAuthorizationCode>> {
- Ok(None)
- }
-
- async fn cleanup_expired(&self) -> anyhow::Result<()> {
- Ok(())
- }
-}
-
-struct NoopOAuthProvider;
-
-impl OAuthProvider for NoopOAuthProvider {
- 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 {
- Ok(UpstreamTokens {
- access_token: AccessToken::from("access"),
- refresh_token: RefreshToken::from("refresh"),
- expires_in: 3600,
- })
- })
- }
-
- fn refresh_access_token<'a>(
- &'a self,
- _refresh_token: &'a RefreshToken,
- ) -> crate::domain::ports::UpstreamTokensFuture<'a> {
- Box::pin(async {
- Ok(UpstreamTokens {
- access_token: AccessToken::from("access"),
- refresh_token: RefreshToken::from("refresh"),
- expires_in: 3600,
- })
- })
- }
-}
-
fn built_router() -> Router {
mcp_router(
- McpAuthProxyServiceImpl::new(
- "https://mcp.example.com".to_owned(),
- Arc::new(NoopInflightAuth),
- Arc::new(NoopOAuthProvider),
- ),
+ Harness::new().service,
JwtValidationArgs::new_testing(),
Router::new().route("/", get(ok)),
)
diff --git a/services/mcp_auth_proxy/src/lib.rs b/services/mcp_auth_proxy/src/lib.rs
index 01a4e5e2c9..c26edc4f66 100644
--- a/services/mcp_auth_proxy/src/lib.rs
+++ b/services/mcp_auth_proxy/src/lib.rs
@@ -25,3 +25,5 @@ pub mod domain;
pub mod inbound;
#[cfg(feature = "outbound")]
pub mod outbound;
+#[cfg(test)]
+mod test_support;
diff --git a/services/mcp_auth_proxy/src/outbound/redis.rs b/services/mcp_auth_proxy/src/outbound/redis.rs
index e81bfb8b1e..d769811340 100644
--- a/services/mcp_auth_proxy/src/outbound/redis.rs
+++ b/services/mcp_auth_proxy/src/outbound/redis.rs
@@ -1,5 +1,8 @@
//! Redis-backed storage for short-lived OAuth handshake state.
+#[cfg(test)]
+mod test;
+
use anyhow::Context;
use redis::AsyncCommands;
use std::{
@@ -8,12 +11,21 @@ use std::{
};
use crate::domain::{
- models::{IssuedAuthorizationCode, PendingAuthorization},
- service::{AUTHORIZATION_CODE_TTL, InflightAuthStore, PENDING_AUTH_TTL},
+ models::{IssuedAuthorizationCode, PendingAuthorization, RegisteredClient},
+ ports::{
+ BoundClientIdFuture, ClientRegistrationStore, RefreshTokenBindingStore,
+ RegisteredClientFuture, StoreWriteFuture,
+ },
+ service::{
+ AUTHORIZATION_CODE_TTL, CLIENT_REGISTRATION_TTL, InflightAuthStore, PENDING_AUTH_TTL,
+ REFRESH_TOKEN_BINDING_TTL,
+ },
};
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:";
/// Redis-backed implementation of the in-flight OAuth state store.
#[derive(Clone)]
@@ -36,8 +48,167 @@ impl RedisInflightAuth {
}
}
+/// Redis-backed store for dynamic client registrations and the refresh token
+/// bindings derived from them.
+#[derive(Clone)]
+pub struct RedisClientRegistry {
+ client: redis::Client,
+}
+
+impl RedisClientRegistry {
+ /// Creates a new Redis-backed client registry.
+ pub fn new(client: redis::Client) -> Self {
+ Self { client }
+ }
+
+ fn client_key(client_id: &str) -> String {
+ format!("{CLIENT_KEY_PREFIX}{client_id}")
+ }
+
+ fn refresh_binding_key(refresh_token_digest: &str) -> String {
+ format!("{REFRESH_BINDING_KEY_PREFIX}{refresh_token_digest}")
+ }
+}
+
+#[derive(serde::Serialize, serde::Deserialize)]
+struct StoredRegisteredClient {
+ client_id: String,
+ client_name: String,
+ redirect_uris: Vec<String>,
+}
+
+impl From<&RegisteredClient> for StoredRegisteredClient {
+ fn from(value: &RegisteredClient) -> Self {
+ Self {
+ client_id: value.client_id.clone(),
+ client_name: value.client_name.clone(),
+ redirect_uris: value.redirect_uris.clone(),
+ }
+ }
+}
+
+impl From<StoredRegisteredClient> for RegisteredClient {
+ fn from(value: StoredRegisteredClient) -> Self {
+ Self {
+ client_id: value.client_id,
+ client_name: value.client_name,
+ redirect_uris: value.redirect_uris,
+ }
+ }
+}
+
+#[allow(clippy::manual_async_fn)]
+impl ClientRegistrationStore for RedisClientRegistry {
+ fn insert_client<'a>(&'a self, client: &'a RegisteredClient) -> StoreWriteFuture<'a> {
+ let redis_client = self.client.clone();
+ let key = Self::client_key(&client.client_id);
+ Box::pin(async move {
+ let value = serde_json::to_string(&StoredRegisteredClient::from(client))
+ .context("failed to serialize client registration")?;
+ let mut conn = redis_client
+ .get_multiplexed_async_connection()
+ .await
+ .context("unable to connect to redis")?;
+ conn.set_ex::<String, String, ()>(
+ key.clone(),
+ value,
+ CLIENT_REGISTRATION_TTL.as_secs(),
+ )
+ .await
+ .with_context(|| format!("failed to persist client registration for key {key}"))?;
+ Ok(())
+ })
+ }
+
+ fn find_client<'a>(&'a self, client_id: &'a str) -> RegisteredClientFuture<'a> {
+ let redis_client = self.client.clone();
+ let key = Self::client_key(client_id);
+ Box::pin(async move {
+ let mut conn = redis_client
+ .get_multiplexed_async_connection()
+ .await
+ .context("unable to connect to redis")?;
+ // GETEX reads and re-arms the TTL in one round trip, which makes a
+ // registration expire only after it has gone unused for the whole
+ // window rather than a fixed time after it was created.
+ let value: Option<String> = redis::cmd("GETEX")
+ .arg(&key)
+ .arg("EX")
+ .arg(CLIENT_REGISTRATION_TTL.as_secs())
+ .query_async(&mut conn)
+ .await
+ .with_context(|| format!("failed to fetch client registration for key {key}"))?;
+ value
+ .map(|json| {
+ serde_json::from_str::<StoredRegisteredClient>(&json)
+ .map(RegisteredClient::from)
+ .context("failed to deserialize client registration")
+ })
+ .transpose()
+ })
+ }
+}
+
+#[allow(clippy::manual_async_fn)]
+impl RefreshTokenBindingStore for RedisClientRegistry {
+ fn bind<'a>(
+ &'a self,
+ refresh_token_digest: &'a str,
+ client_id: &'a str,
+ ) -> StoreWriteFuture<'a> {
+ let redis_client = self.client.clone();
+ let key = Self::refresh_binding_key(refresh_token_digest);
+ Box::pin(async move {
+ let mut conn = redis_client
+ .get_multiplexed_async_connection()
+ .await
+ .context("unable to connect to redis")?;
+ conn.set_ex::<String, &str, ()>(
+ key.clone(),
+ client_id,
+ REFRESH_TOKEN_BINDING_TTL.as_secs(),
+ )
+ .await
+ .with_context(|| format!("failed to persist refresh token binding for key {key}"))?;
+ Ok(())
+ })
+ }
+
+ fn bound_client<'a>(&'a self, refresh_token_digest: &'a str) -> BoundClientIdFuture<'a> {
+ let redis_client = self.client.clone();
+ let key = Self::refresh_binding_key(refresh_token_digest);
+ Box::pin(async move {
+ let mut conn = redis_client
+ .get_multiplexed_async_connection()
+ .await
+ .context("unable to connect to redis")?;
+ let client_id: Option<String> = conn
+ .get(&key)
+ .await
+ .with_context(|| format!("failed to fetch refresh token binding for key {key}"))?;
+ Ok(client_id)
+ })
+ }
+
+ fn unbind<'a>(&'a self, refresh_token_digest: &'a str) -> StoreWriteFuture<'a> {
+ let redis_client = self.client.clone();
+ let key = Self::refresh_binding_key(refresh_token_digest);
+ Box::pin(async move {
+ let mut conn = redis_client
+ .get_multiplexed_async_connection()
+ .await
+ .context("unable to connect to redis")?;
+ conn.del::<&str, ()>(&key)
+ .await
+ .with_context(|| format!("failed to delete refresh token binding for key {key}"))?;
+ Ok(())
+ })
+ }
+}
+
#[derive(serde::Serialize, serde::Deserialize)]
struct StoredPendingAuthorization {
+ client_id: String,
code_challenge: String,
client_state: String,
client_redirect_uri: String,
@@ -46,6 +217,7 @@ struct StoredPendingAuthorization {
impl From<PendingAuthorization> for StoredPendingAuthorization {
fn from(value: PendingAuthorization) -> Self {
Self {
+ client_id: value.client_id,
code_challenge: value.code_challenge,
client_state: value.client_state,
client_redirect_uri: value.client_redirect_uri,
@@ -56,6 +228,7 @@ impl From<PendingAuthorization> for StoredPendingAuthorization {
impl From<StoredPendingAuthorization> for PendingAuthorization {
fn from(value: StoredPendingAuthorization) -> Self {
Self {
+ client_id: value.client_id,
code_challenge: value.code_challenge,
client_state: value.client_state,
client_redirect_uri: value.client_redirect_uri,
@@ -65,6 +238,7 @@ impl From<StoredPendingAuthorization> for PendingAuthorization {
#[derive(serde::Serialize, serde::Deserialize)]
struct StoredIssuedAuthorizationCode {
+ client_id: String,
access_token: crate::domain::models::AccessToken,
refresh_token: crate::domain::models::RefreshToken,
code_challenge: String,
@@ -78,6 +252,7 @@ struct StoredIssuedAuthorizationCode {
impl From<IssuedAuthorizationCode> for StoredIssuedAuthorizationCode {
fn from(value: IssuedAuthorizationCode) -> Self {
Self {
+ client_id: value.client_id,
access_token: value.access_token,
refresh_token: value.refresh_token,
code_challenge: value.code_challenge,
@@ -95,6 +270,7 @@ impl From<IssuedAuthorizationCode> for StoredIssuedAuthorizationCode {
impl From<StoredIssuedAuthorizationCode> for IssuedAuthorizationCode {
fn from(value: StoredIssuedAuthorizationCode) -> Self {
Self {
+ client_id: value.client_id,
access_token: value.access_token,
refresh_token: value.refresh_token,
code_challenge: value.code_challenge,
diff --git a/services/mcp_auth_proxy/src/outbound/redis/test.rs b/services/mcp_auth_proxy/src/outbound/redis/test.rs
new file mode 100644
index 0000000000..109283b7d5
--- /dev/null
+++ b/services/mcp_auth_proxy/src/outbound/redis/test.rs
@@ -0,0 +1,220 @@
+//! Round-trip tests for the Redis adapter against a live local Redis.
+//!
+//! Start it with `bash .cursor/infra.sh` (or `just run_dbs -d`), then run
+//! `cargo test -p mcp_auth_proxy --all-features -- --ignored`.
+
+use redis::AsyncCommands;
+use std::time::{Duration, UNIX_EPOCH};
+
+use super::*;
+use crate::domain::models::{AccessToken, RefreshToken};
+
+const LOCAL_REDIS_URL: &str = "redis://127.0.0.1:6379/";
+
+fn client() -> redis::Client {
+ redis::Client::open(LOCAL_REDIS_URL).expect("local redis url should parse")
+}
+
+fn unique(prefix: &str) -> String {
+ format!("{prefix}-{}", uuid::Uuid::new_v4())
+}
+
+fn registered_client(client_id: &str) -> RegisteredClient {
+ RegisteredClient {
+ client_id: client_id.to_owned(),
+ client_name: "test-client".to_owned(),
+ redirect_uris: vec![
+ "https://claude.ai/api/mcp/auth_callback".to_owned(),
+ "http://127.0.0.1:51000/oauth/callback".to_owned(),
+ ],
+ }
+}
+
+#[tokio::test]
+#[ignore = "requires a local Redis"]
+async fn client_registration_round_trips() {
+ let registry = RedisClientRegistry::new(client());
+ let client_id = unique("client");
+
+ assert!(
+ registry
+ .find_client(&client_id)
+ .await
+ .expect("lookup should succeed")
+ .is_none(),
+ "an unregistered client_id must not resolve"
+ );
+
+ registry
+ .insert_client(&registered_client(&client_id))
+ .await
+ .expect("insert should succeed");
+
+ let found = registry
+ .find_client(&client_id)
+ .await
+ .expect("lookup should succeed")
+ .expect("the registration should be readable");
+
+ assert_eq!(found.client_id, client_id);
+ assert_eq!(found.client_name, "test-client");
+ assert_eq!(
+ found.redirect_uris,
+ vec![
+ "https://claude.ai/api/mcp/auth_callback",
+ "http://127.0.0.1:51000/oauth/callback"
+ ]
+ );
+}
+
+/// The lookup uses `GETEX ... EX`, so reading a registration must push its
+/// expiry back out to the full window.
+#[tokio::test]
+#[ignore = "requires a local Redis"]
+async fn looking_up_a_client_re_arms_its_ttl() {
+ let redis_client = client();
+ let registry = RedisClientRegistry::new(redis_client.clone());
+ let client_id = unique("client-ttl");
+ let key = RedisClientRegistry::client_key(&client_id);
+
+ registry
+ .insert_client(&registered_client(&client_id))
+ .await
+ .expect("insert should succeed");
+
+ let mut conn = redis_client
+ .get_multiplexed_async_connection()
+ .await
+ .expect("redis should be reachable");
+ conn.expire::<&str, ()>(&key, 5)
+ .await
+ .expect("expire should succeed");
+ let shortened: i64 = conn.ttl(&key).await.expect("ttl should succeed");
+ assert!(shortened <= 5, "TTL was not shortened: {shortened}");
+
+ registry
+ .find_client(&client_id)
+ .await
+ .expect("lookup should succeed")
+ .expect("the registration should still be there");
+
+ let re_armed: i64 = conn.ttl(&key).await.expect("ttl should succeed");
+ assert!(
+ re_armed > 5,
+ "lookup did not re-arm the TTL, still {re_armed}"
+ );
+}
+
+#[tokio::test]
+#[ignore = "requires a local Redis"]
+async fn refresh_token_binding_round_trips() {
+ let registry = RedisClientRegistry::new(client());
+ let digest = unique("digest");
+ let client_id = unique("client-binding");
+
+ assert!(
+ registry
+ .bound_client(&digest)
+ .await
+ .expect("lookup should succeed")
+ .is_none(),
+ "an unbound digest must not resolve"
+ );
+
+ registry
+ .bind(&digest, &client_id)
+ .await
+ .expect("bind should succeed");
+ assert_eq!(
+ registry
+ .bound_client(&digest)
+ .await
+ .expect("lookup should succeed"),
+ Some(client_id)
+ );
+
+ registry
+ .unbind(&digest)
+ .await
+ .expect("unbind should succeed");
+ assert!(
+ registry
+ .bound_client(&digest)
+ .await
+ .expect("lookup should succeed")
+ .is_none(),
+ "an unbound digest must not resolve"
+ );
+}
+
+/// Handshake state carries the client id now, so the stored form has to survive
+/// a round trip with it.
+#[tokio::test]
+#[ignore = "requires a local Redis"]
+async fn handshake_state_round_trips_with_its_client_id() {
+ let inflight = RedisInflightAuth::new(client());
+ let session_id = unique("session");
+ let code = unique("code");
+
+ inflight
+ .insert_pending(
+ &session_id,
+ PendingAuthorization {
+ client_id: "client-abc".to_owned(),
+ code_challenge: "challenge".to_owned(),
+ client_state: "state".to_owned(),
+ client_redirect_uri: "https://claude.ai/api/mcp/auth_callback".to_owned(),
+ },
+ )
+ .await
+ .expect("insert should succeed");
+
+ let pending = inflight
+ .take_pending(&session_id)
+ .await
+ .expect("take should succeed")
+ .expect("the pending flow should be readable");
+ assert_eq!(pending.client_id, "client-abc");
+ assert!(
+ inflight
+ .take_pending(&session_id)
+ .await
+ .expect("take should succeed")
+ .is_none(),
+ "a pending flow must be single-use"
+ );
+
+ // Stored as unix seconds, so the round trip is only accurate to a second.
+ let expires_at = UNIX_EPOCH + Duration::from_secs(2_000_000_000);
+ inflight
+ .insert_issued(
+ &code,
+ IssuedAuthorizationCode {
+ client_id: "client-abc".to_owned(),
+ access_token: AccessToken::from("access"),
+ 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),
+ },
+ )
+ .await
+ .expect("insert should succeed");
+
+ let issued = inflight
+ .take_issued(&code)
+ .await
+ .expect("take should succeed")
+ .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!(
+ inflight
+ .take_issued(&code)
+ .await
+ .expect("take should succeed")
+ .is_none(),
+ "an issued code must be single-use"
+ );
+}
diff --git a/services/mcp_auth_proxy/src/test_support.rs b/services/mcp_auth_proxy/src/test_support.rs
new file mode 100644
index 0000000000..6f69045de2
--- /dev/null
+++ b/services/mcp_auth_proxy/src/test_support.rs
@@ -0,0 +1,365 @@
+//! In-memory doubles for the broker's ports, shared by the domain and inbound
+//! tests.
+
+use std::{
+ collections::HashMap,
+ sync::{Arc, Mutex},
+ time::SystemTime,
+};
+
+use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
+use sha2::{Digest, Sha256};
+
+use crate::domain::{
+ models::{
+ AccessToken, AuthorizeRequest, CallbackRequest, ClientRegistrationRequest,
+ IssuedAuthorizationCode, PendingAuthorization, RefreshToken, RegisteredClient,
+ UpstreamTokens,
+ },
+ ports::{
+ BoundClientIdFuture, ClientRegistrationStore, OAuthProvider, RefreshTokenBindingStore,
+ RegisteredClientFuture, StoreWriteFuture, UpstreamTokensFuture,
+ },
+ redirect_uri::RedirectUriPolicy,
+ service::{
+ InflightAuthStore, McpAuthProxyService, McpAuthProxyServiceDeps, McpAuthProxyServiceImpl,
+ },
+};
+
+/// Access token the fake upstream provider returns for a code exchange.
+pub const UPSTREAM_ACCESS_TOKEN: &str = "upstream-access-token";
+/// Refresh token the fake upstream provider returns for a code exchange.
+pub const UPSTREAM_REFRESH_TOKEN: &str = "upstream-refresh-token";
+/// PKCE verifier belonging to the legitimate client.
+pub const VICTIM_CODE_VERIFIER: &str = "victim-code-verifier-that-is-long-enough";
+/// PKCE verifier an attacker generates for a crafted authorize request.
+pub const ATTACKER_CODE_VERIFIER: &str = "attacker-code-verifier-that-is-long-enough";
+/// Loopback callback of a native MCP client.
+pub const LOOPBACK_REDIRECT_URI: &str = "http://127.0.0.1:51000/oauth/callback";
+/// Callback of a browser-based MCP client on a trusted host.
+pub const TRUSTED_REDIRECT_URI: &str = "https://claude.ai/api/mcp/auth_callback";
+/// Callback under an attacker's control.
+pub const ATTACKER_REDIRECT_URI: &str = "https://attacker.example/steal";
+/// Access token the fake upstream provider returns for a refresh.
+pub const REFRESHED_ACCESS_TOKEN: &str = "refreshed-access-token";
+/// Upstream access token lifetime the fake provider reports, matching the one
+/// hour JWT FusionAuth issues.
+pub const UPSTREAM_EXPIRES_IN: u64 = 3600;
+
+/// Computes the S256 challenge for a PKCE verifier.
+pub fn code_challenge_for(verifier: &str) -> String {
+ URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
+}
+
+/// In-memory stand-in for the Redis handshake store.
+#[derive(Default)]
+pub struct FakeInflightAuth {
+ pending: Mutex<HashMap<String, PendingAuthorization>>,
+ issued: Mutex<HashMap<String, IssuedAuthorizationCode>>,
+}
+
+impl FakeInflightAuth {
+ /// Returns the session id of the only pending flow, panicking unless there
+ /// is exactly one.
+ pub fn only_pending_session_id(&self) -> String {
+ let pending = self.pending.lock().expect("pending lock");
+ assert_eq!(pending.len(), 1, "expected exactly one pending session");
+ pending.keys().next().expect("pending session").clone()
+ }
+
+ /// Returns whether any authorization flow is pending.
+ pub fn has_pending(&self) -> bool {
+ !self.pending.lock().expect("pending lock").is_empty()
+ }
+
+ /// Returns whether a broker code is still redeemable.
+ pub fn holds_issued_code(&self, code: &str) -> bool {
+ self.issued.lock().expect("issued lock").contains_key(code)
+ }
+
+ /// Returns the recorded upstream expiry of the only issued code, panicking
+ /// unless there is exactly one.
+ pub fn only_issued_expiry(&self) -> Option<SystemTime> {
+ let issued = self.issued.lock().expect("issued lock");
+ assert_eq!(issued.len(), 1, "expected exactly one issued code");
+ issued
+ .values()
+ .next()
+ .expect("issued code")
+ .access_token_expires_at
+ }
+}
+
+impl InflightAuthStore for FakeInflightAuth {
+ async fn insert_pending(
+ &self,
+ session_id: &str,
+ pending: PendingAuthorization,
+ ) -> anyhow::Result<()> {
+ self.pending
+ .lock()
+ .expect("pending lock")
+ .insert(session_id.to_owned(), pending);
+ Ok(())
+ }
+
+ async fn take_pending(&self, session_id: &str) -> anyhow::Result<Option<PendingAuthorization>> {
+ Ok(self
+ .pending
+ .lock()
+ .expect("pending lock")
+ .remove(session_id))
+ }
+
+ async fn insert_issued(
+ &self,
+ code: &str,
+ issued: IssuedAuthorizationCode,
+ ) -> anyhow::Result<()> {
+ self.issued
+ .lock()
+ .expect("issued lock")
+ .insert(code.to_owned(), issued);
+ Ok(())
+ }
+
+ async fn take_issued(&self, code: &str) -> anyhow::Result<Option<IssuedAuthorizationCode>> {
+ Ok(self.issued.lock().expect("issued lock").remove(code))
+ }
+
+ async fn cleanup_expired(&self) -> anyhow::Result<()> {
+ Ok(())
+ }
+}
+
+/// In-memory stand-in for the Redis client registry.
+#[derive(Default)]
+pub struct FakeClientRegistry {
+ clients: Mutex<HashMap<String, RegisteredClient>>,
+ refresh_bindings: Mutex<HashMap<String, String>>,
+}
+
+impl ClientRegistrationStore for FakeClientRegistry {
+ fn insert_client<'a>(&'a self, client: &'a RegisteredClient) -> StoreWriteFuture<'a> {
+ Box::pin(async move {
+ self.clients
+ .lock()
+ .expect("clients lock")
+ .insert(client.client_id.clone(), client.clone());
+ Ok(())
+ })
+ }
+
+ fn find_client<'a>(&'a self, client_id: &'a str) -> RegisteredClientFuture<'a> {
+ Box::pin(async move {
+ Ok(self
+ .clients
+ .lock()
+ .expect("clients lock")
+ .get(client_id)
+ .cloned())
+ })
+ }
+}
+
+impl RefreshTokenBindingStore for FakeClientRegistry {
+ fn bind<'a>(
+ &'a self,
+ refresh_token_digest: &'a str,
+ client_id: &'a str,
+ ) -> StoreWriteFuture<'a> {
+ Box::pin(async move {
+ self.refresh_bindings
+ .lock()
+ .expect("bindings lock")
+ .insert(refresh_token_digest.to_owned(), client_id.to_owned());
+ Ok(())
+ })
+ }
+
+ fn bound_client<'a>(&'a self, refresh_token_digest: &'a str) -> BoundClientIdFuture<'a> {
+ Box::pin(async move {
+ Ok(self
+ .refresh_bindings
+ .lock()
+ .expect("bindings lock")
+ .get(refresh_token_digest)
+ .cloned())
+ })
+ }
+
+ fn unbind<'a>(&'a self, refresh_token_digest: &'a str) -> StoreWriteFuture<'a> {
+ Box::pin(async move {
+ self.refresh_bindings
+ .lock()
+ .expect("bindings lock")
+ .remove(refresh_token_digest);
+ Ok(())
+ })
+ }
+}
+
+/// Upstream provider that hands back fixed tokens, standing in for FusionAuth.
+pub struct FakeOAuthProvider {
+ rotated_refresh_token: Option<String>,
+}
+
+impl FakeOAuthProvider {
+ /// A provider whose refresh grant returns the presented refresh token
+ /// again, as FusionAuth does on a sliding window.
+ pub fn new() -> Self {
+ Self {
+ rotated_refresh_token: None,
+ }
+ }
+
+ /// 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()),
+ }
+ }
+}
+
+impl OAuthProvider for FakeOAuthProvider {
+ fn construct_authorize_url(&self, state: &str) -> anyhow::Result<String> {
+ Ok(format!("https://upstream.example/authorize?state={state}"))
+ }
+
+ fn exchange_authorization_code<'a>(&'a self, _code: &'a str) -> UpstreamTokensFuture<'a> {
+ Box::pin(async move {
+ Ok(UpstreamTokens {
+ access_token: AccessToken::from(UPSTREAM_ACCESS_TOKEN),
+ refresh_token: RefreshToken::from(UPSTREAM_REFRESH_TOKEN),
+ expires_in: UPSTREAM_EXPIRES_IN,
+ })
+ })
+ }
+
+ fn refresh_access_token<'a>(
+ &'a self,
+ refresh_token: &'a RefreshToken,
+ ) -> UpstreamTokensFuture<'a> {
+ Box::pin(async move {
+ let next = self
+ .rotated_refresh_token
+ .clone()
+ .unwrap_or_else(|| refresh_token.as_str().to_owned());
+ Ok(UpstreamTokens {
+ access_token: AccessToken::from(REFRESHED_ACCESS_TOKEN),
+ refresh_token: RefreshToken::from(next),
+ expires_in: UPSTREAM_EXPIRES_IN,
+ })
+ })
+ }
+}
+
+/// A broker service wired to in-memory stores, trusting only `claude.ai` for
+/// `https` redirect URIs.
+pub struct Harness {
+ /// The service under test.
+ pub service: McpAuthProxyServiceImpl<FakeInflightAuth>,
+ /// The handshake store the service was built with.
+ pub inflight: Arc<FakeInflightAuth>,
+ /// The client registry the service was built with.
+ pub registry: Arc<FakeClientRegistry>,
+}
+
+impl Harness {
+ /// Builds a harness whose upstream refresh grant does not rotate.
+ pub fn new() -> Self {
+ Self::with_provider(FakeOAuthProvider::new())
+ }
+
+ /// Builds a harness over a specific fake upstream provider.
+ pub fn with_provider(provider: FakeOAuthProvider) -> Self {
+ let inflight = Arc::new(FakeInflightAuth::default());
+ let registry = Arc::new(FakeClientRegistry::default());
+ 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(&registry) as Arc<dyn ClientRegistrationStore>,
+ refresh_token_bindings: Arc::clone(&registry) as Arc<dyn RefreshTokenBindingStore>,
+ oauth_provider: Arc::new(provider),
+ });
+
+ Self {
+ service,
+ inflight,
+ registry,
+ }
+ }
+
+ /// Registers a client and returns its assigned id.
+ pub async fn register(&self, redirect_uris: &[&str]) -> String {
+ self.service
+ .register_client(ClientRegistrationRequest {
+ client_name: Some("test-client".to_owned()),
+ redirect_uris: redirect_uris.iter().map(|uri| (*uri).to_owned()).collect(),
+ })
+ .await
+ .expect("registration should succeed")
+ .client_id
+ }
+
+ /// Builds a well-formed authorize request.
+ pub fn authorize_request(
+ &self,
+ client_id: &str,
+ redirect_uri: &str,
+ code_challenge: &str,
+ ) -> AuthorizeRequest {
+ AuthorizeRequest {
+ response_type: "code".to_owned(),
+ client_id: client_id.to_owned(),
+ redirect_uri: redirect_uri.to_owned(),
+ state: "client-state".to_owned(),
+ code_challenge: code_challenge.to_owned(),
+ code_challenge_method: "S256".to_owned(),
+ scope: None,
+ }
+ }
+
+ /// Drives authorize plus the upstream callback and returns the broker code
+ /// delivered to the client's redirect URI.
+ pub async fn complete_flow_to_code(
+ &self,
+ client_id: &str,
+ redirect_uri: &str,
+ code_verifier: &str,
+ ) -> String {
+ self.service
+ .start_authorization(self.authorize_request(
+ client_id,
+ redirect_uri,
+ &code_challenge_for(code_verifier),
+ ))
+ .await
+ .expect("authorize should succeed");
+
+ let session_id = self.inflight.only_pending_session_id();
+ let redirect = self
+ .service
+ .complete_callback(CallbackRequest {
+ code: Some("upstream-code".to_owned()),
+ state: Some(session_id),
+ error: None,
+ error_description: None,
+ })
+ .await
+ .expect("callback should succeed");
+
+ query_param(&redirect, "code").expect("redirect carries a code")
+ }
+}
+
+/// Reads a query parameter from a redirect URL.
+pub fn query_param(url: &str, name: &str) -> Option<String> {
+ let query = url.split_once('?')?.1;
+ let prefix = format!("{name}=");
+ query
+ .split('&')
+ .find_map(|pair| pair.strip_prefix(&prefix))
+ .map(str::to_owned)
+}
diff --git a/services/mcp_service/src/config.rs b/services/mcp_service/src/config.rs
index ef2eaea3a5..8abc6e2466 100644
--- a/services/mcp_service/src/config.rs
+++ b/services/mcp_service/src/config.rs
@@ -14,8 +14,23 @@ use macro_env_var::{env_vars, maybe_env_vars};
maybe_env_vars! {
/// Browser-reachable FusionAuth origin used for OAuth authorization redirects.
pub struct FusionauthPublicUrl;
+ /// Comma-separated hosts allowed as `https` OAuth redirect URI destinations
+ /// for MCP clients. Falls back to [`DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS`]
+ /// when unset. Loopback `http` redirect URIs are always allowed and do not
+ /// need to be listed.
+ pub struct McpAllowedRedirectHosts;
}
+/// Hosts trusted to receive an MCP authorization code when
+/// `MCP_ALLOWED_REDIRECT_HOSTS` is unset.
+///
+/// These are the browser-based MCP clients Macro supports, and match the
+/// origins the FusionAuth application already allows. A host absent from this
+/// list cannot be used as a redirect destination, which is what stops an
+/// attacker from registering a client pointing at a callback they control.
+pub const DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS: [&str; 4] =
+ ["claude.ai", "chatgpt.com", "chat.openai.com", "cursor.com"];
+
env_vars! {
/// Auth key used by the document storage / search / lexical clients.
pub struct DocumentStorageServiceAuthKey;
@@ -96,6 +111,9 @@ pub struct Config {
pub document_storage_service_cloudfront_signer_private_key_secret_name:
DocumentStorageServiceCloudfrontSignerPrivateKeySecretName,
pub mcp_public_url: McpPublicUrl,
+ /// Hosts allowed as `https` MCP OAuth redirect destinations. Falls back to
+ /// [`DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS`] when unset.
+ pub mcp_allowed_redirect_hosts: McpAllowedRedirectHosts,
pub fusionauth_base_url: FusionauthBaseUrl,
/// Browser-reachable FusionAuth URL. Falls back to the API base URL when unset.
pub fusionauth_public_url: FusionauthPublicUrl,
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index af2cfa0723..de56c577dc 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -40,8 +40,14 @@ use macro_service_urls::{
EmailServiceUrl, LexicalServiceUrl, SyncServiceUrl,
};
use mcp_auth_proxy::{
- domain::service::McpAuthProxyServiceImpl,
- outbound::{fusionauth::FusionAuthOAuthProvider, redis::RedisInflightAuth},
+ domain::{
+ redirect_uri::RedirectUriPolicy,
+ service::{McpAuthProxyServiceDeps, McpAuthProxyServiceImpl},
+ },
+ outbound::{
+ fusionauth::FusionAuthOAuthProvider,
+ redis::{RedisClientRegistry, RedisInflightAuth},
+ },
};
use notification::domain::service::{NotificationReaderService, PlatformArnConfig};
use notification::outbound::repository::DbNotificationRepository;
@@ -53,7 +59,7 @@ use sqlx::{PgPool, postgres::PgPoolOptions};
use sync_service_client::SyncServiceClient;
use tokio_util::task::TaskTracker;
-use crate::config::Config;
+use crate::config::{Config, DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS};
#[derive(Clone)]
pub struct McpContext {
@@ -565,10 +571,29 @@ async fn build_auth_proxy(
.context("failed to initialize MCP auth provider")?;
let redis_client = redis::Client::open(config.redis_url.as_ref().to_owned())
.context("failed to initialize redis client for MCP auth proxy")?;
+ let client_registry = Arc::new(RedisClientRegistry::new(redis_client.clone()));
+
+ let redirect_uri_policy = build_redirect_uri_policy(config);
+ tracing::info!(
+ allowed_https_redirect_hosts = ?redirect_uri_policy.allowed_https_hosts().collect::<Vec<_>>(),
+ "initialized MCP OAuth redirect URI policy"
+ );
+
+ Ok(McpAuthProxyServiceImpl::new(McpAuthProxyServiceDeps {
+ public_url: mcp_public_url,
+ redirect_uri_policy,
+ inflight_auth: Arc::new(RedisInflightAuth::new(redis_client)),
+ client_registrations: client_registry.clone(),
+ refresh_token_bindings: client_registry,
+ oauth_provider: Arc::new(auth_provider),
+ }))
+}
- Ok(McpAuthProxyServiceImpl::new(
- mcp_public_url,
- Arc::new(RedisInflightAuth::new(redis_client)),
- Arc::new(auth_provider),
- ))
+/// Builds the redirect URI policy the broker enforces at registration and at
+/// authorize, from the configured host list or the built-in default.
+fn build_redirect_uri_policy(config: &Config) -> RedirectUriPolicy {
+ match config.mcp_allowed_redirect_hosts.value() {
+ Some(hosts) => RedirectUriPolicy::new(hosts.split(',')),
+ None => RedirectUriPolicy::new(DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS),
+ }
}