Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(mcp): let any https MCP client connect after user consent (#9385)

Eric Hayes88d10e81fe6a
diff --git a/.sqlx/query-55496bc527685dbc76bf9d83e5d090fc6b56a918d59c3f159e96ae378c2e8288.json b/.sqlx/query-5f1d0de54d4e8909f0e6e2e1afb1d7b7f7710282cf638c92eab21049ca1cb26e.json
similarity index 60%
rename from .sqlx/query-55496bc527685dbc76bf9d83e5d090fc6b56a918d59c3f159e96ae378c2e8288.json
rename to .sqlx/query-5f1d0de54d4e8909f0e6e2e1afb1d7b7f7710282cf638c92eab21049ca1cb26e.json
index da905238a2..45099f6ab4 100644
--- a/.sqlx/query-55496bc527685dbc76bf9d83e5d090fc6b56a918d59c3f159e96ae378c2e8288.json
+++ b/.sqlx/query-5f1d0de54d4e8909f0e6e2e1afb1d7b7f7710282cf638c92eab21049ca1cb26e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO mcp_oauth_pending_authorizations\n (session_id, client_id, code_challenge, client_state, client_redirect_uri, expires_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n ",
+ "query": "\n INSERT INTO mcp_oauth_pending_authorizations\n (session_id, client_id, code_challenge, client_state, client_redirect_uri,\n browser_binding_digest, expires_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ",
"describe": {
"columns": [],
"parameters": {
@@ -10,10 +10,11 @@
"Text",
"Text",
"Text",
+ "Text",
"Timestamptz"
]
},
"nullable": []
},
- "hash": "55496bc527685dbc76bf9d83e5d090fc6b56a918d59c3f159e96ae378c2e8288"
+ "hash": "5f1d0de54d4e8909f0e6e2e1afb1d7b7f7710282cf638c92eab21049ca1cb26e"
}
diff --git a/.sqlx/query-897d60fda6110a16bd670f70d24ef8c2a713d60e8604c3f888e26b5bc446bc78.json b/.sqlx/query-6c40270a0bb3310a7931300af4ddb135fb32ab143952dfae06da1f3871a3c9a2.json
similarity index 72%
rename from .sqlx/query-897d60fda6110a16bd670f70d24ef8c2a713d60e8604c3f888e26b5bc446bc78.json
rename to .sqlx/query-6c40270a0bb3310a7931300af4ddb135fb32ab143952dfae06da1f3871a3c9a2.json
index efad69c6e5..d93deaface 100644
--- a/.sqlx/query-897d60fda6110a16bd670f70d24ef8c2a713d60e8604c3f888e26b5bc446bc78.json
+++ b/.sqlx/query-6c40270a0bb3310a7931300af4ddb135fb32ab143952dfae06da1f3871a3c9a2.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n DELETE FROM mcp_oauth_pending_authorizations\n WHERE session_id = $1\n RETURNING client_id, code_challenge, client_state, client_redirect_uri, expires_at\n ",
+ "query": "\n DELETE FROM mcp_oauth_pending_authorizations\n WHERE session_id = $1\n RETURNING client_id, code_challenge, client_state, client_redirect_uri,\n browser_binding_digest, expires_at\n ",
"describe": {
"columns": [
{
@@ -25,6 +25,11 @@
},
{
"ordinal": 4,
+ "name": "browser_binding_digest",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
"name": "expires_at",
"type_info": "Timestamptz"
}
@@ -39,8 +44,9 @@
false,
false,
false,
+ true,
false
]
},
- "hash": "897d60fda6110a16bd670f70d24ef8c2a713d60e8604c3f888e26b5bc446bc78"
+ "hash": "6c40270a0bb3310a7931300af4ddb135fb32ab143952dfae06da1f3871a3c9a2"
}
diff --git a/Cargo.lock b/Cargo.lock
index 4424cc78a3..2c9b293488 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -12833,8 +12833,10 @@ version = "0.1.0"
dependencies = [
"ai_toolset",
"anyhow",
+ "askama",
"async-trait",
"axum",
+ "axum-extra",
"base64 0.22.1",
"bot_id",
"chrono",
@@ -12843,11 +12845,14 @@ dependencies = [
"macro_auth",
"macro_db_migrator",
"macro_user_id",
+ "rand 0.9.4",
"redis",
"serde",
"serde_json",
"sha2 0.10.9",
"sqlx",
+ "strum 0.27.2",
+ "subtle",
"thiserror 2.0.18",
"tokio",
"tower 0.5.3",
diff --git a/crates/macro_db_client/migrations/20261104215208_mcp_oauth_pending_browser_binding.sql b/crates/macro_db_client/migrations/20261104215208_mcp_oauth_pending_browser_binding.sql
new file mode 100644
index 0000000000..10b9bed80d
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261104215208_mcp_oauth_pending_browser_binding.sql
@@ -0,0 +1,5 @@
+-- Digest of the secret cookie held by the browser that started an MCP OAuth
+-- authorization; only that browser may complete it. Nullable because rows
+-- written by the previous build carry no binding.
+ALTER TABLE mcp_oauth_pending_authorizations
+ ADD COLUMN browser_binding_digest text;
diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rs
index a8a65e447f..641d858c9f 100644
--- a/services/agent_harness_service/src/config.rs
+++ b/services/agent_harness_service/src/config.rs
@@ -104,7 +104,8 @@ pub struct Config {
pub openai_domain_verification_token: OpenaiDomainVerificationToken,
/// Browser-reachable FusionAuth origin, when different from the API.
pub fusionauth_public_url: FusionauthPublicUrl,
- /// Additional trusted client callback hosts, overriding the built-in list.
+ /// MCP client callback hosts trusted without the consent screen, overriding
+ /// the built-in list.
pub mcp_allowed_redirect_hosts: McpAllowedRedirectHosts,
/// Hide agent DM contexts from standalone lists. Enable only after all
diff --git a/services/agent_harness_service/src/public_mcp.rs b/services/agent_harness_service/src/public_mcp.rs
index b03983625f..3853ae2ca5 100644
--- a/services/agent_harness_service/src/public_mcp.rs
+++ b/services/agent_harness_service/src/public_mcp.rs
@@ -39,6 +39,8 @@ pub struct PublicCodeMode {
pub selector: Arc<dyn agent_inmem::domain::tool_mode::ToolModeSelector>,
}
+/// Browser-based MCP clients Macro has vetted, whose users skip the consent
+/// screen. Any other `https` client works too, after the user approves it.
const DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS: [&str; 5] = [
"claude.ai",
"chatgpt.com",
@@ -270,7 +272,8 @@ fn build_analytics(config: &Config, db: sqlx::PgPool) -> McpAnalytics {
}
/// Builds the redirect URI policy the broker enforces at registration and at
-/// authorize, from the configured host list or the built-in default.
+/// authorize. The configured host list, or the built-in default, names the
+/// `https` hosts trusted without the consent screen.
fn build_redirect_uri_policy(config: &Config) -> RedirectUriPolicy {
match config.mcp_allowed_redirect_hosts.value() {
Some(hosts) => RedirectUriPolicy::new(hosts.split(',')),
diff --git a/services/agent_harness_service/src/public_mcp/test.rs b/services/agent_harness_service/src/public_mcp/test.rs
index e09a0250fb..88753c6c89 100644
--- a/services/agent_harness_service/src/public_mcp/test.rs
+++ b/services/agent_harness_service/src/public_mcp/test.rs
@@ -1,11 +1,17 @@
-use mcp_auth_proxy::domain::redirect_uri::RedirectUriPolicy;
+use mcp_auth_proxy::domain::redirect_uri::{RedirectTrust, RedirectUriPolicy};
use super::*;
#[test]
-fn default_redirect_hosts_permit_cursor_web_agent_callbacks() {
+fn default_redirect_hosts_trust_cursor_web_agent_callbacks() {
let policy = RedirectUriPolicy::new(DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS);
- assert!(policy.permits("https://cursor.com/agents/mcp/oauth/callback"));
- assert!(policy.permits("https://www.cursor.com/agents/mcp/oauth/callback"));
+ assert_eq!(
+ policy.trust("https://cursor.com/agents/mcp/oauth/callback"),
+ Some(RedirectTrust::Trusted)
+ );
+ assert_eq!(
+ policy.trust("https://www.cursor.com/agents/mcp/oauth/callback"),
+ Some(RedirectTrust::Trusted)
+ );
}
diff --git a/services/mcp_auth_proxy/AGENTS.md b/services/mcp_auth_proxy/AGENTS.md
index 3aa79fd959..8ec5d35a14 100644
--- a/services/mcp_auth_proxy/AGENTS.md
+++ b/services/mcp_auth_proxy/AGENTS.md
@@ -15,7 +15,11 @@ in front of FusionAuth, which doesn't support DCR itself.
`/revoke`.
- `src/domain/service.rs` + `src/domain/service/test.rs`: the broker's core
logic (registration, authorize, token/refresh).
-- `src/domain/redirect_uri.rs`: the redirect URI usability policy from the README.
+- `src/domain/redirect_uri.rs`: the redirect URI policy from the README: trusted,
+ needs consent, or refused.
+- `src/domain/browser_binding.rs`: the cookie secret tying a flow to the browser
+ that started it, and the consent form's anti-forgery token.
+- `templates/`: the consent screen and its cancellation page.
- `src/domain/ports.rs`: `ClientRegistrationStore`, `OAuthProvider`,
`RefreshTokenBindingStore` — the ports the service depends on.
- `src/inbound/axum_router.rs`: HTTP routes; `src/inbound/middleware.rs`: auth.
@@ -42,6 +46,9 @@ in front of FusionAuth, which doesn't support DCR itself.
- Change redirect URI policy: `src/domain/redirect_uri.rs` → update the README
section it implements → `services/agent_harness_service/src/public_mcp.rs`
(`DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS`) if the default allowlist changes.
+- Support a new HTTPS MCP client: nothing; users approve it on the consent
+ screen. Add its host to `DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS` only to skip that
+ screen for a client Macro has vetted.
- Add a new grant type: `src/domain/models.rs` → `src/domain/service.rs` →
`src/outbound/fusionauth.rs` → `src/inbound/axum_router.rs`.
@@ -60,8 +67,16 @@ and other library consumers. Both retain OAuth metadata, CORS, and bearer auth.
- Don't add an MCP client's host to FusionAuth's authorized origins
(`infra/stacks/fusionauth-instance/origins.ts`). `/authorize` withholds the
- client's Referer from FusionAuth; a new client needs only a trusted redirect
- host. See README "Origin versus redirect URI".
+ client's Referer from FusionAuth, so a new client needs no origin entry.
+ See README "Origin versus redirect URI".
+- Every `/authorize` response except the sign-in chooser sets the
+ `__Host-macro_mcp_oauth` cookie and `/oauth/callback` requires it. Don't drop
+ the check for trusted clients or relax the cookie to `SameSite=None`; see
+ README "Consent and browser binding".
+ The consent page's CSP has no `form-action`: browsers apply it to the
+ form's redirect to FusionAuth.
+- The consent form re-posts the authorize request, so a new `AuthorizeRequest`
+ field needs a hidden input in `templates/consent.html`.
- `client_id` is not a secret; every endpoint must still check it against a
live registration — see README "Which client a grant belongs to" before
changing token/refresh validation.
diff --git a/services/mcp_auth_proxy/Cargo.toml b/services/mcp_auth_proxy/Cargo.toml
index 41516d66d3..c32bd2f397 100644
--- a/services/mcp_auth_proxy/Cargo.toml
+++ b/services/mcp_auth_proxy/Cargo.toml
@@ -9,7 +9,9 @@ version = "0.1.0"
default = ["inbound", "outbound"]
inbound = [
"dep:ai_toolset",
+ "dep:askama",
"dep:axum",
+ "dep:axum-extra",
"dep:bot_id",
"dep:macro_auth",
"dep:macro_user_id",
@@ -26,8 +28,10 @@ outbound = [
[dependencies]
anyhow = { workspace = true }
+askama = { workspace = true, optional = true }
ai_toolset = { path = "../../crates/ai_toolset", optional = true }
axum = { workspace = true, features = ["tower-log"], optional = true }
+axum-extra = { workspace = true, features = ["cookie"], optional = true }
base64 = { workspace = true }
bot_id = { path = "../../crates/bot_id", optional = true }
chrono = { workspace = true, optional = true }
@@ -35,11 +39,14 @@ cursor_api_key = { path = "../../crates/cursor_api_key", optional = true }
fusionauth = { path = "../../crates/fusionauth", optional = true }
macro_auth = { path = "../../crates/macro_auth", optional = true }
macro_user_id = { path = "../../crates/macro_user_id", optional = true }
+rand = { workspace = true }
redis = { workspace = true, features = ["aio", "tokio-comp"] }
serde = { workspace = true }
serde_json = { workspace = true }
+strum = { workspace = true }
sha2 = { workspace = true }
sqlx = { workspace = true, optional = true }
+subtle = { workspace = true }
thiserror = { workspace = true }
tower = { workspace = true, features = ["util"], optional = true }
tower-http = { workspace = true, optional = true }
diff --git a/services/mcp_auth_proxy/README.md b/services/mcp_auth_proxy/README.md
index 4a9612f179..629857a8ba 100644
--- a/services/mcp_auth_proxy/README.md
+++ b/services/mcp_auth_proxy/README.md
@@ -41,41 +41,73 @@ Google's challenges. The chooser stores nothing; each link is the same
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/agent_harness_service/src/public_mcp.rs`,
- which holds the browser-based MCP clients Macro supports. Subdomains of a
- listed host are not themselves trusted.
+anyone can register a client whose callback they control. FusionAuth also signs
+in a user with an existing session without asking anything, so without another
+check, anyone could register their own callback and send a Macro user a link
+that silently hands them that user's code. A deployment-level policy
+(`domain/redirect_uri.rs`) therefore sorts every redirect URI into one of three
+groups, and a registration can only narrow what it allows:
+
+- **Trusted, delivered directly.** `http` on a loopback host (`localhost`,
+ `127.0.0.1`, `[::1]`), on any port (RFC 8252 section 7.3): a code sent there
+ reaches a listener on the resource owner's own machine. Or `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/agent_harness_service/src/public_mcp.rs`, which holds the
+ browser-based MCP clients Macro has vetted. Subdomains of a listed host are
+ not themselves trusted.
+- **Delivered after consent.** `https` on any other host, such as a self-hosted
+ MCP gateway. `/authorize` shows the consent screen described below before
+ sending the user to sign in.
+- **Refused.** Every other scheme, `http` off loopback, and any URI carrying a
+ fragment or credentials in its authority.
Loopback hosts are interchangeable for this policy, but not for a registration:
a client that registered `http://localhost:6274/...` cannot have a code sent to
`http://127.0.0.1:6274/...`.
-A new third-party HTTPS client therefore needs exactly one change: its callback
-host added to `DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS` (or the deployment's
-`MCP_ALLOWED_REDIRECT_HOSTS`). It needs no FusionAuth origin. Registering through
-DCR alone is not enough, on purpose: FusionAuth signs in a user with an existing
-session without showing a consent screen, so if any registered HTTPS host were
-usable, anyone could register their own callback and send a Macro user a link
-that hands them that user's code.
-
-A redirect URI carrying a fragment or credentials in its authority is refused
-regardless of host.
+A new third-party HTTPS client needs no change at all: its users approve it on
+the consent screen. Adding its callback host to the trusted list only skips that
+screen, so reserve it for clients Macro has vetted. It needs no FusionAuth origin
+either way.
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.
+store one it refuses, and `/authorize` re-applies it before comparing against
+the registration, so narrowing the policy takes effect for clients that
+registered under a wider one.
+
+## Consent and browser binding
+
+`GET /authorize` for a redirect URI that needs consent renders a page naming the
+host the code will go to (punycode for internationalized names, so a lookalike
+cannot pass for the host it imitates) and the client's self-reported name,
+marked as unverified, with control, bidirectional and zero-width characters
+removed and its length capped. Nothing is stored until the user answers.
+**Allow** posts the form back to `POST /authorize`, which starts sign-in;
+**Cancel** shows a closing page and redirects nowhere, so the broker never
+becomes a redirector to a host the user just refused.
+
+Two checks keep a flow tied to the person approving it, using one random secret
+in the `__Host-macro_mcp_oauth` cookie (`Secure`, `HttpOnly`, `SameSite=Lax`),
+which `/authorize` sets on every flow (`domain/browser_binding.rs`):
+
+- **The consent form only counts from the browser that was shown it.** It
+ carries a token derived from the cookie's secret, compared in constant time.
+ A cross-site post carries no `SameSite=Lax` cookie, a page on another origin
+ cannot read the token, and a `Sec-Fetch-Site` other than `same-origin` is
+ refused outright, so no other page can approve on the user's behalf. The page
+ sets `frame-ancestors 'none'` and `X-Frame-Options: DENY`, so it cannot be
+ framed for clickjacking, and loads and runs nothing.
+- **Only the browser that started a flow can finish it.** The pending
+ authorization stores a digest of the secret, and `/oauth/callback` refuses a
+ callback whose cookie does not match. Without this, someone could approve
+ their own flow and send a victim the FusionAuth sign-in URL it produced; the
+ victim's existing session would complete it silently and deliver the victim's
+ code to the starter's client. The binding applies to trusted clients too.
+
+A pending authorization written by a build before the binding has no digest; the
+callback accepts one only when its redirect URI is trusted, which is all that
+build could have stored.
## Which client a grant belongs to
diff --git a/services/mcp_auth_proxy/src/domain.rs b/services/mcp_auth_proxy/src/domain.rs
index 395f0c4199..90bdf455fe 100644
--- a/services/mcp_auth_proxy/src/domain.rs
+++ b/services/mcp_auth_proxy/src/domain.rs
@@ -2,6 +2,8 @@
/// Which registered client each issued access token went to.
pub mod access_token_clients;
+/// The secret tying an OAuth handshake to the browser that started it.
+pub mod browser_binding;
/// Domain models for broker-managed OAuth state and request payloads.
pub mod models;
/// Domain port traits for upstream OAuth providers and broker state stores.
diff --git a/services/mcp_auth_proxy/src/domain/browser_binding.rs b/services/mcp_auth_proxy/src/domain/browser_binding.rs
new file mode 100644
index 0000000000..3c66dbe564
--- /dev/null
+++ b/services/mcp_auth_proxy/src/domain/browser_binding.rs
@@ -0,0 +1,86 @@
+//! The secret that ties one OAuth handshake to the browser that started it.
+
+#[cfg(test)]
+mod test;
+
+use std::fmt;
+
+use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
+use sha2::{Digest, Sha256};
+use subtle::ConstantTimeEq;
+
+/// Random bytes in a binding secret.
+const SECRET_LEN: usize = 32;
+/// Domain separator for the digest stored with a pending authorization.
+const PENDING_DIGEST_PREFIX: &[u8] = b"mcp-oauth-browser-binding:";
+/// Domain separator for the token embedded in the consent form.
+const CONSENT_TOKEN_PREFIX: &[u8] = b"mcp-oauth-consent:";
+
+/// A random secret held in a cookie by the browser that started an
+/// authorization.
+///
+/// `/authorize` stores its digest with the pending authorization and the
+/// upstream callback must present the same cookie, so a sign-in link started
+/// by someone else cannot be completed in a victim's browser. The consent form
+/// carries a token derived from it, so a cross-site form post cannot approve a
+/// client on the user's behalf.
+#[derive(Clone, Eq, PartialEq)]
+pub struct BrowserBinding(String);
+
+impl BrowserBinding {
+ /// Generates a fresh secret.
+ pub fn generate() -> Self {
+ let secret: [u8; SECRET_LEN] = rand::random();
+ Self(URL_SAFE_NO_PAD.encode(secret))
+ }
+
+ /// Parses a secret presented by a browser, refusing anything that is not
+ /// the shape `generate` produces.
+ pub fn parse(value: &str) -> Option<Self> {
+ let decoded = URL_SAFE_NO_PAD.decode(value).ok()?;
+ (decoded.len() == SECRET_LEN).then(|| Self(value.to_owned()))
+ }
+
+ /// The secret, for the cookie that carries it.
+ pub fn as_str(&self) -> &str {
+ &self.0
+ }
+
+ /// The digest stored with a pending authorization, so the store never
+ /// holds the secret itself.
+ pub fn digest(&self) -> String {
+ self.derive(PENDING_DIGEST_PREFIX)
+ }
+
+ /// Returns whether `digest` was taken from this secret, in constant time.
+ pub fn matches_digest(&self, digest: &str) -> bool {
+ self.digest().as_bytes().ct_eq(digest.as_bytes()).into()
+ }
+
+ /// The anti-forgery token the consent form carries.
+ pub fn consent_token(&self) -> String {
+ self.derive(CONSENT_TOKEN_PREFIX)
+ }
+
+ /// Returns whether `token` is this secret's consent token, in constant
+ /// time.
+ pub fn accepts_consent_token(&self, token: &str) -> bool {
+ self.consent_token()
+ .as_bytes()
+ .ct_eq(token.as_bytes())
+ .into()
+ }
+
+ fn derive(&self, prefix: &[u8]) -> String {
+ let mut hasher = Sha256::new();
+ hasher.update(prefix);
+ hasher.update(self.0.as_bytes());
+ URL_SAFE_NO_PAD.encode(hasher.finalize())
+ }
+}
+
+impl fmt::Debug for BrowserBinding {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("BrowserBinding([REDACTED])")
+ }
+}
diff --git a/services/mcp_auth_proxy/src/domain/browser_binding/test.rs b/services/mcp_auth_proxy/src/domain/browser_binding/test.rs
new file mode 100644
index 0000000000..71a562e07f
--- /dev/null
+++ b/services/mcp_auth_proxy/src/domain/browser_binding/test.rs
@@ -0,0 +1,49 @@
+use super::*;
+
+#[test]
+fn generated_secret_round_trips_through_parse() {
+ let binding = BrowserBinding::generate();
+
+ assert_eq!(BrowserBinding::parse(binding.as_str()), Some(binding));
+}
+
+#[test]
+fn parse_refuses_a_secret_of_the_wrong_length() {
+ assert_eq!(BrowserBinding::parse("c2hvcnQ"), None);
+ assert_eq!(BrowserBinding::parse(""), None);
+}
+
+#[test]
+fn parse_refuses_text_that_is_not_base64url() {
+ assert_eq!(
+ BrowserBinding::parse("not base64 at all, and long enough to look like a secret!"),
+ None
+ );
+}
+
+#[test]
+fn digest_matches_only_its_own_secret() {
+ let binding = BrowserBinding::generate();
+ let other = BrowserBinding::generate();
+
+ assert!(binding.matches_digest(&binding.digest()));
+ assert!(!other.matches_digest(&binding.digest()));
+}
+
+#[test]
+fn consent_token_is_accepted_only_for_its_own_secret() {
+ let binding = BrowserBinding::generate();
+ let other = BrowserBinding::generate();
+
+ assert!(binding.accepts_consent_token(&binding.consent_token()));
+ assert!(!other.accepts_consent_token(&binding.consent_token()));
+ assert!(!binding.accepts_consent_token(""));
+}
+
+#[test]
+fn consent_token_is_not_the_stored_digest() {
+ let binding = BrowserBinding::generate();
+
+ assert!(!binding.accepts_consent_token(&binding.digest()));
+ assert!(!binding.matches_digest(&binding.consent_token()));
+}
diff --git a/services/mcp_auth_proxy/src/domain/models.rs b/services/mcp_auth_proxy/src/domain/models.rs
index 9b3418817d..58152d5d48 100644
--- a/services/mcp_auth_proxy/src/domain/models.rs
+++ b/services/mcp_auth_proxy/src/domain/models.rs
@@ -161,6 +161,40 @@ pub struct PendingAuthorization {
pub client_state: String,
/// Where to redirect back to the client with the authorization code.
pub client_redirect_uri: String,
+ /// Digest of the `BrowserBinding` held by the browser that started the
+ /// flow; only that browser may complete it. `None` only on a flow started
+ /// by a build that predates the binding, which could only have used a
+ /// trusted redirect URI.
+ pub browser_binding_digest: Option<String>,
+}
+
+/// Whether the user has approved the client on the consent screen.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum UserConsent {
+ /// The user has not been asked yet.
+ NotAsked,
+ /// The user approved the client on the consent screen.
+ Approved,
+}
+
+/// What the consent screen shows the user about the client asking for access.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct ConsentPrompt {
+ /// The name the client registered with. Self-reported, so it is shown as
+ /// unverified.
+ pub client_name: String,
+ /// The host the authorization code will be sent to: the identity the user
+ /// is actually approving.
+ pub redirect_host: String,
+}
+
+/// How an authorize request proceeds.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub enum AuthorizationStart {
+ /// Send the browser to the upstream sign-in at this URL.
+ SignIn(String),
+ /// Ask the user to approve the client before signing in.
+ ConsentRequired(ConsentPrompt),
}
/// An authorization code issued by this broker and backed by an upstream token.
@@ -183,8 +217,9 @@ pub struct IssuedAuthorizationCode {
}
/// How a user signs in upstream during an authorize flow.
-#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
+#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, strum::Display)]
#[serde(rename_all = "lowercase")]
+#[strum(serialize_all = "lowercase")]
pub enum SignInMethod {
/// Straight to Google, the default for every client.
#[default]
@@ -194,13 +229,13 @@ pub enum SignInMethod {
}
/// OAuth authorize request from the MCP client.
-#[derive(Deserialize)]
+#[derive(Clone, Deserialize)]
pub struct AuthorizeRequest {
/// Expected to be `code`.
pub response_type: String,
/// Dynamically registered client id.
pub client_id: String,
- /// Loopback callback URI owned by the MCP client.
+ /// Callback URI owned by the MCP client.
pub redirect_uri: String,
/// Opaque state from the client.
pub state: String,
@@ -213,7 +248,6 @@ pub struct AuthorizeRequest {
pub sign_in: Option<SignInMethod>,
/// Optional requested scopes.
#[serde(default)]
- #[allow(dead_code)]
pub scope: Option<String>,
}
diff --git a/services/mcp_auth_proxy/src/domain/redirect_uri.rs b/services/mcp_auth_proxy/src/domain/redirect_uri.rs
index e23badc1a9..eea0bdb3df 100644
--- a/services/mcp_auth_proxy/src/domain/redirect_uri.rs
+++ b/services/mcp_auth_proxy/src/domain/redirect_uri.rs
@@ -7,23 +7,37 @@ use std::collections::BTreeSet;
/// 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.
+/// How far the broker trusts a redirect URI it is willing to deliver a code to.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum RedirectTrust {
+ /// A loopback listener or a host the deployment trusts. The code reaches
+ /// the user who authorized it or a client Macro has vetted, so it is
+ /// delivered without asking the user first.
+ Trusted,
+ /// Any other `https` host. Whoever registered the client chose it, so the
+ /// user must approve that host on the consent screen before sign-in starts.
+ RequiresConsent,
+}
+
+/// The policy deciding which destinations the broker will hand an
+/// authorization code to, and which of those need the user's consent.
///
/// 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.
+/// policy is the check that does not depend on the requester: a loopback `http`
+/// redirect or an `https` one on a host the deployment trusts is delivered
+/// directly, any other `https` host only after the user approves it, and
+/// everything else is refused.
#[derive(Clone, Debug)]
pub struct RedirectUriPolicy {
allowed_https_hosts: BTreeSet<String>,
}
impl RedirectUriPolicy {
- /// Builds a policy trusting `https` redirect URIs on the given hosts.
+ /// Builds a policy trusting `https` redirect URIs on the given hosts
+ /// without asking for consent.
///
/// Hosts are matched exactly after lowercasing; subdomains of a trusted
/// host are not themselves trusted.
@@ -41,11 +55,10 @@ impl RedirectUriPolicy {
}
}
- /// 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;
- };
+ /// Returns how far the broker trusts `uri`, or `None` when it may never
+ /// redirect there.
+ pub fn trust(&self, uri: &str) -> Option<RedirectTrust> {
+ let parsed = url::Url::parse(uri).ok()?;
// RFC 6749 section 3.1.2 forbids a fragment on a redirection endpoint,
// and credentials in the authority would change who the URI resolves
@@ -54,17 +67,16 @@ impl RedirectUriPolicy {
|| !parsed.username().is_empty()
|| parsed.password().is_some()
{
- return false;
+ return None;
}
- let Some(host) = parsed.host_str() else {
- return false;
- };
+ let host = parsed.host_str()?;
match parsed.scheme() {
- "http" => LOOPBACK_HOSTS.contains(&host),
- "https" => self.allowed_https_hosts.contains(host),
- _ => false,
+ "http" if LOOPBACK_HOSTS.contains(&host) => Some(RedirectTrust::Trusted),
+ "https" if self.allowed_https_hosts.contains(host) => Some(RedirectTrust::Trusted),
+ "https" => Some(RedirectTrust::RequiresConsent),
+ _ => None,
}
}
diff --git a/services/mcp_auth_proxy/src/domain/redirect_uri/test.rs b/services/mcp_auth_proxy/src/domain/redirect_uri/test.rs
index ff9f550ea9..a9c019b202 100644
--- a/services/mcp_auth_proxy/src/domain/redirect_uri/test.rs
+++ b/services/mcp_auth_proxy/src/domain/redirect_uri/test.rs
@@ -5,70 +5,103 @@ fn policy() -> RedirectUriPolicy {
}
#[test]
-fn permits_trusted_https_host() {
- assert!(policy().permits("https://claude.ai/api/mcp/auth_callback"));
+fn trusts_listed_https_host() {
+ assert_eq!(
+ policy().trust("https://claude.ai/api/mcp/auth_callback"),
+ Some(RedirectTrust::Trusted)
+ );
}
#[test]
-fn permits_trusted_https_host_regardless_of_case() {
- assert!(policy().permits("https://Claude.AI/api/mcp/auth_callback"));
+fn trusts_listed_https_host_regardless_of_case() {
+ assert_eq!(
+ policy().trust("https://Claude.AI/api/mcp/auth_callback"),
+ Some(RedirectTrust::Trusted)
+ );
}
#[test]
-fn rejects_untrusted_https_host() {
- assert!(!policy().permits("https://attacker.example/callback"));
+fn unlisted_https_host_requires_consent() {
+ assert_eq!(
+ policy().trust("https://gateway.example/oauth/callback"),
+ Some(RedirectTrust::RequiresConsent)
+ );
}
#[test]
-fn rejects_subdomain_of_trusted_host() {
- assert!(!policy().permits("https://mcp.claude.ai/callback"));
+fn subdomain_of_listed_host_requires_consent() {
+ assert_eq!(
+ policy().trust("https://mcp.claude.ai/callback"),
+ Some(RedirectTrust::RequiresConsent)
+ );
}
#[test]
-fn rejects_trusted_host_used_as_a_subdomain_label() {
- assert!(!policy().permits("https://claude.ai.attacker.example/callback"));
+fn listed_host_used_as_a_subdomain_label_requires_consent() {
+ assert_eq!(
+ policy().trust("https://claude.ai.attacker.example/callback"),
+ Some(RedirectTrust::RequiresConsent)
+ );
}
#[test]
-fn rejects_trusted_host_in_userinfo() {
- assert!(!policy().permits("https://[email protected]/callback"));
+fn rejects_credentials_in_the_authority() {
+ assert_eq!(
+ policy().trust("https://[email protected]/callback"),
+ None
+ );
}
#[test]
fn rejects_fragment_on_redirect_uri() {
- assert!(!policy().permits("https://claude.ai/callback#fragment"));
+ assert_eq!(policy().trust("https://claude.ai/callback#fragment"), None);
}
#[test]
-fn permits_loopback_http_on_any_port() {
+fn trusts_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"));
+ assert_eq!(
+ policy.trust("http://127.0.0.1:51000/oauth/callback"),
+ Some(RedirectTrust::Trusted)
+ );
+ assert_eq!(
+ policy.trust("http://localhost:8123/callback"),
+ Some(RedirectTrust::Trusted)
+ );
+ assert_eq!(
+ policy.trust("http://[::1]:9000/callback"),
+ Some(RedirectTrust::Trusted)
+ );
}
#[test]
fn rejects_non_loopback_http() {
- assert!(!policy().permits("http://claude.ai/callback"));
- assert!(!policy().permits("http://attacker.example/callback"));
+ assert_eq!(policy().trust("http://claude.ai/callback"), None);
+ assert_eq!(policy().trust("http://attacker.example/callback"), None);
}
#[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"));
+ assert_eq!(policy.trust("javascript:alert(1)"), None);
+ assert_eq!(policy.trust("data:text/html,hi"), None);
+ assert_eq!(policy.trust("com.attacker.app:/callback"), None);
}
#[test]
fn rejects_unparseable_uri() {
- assert!(!policy().permits("not a uri"));
+ assert_eq!(policy().trust("not a uri"), None);
}
#[test]
-fn empty_allowlist_permits_only_loopback() {
+fn empty_allowlist_trusts_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"));
+ assert_eq!(
+ policy.trust("http://127.0.0.1:51000/oauth/callback"),
+ Some(RedirectTrust::Trusted)
+ );
+ assert_eq!(
+ policy.trust("https://claude.ai/api/mcp/auth_callback"),
+ Some(RedirectTrust::RequiresConsent)
+ );
}
diff --git a/services/mcp_auth_proxy/src/domain/service.rs b/services/mcp_auth_proxy/src/domain/service.rs
index 10d040c30b..f9b514aff1 100644
--- a/services/mcp_auth_proxy/src/domain/service.rs
+++ b/services/mcp_auth_proxy/src/domain/service.rs
@@ -13,13 +13,15 @@ use std::{
use super::{
access_token_clients::AccessTokenClients,
+ browser_binding::BrowserBinding,
models::{
- AuthorizeRequest, CallbackRequest, ClientRegistrationRequest, ClientRegistrationResponse,
- IssuedAuthorizationCode, PendingAuthorization, RefreshToken, RefreshTokenBinding,
- RegisteredClient, RevocationRequest, TokenRequest, TokenResponse,
+ AuthorizationStart, AuthorizeRequest, CallbackRequest, ClientRegistrationRequest,
+ ClientRegistrationResponse, ConsentPrompt, IssuedAuthorizationCode, PendingAuthorization,
+ RefreshToken, RefreshTokenBinding, RegisteredClient, RevocationRequest, TokenRequest,
+ TokenResponse, UserConsent,
},
ports::{ClientRegistrationStore, OAuthProvider, RefreshTokenBindingStore},
- redirect_uri::RedirectUriPolicy,
+ redirect_uri::{RedirectTrust, RedirectUriPolicy},
};
pub(crate) const PENDING_AUTH_TTL: Duration = Duration::from_secs(10 * 60);
@@ -43,6 +45,10 @@ pub const REVOKED_GRANT_TTL: Duration = REFRESH_TOKEN_BINDING_TTL;
const MAX_REDIRECT_URIS_PER_CLIENT: usize = 8;
/// Longest redirect URI accepted at registration.
const MAX_REDIRECT_URI_LEN: usize = 512;
+/// Longest client name the consent screen shows before shortening it.
+const MAX_CONSENT_CLIENT_NAME_CHARS: usize = 64;
+/// What the consent screen calls a client whose name has nothing printable.
+const UNNAMED_CLIENT: &str = "Unnamed app";
/// Domain interface for the MCP OAuth broker.
pub trait McpAuthProxyService: Clone + Send + Sync + 'static {
@@ -55,15 +61,21 @@ pub trait McpAuthProxyService: Clone + Send + Sync + 'static {
&self,
request: ClientRegistrationRequest,
) -> impl Future<Output = Result<ClientRegistrationResponse, RegisterClientError>> + Send;
- /// Starts an OAuth authorization flow and returns the upstream authorize URL.
+ /// Starts an OAuth authorization flow for the browser holding `browser`:
+ /// either the upstream sign-in to send it to, or the consent prompt to show
+ /// first when the client's redirect URI needs the user's approval.
fn start_authorization(
&self,
params: AuthorizeRequest,
- ) -> impl Future<Output = Result<String, StartAuthorizationError>> + Send;
- /// Completes the upstream callback and returns the loopback redirect URL.
+ browser: BrowserBinding,
+ consent: UserConsent,
+ ) -> impl Future<Output = Result<AuthorizationStart, StartAuthorizationError>> + Send;
+ /// Completes the upstream callback in the browser that started the flow
+ /// and returns the client redirect URL.
fn complete_callback(
&self,
params: CallbackRequest,
+ browser: Option<BrowserBinding>,
) -> impl Future<Output = Result<String, CompleteCallbackError>> + Send;
/// Exchanges a broker-issued code or refresh token for bearer credentials.
fn exchange_token(
@@ -412,9 +424,9 @@ where
/// Handles dynamic client registration for public MCP clients.
///
/// 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.
+ /// unconstrained: every submitted redirect URI must be one the redirect
+ /// URI policy accepts at all, and the accepted set is persisted so later
+ /// authorize requests have something to be checked against.
async fn register_client(
&self,
request: ClientRegistrationRequest,
@@ -426,7 +438,7 @@ where
return Err(RegisterClientError::TooManyRedirectUris);
}
for uri in &request.redirect_uris {
- if uri.len() > MAX_REDIRECT_URI_LEN || !self.redirect_uri_policy.permits(uri) {
+ if uri.len() > MAX_REDIRECT_URI_LEN || self.redirect_uri_policy.trust(uri).is_none() {
return Err(RegisterClientError::UnsupportedRedirectUri { uri: uri.clone() });
}
}
@@ -461,11 +473,18 @@ where
})
}
- /// Starts an OAuth authorization flow and returns the upstream authorize URL.
+ /// Starts an OAuth authorization flow.
+ ///
+ /// A redirect URI the deployment does not trust needs the user's approval
+ /// first, so until the consent screen reports it the flow stops at the
+ /// prompt and records nothing. The pending flow is bound to `browser`, so
+ /// only the browser that was shown the prompt can finish it.
fn start_authorization(
&self,
params: AuthorizeRequest,
- ) -> impl Future<Output = Result<String, StartAuthorizationError>> + Send {
+ browser: BrowserBinding,
+ consent: UserConsent,
+ ) -> impl Future<Output = Result<AuthorizationStart, StartAuthorizationError>> + Send {
let service = self.clone();
async move {
if params.response_type != "code" {
@@ -476,9 +495,10 @@ where
}
// 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 trust = service
+ .redirect_uri_policy
+ .trust(&params.redirect_uri)
+ .ok_or(StartAuthorizationError::InvalidRedirectUri)?;
let client = service
.client_registrations
@@ -495,6 +515,29 @@ where
return Err(StartAuthorizationError::UnregisteredRedirectUri);
}
+ if trust == RedirectTrust::RequiresConsent {
+ let redirect_host = redirect_host(&params.redirect_uri)
+ .ok_or(StartAuthorizationError::InvalidRedirectUri)?;
+
+ if consent == UserConsent::NotAsked {
+ tracing::info!(
+ client_id = %client.client_id,
+ %redirect_host,
+ "asking the user to approve an MCP client"
+ );
+ return Ok(AuthorizationStart::ConsentRequired(ConsentPrompt {
+ client_name: consent_client_name(&client.client_name),
+ redirect_host,
+ }));
+ }
+
+ tracing::info!(
+ client_id = %client.client_id,
+ %redirect_host,
+ "user approved an MCP client"
+ );
+ }
+
let session_id = uuid::Uuid::new_v4().to_string();
let sign_in = params.sign_in.unwrap_or_default();
tracing::info!(%session_id, client_id = %client.client_id, "starting OAuth authorize flow");
@@ -508,6 +551,7 @@ where
code_challenge: params.code_challenge,
client_state: params.state,
client_redirect_uri: params.redirect_uri,
+ browser_binding_digest: Some(browser.digest()),
},
)
.await
@@ -516,15 +560,23 @@ where
service
.oauth_provider
.construct_authorize_url(&session_id, sign_in)
+ .map(AuthorizationStart::SignIn)
.map_err(StartAuthorizationError::ConstructAuthorizeUrl)
}
}
/// Completes the upstream OAuth callback and returns the redirect URL for
- /// the MCP client loopback callback.
+ /// the MCP client callback.
+ ///
+ /// The upstream signs in a user with an existing session without asking,
+ /// so a sign-in link someone else started would otherwise complete
+ /// silently in a victim's browser and send the victim's code to the
+ /// starter's client. Requiring the browser binding of the browser that
+ /// started the flow closes that.
async fn complete_callback(
&self,
params: CallbackRequest,
+ browser: Option<BrowserBinding>,
) -> Result<String, CompleteCallbackError> {
let session_id = params
.state
@@ -541,6 +593,22 @@ where
.map_err(CompleteCallbackError::InflightStore)?
.ok_or(CompleteCallbackError::UnknownOrExpiredSession)?;
+ let started_in_this_browser = match &pending.browser_binding_digest {
+ Some(digest) => browser.is_some_and(|browser| browser.matches_digest(digest)),
+ None => {
+ self.redirect_uri_policy.trust(&pending.client_redirect_uri)
+ == Some(RedirectTrust::Trusted)
+ }
+ };
+ if !started_in_this_browser {
+ tracing::warn!(
+ %session_id,
+ client_id = %pending.client_id,
+ "oauth callback arrived in a browser that did not start the flow"
+ );
+ return Err(CompleteCallbackError::DifferentBrowser);
+ }
+
if let Some(error) = params.error {
tracing::warn!(
%session_id,
@@ -691,6 +759,56 @@ fn refresh_token_digest(refresh_token: &RefreshToken) -> String {
URL_SAFE_NO_PAD.encode(digest)
}
+/// The host (and port, when not the default) a redirect URI delivers to, as
+/// the consent screen names it. `url` renders internationalized hosts in
+/// punycode, so a lookalike host cannot pass for the one it imitates.
+fn redirect_host(uri: &str) -> Option<String> {
+ let parsed = url::Url::parse(uri).ok()?;
+ let host = parsed.host_str()?;
+
+ match parsed.port() {
+ Some(port) => Some(format!("{host}:{port}")),
+ None => Some(host.to_owned()),
+ }
+}
+
+/// The self-reported client name as the consent screen shows it: control,
+/// bidirectional-override and zero-width characters dropped and length
+/// capped, so a name cannot restyle or crowd out the rest of the prompt.
+fn consent_client_name(client_name: &str) -> String {
+ let printable: String = client_name
+ .chars()
+ .filter(|character| !character.is_control() && !is_invisible_formatting(*character))
+ .collect();
+ let trimmed = printable.trim();
+
+ if trimmed.is_empty() {
+ return UNNAMED_CLIENT.to_owned();
+ }
+ if trimmed.chars().count() <= MAX_CONSENT_CLIENT_NAME_CHARS {
+ return trimmed.to_owned();
+ }
+
+ let mut shortened: String = trimmed
+ .chars()
+ .take(MAX_CONSENT_CLIENT_NAME_CHARS)
+ .collect();
+ shortened.push('\u{2026}');
+ shortened
+}
+
+/// Characters that change how surrounding text renders without showing
+/// themselves: bidirectional overrides and isolates, and zero-width marks.
+fn is_invisible_formatting(character: char) -> bool {
+ matches!(
+ character,
+ '\u{200B}'..='\u{200F}'
+ | '\u{202A}'..='\u{202E}'
+ | '\u{2060}'..='\u{2069}'
+ | '\u{FEFF}'
+ )
+}
+
/// 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 {
@@ -767,6 +885,10 @@ pub enum CompleteCallbackError {
/// Pending broker session was missing or expired.
#[error("unknown or expired session")]
UnknownOrExpiredSession,
+ /// The callback arrived in a browser other than the one that started the
+ /// flow.
+ #[error("authorization was started in a different browser")]
+ DifferentBrowser,
/// Inflight auth state could not be loaded or updated.
#[error("failed to access inflight auth state")]
InflightStore(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 e3a418c7ef..7d1db1fb85 100644
--- a/services/mcp_auth_proxy/src/domain/service/test.rs
+++ b/services/mcp_auth_proxy/src/domain/service/test.rs
@@ -2,11 +2,15 @@ use std::time::{Duration, SystemTime};
use super::*;
use crate::{
- domain::models::{AccessToken, ClientRegistrationRequest},
+ domain::{
+ browser_binding::BrowserBinding,
+ 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,
+ ATTACKER_CODE_VERIFIER, ATTACKER_REDIRECT_URI, FakeOAuthProvider, GATEWAY_REDIRECT_URI,
+ 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,
},
};
@@ -28,17 +32,32 @@ async fn registration_persists_the_submitted_redirect_uris() {
}
#[tokio::test]
-async fn registration_rejects_an_untrusted_https_redirect_uri() {
+async fn registration_accepts_an_unlisted_https_redirect_uri() {
+ let harness = Harness::new();
+ let client_id = harness.register(&[GATEWAY_REDIRECT_URI]).await;
+
+ let stored = harness
+ .registry
+ .find_client(&client_id)
+ .await
+ .expect("lookup should succeed")
+ .expect("client should be persisted");
+
+ assert_eq!(stored.redirect_uris, vec![GATEWAY_REDIRECT_URI]);
+}
+
+#[tokio::test]
+async fn registration_rejects_a_non_loopback_http_redirect_uri() {
let harness = Harness::new();
let error = harness
.service
.register_client(ClientRegistrationRequest {
client_name: None,
- redirect_uris: vec![ATTACKER_REDIRECT_URI.to_owned()],
+ redirect_uris: vec!["http://gateway.example/oauth/callback".to_owned()],
})
.await
- .expect_err("an untrusted host must not be registrable");
+ .expect_err("plain http off loopback must not be registrable");
assert!(matches!(
error,
@@ -70,11 +89,15 @@ async fn authorize_rejects_an_unknown_client_id() {
let error = harness
.service
- .start_authorization(harness.authorize_request(
- "never-registered",
- LOOPBACK_REDIRECT_URI,
- &code_challenge_for(VICTIM_CODE_VERIFIER),
- ))
+ .start_authorization(
+ harness.authorize_request(
+ "never-registered",
+ LOOPBACK_REDIRECT_URI,
+ &code_challenge_for(VICTIM_CODE_VERIFIER),
+ ),
+ harness.browser.clone(),
+ UserConsent::NotAsked,
+ )
.await
.expect_err("an unregistered client_id must be rejected");
@@ -88,11 +111,15 @@ async fn authorize_rejects_a_redirect_uri_the_client_did_not_register() {
let error = harness
.service
- .start_authorization(harness.authorize_request(
- &client_id,
- "https://claude.ai/some/other/path",
- &code_challenge_for(VICTIM_CODE_VERIFIER),
- ))
+ .start_authorization(
+ harness.authorize_request(
+ &client_id,
+ "https://claude.ai/some/other/path",
+ &code_challenge_for(VICTIM_CODE_VERIFIER),
+ ),
+ harness.browser.clone(),
+ UserConsent::NotAsked,
+ )
.await
.expect_err("a redirect_uri outside the registration must be rejected");
@@ -103,64 +130,291 @@ async fn authorize_rejects_a_redirect_uri_the_client_did_not_register() {
}
#[tokio::test]
-async fn authorize_rejects_an_attacker_controlled_redirect_uri() {
+async fn authorize_rejects_an_unregistered_attacker_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),
- ))
+ .start_authorization(
+ harness.authorize_request(
+ &client_id,
+ ATTACKER_REDIRECT_URI,
+ &code_challenge_for(ATTACKER_CODE_VERIFIER),
+ ),
+ harness.browser.clone(),
+ UserConsent::Approved,
+ )
.await
- .expect_err("an untrusted host must be rejected at authorize");
+ .expect_err("a callback the client did not register must be rejected");
+
+ assert!(matches!(
+ error,
+ StartAuthorizationError::UnregisteredRedirectUri
+ ));
+ assert!(!harness.inflight.has_pending());
+}
+
+#[tokio::test]
+async fn authorize_rejects_a_redirect_uri_the_policy_refuses() {
+ let harness = Harness::new();
+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
+
+ let error = harness
+ .service
+ .start_authorization(
+ harness.authorize_request(
+ &client_id,
+ "http://attacker.example/steal",
+ &code_challenge_for(ATTACKER_CODE_VERIFIER),
+ ),
+ harness.browser.clone(),
+ UserConsent::Approved,
+ )
+ .await
+ .expect_err("plain http off loopback must be rejected at authorize");
assert!(matches!(error, StartAuthorizationError::InvalidRedirectUri));
}
-/// 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() {
+async fn authorize_for_an_unlisted_host_asks_for_consent_and_stores_nothing() {
let harness = Harness::new();
+ let client_id = harness.register(&[GATEWAY_REDIRECT_URI]).await;
- let attacker_registration = harness
+ let start = harness
.service
- .register_client(ClientRegistrationRequest {
- client_name: Some("totally-legitimate-client".to_owned()),
- redirect_uris: vec![ATTACKER_REDIRECT_URI.to_owned()],
+ .start_authorization(
+ harness.authorize_request(
+ &client_id,
+ GATEWAY_REDIRECT_URI,
+ &code_challenge_for(VICTIM_CODE_VERIFIER),
+ ),
+ harness.browser.clone(),
+ UserConsent::NotAsked,
+ )
+ .await
+ .expect("authorize should succeed");
+
+ assert_eq!(
+ start,
+ AuthorizationStart::ConsentRequired(ConsentPrompt {
+ client_name: "test-client".to_owned(),
+ redirect_host: "gateway.example".to_owned(),
})
- .await;
+ );
assert!(
- attacker_registration.is_err(),
- "the attacker must not be able to register their callback"
+ !harness.inflight.has_pending(),
+ "nothing may be stored before the user answers"
);
+}
- // 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
+#[tokio::test]
+async fn authorize_for_a_trusted_host_signs_in_without_consent() {
+ let harness = Harness::new();
+ let client_id = harness.register(&[TRUSTED_REDIRECT_URI]).await;
+
+ let start = harness
.service
- .start_authorization(harness.authorize_request(
- &victim_client_id,
- ATTACKER_REDIRECT_URI,
- &code_challenge_for(ATTACKER_CODE_VERIFIER),
- ))
+ .start_authorization(
+ harness.authorize_request(
+ &client_id,
+ TRUSTED_REDIRECT_URI,
+ &code_challenge_for(VICTIM_CODE_VERIFIER),
+ ),
+ harness.browser.clone(),
+ UserConsent::NotAsked,
+ )
.await
- .expect_err("the crafted authorize request must fail");
+ .expect("authorize should succeed");
+
+ assert!(matches!(start, AuthorizationStart::SignIn(_)));
+}
+
+#[tokio::test]
+async fn approved_client_on_an_unlisted_host_completes_the_flow() {
+ let harness = Harness::new();
+ let client_id = harness.register(&[GATEWAY_REDIRECT_URI]).await;
+
+ let start = harness
+ .service
+ .start_authorization(
+ harness.authorize_request(
+ &client_id,
+ GATEWAY_REDIRECT_URI,
+ &code_challenge_for(VICTIM_CODE_VERIFIER),
+ ),
+ harness.browser.clone(),
+ UserConsent::Approved,
+ )
+ .await
+ .expect("authorize should succeed");
+ assert!(matches!(start, AuthorizationStart::SignIn(_)));
+
+ let redirect = harness
+ .service
+ .complete_callback(
+ upstream_callback(&harness.inflight.only_pending_session_id()),
+ Some(harness.browser.clone()),
+ )
+ .await
+ .expect("callback should succeed");
- assert!(matches!(error, StartAuthorizationError::InvalidRedirectUri));
assert!(
- !harness.inflight.has_pending(),
- "no handshake state may be created for a rejected authorize request"
+ redirect.starts_with(&format!("{GATEWAY_REDIRECT_URI}?code=")),
+ "unexpected redirect: {redirect}"
);
}
+/// The attack the consent screen alone does not stop: an attacker approves
+/// their own client, takes the upstream sign-in URL that produces, and sends
+/// it to a victim, whose existing upstream session completes it silently. The
+/// callback arrives in the victim's browser, which does not hold the binding
+/// the flow was started with, so no code is issued.
+#[tokio::test]
+async fn a_flow_started_in_another_browser_cannot_be_completed() {
+ let harness = Harness::new();
+ let client_id = harness.register(&[ATTACKER_REDIRECT_URI]).await;
+ let attacker_browser = BrowserBinding::generate();
+
+ harness
+ .service
+ .start_authorization(
+ harness.authorize_request(
+ &client_id,
+ ATTACKER_REDIRECT_URI,
+ &code_challenge_for(ATTACKER_CODE_VERIFIER),
+ ),
+ attacker_browser,
+ UserConsent::Approved,
+ )
+ .await
+ .expect("the attacker can approve their own client");
+ let session_id = harness.inflight.only_pending_session_id();
+
+ let error = harness
+ .service
+ .complete_callback(
+ upstream_callback(&session_id),
+ Some(harness.browser.clone()),
+ )
+ .await
+ .expect_err("the victim's browser must not complete the attacker's flow");
+
+ assert!(matches!(error, CompleteCallbackError::DifferentBrowser));
+ assert!(!harness.inflight.holds_any_issued_code());
+}
+
+#[tokio::test]
+async fn a_callback_without_the_binding_cookie_is_refused() {
+ 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),
+ ),
+ harness.browser.clone(),
+ UserConsent::NotAsked,
+ )
+ .await
+ .expect("authorize should succeed");
+
+ let error = harness
+ .service
+ .complete_callback(
+ upstream_callback(&harness.inflight.only_pending_session_id()),
+ None,
+ )
+ .await
+ .expect_err("a callback without the cookie must be refused");
+
+ assert!(matches!(error, CompleteCallbackError::DifferentBrowser));
+}
+
+/// A flow stored by the build before browser binding carries no digest. That
+/// build only accepted trusted redirect URIs, so only those may complete
+/// unbound.
+#[tokio::test]
+async fn an_unbound_pending_flow_completes_only_to_a_trusted_redirect_uri() {
+ let harness = Harness::new();
+
+ for (redirect_uri, completes) in [(TRUSTED_REDIRECT_URI, true), (GATEWAY_REDIRECT_URI, false)] {
+ let session_id = format!("legacy-{completes}");
+ harness
+ .inflight
+ .insert_pending(
+ &session_id,
+ PendingAuthorization {
+ client_id: "legacy-client".to_owned(),
+ code_challenge: code_challenge_for(VICTIM_CODE_VERIFIER),
+ client_state: "client-state".to_owned(),
+ client_redirect_uri: redirect_uri.to_owned(),
+ browser_binding_digest: None,
+ },
+ )
+ .await
+ .expect("insert should succeed");
+
+ let result = harness
+ .service
+ .complete_callback(upstream_callback(&session_id), None)
+ .await;
+
+ assert_eq!(result.is_ok(), completes, "redirect_uri {redirect_uri}");
+ }
+}
+
+#[tokio::test]
+async fn consent_prompt_strips_formatting_tricks_from_the_client_name() {
+ let harness = Harness::new();
+ let registration = harness
+ .service
+ .register_client(ClientRegistrationRequest {
+ client_name: Some(format!(
+ "Claude\u{202E}moc.elgoog\u{200B}\n{}",
+ "x".repeat(100)
+ )),
+ redirect_uris: vec!["https://xn--claud-7ra.example:8443/callback".to_owned()],
+ })
+ .await
+ .expect("registration should succeed");
+
+ let start = harness
+ .service
+ .start_authorization(
+ harness.authorize_request(
+ &registration.client_id,
+ "https://xn--claud-7ra.example:8443/callback",
+ &code_challenge_for(VICTIM_CODE_VERIFIER),
+ ),
+ harness.browser.clone(),
+ UserConsent::NotAsked,
+ )
+ .await
+ .expect("authorize should succeed");
+
+ let AuthorizationStart::ConsentRequired(prompt) = start else {
+ panic!("an unlisted host must ask for consent");
+ };
+ let expected_name = format!("Claudemoc.elgoog{}\u{2026}", "x".repeat(48));
+ assert_eq!(prompt.client_name, expected_name);
+ assert_eq!(prompt.redirect_host, "xn--claud-7ra.example:8443");
+}
+
+fn upstream_callback(session_id: &str) -> CallbackRequest {
+ CallbackRequest {
+ code: Some("upstream-code".to_owned()),
+ state: Some(session_id.to_owned()),
+ error: None,
+ error_description: None,
+ }
+}
+
// --- Token exchange ----------------------------------------------------
#[tokio::test]
@@ -649,22 +903,29 @@ async fn callback_redirect_preserves_a_query_on_the_registered_redirect_uri() {
harness
.service
- .start_authorization(harness.authorize_request(
- &client_id,
- redirect_uri,
- &code_challenge_for(VICTIM_CODE_VERIFIER),
- ))
+ .start_authorization(
+ harness.authorize_request(
+ &client_id,
+ redirect_uri,
+ &code_challenge_for(VICTIM_CODE_VERIFIER),
+ ),
+ harness.browser.clone(),
+ UserConsent::NotAsked,
+ )
.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,
- })
+ .complete_callback(
+ CallbackRequest {
+ code: Some("upstream-code".to_owned()),
+ state: Some(harness.inflight.only_pending_session_id()),
+ error: None,
+ error_description: None,
+ },
+ Some(harness.browser.clone()),
+ )
.await
.expect("callback should succeed");
@@ -821,22 +1082,29 @@ async fn callback_records_upstream_expiry_on_the_issued_code() {
harness
.service
- .start_authorization(harness.authorize_request(
- &client_id,
- TRUSTED_REDIRECT_URI,
- &code_challenge_for(VICTIM_CODE_VERIFIER),
- ))
+ .start_authorization(
+ harness.authorize_request(
+ &client_id,
+ TRUSTED_REDIRECT_URI,
+ &code_challenge_for(VICTIM_CODE_VERIFIER),
+ ),
+ harness.browser.clone(),
+ UserConsent::NotAsked,
+ )
.await
.expect("authorize should succeed");
harness
.service
- .complete_callback(CallbackRequest {
- code: Some("upstream-code".to_owned()),
- state: Some(harness.inflight.only_pending_session_id()),
- error: None,
- error_description: None,
- })
+ .complete_callback(
+ CallbackRequest {
+ code: Some("upstream-code".to_owned()),
+ state: Some(harness.inflight.only_pending_session_id()),
+ error: None,
+ error_description: None,
+ },
+ Some(harness.browser.clone()),
+ )
.await
.expect("callback should succeed");
diff --git a/services/mcp_auth_proxy/src/inbound/axum_router.rs b/services/mcp_auth_proxy/src/inbound/axum_router.rs
index 04660c5ee4..8c4f958e74 100644
--- a/services/mcp_auth_proxy/src/inbound/axum_router.rs
+++ b/services/mcp_auth_proxy/src/inbound/axum_router.rs
@@ -5,21 +5,25 @@ mod test;
use std::time::Duration;
+use askama::Template;
use axum::{
Router,
extract::{Query, RawQuery, State},
- http::{HeaderName, Method, header},
+ http::{HeaderMap, HeaderName, Method, header},
middleware as axum_mw,
response::{Html, IntoResponse, Json, Redirect, Response},
routing,
};
+use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
+use serde::Deserialize;
use tower_http::cors::{AllowOrigin, CorsLayer};
use crate::domain::{
+ browser_binding::BrowserBinding,
models::{
- AuthorizeRequest, CallbackRequest, ClientRegistrationRequest, RevocationRequest,
- TokenRequest,
+ AuthorizationStart, AuthorizeRequest, CallbackRequest, ClientRegistrationRequest,
+ ConsentPrompt, RevocationRequest, TokenRequest, UserConsent,
},
service::{
CompleteCallbackError, InflightAuthStore, McpAuthProxyService, McpAuthProxyServiceImpl,
@@ -27,6 +31,13 @@ use crate::domain::{
},
};
+/// Fetch metadata header naming how the request's initiator relates to this
+/// origin; browsers set it on every request.
+const SEC_FETCH_SITE: HeaderName = HeaderName::from_static("sec-fetch-site");
+
+const INVALID_REDIRECT_URI: &str =
+ "redirect_uri must be an https URL or an http URL on a loopback address";
+
/// Health check handler for ALB.
async fn health() -> &'static str {
"ok"
@@ -67,11 +78,7 @@ async fn register<I: InflightAuthStore + 'static>(
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()
+ (axum::http::StatusCode::BAD_REQUEST, INVALID_REDIRECT_URI).into_response()
}
Err(RegisterClientError::ClientRegistrationStore(error)) => {
tracing::error!(error=?error, "failed to persist client registration");
@@ -84,6 +91,78 @@ async fn register<I: InflightAuthStore + 'static>(
}
}
+/// Cookie carrying the browser's `BrowserBinding`. The `__Host-` prefix makes
+/// browsers refuse it unless it is `Secure`, host-only and on `/`, so no
+/// sibling domain can plant one.
+const BROWSER_BINDING_COOKIE: &str = "__Host-macro_mcp_oauth";
+
+/// The consent screen loads nothing, runs nothing, and cannot be framed, so a
+/// page that overlays it cannot trick a click onto Allow.
+const CONSENT_PAGE_CSP: &str =
+ "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'";
+
+const CONSENT_DECLINED_PAGE: &str = include_str!("../../templates/consent_declined.html");
+
+#[derive(Template)]
+#[template(path = "consent.html")]
+struct ConsentPage<'a> {
+ client_name: &'a str,
+ redirect_host: &'a str,
+ request: &'a AuthorizeRequest,
+ consent_token: &'a str,
+}
+
+/// What the user chose on the consent screen.
+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
+#[serde(rename_all = "lowercase")]
+enum ConsentDecision {
+ Approve,
+ Deny,
+}
+
+/// The consent screen's form: the authorize request it was shown for, the
+/// anti-forgery token, and the user's choice.
+#[derive(Deserialize)]
+struct ConsentSubmission {
+ #[serde(flatten)]
+ request: AuthorizeRequest,
+ consent_token: String,
+ decision: ConsentDecision,
+}
+
+fn browser_binding(jar: &CookieJar) -> Option<BrowserBinding> {
+ jar.get(BROWSER_BINDING_COOKIE)
+ .and_then(|cookie| BrowserBinding::parse(cookie.value()))
+}
+
+fn browser_binding_cookie(browser: &BrowserBinding) -> Cookie<'static> {
+ // `Lax` still reaches the upstream's redirect back to `/oauth/callback`,
+ // a top-level navigation, but not a cross-site form post.
+ Cookie::build((BROWSER_BINDING_COOKIE, browser.as_str().to_owned()))
+ .path("/")
+ .secure(true)
+ .http_only(true)
+ .same_site(SameSite::Lax)
+ .build()
+}
+
+/// A broker-rendered page with the headers that keep it from being framed,
+/// cached, or leaking its URL.
+fn html_page(body: String) -> Response {
+ (
+ [
+ (header::CONTENT_TYPE, "text/html; charset=utf-8"),
+ (header::CONTENT_SECURITY_POLICY, CONSENT_PAGE_CSP),
+ (header::X_FRAME_OPTIONS, "DENY"),
+ (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
+ (header::CACHE_CONTROL, "no-store"),
+ (header::REFERRER_POLICY, "no-referrer"),
+ ],
+ body,
+ )
+ .into_response()
+}
+
/// Hosts whose users pick how to sign in, rather than going straight to
/// Google. OpenAI's reviewers sign in with a password, and can't get through
/// Google's challenges on a shared account.
@@ -129,52 +208,161 @@ fn sign_in_choice(query: Option<String>) -> Response {
.into_response()
}
+fn consent_page(
+ prompt: &ConsentPrompt,
+ request: &AuthorizeRequest,
+ browser: &BrowserBinding,
+) -> Response {
+ let page = ConsentPage {
+ client_name: &prompt.client_name,
+ redirect_host: &prompt.redirect_host,
+ request,
+ consent_token: &browser.consent_token(),
+ };
+
+ match page.render() {
+ Ok(body) => html_page(body),
+ Err(error) => {
+ tracing::error!(error=?error, "failed to render the consent page");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to render the consent page",
+ )
+ .into_response()
+ }
+ }
+}
+
+/// Answers an authorize request, or an approved consent form, with the
+/// upstream sign-in or the consent screen. `redirect` builds the redirect to
+/// the sign-in: a `307` for `GET /authorize`, a `303` after the form post.
+async fn authorization_response<I: InflightAuthStore + 'static>(
+ auth_proxy: &McpAuthProxyServiceImpl<I>,
+ request: AuthorizeRequest,
+ browser: BrowserBinding,
+ consent: UserConsent,
+ redirect: fn(&str) -> Redirect,
+) -> Response {
+ match auth_proxy
+ .start_authorization(request.clone(), browser.clone(), consent)
+ .await
+ {
+ // The browser carries the MCP client page's Referer across this
+ // redirect, and FusionAuth rejects any Referer outside its first-party
+ // origin list with "Invalid origin uri". The redirect URI policy has
+ // already vetted the client, so the client's origin is withheld.
+ Ok(AuthorizationStart::SignIn(url)) => {
+ ([(header::REFERRER_POLICY, "no-referrer")], redirect(&url)).into_response()
+ }
+ Ok(AuthorizationStart::ConsentRequired(prompt)) => {
+ consent_page(&prompt, &request, &browser)
+ }
+ Err(error) => start_authorization_error_response(error),
+ }
+}
+
async fn authorize<I: InflightAuthStore + 'static>(
State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,
+ jar: CookieJar,
RawQuery(query): RawQuery,
Query(params): Query<AuthorizeRequest>,
) -> Response {
if params.sign_in.is_none() && offers_sign_in_choice(&params.redirect_uri) {
return sign_in_choice(query);
}
- match auth_proxy.start_authorization(params).await {
- // The browser carries the MCP client page's Referer across this
- // redirect, and FusionAuth rejects any Referer outside its first-party
- // origin list with "Invalid origin uri". The redirect URI policy has
- // already vetted the client, so the client's origin is withheld.
- Ok(url) => (
- [(header::REFERRER_POLICY, "no-referrer")],
- Redirect::temporary(&url),
+
+ let browser = browser_binding(&jar).unwrap_or_else(BrowserBinding::generate);
+ let jar = jar.add(browser_binding_cookie(&browser));
+
+ let response = authorization_response(
+ &auth_proxy,
+ params,
+ browser,
+ UserConsent::NotAsked,
+ Redirect::temporary,
+ )
+ .await;
+ (jar, response).into_response()
+}
+
+/// Receives the consent screen's form.
+///
+/// The form only counts when it was posted by the browser that was shown it:
+/// the browser binding cookie must be present (a cross-site post does not
+/// carry a `SameSite=Lax` cookie) and the form's token must be the one derived
+/// from it, which a page on another origin cannot read.
+async fn submit_consent<I: InflightAuthStore + 'static>(
+ State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,
+ jar: CookieJar,
+ headers: HeaderMap,
+ axum::Form(submission): axum::Form<ConsentSubmission>,
+) -> Response {
+ let cross_site = headers
+ .get(SEC_FETCH_SITE)
+ .is_some_and(|site| site.as_bytes() != b"same-origin");
+ let browser = browser_binding(&jar)
+ .filter(|browser| browser.accepts_consent_token(&submission.consent_token));
+
+ let Some(browser) = browser.filter(|_| !cross_site) else {
+ tracing::warn!(
+ client_id = %submission.request.client_id,
+ cross_site,
+ "consent form submission could not be verified"
+ );
+ return (
+ axum::http::StatusCode::FORBIDDEN,
+ "This approval could not be verified. Start connecting again from the app you \
+ are connecting.",
)
- .into_response(),
- Err(StartAuthorizationError::UnsupportedResponseType) => (
+ .into_response();
+ };
+
+ match submission.decision {
+ ConsentDecision::Deny => {
+ tracing::info!(client_id = %submission.request.client_id, "user declined an MCP client");
+ html_page(CONSENT_DECLINED_PAGE.to_owned())
+ }
+ ConsentDecision::Approve => {
+ authorization_response(
+ &auth_proxy,
+ submission.request,
+ browser,
+ UserConsent::Approved,
+ Redirect::to,
+ )
+ .await
+ }
+ }
+}
+
+fn start_authorization_error_response(error: StartAuthorizationError) -> Response {
+ match error {
+ StartAuthorizationError::UnsupportedResponseType => (
axum::http::StatusCode::BAD_REQUEST,
"unsupported response_type",
)
.into_response(),
- Err(StartAuthorizationError::UnsupportedCodeChallengeMethod) => (
+ StartAuthorizationError::UnsupportedCodeChallengeMethod => (
axum::http::StatusCode::BAD_REQUEST,
"unsupported code_challenge_method",
)
.into_response(),
- Err(StartAuthorizationError::InvalidRedirectUri) => (
- axum::http::StatusCode::BAD_REQUEST,
- "redirect_uri must be a loopback address or a trusted MCP client host",
- )
- .into_response(),
- Err(StartAuthorizationError::UnregisteredRedirectUri) => (
+ StartAuthorizationError::InvalidRedirectUri => {
+ (axum::http::StatusCode::BAD_REQUEST, INVALID_REDIRECT_URI).into_response()
+ }
+ StartAuthorizationError::UnregisteredRedirectUri => (
axum::http::StatusCode::BAD_REQUEST,
"redirect_uri was not registered for this client",
)
.into_response(),
- Err(StartAuthorizationError::UnknownClient) => (
+ StartAuthorizationError::UnknownClient => (
axum::http::StatusCode::BAD_REQUEST,
"Your Macro connection needs to be reconnected. In the app you are connecting from, \
remove the Macro MCP connection, add it again, and sign in to Macro. \
Signing in again without removing the connection may reuse the old registration.",
)
.into_response(),
- Err(StartAuthorizationError::ClientRegistrationStore(error)) => {
+ StartAuthorizationError::ClientRegistrationStore(error) => {
tracing::error!(error=?error, "failed to read client registrations");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
@@ -182,7 +370,7 @@ async fn authorize<I: InflightAuthStore + 'static>(
)
.into_response()
}
- Err(StartAuthorizationError::InflightStore(error)) => {
+ StartAuthorizationError::InflightStore(error) => {
tracing::error!(error=?error, "failed to persist inflight auth state");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
@@ -190,7 +378,7 @@ async fn authorize<I: InflightAuthStore + 'static>(
)
.into_response()
}
- Err(StartAuthorizationError::ConstructAuthorizeUrl(error)) => {
+ StartAuthorizationError::ConstructAuthorizeUrl(error) => {
tracing::error!(error=?error, "failed to construct upstream authorize URL");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
@@ -203,9 +391,13 @@ async fn authorize<I: InflightAuthStore + 'static>(
async fn oauth_callback<I: InflightAuthStore + 'static>(
State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,
+ jar: CookieJar,
Query(params): Query<CallbackRequest>,
) -> Response {
- match auth_proxy.complete_callback(params).await {
+ match auth_proxy
+ .complete_callback(params, browser_binding(&jar))
+ .await
+ {
Ok(url) => Redirect::temporary(&url).into_response(),
Err(CompleteCallbackError::MissingState) => {
tracing::warn!("no state parameter in upstream OAuth callback");
@@ -228,6 +420,12 @@ async fn oauth_callback<I: InflightAuthStore + 'static>(
"unknown or expired session",
)
.into_response(),
+ Err(CompleteCallbackError::DifferentBrowser) => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "This sign-in was started in a different browser. Start connecting again from the \
+ app you are connecting, and finish signing in in the browser it opens.",
+ )
+ .into_response(),
Err(CompleteCallbackError::InflightStore(error)) => {
tracing::error!(error=?error, "failed to access inflight auth state");
(
@@ -412,7 +610,7 @@ fn oauth_routes<I: InflightAuthStore + 'static>(auth_proxy: McpAuthProxyServiceI
"/.well-known/oauth-authorization-server/mcp",
routing::get(authorization_server_metadata),
)
- .route("/authorize", routing::get(authorize))
+ .route("/authorize", routing::get(authorize).post(submit_consent))
.route("/register", routing::post(register))
.route("/oauth/callback", routing::get(oauth_callback))
.route("/token", routing::post(token))
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 6ad3e5bfc1..04017ee837 100644
--- a/services/mcp_auth_proxy/src/inbound/axum_router/test.rs
+++ b/services/mcp_auth_proxy/src/inbound/axum_router/test.rs
@@ -8,10 +8,11 @@ use axum::{
use tower::ServiceExt;
use super::{health, mcp_router, mount_at_root_and_prefix, oauth_router};
+use crate::domain::browser_binding::BrowserBinding;
use crate::test_support::{
- ATTACKER_CODE_VERIFIER, ATTACKER_REDIRECT_URI, Harness, TRUSTED_REDIRECT_URI,
- UPSTREAM_ACCESS_TOKEN, UPSTREAM_REFRESH_TOKEN, VICTIM_CODE_VERIFIER, code_challenge_for,
- query_param,
+ ATTACKER_CODE_VERIFIER, ATTACKER_REDIRECT_URI, GATEWAY_REDIRECT_URI, Harness,
+ TRUSTED_REDIRECT_URI, UPSTREAM_ACCESS_TOKEN, UPSTREAM_REFRESH_TOKEN, VICTIM_CODE_VERIFIER,
+ code_challenge_for, query_param,
};
use axum::{Router, routing::get};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
@@ -22,6 +23,9 @@ struct Response {
status: StatusCode,
location: Option<String>,
referrer_policy: Option<String>,
+ set_cookie: Option<String>,
+ csp: Option<String>,
+ x_frame_options: Option<String>,
body: String,
}
@@ -38,14 +42,17 @@ async fn send(harness: &Harness, request: Request<Body>) -> Response {
.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 referrer_policy = response
- .headers()
- .get(header::REFERRER_POLICY)
- .map(|value| value.to_str().expect("Referrer-Policy is text").to_owned());
+ let header_text = |name: header::HeaderName| {
+ response
+ .headers()
+ .get(name)
+ .map(|value| value.to_str().expect("header is text").to_owned())
+ };
+ let location = header_text(header::LOCATION);
+ let referrer_policy = header_text(header::REFERRER_POLICY);
+ let set_cookie = header_text(header::SET_COOKIE);
+ let csp = header_text(header::CONTENT_SECURITY_POLICY);
+ let x_frame_options = header_text(header::X_FRAME_OPTIONS);
let bytes = axum::body::to_bytes(response.into_body(), BODY_LIMIT)
.await
.expect("body should be readable");
@@ -54,6 +61,9 @@ async fn send(harness: &Harness, request: Request<Body>) -> Response {
status,
location,
referrer_policy,
+ set_cookie,
+ csp,
+ x_frame_options,
body: String::from_utf8(bytes.to_vec()).expect("body should be UTF-8"),
}
}
@@ -91,55 +101,359 @@ fn token_request(form: &str) -> Request<Body> {
.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())
+fn callback_request(session_id: &str, cookie: Option<&str>) -> Request<Body> {
+ let mut request = Request::builder().method("GET").uri(format!(
+ "/oauth/callback?code=upstream-code&state={session_id}"
+ ));
+ if let Some(cookie) = cookie {
+ request = request.header(header::COOKIE, cookie);
+ }
+ request.body(Body::empty()).expect("request should build")
+}
+
+/// The `name=value` pair a browser sends back for a `Set-Cookie` header.
+fn cookie_pair(set_cookie: &str) -> String {
+ set_cookie
+ .split(';')
+ .next()
+ .expect("Set-Cookie has a name=value pair")
+ .to_owned()
+}
+
+/// Reads the anti-forgery token out of a rendered consent page.
+fn consent_token(page: &str) -> String {
+ let marker = r#"name="consent_token" value=""#;
+ let start = page.find(marker).expect("page carries a consent token") + marker.len();
+ let length = page[start..].find('"').expect("token value is quoted");
+ page[start..start + length].to_owned()
+}
+
+fn consent_submission(
+ client_id: &str,
+ redirect_uri: &str,
+ token: &str,
+ decision: &str,
+ cookie: Option<&str>,
+ fetch_site: &str,
+) -> Request<Body> {
+ let mut request = Request::builder()
+ .method("POST")
+ .uri("/authorize")
+ .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
+ .header("sec-fetch-site", fetch_site);
+ if let Some(cookie) = cookie {
+ request = request.header(header::COOKIE, cookie);
+ }
+ request
+ .body(Body::from(format!(
+ "response_type=code&client_id={client_id}&redirect_uri={}&state=client-state\
+ &code_challenge={}&code_challenge_method=S256&consent_token={token}\
+ &decision={decision}",
+ urlencoding::encode(redirect_uri),
+ code_challenge_for(VICTIM_CODE_VERIFIER),
+ )))
.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.
+async fn register_client(harness: &Harness, redirect_uri: &str) -> String {
+ let registration = send(harness, register_request(redirect_uri)).await;
+ assert_eq!(registration.status, StatusCode::OK, "{redirect_uri}");
+ registration.json()["client_id"]
+ .as_str()
+ .expect("registration returns a client_id")
+ .to_owned()
+}
+
+/// A client on a host outside the trusted list gets a consent screen, not a
+/// sign-in, and the screen cannot be framed or cached.
#[tokio::test]
-async fn attacker_cannot_have_a_code_delivered_to_their_own_callback() {
+async fn authorize_for_an_unlisted_host_shows_the_consent_screen() {
let harness = Harness::new();
+ let client_id = register_client(&harness, GATEWAY_REDIRECT_URI).await;
- 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 page = send(
+ &harness,
+ authorize_request(&client_id, GATEWAY_REDIRECT_URI, VICTIM_CODE_VERIFIER),
+ )
+ .await;
+
+ assert_eq!(page.status, StatusCode::OK);
+ assert_eq!(page.location, None);
+ assert!(page.body.contains("gateway.example"));
+ assert_eq!(page.x_frame_options.as_deref(), Some("DENY"));
+ assert!(
+ page.csp
+ .as_deref()
+ .is_some_and(|csp| csp.contains("frame-ancestors 'none'")),
+ "unexpected CSP: {:?}",
+ page.csp
);
+ let set_cookie = page.set_cookie.expect("authorize sets the binding cookie");
+ assert!(set_cookie.starts_with("__Host-macro_mcp_oauth="));
+ for attribute in ["Secure", "HttpOnly", "SameSite=Lax", "Path=/"] {
+ assert!(
+ set_cookie.contains(attribute),
+ "{set_cookie} lacks {attribute}"
+ );
+ }
+ assert!(!harness.inflight.has_pending());
+}
- 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"]
+/// The client name is self-reported, so markup in it must render as text.
+#[tokio::test]
+async fn consent_screen_escapes_the_client_name() {
+ let harness = Harness::new();
+ let registration = send(
+ &harness,
+ Request::builder()
+ .method("POST")
+ .uri("/register")
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(Body::from(format!(
+ r#"{{"client_name":"<script>alert(1)</script>","redirect_uris":["{GATEWAY_REDIRECT_URI}"]}}"#
+ )))
+ .expect("request should build"),
+ )
+ .await;
+ let client_id = registration.json()["client_id"]
.as_str()
.expect("registration returns a client_id")
.to_owned();
- let crafted = send(
+ let page = send(
&harness,
- authorize_request(&client_id, ATTACKER_REDIRECT_URI, ATTACKER_CODE_VERIFIER),
+ authorize_request(&client_id, GATEWAY_REDIRECT_URI, VICTIM_CODE_VERIFIER),
)
.await;
- assert_eq!(crafted.status, StatusCode::BAD_REQUEST);
- assert_eq!(
- crafted.location, None,
- "a rejected authorize request must not redirect anywhere"
+ assert!(!page.body.contains("<script>"));
+ assert!(page.body.contains("&#60;script&#62;") || page.body.contains("&lt;script&gt;"));
+}
+
+/// Approving on the consent screen, in the browser that was shown it, signs
+/// the user in and delivers the code to the approved host.
+#[tokio::test]
+async fn approved_client_on_an_unlisted_host_completes_the_flow() {
+ let harness = Harness::new();
+ let client_id = register_client(&harness, GATEWAY_REDIRECT_URI).await;
+
+ let page = send(
+ &harness,
+ authorize_request(&client_id, GATEWAY_REDIRECT_URI, VICTIM_CODE_VERIFIER),
+ )
+ .await;
+ let cookie = cookie_pair(&page.set_cookie.expect("authorize sets the binding cookie"));
+ let token = consent_token(&page.body);
+
+ let approved = send(
+ &harness,
+ consent_submission(
+ &client_id,
+ GATEWAY_REDIRECT_URI,
+ &token,
+ "approve",
+ Some(&cookie),
+ "same-origin",
+ ),
+ )
+ .await;
+ assert_eq!(approved.status, StatusCode::SEE_OTHER);
+ assert_eq!(approved.referrer_policy.as_deref(), Some("no-referrer"));
+ assert!(
+ approved
+ .location
+ .as_deref()
+ .is_some_and(|location| location.starts_with("https://upstream.example/authorize")),
+ "unexpected redirect: {:?}",
+ approved.location
);
+
+ let session_id = harness.inflight.only_pending_session_id();
+ let callback = send(&harness, callback_request(&session_id, Some(&cookie))).await;
+ assert_eq!(callback.status, StatusCode::TEMPORARY_REDIRECT);
+ let client_redirect = callback.location.expect("callback redirects to the client");
assert!(
- !harness.inflight.has_pending(),
- "a rejected authorize request must not create handshake state"
+ client_redirect.starts_with(&format!("{GATEWAY_REDIRECT_URI}?code=")),
+ "unexpected redirect: {client_redirect}"
);
}
+/// A sign-in method named on the authorize request survives the consent form.
+#[tokio::test]
+async fn approving_keeps_the_requested_sign_in_method() {
+ let harness = Harness::new();
+ let client_id = register_client(&harness, GATEWAY_REDIRECT_URI).await;
+
+ let mut authorize = authorize_request(&client_id, GATEWAY_REDIRECT_URI, VICTIM_CODE_VERIFIER);
+ *authorize.uri_mut() = format!("{}&sign_in=login", authorize.uri())
+ .parse()
+ .expect("uri should parse");
+ let page = send(&harness, authorize).await;
+ assert!(
+ page.body
+ .contains(r#"<input type="hidden" name="sign_in" value="login" />"#),
+ "{}",
+ page.body
+ );
+ let cookie = cookie_pair(&page.set_cookie.expect("authorize sets the binding cookie"));
+
+ let (parts, body) = consent_submission(
+ &client_id,
+ GATEWAY_REDIRECT_URI,
+ &consent_token(&page.body),
+ "approve",
+ Some(&cookie),
+ "same-origin",
+ )
+ .into_parts();
+ let form = axum::body::to_bytes(body, 64 * 1024)
+ .await
+ .expect("form should read");
+ let form = format!("{}&sign_in=login", String::from_utf8_lossy(&form));
+ let approved = send(&harness, Request::from_parts(parts, Body::from(form))).await;
+
+ assert_eq!(approved.status, StatusCode::SEE_OTHER);
+ assert!(
+ approved
+ .location
+ .as_deref()
+ .is_some_and(|location| location.starts_with("https://upstream.example/login")),
+ "unexpected redirect: {:?}",
+ approved.location
+ );
+}
+
+/// No other page can approve on the user's behalf: the post must carry the
+/// binding cookie, the token derived from it, and come from this origin.
+#[tokio::test]
+async fn a_forged_consent_submission_is_refused() {
+ let harness = Harness::new();
+ let client_id = register_client(&harness, GATEWAY_REDIRECT_URI).await;
+ let page = send(
+ &harness,
+ authorize_request(&client_id, GATEWAY_REDIRECT_URI, VICTIM_CODE_VERIFIER),
+ )
+ .await;
+ let cookie = cookie_pair(&page.set_cookie.expect("authorize sets the binding cookie"));
+ let token = consent_token(&page.body);
+ let other_browser = format!(
+ "__Host-macro_mcp_oauth={}",
+ BrowserBinding::generate().as_str()
+ );
+
+ let forgeries = [
+ ("no cookie", None, token.as_str(), "same-origin"),
+ (
+ "another browser's cookie",
+ Some(other_browser.as_str()),
+ token.as_str(),
+ "same-origin",
+ ),
+ (
+ "wrong token",
+ Some(cookie.as_str()),
+ "forged-token",
+ "same-origin",
+ ),
+ (
+ "cross-site post",
+ Some(cookie.as_str()),
+ token.as_str(),
+ "cross-site",
+ ),
+ ];
+ for (case, cookie, token, fetch_site) in forgeries {
+ let response = send(
+ &harness,
+ consent_submission(
+ &client_id,
+ GATEWAY_REDIRECT_URI,
+ token,
+ "approve",
+ cookie,
+ fetch_site,
+ ),
+ )
+ .await;
+
+ assert_eq!(response.status, StatusCode::FORBIDDEN, "{case}");
+ assert_eq!(response.location, None, "{case}");
+ assert!(!harness.inflight.has_pending(), "{case}");
+ }
+}
+
+/// Cancelling sends the browser nowhere, so the broker cannot be used to
+/// redirect to a host the user just refused.
+#[tokio::test]
+async fn declining_consent_redirects_nowhere() {
+ let harness = Harness::new();
+ let client_id = register_client(&harness, GATEWAY_REDIRECT_URI).await;
+ let page = send(
+ &harness,
+ authorize_request(&client_id, GATEWAY_REDIRECT_URI, VICTIM_CODE_VERIFIER),
+ )
+ .await;
+ let cookie = cookie_pair(&page.set_cookie.expect("authorize sets the binding cookie"));
+
+ let declined = send(
+ &harness,
+ consent_submission(
+ &client_id,
+ GATEWAY_REDIRECT_URI,
+ &consent_token(&page.body),
+ "deny",
+ Some(&cookie),
+ "same-origin",
+ ),
+ )
+ .await;
+
+ assert_eq!(declined.status, StatusCode::OK);
+ assert_eq!(declined.location, None);
+ assert!(!harness.inflight.has_pending());
+}
+
+/// An attacker who approves their own client cannot hand the resulting
+/// sign-in to a victim: the callback lands in the victim's browser, without
+/// the attacker's binding cookie, and no code is issued.
+#[tokio::test]
+async fn a_sign_in_started_in_another_browser_issues_no_code() {
+ let harness = Harness::new();
+ let client_id = register_client(&harness, ATTACKER_REDIRECT_URI).await;
+ let page = send(
+ &harness,
+ authorize_request(&client_id, ATTACKER_REDIRECT_URI, VICTIM_CODE_VERIFIER),
+ )
+ .await;
+ let attacker_cookie = cookie_pair(&page.set_cookie.expect("authorize sets the binding cookie"));
+ let approved = send(
+ &harness,
+ consent_submission(
+ &client_id,
+ ATTACKER_REDIRECT_URI,
+ &consent_token(&page.body),
+ "approve",
+ Some(&attacker_cookie),
+ "same-origin",
+ ),
+ )
+ .await;
+ assert_eq!(approved.status, StatusCode::SEE_OTHER);
+ let session_id = harness.inflight.only_pending_session_id();
+ let victim_cookie = format!(
+ "__Host-macro_mcp_oauth={}",
+ BrowserBinding::generate().as_str()
+ );
+
+ for cookie in [None, Some(victim_cookie.as_str())] {
+ let callback = send(&harness, callback_request(&session_id, cookie)).await;
+
+ assert_eq!(callback.status, StatusCode::BAD_REQUEST);
+ assert_eq!(callback.location, None);
+ }
+ assert!(!harness.inflight.holds_any_issued_code());
+}
+
#[tokio::test]
async fn authorize_explains_how_to_reconnect_an_unregistered_client() {
let harness = Harness::new();
@@ -240,6 +554,10 @@ async fn authorize_offers_chatgpt_a_sign_in_choice() {
};
let login = send(&harness, chosen("login")).await;
assert_eq!(login.status, StatusCode::TEMPORARY_REDIRECT);
+ assert!(
+ login.set_cookie.is_some(),
+ "the flow needs its binding cookie"
+ );
let location = login.location.expect("redirect has a location");
assert!(
location.starts_with("https://upstream.example/login"),
@@ -331,14 +649,22 @@ async fn registered_client_completes_the_whole_flow() {
)
.await;
assert_eq!(authorize.status, StatusCode::TEMPORARY_REDIRECT);
- let upstream = authorize.location.expect("authorize redirects upstream");
+ let upstream = authorize
+ .location
+ .clone()
+ .expect("authorize redirects upstream");
assert!(
upstream.starts_with("https://upstream.example/authorize"),
"unexpected upstream redirect: {upstream}"
);
+ let cookie = cookie_pair(
+ &authorize
+ .set_cookie
+ .expect("authorize sets the binding cookie"),
+ );
let session_id = harness.inflight.only_pending_session_id();
- let callback = send(&harness, callback_request(&session_id)).await;
+ let callback = send(&harness, callback_request(&session_id, Some(&cookie))).await;
assert_eq!(callback.status, StatusCode::TEMPORARY_REDIRECT);
let client_redirect = callback.location.expect("callback redirects to the client");
assert!(
diff --git a/services/mcp_auth_proxy/src/lib.rs b/services/mcp_auth_proxy/src/lib.rs
index a63721b982..0f429c8dfe 100644
--- a/services/mcp_auth_proxy/src/lib.rs
+++ b/services/mcp_auth_proxy/src/lib.rs
@@ -6,8 +6,9 @@
//!
//! High-level flow:
//! 1. expose protected-resource and authorization-server discovery metadata
-//! 2. accept dynamic registration for public loopback clients
-//! 3. redirect the user to the upstream provider from `/authorize`
+//! 2. accept dynamic registration for public clients
+//! 3. from `/authorize`, ask the user to approve a client whose redirect URI the
+//! deployment does not trust, then redirect to the upstream provider
//! 4. exchange the upstream callback code at `/oauth/callback`
//! 5. issue a short-lived broker code for the MCP client loopback callback
//! 6. exchange that code at `/token` after redirect URI and PKCE validation
diff --git a/services/mcp_auth_proxy/src/outbound/postgres.rs b/services/mcp_auth_proxy/src/outbound/postgres.rs
index dbfcb47670..bbda73f548 100644
--- a/services/mcp_auth_proxy/src/outbound/postgres.rs
+++ b/services/mcp_auth_proxy/src/outbound/postgres.rs
@@ -321,14 +321,16 @@ impl InflightAuthStore for PostgresAuthStore {
sqlx::query!(
r#"
INSERT INTO mcp_oauth_pending_authorizations
- (session_id, client_id, code_challenge, client_state, client_redirect_uri, expires_at)
- VALUES ($1, $2, $3, $4, $5, $6)
+ (session_id, client_id, code_challenge, client_state, client_redirect_uri,
+ browser_binding_digest, expires_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
"#,
session_id,
pending.client_id,
pending.code_challenge,
pending.client_state,
pending.client_redirect_uri,
+ pending.browser_binding_digest,
expires_at(PENDING_AUTH_TTL)?,
)
.execute(&self.pool)
@@ -344,7 +346,8 @@ impl InflightAuthStore for PostgresAuthStore {
r#"
DELETE FROM mcp_oauth_pending_authorizations
WHERE session_id = $1
- RETURNING client_id, code_challenge, client_state, client_redirect_uri, expires_at
+ RETURNING client_id, code_challenge, client_state, client_redirect_uri,
+ browser_binding_digest, expires_at
"#,
session_id,
)
@@ -358,6 +361,7 @@ impl InflightAuthStore for PostgresAuthStore {
code_challenge: row.code_challenge,
client_state: row.client_state,
client_redirect_uri: row.client_redirect_uri,
+ browser_binding_digest: row.browser_binding_digest,
}))
}
diff --git a/services/mcp_auth_proxy/src/outbound/postgres/test.rs b/services/mcp_auth_proxy/src/outbound/postgres/test.rs
index fb59156a76..cc03f176e2 100644
--- a/services/mcp_auth_proxy/src/outbound/postgres/test.rs
+++ b/services/mcp_auth_proxy/src/outbound/postgres/test.rs
@@ -174,6 +174,7 @@ async fn a_pending_authorization_is_taken_once(pool: PgPool) {
code_challenge: "challenge".to_owned(),
client_state: "state".to_owned(),
client_redirect_uri: "http://127.0.0.1:51000/oauth/callback".to_owned(),
+ browser_binding_digest: Some("binding-digest".to_owned()),
},
)
.await
@@ -185,6 +186,10 @@ async fn a_pending_authorization_is_taken_once(pool: PgPool) {
.expect("take")
.expect("pending");
assert_eq!(pending.client_state, "state");
+ assert_eq!(
+ pending.browser_binding_digest.as_deref(),
+ Some("binding-digest")
+ );
assert!(store.take_pending("session").await.expect("take").is_none());
}
diff --git a/services/mcp_auth_proxy/src/outbound/redis.rs b/services/mcp_auth_proxy/src/outbound/redis.rs
index 40beaf7dfd..6b4cb97f8e 100644
--- a/services/mcp_auth_proxy/src/outbound/redis.rs
+++ b/services/mcp_auth_proxy/src/outbound/redis.rs
@@ -383,6 +383,8 @@ struct StoredPendingAuthorization {
code_challenge: String,
client_state: String,
client_redirect_uri: String,
+ #[serde(default)]
+ browser_binding_digest: Option<String>,
}
impl From<PendingAuthorization> for StoredPendingAuthorization {
@@ -392,6 +394,7 @@ impl From<PendingAuthorization> for StoredPendingAuthorization {
code_challenge: value.code_challenge,
client_state: value.client_state,
client_redirect_uri: value.client_redirect_uri,
+ browser_binding_digest: value.browser_binding_digest,
}
}
}
@@ -403,6 +406,7 @@ impl From<StoredPendingAuthorization> for PendingAuthorization {
code_challenge: value.code_challenge,
client_state: value.client_state,
client_redirect_uri: value.client_redirect_uri,
+ browser_binding_digest: value.browser_binding_digest,
}
}
}
diff --git a/services/mcp_auth_proxy/src/outbound/redis/test.rs b/services/mcp_auth_proxy/src/outbound/redis/test.rs
index 0bfb95bcdd..d9927e05a7 100644
--- a/services/mcp_auth_proxy/src/outbound/redis/test.rs
+++ b/services/mcp_auth_proxy/src/outbound/redis/test.rs
@@ -210,6 +210,7 @@ async fn handshake_state_round_trips_with_its_client_id() {
code_challenge: "challenge".to_owned(),
client_state: "state".to_owned(),
client_redirect_uri: "https://claude.ai/api/mcp/auth_callback".to_owned(),
+ browser_binding_digest: Some("binding-digest".to_owned()),
},
)
.await
@@ -221,6 +222,10 @@ async fn handshake_state_round_trips_with_its_client_id() {
.expect("take should succeed")
.expect("the pending flow should be readable");
assert_eq!(pending.client_id, "client-abc");
+ assert_eq!(
+ pending.browser_binding_digest.as_deref(),
+ Some("binding-digest")
+ );
assert!(
inflight
.take_pending(&session_id)
diff --git a/services/mcp_auth_proxy/src/test_support.rs b/services/mcp_auth_proxy/src/test_support.rs
index 13a3d48f5f..3b52cb207f 100644
--- a/services/mcp_auth_proxy/src/test_support.rs
+++ b/services/mcp_auth_proxy/src/test_support.rs
@@ -11,10 +11,11 @@ use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use sha2::{Digest, Sha256};
use crate::domain::{
+ browser_binding::BrowserBinding,
models::{
AccessToken, AuthorizeRequest, CallbackRequest, ClientRegistrationRequest,
IssuedAuthorizationCode, PendingAuthorization, RefreshToken, RefreshTokenBinding,
- RegisteredClient, SignInMethod, UpstreamTokens,
+ RegisteredClient, SignInMethod, UpstreamTokens, UserConsent,
},
ports::{
ClientRegistrationStore, GrantRevokedFuture, OAuthProvider, RefreshTokenBindingFuture,
@@ -41,6 +42,9 @@ pub const LOOPBACK_REDIRECT_URI: &str = "http://127.0.0.1:51000/oauth/callback";
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";
+/// An `https` callback on a host outside the trusted list, such as a
+/// self-hosted MCP gateway's.
+pub const GATEWAY_REDIRECT_URI: &str = "https://gateway.example/oauth/callback";
/// 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
@@ -78,6 +82,11 @@ impl FakeInflightAuth {
self.issued.lock().expect("issued lock").contains_key(code)
}
+ /// Returns whether any broker code has been issued.
+ pub fn holds_any_issued_code(&self) -> bool {
+ !self.issued.lock().expect("issued lock").is_empty()
+ }
+
/// Returns the recorded upstream expiry of the only issued code, panicking
/// unless there is exactly one.
pub fn only_issued_expiry(&self) -> SystemTime {
@@ -327,6 +336,8 @@ pub struct Harness {
pub registry: Arc<FakeClientRegistry>,
/// The upstream provider the service was built with.
pub provider: Arc<FakeOAuthProvider>,
+ /// The secret cookie of the browser the tests drive flows from.
+ pub browser: BrowserBinding,
}
impl Harness {
@@ -354,6 +365,7 @@ impl Harness {
inflight,
registry,
provider,
+ browser: BrowserBinding::generate(),
}
}
@@ -397,23 +409,26 @@ impl Harness {
code_verifier: &str,
) -> String {
self.service
- .start_authorization(self.authorize_request(
- client_id,
- redirect_uri,
- &code_challenge_for(code_verifier),
- ))
+ .start_authorization(
+ self.authorize_request(client_id, redirect_uri, &code_challenge_for(code_verifier)),
+ self.browser.clone(),
+ UserConsent::NotAsked,
+ )
.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,
- })
+ .complete_callback(
+ CallbackRequest {
+ code: Some("upstream-code".to_owned()),
+ state: Some(session_id),
+ error: None,
+ error_description: None,
+ },
+ Some(self.browser.clone()),
+ )
.await
.expect("callback should succeed");
diff --git a/services/mcp_auth_proxy/templates/consent.html b/services/mcp_auth_proxy/templates/consent.html
new file mode 100644
index 0000000000..723fe90691
--- /dev/null
+++ b/services/mcp_auth_proxy/templates/consent.html
@@ -0,0 +1,124 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="robots" content="noindex" />
+ <title>Connect an app to Macro</title>
+ <style>
+ body {
+ margin: 0;
+ min-height: 100vh;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: #f5f5f4;
+ color: #1c1917;
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
+ }
+ main {
+ box-sizing: border-box;
+ width: 100%;
+ max-width: 440px;
+ margin: 24px 16px;
+ padding: 32px 28px;
+ background: #ffffff;
+ border: 1px solid #e7e5e4;
+ border-radius: 8px;
+ }
+ h1 {
+ margin: 0 0 16px;
+ font-size: 20px;
+ font-weight: 600;
+ line-height: 1.3;
+ overflow-wrap: anywhere;
+ }
+ p {
+ margin: 0 0 16px;
+ font-size: 14px;
+ line-height: 1.5;
+ }
+ .destination {
+ margin: 0 0 16px;
+ padding: 12px 14px;
+ background: #fafaf9;
+ border: 1px solid #e7e5e4;
+ border-radius: 6px;
+ font-family: ui-monospace, "SF Mono", Menlo, monospace;
+ font-size: 15px;
+ font-weight: 600;
+ overflow-wrap: anywhere;
+ }
+ .warning {
+ padding: 12px 14px;
+ background: #fffbeb;
+ border: 1px solid #fde68a;
+ border-radius: 6px;
+ color: #78350f;
+ }
+ .actions {
+ display: flex;
+ gap: 12px;
+ margin-top: 24px;
+ }
+ button {
+ flex: 1;
+ padding: 10px 16px;
+ border-radius: 6px;
+ font: inherit;
+ font-size: 14px;
+ font-weight: 600;
+ cursor: pointer;
+ }
+ .deny {
+ background: #ffffff;
+ border: 1px solid #d6d3d1;
+ color: #1c1917;
+ }
+ .approve {
+ background: #1c1917;
+ border: 1px solid #1c1917;
+ color: #ffffff;
+ }
+ </style>
+ </head>
+ <body>
+ <main>
+ <h1>Allow “{{ client_name }}” to access your Macro account?</h1>
+ <p>
+ If you allow it, Macro will sign you in and send access to your account
+ to:
+ </p>
+ <p class="destination">{{ redirect_host }}</p>
+ <p>
+ That app will be able to read and change your Macro documents,
+ messages and other data, as you, until you disconnect it.
+ </p>
+ <p class="warning">
+ Only allow this if you just started connecting this app to Macro
+ yourself and you recognize the address above. The name
+ “{{ client_name }}” is provided by the app and is not verified by
+ Macro.
+ </p>
+ <form method="post" action="authorize">
+ <input type="hidden" name="response_type" value="{{ request.response_type }}" />
+ <input type="hidden" name="client_id" value="{{ request.client_id }}" />
+ <input type="hidden" name="redirect_uri" value="{{ request.redirect_uri }}" />
+ <input type="hidden" name="state" value="{{ request.state }}" />
+ <input type="hidden" name="code_challenge" value="{{ request.code_challenge }}" />
+ <input type="hidden" name="code_challenge_method" value="{{ request.code_challenge_method }}" />
+ {% if let Some(scope) = request.scope %}
+ <input type="hidden" name="scope" value="{{ scope }}" />
+ {% endif %}
+ {% if let Some(sign_in) = request.sign_in %}
+ <input type="hidden" name="sign_in" value="{{ sign_in }}" />
+ {% endif %}
+ <input type="hidden" name="consent_token" value="{{ consent_token }}" />
+ <div class="actions">
+ <button class="deny" type="submit" name="decision" value="deny">Cancel</button>
+ <button class="approve" type="submit" name="decision" value="approve">Allow</button>
+ </div>
+ </form>
+ </main>
+ </body>
+</html>
diff --git a/services/mcp_auth_proxy/templates/consent_declined.html b/services/mcp_auth_proxy/templates/consent_declined.html
new file mode 100644
index 0000000000..73c67cffa0
--- /dev/null
+++ b/services/mcp_auth_proxy/templates/consent_declined.html
@@ -0,0 +1,47 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="robots" content="noindex" />
+ <title>Connection cancelled</title>
+ <style>
+ body {
+ margin: 0;
+ min-height: 100vh;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: #f5f5f4;
+ color: #1c1917;
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
+ }
+ main {
+ box-sizing: border-box;
+ width: 100%;
+ max-width: 440px;
+ margin: 24px 16px;
+ padding: 32px 28px;
+ background: #ffffff;
+ border: 1px solid #e7e5e4;
+ border-radius: 8px;
+ }
+ h1 {
+ margin: 0 0 16px;
+ font-size: 20px;
+ font-weight: 600;
+ }
+ p {
+ margin: 0;
+ font-size: 14px;
+ line-height: 1.5;
+ }
+ </style>
+ </head>
+ <body>
+ <main>
+ <h1>Connection cancelled</h1>
+ <p>The app was not given access to your Macro account. You can close this window.</p>
+ </main>
+ </body>
+</html>