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): sign in with email and finish from another machine (#9874)

Eric Hayesb179462eadef
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 995556d108..8c54ca372e 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -10391,16 +10391,37 @@
"crates/maybe_send"
],
"mcp_auth_proxy": [
+ "crates/agent",
"crates/ai_toolset",
+ "crates/ai_usage",
+ "crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/cursor_api_key",
+ "crates/document_sub_type",
"crates/fusionauth",
"crates/genai_telemetry",
+ "crates/harness_id",
+ "crates/harness_token",
"crates/macro_auth",
+ "crates/macro_authorization",
"crates/macro_env",
"crates/macro_env_var",
+ "crates/macro_tower_layers",
"crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/model",
+ "crates/model-entity",
+ "crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_owner",
+ "crates/model_user",
+ "crates/models_bulk_upload",
+ "crates/models_pagination",
+ "crates/models_permissions",
+ "crates/non_empty",
+ "crates/prompt",
"crates/remote_env_var",
"crates/upstream_error",
"crates/workspace-hack",
diff --git a/.sqlx/query-5f1d0de54d4e8909f0e6e2e1afb1d7b7f7710282cf638c92eab21049ca1cb26e.json b/.sqlx/query-8446e40d8a644fb99e81f058c6338a92c151a4842c5f538a661c85534dcc261c.json
similarity index 68%
rename from .sqlx/query-5f1d0de54d4e8909f0e6e2e1afb1d7b7f7710282cf638c92eab21049ca1cb26e.json
rename to .sqlx/query-8446e40d8a644fb99e81f058c6338a92c151a4842c5f538a661c85534dcc261c.json
index 45099f6ab4..68c08408f2 100644
--- a/.sqlx/query-5f1d0de54d4e8909f0e6e2e1afb1d7b7f7710282cf638c92eab21049ca1cb26e.json
+++ b/.sqlx/query-8446e40d8a644fb99e81f058c6338a92c151a4842c5f538a661c85534dcc261c.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,\n browser_binding_digest, expires_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7)\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, deliver_manually, expires_at)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8)\n ",
"describe": {
"columns": [],
"parameters": {
@@ -11,10 +11,11 @@
"Text",
"Text",
"Text",
+ "Bool",
"Timestamptz"
]
},
"nullable": []
},
- "hash": "5f1d0de54d4e8909f0e6e2e1afb1d7b7f7710282cf638c92eab21049ca1cb26e"
+ "hash": "8446e40d8a644fb99e81f058c6338a92c151a4842c5f538a661c85534dcc261c"
}
diff --git a/.sqlx/query-866b5f44f7966b02277f3ab9978ab3f0e61dc7111aa3dad0aca3e98f4b088042.json b/.sqlx/query-866b5f44f7966b02277f3ab9978ab3f0e61dc7111aa3dad0aca3e98f4b088042.json
new file mode 100644
index 0000000000..36c9704d21
--- /dev/null
+++ b/.sqlx/query-866b5f44f7966b02277f3ab9978ab3f0e61dc7111aa3dad0aca3e98f4b088042.json
@@ -0,0 +1,52 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT client_id, code_challenge, client_state, client_redirect_uri,\n browser_binding_digest, deliver_manually\n FROM mcp_oauth_pending_authorizations\n WHERE session_id = $1 AND expires_at > now()\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "client_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "code_challenge",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "client_state",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "client_redirect_uri",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "browser_binding_digest",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "deliver_manually",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true,
+ false
+ ]
+ },
+ "hash": "866b5f44f7966b02277f3ab9978ab3f0e61dc7111aa3dad0aca3e98f4b088042"
+}
diff --git a/.sqlx/query-6c40270a0bb3310a7931300af4ddb135fb32ab143952dfae06da1f3871a3c9a2.json b/.sqlx/query-8b75c6f2bd5f18d35d7c618cf8fd6580936f64d75b6c837a78221e2ee4d3680d.json
similarity index 79%
rename from .sqlx/query-6c40270a0bb3310a7931300af4ddb135fb32ab143952dfae06da1f3871a3c9a2.json
rename to .sqlx/query-8b75c6f2bd5f18d35d7c618cf8fd6580936f64d75b6c837a78221e2ee4d3680d.json
index d93deaface..ccae012203 100644
--- a/.sqlx/query-6c40270a0bb3310a7931300af4ddb135fb32ab143952dfae06da1f3871a3c9a2.json
+++ b/.sqlx/query-8b75c6f2bd5f18d35d7c618cf8fd6580936f64d75b6c837a78221e2ee4d3680d.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,\n browser_binding_digest, 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, deliver_manually, expires_at\n ",
"describe": {
"columns": [
{
@@ -30,6 +30,11 @@
},
{
"ordinal": 5,
+ "name": "deliver_manually",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 6,
"name": "expires_at",
"type_info": "Timestamptz"
}
@@ -45,8 +50,9 @@
false,
false,
true,
+ false,
false
]
},
- "hash": "6c40270a0bb3310a7931300af4ddb135fb32ab143952dfae06da1f3871a3c9a2"
+ "hash": "8b75c6f2bd5f18d35d7c618cf8fd6580936f64d75b6c837a78221e2ee4d3680d"
}
diff --git a/Cargo.lock b/Cargo.lock
index cc11ad6015..cae6b045e8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -12879,9 +12879,12 @@ dependencies = [
"fusionauth",
"macro_auth",
"macro_db_migrator",
+ "macro_tower_layers",
"macro_user_id",
+ "model",
"rand 0.9.4",
"redis",
+ "reqwest 0.13.4",
"serde",
"serde_json",
"sha2 0.10.9",
@@ -12897,6 +12900,7 @@ dependencies = [
"url",
"urlencoding",
"uuid",
+ "wiremock",
"workspace-hack",
"zeroize",
]
diff --git a/apps/docs/AI/mcp/overview.mdx b/apps/docs/AI/mcp/overview.mdx
index 6e793e501a..84507146bf 100644
--- a/apps/docs/AI/mcp/overview.mdx
+++ b/apps/docs/AI/mcp/overview.mdx
@@ -10,7 +10,7 @@ Macro's MCP endpoint is:
https://mcp-server.macro.com/mcp
```
-The server is remote; no local process is required. Authentication happens through Macro's OAuth flow when the client connects.
+The server is remote; no local process is required. Authentication happens through Macro's OAuth flow when the client connects. Sign in with Google, a code sent to your email, or a password.
MCP access is available on every Macro plan, including Free.
## Claude Code
@@ -29,6 +29,15 @@ codex mcp add macro --url https://mcp-server.macro.com/mcp
Start Codex CLI, invoke the `macro` MCP server, and complete the OAuth login flow in the browser.
+## Connect from a remote machine
+
+If your client runs on another machine, such as over SSH or in a container, a browser on your computer can't reach the client when sign-in finishes. Sign in like this instead:
+
+1. Start the login on the remote machine. For Claude Code, run `claude mcp login macro --no-browser`. For Codex CLI, run `codex mcp login macro`.
+2. Open the printed link in a browser on your computer.
+3. Select **The app I'm connecting runs on another machine**, then choose how to sign in.
+4. After you sign in, Macro shows a link and a `curl` command. If your client asks for a redirect URL, as Claude Code does, paste the link. Otherwise, run the `curl` command on the remote machine while the client is waiting, as with Codex CLI.
+
## IDE / JSON Configuration
For editors that accept JSON MCP server config, add this under `mcpServers`:
diff --git a/crates/macro_db_client/migrations/20261105180729_mcp_oauth_pending_manual_delivery.sql b/crates/macro_db_client/migrations/20261105180729_mcp_oauth_pending_manual_delivery.sql
new file mode 100644
index 0000000000..97e744affb
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261105180729_mcp_oauth_pending_manual_delivery.sql
@@ -0,0 +1,6 @@
+-- Whether an MCP OAuth authorization shows the user its callback URL to carry to
+-- the client, rather than redirecting to it, because the client's loopback
+-- listener is on another machine than the browser. Defaulted so rows and writers
+-- from the previous build keep redirecting.
+ALTER TABLE mcp_oauth_pending_authorizations
+ ADD COLUMN deliver_manually boolean NOT NULL DEFAULT false;
diff --git a/services/agent_harness_service/src/public_mcp.rs b/services/agent_harness_service/src/public_mcp.rs
index 3853ae2ca5..d52a225695 100644
--- a/services/agent_harness_service/src/public_mcp.rs
+++ b/services/agent_harness_service/src/public_mcp.rs
@@ -19,6 +19,7 @@ use mcp_auth_proxy::{
service::{McpAuthProxyService, McpAuthProxyServiceDeps, McpAuthProxyServiceImpl},
},
outbound::{
+ email_sign_in::AuthServiceEmailCodes,
fusionauth::FusionAuthOAuthProvider,
postgres::PostgresAuthStore,
redis::{RedisClientRegistry, RedisInflightAuth},
@@ -166,6 +167,11 @@ async fn build_auth_proxy(
)> {
let mcp_public_url = public_url.to_string();
let mcp_oauth_redirect_uri = format!("{mcp_public_url}/oauth/callback");
+ let email_codes = AuthServiceEmailCodes::new(
+ &macro_service_urls::AuthServiceUrl::new()?,
+ mcp_oauth_redirect_uri.clone(),
+ )
+ .context("failed to initialize MCP email sign-in")?;
let fusionauth_api_key = LocalOrRemoteSecret::new_from_secret_manager(
config.fusionauth_api_key_secret_key.as_ref().to_owned(),
@@ -243,6 +249,7 @@ async fn build_auth_proxy(
client_registrations: store.clone(),
refresh_token_bindings: store,
oauth_provider: Arc::new(auth_provider),
+ email_codes: Arc::new(email_codes),
});
Ok((auth_proxy, backfill))
}
diff --git a/services/mcp_auth_proxy/AGENTS.md b/services/mcp_auth_proxy/AGENTS.md
index b06ef82e60..81bdf47043 100644
--- a/services/mcp_auth_proxy/AGENTS.md
+++ b/services/mcp_auth_proxy/AGENTS.md
@@ -18,10 +18,12 @@ in front of FusionAuth, which doesn't support DCR itself.
- `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.
+ that started it, and the anti-forgery token the broker's forms carry.
+- `templates/`: the broker's pages (sign-in chooser, consent and its cancellation,
+ email sign-in, manual delivery), which share `broker_page.css`.
- `src/domain/ports.rs`: `ClientRegistrationStore`, `OAuthProvider`,
- `RefreshTokenBindingStore` — the ports the service depends on.
+ `EmailCodeProvider`, `RefreshTokenBindingStore` — the ports the service depends
+ on.
- `src/inbound/axum_router.rs`: HTTP routes; `src/inbound/middleware.rs`: auth.
- `src/outbound/postgres.rs`: the store of record for all broker state
(registrations, refresh token bindings, pending authorizations, issued
@@ -30,15 +32,18 @@ in front of FusionAuth, which doesn't support DCR itself.
- `src/outbound/redis_cutover.rs`: wraps the Postgres store during the move
off Redis: Postgres first, Redis fallback with copy-forward, registrations
and bindings mirrored to Redis, plus the startup backfill.
+- `src/outbound/email_sign_in.rs`: emailed sign-in codes, through the
+ authentication service's public login endpoints.
- `src/outbound/fusionauth.rs`, `src/outbound/redis.rs`: the upstream provider
and the legacy Redis store (all adapters gated behind the `outbound`
feature; `inbound`/`outbound` are each optional).
## Scope
-- Owns: DCR-compliant client registration, authorization-code issuance,
- refresh-token rotation/binding, and RFC 7009 revocation, all proxied in
- front of FusionAuth.
+- Owns: DCR-compliant client registration, the sign-in chooser and email sign-in
+ form, authorization-code issuance (including manual delivery for clients on
+ another machine), refresh-token rotation/binding, and RFC 7009 revocation, all
+ proxied in front of FusionAuth.
- Not here: the MCP tool surface itself → `services/agent_harness_service/src/public_mcp.rs`.
## Recipes
@@ -76,7 +81,13 @@ and other library consumers. Both retain OAuth metadata, CORS, and bearer auth.
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`.
+ field needs a hidden input in `templates/consent.html`. The chooser repeats its
+ query on its own.
+- The manual delivery page puts the callback URL in a shell command. Don't widen
+ `RedirectUriPolicy::allows_manual_delivery` past characters that are inert in
+ single quotes; see README "Signing in from another machine".
+- Pending flows are consumed only by a callback or a redeemed email code. Email
+ steps read them with `find_pending`, so a mistyped code doesn't end the sign-in.
- `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 fac95e0b86..940ebd238b 100644
--- a/services/mcp_auth_proxy/Cargo.toml
+++ b/services/mcp_auth_proxy/Cargo.toml
@@ -22,6 +22,9 @@ outbound = [
"dep:chrono",
"dep:cursor_api_key",
"dep:fusionauth",
+ "dep:macro_tower_layers",
+ "dep:model",
+ "dep:reqwest",
"dep:sqlx",
"dep:upstream_error",
"dep:zeroize",
@@ -39,9 +42,12 @@ chrono = { workspace = true, optional = true }
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_tower_layers = { path = "../../crates/macro_tower_layers", optional = true }
macro_user_id = { path = "../../crates/macro_user_id", optional = true }
+model = { path = "../../crates/model", optional = true }
rand = { workspace = true }
redis = { workspace = true, features = ["aio", "tokio-comp"] }
+reqwest = { workspace = true, optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
strum = { workspace = true }
@@ -64,3 +70,4 @@ async-trait = { workspace = true }
macro_auth = { path = "../../crates/macro_auth", features = ["testing"] }
macro_db_migrator = { path = "../../crates/macro_db_migrator" }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+wiremock = { workspace = true }
diff --git a/services/mcp_auth_proxy/README.md b/services/mcp_auth_proxy/README.md
index 056daaa56e..975b8e91f2 100644
--- a/services/mcp_auth_proxy/README.md
+++ b/services/mcp_auth_proxy/README.md
@@ -30,12 +30,48 @@ client may sign in is decided only by its redirect URI.
## How a user signs in
-`/authorize` sends the browser straight to Google through FusionAuth. Clients on
-`SIGN_IN_CHOICE_HOSTS` (ChatGPT) get a small chooser first: Google, or
-FusionAuth's own login page, where an account with a password can sign in.
-OpenAI's reviewers need that path, because a shared Google account trips
-Google's challenges. The chooser stores nothing; each link is the same
-`/authorize` request with `sign_in` added.
+`/authorize` first shows every client's user a chooser, because the client cannot
+know how that user's account signs in. The chooser stores nothing; its form is
+the same `/authorize` request with `sign_in` added.
+
+- **Google** goes straight to Google through FusionAuth.
+- **Email** is the one-time code the Macro app uses. `/authorize` records the
+ pending flow and redirects to `email-sign-in`, the broker's own form. The form
+ calls the authentication service's public endpoints
+ (`outbound/email_sign_in.rs`), so its address checks, per-address rate limits,
+ and signup policy apply as they do in the app. An address on a single sign-on
+ domain is sent to its provider instead, on the same pending flow. The form is
+ tied to the browser like the consent form, and a mistyped code leaves the flow
+ pending: only a redeemed code consumes it.
+- **Password** goes to FusionAuth's own login page. Accounts created by an emailed
+ code have only a random password, so this is for accounts that set one, such as
+ shared review accounts that cannot pass Google's challenges.
+
+## Signing in from another machine
+
+An MCP client on a server, reached over SSH or in a container, registers a
+loopback redirect URI, but the user's browser is on a different machine, so a
+redirect to it goes nowhere. The chooser therefore offers loopback clients an
+option to finish elsewhere (`delivery=manual`). After sign-in, the broker shows
+the client's callback URL instead of redirecting to it, for the user to either:
+
+- paste into a client that asks for it, as `claude mcp login <name> --no-browser`
+ does, or
+- fetch with `curl` on the client's machine, which reaches the listener of any
+ waiting loopback client, such as `codex mcp login <name>`, with no client support
+ needed.
+
+The authorization code still needs the client's PKCE verifier. Because the code
+leaves the user's own machine, which is what made a loopback redirect trustworthy,
+manual delivery goes through the consent screen first. The URL is shown inside a
+command the user is told to run and registration is open, so a redirect URI with
+anything that could break out of the quotes, or make `curl` and the broker
+disagree about its host, cannot use it (`RedirectUriPolicy::allows_manual_delivery`).
+
+The broker does not implement the device authorization grant (RFC 8628). The MCP
+authorization spec does not include it and no client we checked requests it for
+MCP servers, so advertising a `device_authorization_endpoint` would not change what
+any user sees. Add it if a client starts using it.
## Which redirect URIs are usable
@@ -58,7 +94,8 @@ groups, and a registration can only narrow what it allows:
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.
+ sending the user to sign in. So does a loopback redirect when the user asks to
+ carry the code to another machine.
- **Refused.** Every other scheme, `http` off loopback, and any URI carrying a
fragment or credentials in its authority.
@@ -89,7 +126,8 @@ 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`):
+which `/authorize` sets on every flow past the chooser
+(`domain/browser_binding.rs`). The email sign-in form is held to the same checks:
- **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.
diff --git a/services/mcp_auth_proxy/src/domain/browser_binding.rs b/services/mcp_auth_proxy/src/domain/browser_binding.rs
index 3c66dbe564..b7fccf63ee 100644
--- a/services/mcp_auth_proxy/src/domain/browser_binding.rs
+++ b/services/mcp_auth_proxy/src/domain/browser_binding.rs
@@ -13,17 +13,17 @@ use subtle::ConstantTimeEq;
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:";
+/// Domain separator for the token embedded in the broker's forms.
+const FORM_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.
+/// by someone else cannot be completed in a victim's browser. The broker's forms
+/// carry a token derived from it, so a cross-site form post cannot approve a
+/// client or submit a sign-in on the user's behalf.
#[derive(Clone, Eq, PartialEq)]
pub struct BrowserBinding(String);
@@ -57,18 +57,14 @@ impl BrowserBinding {
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)
+ /// The anti-forgery token the broker's forms carry.
+ pub fn form_token(&self) -> String {
+ self.derive(FORM_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()
+ /// Returns whether `token` is this secret's form token, in constant time.
+ pub fn accepts_form_token(&self, token: &str) -> bool {
+ self.form_token().as_bytes().ct_eq(token.as_bytes()).into()
}
fn derive(&self, prefix: &[u8]) -> String {
diff --git a/services/mcp_auth_proxy/src/domain/browser_binding/test.rs b/services/mcp_auth_proxy/src/domain/browser_binding/test.rs
index 71a562e07f..69a46b3074 100644
--- a/services/mcp_auth_proxy/src/domain/browser_binding/test.rs
+++ b/services/mcp_auth_proxy/src/domain/browser_binding/test.rs
@@ -35,15 +35,15 @@ 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(""));
+ assert!(binding.accepts_form_token(&binding.form_token()));
+ assert!(!other.accepts_form_token(&binding.form_token()));
+ assert!(!binding.accepts_form_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()));
+ assert!(!binding.accepts_form_token(&binding.digest()));
+ assert!(!binding.matches_digest(&binding.form_token()));
}
diff --git a/services/mcp_auth_proxy/src/domain/models.rs b/services/mcp_auth_proxy/src/domain/models.rs
index 58152d5d48..f158725392 100644
--- a/services/mcp_auth_proxy/src/domain/models.rs
+++ b/services/mcp_auth_proxy/src/domain/models.rs
@@ -166,6 +166,30 @@ pub struct PendingAuthorization {
/// by a build that predates the binding, which could only have used a
/// trusted redirect URI.
pub browser_binding_digest: Option<String>,
+ /// How the authorization code reaches the client once the user signs in.
+ pub delivery: CodeDelivery,
+}
+
+/// How an authorization code reaches the client.
+#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, strum::Display)]
+#[serde(rename_all = "lowercase")]
+#[strum(serialize_all = "lowercase")]
+pub enum CodeDelivery {
+ /// Redirect the browser to the client's redirect URI.
+ #[default]
+ Redirect,
+ /// Show the user the callback URL to carry over themselves, because the
+ /// client's loopback listener is on another machine than the browser.
+ Manual,
+}
+
+/// The client callback URL a finished flow produced, and how it gets there.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub struct ClientDelivery {
+ /// The client's redirect URI with the code, or error, appended.
+ pub url: String,
+ /// How the URL reaches the client.
+ pub method: CodeDelivery,
}
/// Whether the user has approved the client on the consent screen.
@@ -186,6 +210,8 @@ pub struct ConsentPrompt {
/// The host the authorization code will be sent to: the identity the user
/// is actually approving.
pub redirect_host: String,
+ /// How the code will leave the browser.
+ pub delivery: CodeDelivery,
}
/// How an authorize request proceeds.
@@ -193,6 +219,11 @@ pub struct ConsentPrompt {
pub enum AuthorizationStart {
/// Send the browser to the upstream sign-in at this URL.
SignIn(String),
+ /// Send the browser to the broker's email sign-in for this session.
+ EmailSignIn {
+ /// The broker session the sign-in completes.
+ session_id: String,
+ },
/// Ask the user to approve the client before signing in.
ConsentRequired(ConsentPrompt),
}
@@ -221,13 +252,52 @@ pub struct IssuedAuthorizationCode {
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum SignInMethod {
- /// Straight to Google, the default for every client.
+ /// Straight to Google.
#[default]
Google,
+ /// A one-time code sent by email, the way the Macro app signs users in.
+ Email,
/// FusionAuth's login page: password and every other provider.
Login,
}
+/// The upstream page a browser is sent to.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum UpstreamLogin<'a> {
+ /// Straight to Google.
+ Google,
+ /// FusionAuth's login page.
+ LoginPage,
+ /// The single sign-on provider an email address's domain requires.
+ Sso {
+ /// The upstream identity provider.
+ idp_id: &'a str,
+ /// The address the user entered, so the provider need not ask again.
+ email: &'a str,
+ },
+}
+
+/// The upstream's answer to a request to email a sign-in code.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub enum EmailCodeRequest {
+ /// The code was emailed.
+ Sent,
+ /// The address's domain signs in through this identity provider instead.
+ SsoRequired {
+ /// The upstream identity provider.
+ idp_id: String,
+ },
+}
+
+/// What the email sign-in form does next.
+#[derive(Clone, Debug, Eq, PartialEq)]
+pub enum EmailSignInStep {
+ /// Ask the user for the code that was emailed.
+ EnterCode,
+ /// Send the browser to the single sign-on provider at this URL.
+ Sso(String),
+}
+
/// OAuth authorize request from the MCP client.
#[derive(Clone, Deserialize)]
pub struct AuthorizeRequest {
@@ -246,6 +316,10 @@ pub struct AuthorizeRequest {
/// The sign-in the user picked on the chooser, when it was shown.
#[serde(default)]
pub sign_in: Option<SignInMethod>,
+ /// How the user asked for the code to reach the client, when they picked
+ /// on the chooser.
+ #[serde(default)]
+ pub delivery: Option<CodeDelivery>,
/// Optional requested scopes.
#[serde(default)]
pub scope: Option<String>,
diff --git a/services/mcp_auth_proxy/src/domain/ports.rs b/services/mcp_auth_proxy/src/domain/ports.rs
index 3d45e22fe9..834f8ca388 100644
--- a/services/mcp_auth_proxy/src/domain/ports.rs
+++ b/services/mcp_auth_proxy/src/domain/ports.rs
@@ -3,7 +3,8 @@
use std::{future::Future, pin::Pin, time::Duration};
use super::models::{
- RefreshToken, RefreshTokenBinding, RegisteredClient, SignInMethod, UpstreamTokens,
+ EmailCodeRequest, RefreshToken, RefreshTokenBinding, RegisteredClient, UpstreamLogin,
+ UpstreamTokens,
};
/// Boxed future returning a token grant from the upstream provider.
@@ -100,8 +101,11 @@ pub trait RefreshTokenBindingStore: Send + Sync {
/// Upstream OAuth provider used by the broker.
pub trait OAuthProvider: Send + Sync {
/// Builds the upstream authorize URL for a broker session.
- fn construct_authorize_url(&self, state: &str, sign_in: SignInMethod)
- -> anyhow::Result<String>;
+ fn construct_authorize_url(
+ &self,
+ state: &str,
+ login: UpstreamLogin<'_>,
+ ) -> anyhow::Result<String>;
/// Exchanges an upstream authorization code for tokens.
fn exchange_authorization_code<'a>(&'a self, code: &'a str) -> UpstreamTokensFuture<'a>;
@@ -119,3 +123,43 @@ pub trait OAuthProvider: Send + Sync {
refresh_token: &'a RefreshToken,
) -> UpstreamRevocationFuture<'a>;
}
+
+/// Boxed future returning the upstream's answer to an emailed code request.
+pub type EmailCodeRequestFuture<'a> =
+ Pin<Box<dyn Future<Output = Result<EmailCodeRequest, EmailCodeError>> + Send + 'a>>;
+
+/// Boxed future returning the tokens an emailed code redeems for.
+pub type EmailCodeTokensFuture<'a> =
+ Pin<Box<dyn Future<Output = Result<UpstreamTokens, EmailCodeError>> + Send + 'a>>;
+
+/// Why the upstream refused or failed an emailed code step.
+#[derive(Debug, thiserror::Error)]
+pub enum EmailCodeError {
+ /// The address is malformed.
+ #[error("invalid email address")]
+ InvalidEmail,
+ /// The address may not sign in.
+ #[error("email address may not sign in")]
+ NotAllowed,
+ /// The code is wrong or has expired.
+ #[error("invalid or expired code")]
+ InvalidCode,
+ /// Too many attempts for this address.
+ #[error("too many attempts")]
+ RateLimited,
+ /// The upstream could not be reached or answered unexpectedly.
+ #[error("email sign-in is unavailable")]
+ Unavailable(#[source] anyhow::Error),
+}
+
+/// Signs a user in with a one-time code sent to their email address.
+///
+/// Object-safe, like the other ports here, so the service holds it as a
+/// trait object.
+pub trait EmailCodeProvider: Send + Sync {
+ /// Emails a sign-in code, or reports the single sign-on the address needs.
+ fn request_code<'a>(&'a self, email: &'a str) -> EmailCodeRequestFuture<'a>;
+
+ /// Redeems an emailed code for tokens.
+ fn redeem_code<'a>(&'a self, email: &'a str, code: &'a str) -> EmailCodeTokensFuture<'a>;
+}
diff --git a/services/mcp_auth_proxy/src/domain/redirect_uri.rs b/services/mcp_auth_proxy/src/domain/redirect_uri.rs
index eea0bdb3df..25730eb104 100644
--- a/services/mcp_auth_proxy/src/domain/redirect_uri.rs
+++ b/services/mcp_auth_proxy/src/domain/redirect_uri.rs
@@ -7,6 +7,11 @@ 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]"];
+/// Punctuation a redirect URI may hold for its callback URL to be shown to the
+/// user. None of it means anything inside a single-quoted shell string, or
+/// changes where `curl` and a URL parser disagree the host is.
+const MANUAL_DELIVERY_URI_PUNCTUATION: &str = "-._~:/?&=%[]";
+
/// 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 {
@@ -80,6 +85,31 @@ impl RedirectUriPolicy {
}
}
+ /// Returns whether the user may be shown the callback URL for `uri` to
+ /// carry to the client themselves, instead of being redirected there.
+ ///
+ /// Only a loopback listener needs that: its browser may be on another
+ /// machine. The URL ends up in a command the user is told to run, and
+ /// registration is open, so a URI that could break out of the quotes around
+ /// it is refused.
+ pub fn allows_manual_delivery(&self, uri: &str) -> bool {
+ let safe_to_show = uri.chars().all(|character| {
+ character.is_ascii_alphanumeric() || MANUAL_DELIVERY_URI_PUNCTUATION.contains(character)
+ });
+ if !safe_to_show {
+ return false;
+ }
+
+ let Ok(parsed) = url::Url::parse(uri) else {
+ return false;
+ };
+
+ parsed.scheme() == "http"
+ && parsed
+ .host_str()
+ .is_some_and(|host| LOOPBACK_HOSTS.contains(&host))
+ }
+
/// Returns the trusted `https` hosts, for logging at startup.
pub fn allowed_https_hosts(&self) -> impl Iterator<Item = &str> {
self.allowed_https_hosts.iter().map(String::as_str)
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 a9c019b202..a47f13318c 100644
--- a/services/mcp_auth_proxy/src/domain/redirect_uri/test.rs
+++ b/services/mcp_auth_proxy/src/domain/redirect_uri/test.rs
@@ -105,3 +105,28 @@ fn empty_allowlist_trusts_only_loopback() {
Some(RedirectTrust::RequiresConsent)
);
}
+
+#[test]
+fn manual_delivery_is_for_loopback_uris_safe_to_put_in_a_command() {
+ let policy = policy();
+
+ for allowed in [
+ "http://127.0.0.1:51000/oauth/callback",
+ "http://localhost:6274/callback?client=a%20b",
+ "http://[::1]:51000/callback",
+ ] {
+ assert!(policy.allows_manual_delivery(allowed), "{allowed}");
+ }
+
+ for refused in [
+ "https://claude.ai/api/mcp/auth_callback",
+ "http://example.com/callback",
+ "http://127.0.0.1:51000/a'b",
+ "http://127.0.0.1:51000/$(id)",
+ "http://127.0.0.1:51000/a b",
+ "http://127.0.0.1:51000\\@example.com/",
+ "http://[email protected]:51000/",
+ ] {
+ assert!(!policy.allows_manual_delivery(refused), "{refused}");
+ }
+}
diff --git a/services/mcp_auth_proxy/src/domain/service.rs b/services/mcp_auth_proxy/src/domain/service.rs
index 1708278693..b822722ab7 100644
--- a/services/mcp_auth_proxy/src/domain/service.rs
+++ b/services/mcp_auth_proxy/src/domain/service.rs
@@ -15,12 +15,16 @@ use super::{
access_token_clients::AccessTokenClients,
browser_binding::BrowserBinding,
models::{
- AuthorizationStart, AuthorizeRequest, CallbackRequest, ClientRegistrationRequest,
- ClientRegistrationResponse, ConsentPrompt, IssuedAuthorizationCode, PendingAuthorization,
- RefreshToken, RefreshTokenBinding, RegisteredClient, RevocationRequest, TokenRequest,
- TokenResponse, UserConsent,
+ AuthorizationStart, AuthorizeRequest, CallbackRequest, ClientDelivery,
+ ClientRegistrationRequest, ClientRegistrationResponse, CodeDelivery, ConsentPrompt,
+ EmailCodeRequest, EmailSignInStep, IssuedAuthorizationCode, PendingAuthorization,
+ RefreshToken, RefreshTokenBinding, RegisteredClient, RevocationRequest, SignInMethod,
+ TokenRequest, TokenResponse, UpstreamLogin, UpstreamTokens, UserConsent,
+ },
+ ports::{
+ ClientRegistrationStore, EmailCodeError, EmailCodeProvider, OAuthProvider,
+ RefreshTokenBindingStore, UpstreamGrantError,
},
- ports::{ClientRegistrationStore, OAuthProvider, RefreshTokenBindingStore, UpstreamGrantError},
redirect_uri::{RedirectTrust, RedirectUriPolicy},
};
@@ -70,13 +74,39 @@ pub trait McpAuthProxyService: Clone + Send + Sync + 'static {
browser: BrowserBinding,
consent: UserConsent,
) -> impl Future<Output = Result<AuthorizationStart, StartAuthorizationError>> + Send;
+ /// Returns whether the user may carry the callback URL to the client
+ /// themselves, because the client may be on another machine.
+ fn allows_manual_delivery(&self, redirect_uri: &str) -> bool;
/// Completes the upstream callback in the browser that started the flow
- /// and returns the client redirect URL.
+ /// and returns the client callback URL.
fn complete_callback(
&self,
params: CallbackRequest,
browser: Option<BrowserBinding>,
- ) -> impl Future<Output = Result<String, CompleteCallbackError>> + Send;
+ ) -> impl Future<Output = Result<ClientDelivery, CompleteCallbackError>> + Send;
+ /// Checks that an email sign-in session is live and belongs to `browser`.
+ fn check_email_sign_in(
+ &self,
+ session_id: &str,
+ browser: &BrowserBinding,
+ ) -> impl Future<Output = Result<(), EmailSignInError>> + Send;
+ /// Emails a sign-in code for a session, or names the single sign-on the
+ /// address needs instead.
+ fn request_email_code(
+ &self,
+ session_id: &str,
+ email: &str,
+ browser: &BrowserBinding,
+ ) -> impl Future<Output = Result<EmailSignInStep, EmailSignInError>> + Send;
+ /// Redeems an emailed code and completes the session. A wrong code leaves
+ /// the session live, so the user can try again.
+ fn verify_email_code(
+ &self,
+ session_id: &str,
+ email: &str,
+ code: &str,
+ browser: &BrowserBinding,
+ ) -> impl Future<Output = Result<ClientDelivery, EmailSignInError>> + Send;
/// Exchanges a broker-issued code or refresh token for bearer credentials.
fn exchange_token(
&self,
@@ -100,6 +130,12 @@ pub trait InflightAuthStore: Send + Sync {
pending: PendingAuthorization,
) -> impl Future<Output = anyhow::Result<()>> + Send;
+ /// Returns a live pending authorization flow without consuming it.
+ fn find_pending(
+ &self,
+ session_id: &str,
+ ) -> impl Future<Output = anyhow::Result<Option<PendingAuthorization>>> + Send;
+
/// Removes and returns a pending authorization flow, if present.
fn take_pending(
&self,
@@ -137,6 +173,8 @@ pub struct McpAuthProxyServiceDeps<I> {
pub refresh_token_bindings: Arc<dyn RefreshTokenBindingStore>,
/// Upstream OAuth provider the broker fronts.
pub oauth_provider: Arc<dyn OAuthProvider>,
+ /// Sends and redeems emailed sign-in codes.
+ pub email_codes: Arc<dyn EmailCodeProvider>,
}
/// Streamable HTTP resource URL advertised in protected-resource metadata.
@@ -160,6 +198,7 @@ pub struct McpAuthProxyServiceImpl<I> {
refresh_token_bindings: Arc<dyn RefreshTokenBindingStore>,
access_token_clients: AccessTokenClients,
oauth_provider: Arc<dyn OAuthProvider>,
+ email_codes: Arc<dyn EmailCodeProvider>,
redirect_uri_policy: RedirectUriPolicy,
public_url: String,
}
@@ -172,6 +211,7 @@ impl<I> Clone for McpAuthProxyServiceImpl<I> {
refresh_token_bindings: Arc::clone(&self.refresh_token_bindings),
access_token_clients: self.access_token_clients.clone(),
oauth_provider: Arc::clone(&self.oauth_provider),
+ email_codes: Arc::clone(&self.email_codes),
redirect_uri_policy: self.redirect_uri_policy.clone(),
public_url: self.public_url.clone(),
}
@@ -191,6 +231,7 @@ where
client_registrations,
refresh_token_bindings,
oauth_provider,
+ email_codes,
} = deps;
Self {
@@ -202,11 +243,83 @@ where
client_registrations,
refresh_token_bindings,
oauth_provider,
+ email_codes,
redirect_uri_policy,
public_url,
}
}
+ /// Issues the broker code for upstream tokens and returns the client
+ /// callback URL carrying it.
+ async fn issue_code(
+ &self,
+ pending: PendingAuthorization,
+ tokens: UpstreamTokens,
+ ) -> anyhow::Result<ClientDelivery> {
+ // The client may sit on the broker code for up to `AUTHORIZATION_CODE_TTL`
+ // before redeeming it, so record when the upstream token actually expires
+ // and count down from that at token exchange rather than replaying a stale
+ // `expires_in`.
+ let access_token_expires_at = SystemTime::now()
+ .checked_add(Duration::from_secs(tokens.expires_in))
+ .ok_or_else(|| {
+ anyhow::anyhow!("upstream expires_in {} is out of range", tokens.expires_in)
+ })?;
+
+ let issued_code = uuid::Uuid::new_v4().to_string();
+ self.inflight_auth
+ .insert_issued(
+ &issued_code,
+ IssuedAuthorizationCode {
+ client_id: pending.client_id,
+ access_token: tokens.access_token,
+ refresh_token: tokens.refresh_token,
+ code_challenge: pending.code_challenge,
+ redirect_uri: pending.client_redirect_uri.clone(),
+ access_token_expires_at,
+ },
+ )
+ .await?;
+
+ Ok(ClientDelivery {
+ url: append_query_params(
+ &pending.client_redirect_uri,
+ &[("code", issued_code), ("state", pending.client_state)],
+ ),
+ method: pending.delivery,
+ })
+ }
+
+ /// The live pending flow behind an email sign-in, provided this browser
+ /// started it. The flow stays pending: only a redeemed code consumes it.
+ async fn email_sign_in_session(
+ &self,
+ session_id: &str,
+ browser: &BrowserBinding,
+ ) -> Result<PendingAuthorization, EmailSignInError> {
+ let pending = self
+ .inflight_auth
+ .find_pending(session_id)
+ .await
+ .map_err(EmailSignInError::InflightStore)?
+ .ok_or(EmailSignInError::UnknownOrExpiredSession)?;
+
+ let started_in_this_browser = pending
+ .browser_binding_digest
+ .as_deref()
+ .is_some_and(|digest| browser.matches_digest(digest));
+ if !started_in_this_browser {
+ tracing::warn!(
+ %session_id,
+ client_id = %pending.client_id,
+ "email sign-in submitted from a browser that did not start the flow"
+ );
+ return Err(EmailSignInError::DifferentBrowser);
+ }
+
+ Ok(pending)
+ }
+
/// The record of which client each issued access token went to, for the
/// MCP route to label what a client writes.
pub fn access_token_clients(&self) -> AccessTokenClients {
@@ -532,7 +645,19 @@ where
return Err(StartAuthorizationError::UnregisteredRedirectUri);
}
- if trust == RedirectTrust::RequiresConsent {
+ let delivery = params.delivery.unwrap_or_default();
+ if delivery == CodeDelivery::Manual
+ && !service
+ .redirect_uri_policy
+ .allows_manual_delivery(&params.redirect_uri)
+ {
+ return Err(StartAuthorizationError::ManualDeliveryUnavailable);
+ }
+
+ // A loopback redirect is trusted because the code stays on the
+ // user's machine. Showing it for them to carry elsewhere gives that
+ // up, so the user approves it like any other destination.
+ if trust == RedirectTrust::RequiresConsent || delivery == CodeDelivery::Manual {
let redirect_host = redirect_host(&params.redirect_uri)
.ok_or(StartAuthorizationError::InvalidRedirectUri)?;
@@ -545,6 +670,7 @@ where
return Ok(AuthorizationStart::ConsentRequired(ConsentPrompt {
client_name: consent_client_name(&client.client_name),
redirect_host,
+ delivery,
}));
}
@@ -557,7 +683,13 @@ where
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");
+ tracing::info!(
+ %session_id,
+ client_id = %client.client_id,
+ %sign_in,
+ %delivery,
+ "starting OAuth authorize flow"
+ );
service
.inflight_auth
@@ -569,21 +701,35 @@ where
client_state: params.state,
client_redirect_uri: params.redirect_uri,
browser_binding_digest: Some(browser.digest()),
+ delivery,
},
)
.await
.map_err(StartAuthorizationError::InflightStore)?;
+ let login = match sign_in {
+ SignInMethod::Email => {
+ return Ok(AuthorizationStart::EmailSignIn { session_id });
+ }
+ SignInMethod::Google => UpstreamLogin::Google,
+ SignInMethod::Login => UpstreamLogin::LoginPage,
+ };
+
service
.oauth_provider
- .construct_authorize_url(&session_id, sign_in)
+ .construct_authorize_url(&session_id, login)
.map(AuthorizationStart::SignIn)
.map_err(StartAuthorizationError::ConstructAuthorizeUrl)
}
}
- /// Completes the upstream OAuth callback and returns the redirect URL for
- /// the MCP client callback.
+ fn allows_manual_delivery(&self, redirect_uri: &str) -> bool {
+ self.redirect_uri_policy
+ .allows_manual_delivery(redirect_uri)
+ }
+
+ /// Completes the upstream OAuth callback and returns the URL of 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
@@ -594,7 +740,7 @@ where
&self,
params: CallbackRequest,
browser: Option<BrowserBinding>,
- ) -> Result<String, CompleteCallbackError> {
+ ) -> Result<ClientDelivery, CompleteCallbackError> {
let session_id = params
.state
.as_deref()
@@ -638,10 +784,10 @@ where
if let Some(desc) = params.error_description {
params_to_append.push(("error_description", desc));
}
- return Ok(append_query_params(
- &pending.client_redirect_uri,
- &params_to_append,
- ));
+ return Ok(ClientDelivery {
+ url: append_query_params(&pending.client_redirect_uri, &params_to_append),
+ method: pending.delivery,
+ });
}
let code = params.code.ok_or(CompleteCallbackError::MissingCode)?;
@@ -652,41 +798,90 @@ where
.await
.map_err(CompleteCallbackError::AuthorizationCodeExchangeFailed)?;
- // The client may sit on the broker code for up to `AUTHORIZATION_CODE_TTL`
- // before redeeming it, so record when the upstream token actually expires
- // and count down from that at token exchange rather than replaying a stale
- // `expires_in`.
- let access_token_expires_at = SystemTime::now()
- .checked_add(Duration::from_secs(tokens.expires_in))
- .ok_or_else(|| {
- CompleteCallbackError::AuthorizationCodeExchangeFailed(UpstreamGrantError::Failed(
- anyhow::anyhow!("upstream expires_in {} is out of range", tokens.expires_in),
- ))
- })?;
+ self.issue_code(pending, tokens)
+ .await
+ .map_err(CompleteCallbackError::InflightStore)
+ }
- let issued_code = uuid::Uuid::new_v4().to_string();
- self.inflight_auth
- .insert_issued(
- &issued_code,
- IssuedAuthorizationCode {
- client_id: pending.client_id,
- access_token: tokens.access_token,
- refresh_token: tokens.refresh_token,
- code_challenge: pending.code_challenge,
- redirect_uri: pending.client_redirect_uri.clone(),
- access_token_expires_at,
- },
- )
+ #[tracing::instrument(
+ name = "mcp_oauth.email_sign_in.check",
+ skip_all,
+ err(level = "warn"),
+ fields(%session_id)
+ )]
+ async fn check_email_sign_in(
+ &self,
+ session_id: &str,
+ browser: &BrowserBinding,
+ ) -> Result<(), EmailSignInError> {
+ self.email_sign_in_session(session_id, browser).await?;
+ Ok(())
+ }
+
+ #[tracing::instrument(
+ name = "mcp_oauth.email_sign_in.request_code",
+ skip_all,
+ err(level = "warn"),
+ fields(%session_id, client_id = tracing::field::Empty)
+ )]
+ async fn request_email_code(
+ &self,
+ session_id: &str,
+ email: &str,
+ browser: &BrowserBinding,
+ ) -> Result<EmailSignInStep, EmailSignInError> {
+ let pending = self.email_sign_in_session(session_id, browser).await?;
+ tracing::Span::current().record("client_id", pending.client_id.as_str());
+
+ match self.email_codes.request_code(email.trim()).await? {
+ EmailCodeRequest::Sent => Ok(EmailSignInStep::EnterCode),
+ EmailCodeRequest::SsoRequired { idp_id } => self
+ .oauth_provider
+ .construct_authorize_url(
+ session_id,
+ UpstreamLogin::Sso {
+ idp_id: &idp_id,
+ email: email.trim(),
+ },
+ )
+ .map(EmailSignInStep::Sso)
+ .map_err(EmailSignInError::ConstructAuthorizeUrl),
+ }
+ }
+
+ /// The session is consumed only after the code redeems, so a mistyped code
+ /// costs one of the upstream's attempts rather than the whole sign-in.
+ #[tracing::instrument(
+ name = "mcp_oauth.email_sign_in.verify_code",
+ skip_all,
+ err(level = "warn"),
+ fields(%session_id, client_id = tracing::field::Empty)
+ )]
+ async fn verify_email_code(
+ &self,
+ session_id: &str,
+ email: &str,
+ code: &str,
+ browser: &BrowserBinding,
+ ) -> Result<ClientDelivery, EmailSignInError> {
+ let pending = self.email_sign_in_session(session_id, browser).await?;
+ tracing::Span::current().record("client_id", pending.client_id.as_str());
+
+ let tokens = self
+ .email_codes
+ .redeem_code(email.trim(), code.trim())
+ .await?;
+
+ let pending = self
+ .inflight_auth
+ .take_pending(session_id)
.await
- .map_err(CompleteCallbackError::InflightStore)?;
-
- Ok(append_query_params(
- &pending.client_redirect_uri,
- &[
- ("code", issued_code),
- ("state", pending.client_state.clone()),
- ],
- ))
+ .map_err(EmailSignInError::InflightStore)?
+ .ok_or(EmailSignInError::UnknownOrExpiredSession)?;
+
+ self.issue_code(pending, tokens)
+ .await
+ .map_err(EmailSignInError::InflightStore)
}
/// Exchanges a broker-issued authorization code for an upstream bearer
@@ -887,6 +1082,31 @@ pub enum StartAuthorizationError {
/// Upstream authorize URL construction failed.
#[error("failed to construct authorize URL")]
ConstructAuthorizeUrl(anyhow::Error),
+ /// The user asked to carry the code themselves, which only a loopback
+ /// redirect URI this broker can safely show allows.
+ #[error("redirect_uri cannot be delivered manually")]
+ ManualDeliveryUnavailable,
+}
+
+/// Errors returned while signing in with an emailed code.
+#[derive(Debug, thiserror::Error)]
+pub enum EmailSignInError {
+ /// The pending session was missing or expired.
+ #[error("unknown or expired session")]
+ UnknownOrExpiredSession,
+ /// The form was submitted by a browser other than the one that started the
+ /// flow.
+ #[error("authorization was started in a different browser")]
+ DifferentBrowser,
+ /// The upstream refused or failed the step.
+ #[error(transparent)]
+ EmailCode(#[from] EmailCodeError),
+ /// Inflight auth state could not be loaded or updated.
+ #[error("failed to access inflight auth state")]
+ InflightStore(anyhow::Error),
+ /// Upstream authorize URL construction failed.
+ #[error("failed to construct authorize URL")]
+ ConstructAuthorizeUrl(anyhow::Error),
}
/// Errors returned when handling the upstream callback.
diff --git a/services/mcp_auth_proxy/src/domain/service/test.rs b/services/mcp_auth_proxy/src/domain/service/test.rs
index 97591ccea8..8d4803b709 100644
--- a/services/mcp_auth_proxy/src/domain/service/test.rs
+++ b/services/mcp_auth_proxy/src/domain/service/test.rs
@@ -201,6 +201,7 @@ async fn authorize_for_an_unlisted_host_asks_for_consent_and_stores_nothing() {
AuthorizationStart::ConsentRequired(ConsentPrompt {
client_name: "test-client".to_owned(),
redirect_host: "gateway.example".to_owned(),
+ delivery: crate::domain::models::CodeDelivery::Redirect,
})
);
assert!(
@@ -258,7 +259,8 @@ async fn approved_client_on_an_unlisted_host_completes_the_flow() {
Some(harness.browser.clone()),
)
.await
- .expect("callback should succeed");
+ .expect("callback should succeed")
+ .url;
assert!(
redirect.starts_with(&format!("{GATEWAY_REDIRECT_URI}?code=")),
@@ -355,6 +357,7 @@ async fn an_unbound_pending_flow_completes_only_to_a_trusted_redirect_uri() {
client_state: "client-state".to_owned(),
client_redirect_uri: redirect_uri.to_owned(),
browser_binding_digest: None,
+ delivery: crate::domain::models::CodeDelivery::Redirect,
},
)
.await
@@ -1039,7 +1042,8 @@ async fn callback_redirect_preserves_a_query_on_the_registered_redirect_uri() {
Some(harness.browser.clone()),
)
.await
- .expect("callback should succeed");
+ .expect("callback should succeed")
+ .url;
assert!(
redirect.starts_with("https://claude.ai/api/mcp/auth_callback?tenant=macro&code="),
diff --git a/services/mcp_auth_proxy/src/inbound/axum_router.rs b/services/mcp_auth_proxy/src/inbound/axum_router.rs
index 231086b128..6f4871ca11 100644
--- a/services/mcp_auth_proxy/src/inbound/axum_router.rs
+++ b/services/mcp_auth_proxy/src/inbound/axum_router.rs
@@ -11,7 +11,7 @@ use axum::{
extract::{Query, RawQuery, State, rejection::FormRejection},
http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header},
middleware as axum_mw,
- response::{Html, IntoResponse, Json, Redirect, Response},
+ response::{IntoResponse, Json, Redirect, Response},
routing,
};
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
@@ -22,13 +22,15 @@ use tower_http::cors::{AllowOrigin, CorsLayer};
use crate::domain::{
browser_binding::BrowserBinding,
models::{
- AuthorizationStart, AuthorizeRequest, CallbackRequest, ClientRegistrationRequest,
- ConsentPrompt, RevocationRequest, TokenRequest, UserConsent,
+ AuthorizationStart, AuthorizeRequest, CallbackRequest, ClientDelivery,
+ ClientRegistrationRequest, CodeDelivery, ConsentPrompt, EmailSignInStep, RevocationRequest,
+ TokenRequest, UserConsent,
},
- ports::UpstreamGrantError,
+ ports::{EmailCodeError, UpstreamGrantError},
service::{
- CompleteCallbackError, InflightAuthStore, McpAuthProxyService, McpAuthProxyServiceImpl,
- RegisterClientError, RevokeTokenError, StartAuthorizationError, TokenExchangeError,
+ CompleteCallbackError, EmailSignInError, InflightAuthStore, McpAuthProxyService,
+ McpAuthProxyServiceImpl, RegisterClientError, RevokeTokenError, StartAuthorizationError,
+ TokenExchangeError,
},
};
@@ -92,6 +94,9 @@ async fn register<I: InflightAuthStore + 'static>(
}
}
+/// The broker's email sign-in page, relative to `/authorize`.
+const EMAIL_SIGN_IN_PATH: &str = "email-sign-in";
+
/// 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.
@@ -111,6 +116,29 @@ struct ConsentPage<'a> {
redirect_host: &'a str,
request: &'a AuthorizeRequest,
consent_token: &'a str,
+ manual_delivery: bool,
+}
+
+#[derive(Template)]
+#[template(path = "sign_in_choice.html")]
+struct SignInChoicePage {
+ params: Vec<(String, String)>,
+ offers_manual_delivery: bool,
+}
+
+#[derive(Template)]
+#[template(path = "email_sign_in.html")]
+struct EmailSignInPage<'a> {
+ session: &'a str,
+ form_token: &'a str,
+ code_sent_to: Option<&'a str>,
+ error: Option<&'a str>,
+}
+
+#[derive(Template)]
+#[template(path = "manual_delivery.html")]
+struct ManualDeliveryPage<'a> {
+ url: &'a str,
}
/// What the user chose on the consent screen.
@@ -147,6 +175,21 @@ fn browser_binding_cookie(browser: &BrowserBinding) -> Cookie<'static> {
.build()
}
+/// Renders a template as a broker page, naming it in the log if it cannot be.
+fn render_page(page: &impl Template, name: &'static str) -> Response {
+ match page.render() {
+ Ok(body) => html_page(body),
+ Err(error) => {
+ tracing::error!(error=?error, page = name, "failed to render a broker page");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to render the page",
+ )
+ .into_response()
+ }
+ }
+}
+
/// A broker-rendered page with the headers that keep it from being framed,
/// cached, or leaking its URL.
fn html_page(body: String) -> Response {
@@ -164,49 +207,20 @@ fn html_page(body: String) -> Response {
.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.
-const SIGN_IN_CHOICE_HOSTS: [&str; 2] = ["chatgpt.com", "chat.openai.com"];
-
-fn offers_sign_in_choice(redirect_uri: &str) -> bool {
- url::Url::parse(redirect_uri).is_ok_and(|uri| {
- uri.scheme() == "https"
- && uri
- .host_str()
- .is_some_and(|host| SIGN_IN_CHOICE_HOSTS.contains(&host))
- })
-}
-
-/// The sign-in chooser. Each link repeats the authorize request with the
-/// choice added; the query is re-encoded, so nothing from it reaches the page
-/// unescaped. Nothing is stored until a link is followed.
-fn sign_in_choice(query: Option<String>) -> Response {
- let link = |choice: &str| {
- let query = query.as_deref().unwrap_or_default();
- let mut params = url::form_urlencoded::Serializer::new(String::new());
- params.extend_pairs(url::form_urlencoded::parse(query.as_bytes()));
- params.append_pair("sign_in", choice);
- format!("/authorize?{}", params.finish()).replace('&', "&amp;")
- };
- let page = format!(
- include_str!("sign_in_choice.html"),
- google = link("google"),
- login = link("login"),
- );
- (
- [
- (header::CACHE_CONTROL, "no-store"),
- (header::REFERRER_POLICY, "no-referrer"),
- (header::X_FRAME_OPTIONS, "DENY"),
- (
- header::CONTENT_SECURITY_POLICY,
- "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'",
- ),
- ],
- Html(page),
+/// The sign-in chooser, shown before any flow starts so it stores nothing.
+/// Its form repeats the authorize request with the choices added.
+fn sign_in_choice(query: Option<&str>, offers_manual_delivery: bool) -> Response {
+ let params = url::form_urlencoded::parse(query.unwrap_or_default().as_bytes())
+ .into_owned()
+ .collect();
+
+ render_page(
+ &SignInChoicePage {
+ params,
+ offers_manual_delivery,
+ },
+ "sign_in_choice",
)
- .into_response()
}
fn consent_page(
@@ -214,23 +228,27 @@ fn consent_page(
request: &AuthorizeRequest,
browser: &BrowserBinding,
) -> Response {
- let page = ConsentPage {
- client_name: &prompt.client_name,
- redirect_host: &prompt.redirect_host,
- request,
- consent_token: &browser.consent_token(),
- };
+ render_page(
+ &ConsentPage {
+ client_name: &prompt.client_name,
+ redirect_host: &prompt.redirect_host,
+ request,
+ consent_token: &browser.form_token(),
+ manual_delivery: prompt.delivery == CodeDelivery::Manual,
+ },
+ "consent",
+ )
+}
- 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()
- }
+/// Sends a finished flow's callback URL to the client: by `redirect`, or by
+/// showing it when the user is carrying it to another machine.
+fn delivery_response(delivery: &ClientDelivery, redirect: fn(&str) -> Redirect) -> Response {
+ match delivery.method {
+ CodeDelivery::Redirect => redirect(&delivery.url).into_response(),
+ CodeDelivery::Manual => render_page(
+ &ManualDeliveryPage { url: &delivery.url },
+ "manual_delivery",
+ ),
}
}
@@ -255,6 +273,10 @@ async fn authorization_response<I: InflightAuthStore + 'static>(
Ok(AuthorizationStart::SignIn(url)) => {
([(header::REFERRER_POLICY, "no-referrer")], redirect(&url)).into_response()
}
+ // Relative, so it stays under the prefix the gateway mounted this on.
+ Ok(AuthorizationStart::EmailSignIn { session_id }) => {
+ redirect(&format!("{EMAIL_SIGN_IN_PATH}?session={session_id}")).into_response()
+ }
Ok(AuthorizationStart::ConsentRequired(prompt)) => {
consent_page(&prompt, &request, &browser)
}
@@ -268,8 +290,9 @@ async fn authorize<I: InflightAuthStore + 'static>(
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);
+ if params.sign_in.is_none() {
+ let offers_manual_delivery = auth_proxy.allows_manual_delivery(&params.redirect_uri);
+ return sign_in_choice(query.as_deref(), offers_manual_delivery);
}
let browser = browser_binding(&jar).unwrap_or_else(BrowserBinding::generate);
@@ -286,28 +309,31 @@ async fn authorize<I: InflightAuthStore + 'static>(
(jar, response).into_response()
}
+/// The browser submitting one of the broker's forms, provided it is the one
+/// that was shown the form: 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.
+fn form_browser(jar: &CookieJar, headers: &HeaderMap, form_token: &str) -> Option<BrowserBinding> {
+ let cross_site = headers
+ .get(SEC_FETCH_SITE)
+ .is_some_and(|site| site.as_bytes() != b"same-origin");
+ if cross_site {
+ return None;
+ }
+
+ browser_binding(jar).filter(|browser| browser.accepts_form_token(form_token))
+}
+
/// 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 {
+ let Some(browser) = form_browser(&jar, &headers, &submission.consent_token) else {
tracing::warn!(
client_id = %submission.request.client_id,
- cross_site,
"consent form submission could not be verified"
);
return (
@@ -336,8 +362,183 @@ async fn submit_consent<I: InflightAuthStore + 'static>(
}
}
+/// The session an email sign-in page belongs to.
+#[derive(Deserialize)]
+struct EmailSignInQuery {
+ session: String,
+}
+
+/// The email sign-in form: an address alone asks for a code, and an address
+/// with a code redeems it.
+#[derive(Deserialize)]
+struct EmailSignInSubmission {
+ session: String,
+ form_token: String,
+ email: String,
+ #[serde(default)]
+ code: Option<String>,
+}
+
+fn email_sign_in_page(
+ session: &str,
+ browser: &BrowserBinding,
+ code_sent_to: Option<&str>,
+ error: Option<&str>,
+) -> Response {
+ render_page(
+ &EmailSignInPage {
+ session,
+ form_token: &browser.form_token(),
+ code_sent_to,
+ error,
+ },
+ "email_sign_in",
+ )
+}
+
+/// What the user is told about a refused step, or `None` when the page cannot
+/// help and the flow has to be answered as an error.
+fn email_code_refusal(error: &EmailSignInError) -> Option<&'static str> {
+ let EmailSignInError::EmailCode(error) = error else {
+ return None;
+ };
+
+ match error {
+ EmailCodeError::InvalidEmail => Some("Enter a valid email address."),
+ EmailCodeError::NotAllowed => Some("That email address can't sign in to Macro."),
+ EmailCodeError::InvalidCode => Some("That code isn't right, or it has expired."),
+ EmailCodeError::RateLimited => Some("Too many attempts. Wait a minute and try again."),
+ EmailCodeError::Unavailable(_) => None,
+ }
+}
+
+fn email_sign_in_error_response(error: EmailSignInError) -> Response {
+ match error {
+ EmailSignInError::UnknownOrExpiredSession => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "This sign-in has expired. Start connecting again from the app you are connecting.",
+ )
+ .into_response(),
+ EmailSignInError::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(),
+ EmailSignInError::EmailCode(error) => {
+ tracing::error!(error=?error, "email sign-in step failed");
+ (
+ axum::http::StatusCode::BAD_GATEWAY,
+ "Email sign-in is unavailable right now. Try again shortly.",
+ )
+ .into_response()
+ }
+ EmailSignInError::InflightStore(error) => {
+ tracing::error!(error=?error, "failed to access inflight auth state");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to access inflight auth state",
+ )
+ .into_response()
+ }
+ EmailSignInError::ConstructAuthorizeUrl(error) => {
+ tracing::error!(error=?error, "failed to construct upstream authorize URL");
+ (
+ axum::http::StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to construct authorize URL",
+ )
+ .into_response()
+ }
+ }
+}
+
+/// Shows the email form for a session this browser started.
+async fn show_email_sign_in<I: InflightAuthStore + 'static>(
+ State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,
+ jar: CookieJar,
+ Query(query): Query<EmailSignInQuery>,
+) -> Response {
+ let Some(browser) = browser_binding(&jar) else {
+ return email_sign_in_error_response(EmailSignInError::DifferentBrowser);
+ };
+
+ match auth_proxy
+ .check_email_sign_in(&query.session, &browser)
+ .await
+ {
+ Ok(()) => email_sign_in_page(&query.session, &browser, None, None),
+ Err(error) => email_sign_in_error_response(error),
+ }
+}
+
+/// Receives the email form: asks for a code, or redeems one.
+async fn submit_email_sign_in<I: InflightAuthStore + 'static>(
+ State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,
+ jar: CookieJar,
+ headers: HeaderMap,
+ axum::Form(submission): axum::Form<EmailSignInSubmission>,
+) -> Response {
+ let Some(browser) = form_browser(&jar, &headers, &submission.form_token) else {
+ tracing::warn!(
+ session_id = %submission.session,
+ "email sign-in submission could not be verified"
+ );
+ return (
+ axum::http::StatusCode::FORBIDDEN,
+ "This sign-in could not be verified. Start connecting again from the app you are \
+ connecting.",
+ )
+ .into_response();
+ };
+ let EmailSignInSubmission {
+ session,
+ email,
+ code,
+ ..
+ } = submission;
+
+ match code {
+ Some(code) => {
+ match auth_proxy
+ .verify_email_code(&session, &email, &code, &browser)
+ .await
+ {
+ Ok(delivery) => delivery_response(&delivery, Redirect::to),
+ Err(error) => match email_code_refusal(&error) {
+ Some(refusal) => {
+ email_sign_in_page(&session, &browser, Some(&email), Some(refusal))
+ }
+ None => email_sign_in_error_response(error),
+ },
+ }
+ }
+ None => match auth_proxy
+ .request_email_code(&session, &email, &browser)
+ .await
+ {
+ Ok(EmailSignInStep::EnterCode) => {
+ email_sign_in_page(&session, &browser, Some(&email), None)
+ }
+ Ok(EmailSignInStep::Sso(url)) => (
+ [(header::REFERRER_POLICY, "no-referrer")],
+ Redirect::to(&url),
+ )
+ .into_response(),
+ Err(error) => match email_code_refusal(&error) {
+ Some(refusal) => email_sign_in_page(&session, &browser, None, Some(refusal)),
+ None => email_sign_in_error_response(error),
+ },
+ },
+ }
+}
+
fn start_authorization_error_response(error: StartAuthorizationError) -> Response {
match error {
+ StartAuthorizationError::ManualDeliveryUnavailable => (
+ axum::http::StatusCode::BAD_REQUEST,
+ "This app can't finish signing in on another machine.",
+ )
+ .into_response(),
StartAuthorizationError::UnsupportedResponseType => (
axum::http::StatusCode::BAD_REQUEST,
"unsupported response_type",
@@ -399,7 +600,7 @@ async fn oauth_callback<I: InflightAuthStore + 'static>(
.complete_callback(params, browser_binding(&jar))
.await
{
- Ok(url) => Redirect::temporary(&url).into_response(),
+ Ok(delivery) => delivery_response(&delivery, Redirect::temporary),
Err(CompleteCallbackError::MissingState) => {
tracing::warn!("no state parameter in upstream OAuth callback");
(
@@ -673,6 +874,10 @@ fn oauth_routes<I: InflightAuthStore + 'static>(auth_proxy: McpAuthProxyServiceI
routing::get(authorization_server_metadata),
)
.route("/authorize", routing::get(authorize).post(submit_consent))
+ .route(
+ &format!("/{EMAIL_SIGN_IN_PATH}"),
+ routing::get(show_email_sign_in).post(submit_email_sign_in),
+ )
.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 01c65d46c2..5050d58856 100644
--- a/services/mcp_auth_proxy/src/inbound/axum_router/test.rs
+++ b/services/mcp_auth_proxy/src/inbound/axum_router/test.rs
@@ -13,9 +13,10 @@ use super::{health, mcp_router, mount_at_root_and_prefix, oauth_router};
use crate::domain::browser_binding::BrowserBinding;
use crate::domain::ports::UpstreamGrantError;
use crate::test_support::{
- ATTACKER_CODE_VERIFIER, ATTACKER_REDIRECT_URI, FakeOAuthProvider, GATEWAY_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, EMAIL_ADDRESS, EMAIL_CODE, FakeOAuthProvider,
+ GATEWAY_REDIRECT_URI, Harness, LOOPBACK_REDIRECT_URI, SSO_EMAIL_ADDRESS, 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;
@@ -95,7 +96,8 @@ fn authorize_request(client_id: &str, redirect_uri: &str, code_verifier: &str) -
.method("GET")
.uri(format!(
"/authorize?response_type=code&client_id={client_id}&redirect_uri={redirect_uri}\
- &state=client-state&code_challenge={code_challenge}&code_challenge_method=S256"
+ &state=client-state&code_challenge={code_challenge}&code_challenge_method=S256\
+ &sign_in=google"
))
.body(Body::empty())
.expect("request should build")
@@ -294,7 +296,10 @@ async fn approving_keeps_the_requested_sign_in_method() {
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())
+ *authorize.uri_mut() = authorize
+ .uri()
+ .to_string()
+ .replace("sign_in=google", "sign_in=login")
.parse()
.expect("uri should parse");
let page = send(&harness, authorize).await;
@@ -464,7 +469,7 @@ async fn a_sign_in_started_in_another_browser_issues_no_code() {
}
#[tokio::test]
-async fn authorize_explains_how_to_reconnect_an_unregistered_client() {
+async fn authorize_explains_how_to_reconnect_an_unregister_client() {
let harness = Harness::new();
let response = send(
@@ -524,66 +529,79 @@ async fn authorize_withholds_the_client_origin_from_the_identity_provider() {
}
}
-/// ChatGPT's reviewers sign in with a password, so its users pick; the choice
-/// carries the whole request, escaped, and only then does the flow start.
+/// An authorize request as a client first sends it, before the user has picked
+/// how to sign in, with `extra` appended.
+fn unchosen_authorize_uri(client_id: &str, redirect_uri: &str, extra: &str) -> String {
+ format!(
+ "/authorize?response_type=code&client_id={client_id}&redirect_uri={}\
+ &state=client-state&code_challenge={}&code_challenge_method=S256{extra}",
+ urlencoding::encode(redirect_uri),
+ code_challenge_for(VICTIM_CODE_VERIFIER),
+ )
+}
+
+fn get_page(uri: &str, cookie: Option<&str>) -> Request<Body> {
+ let mut request = Request::builder().method("GET").uri(uri);
+ if let Some(cookie) = cookie {
+ request = request.header(header::COOKIE, cookie);
+ }
+ request.body(Body::empty()).expect("request should build")
+}
+
+fn post_form(uri: &str, cookie: &str, form: String) -> Request<Body> {
+ Request::builder()
+ .method("POST")
+ .uri(uri)
+ .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
+ .header(header::COOKIE, cookie)
+ .body(Body::from(form))
+ .expect("request should build")
+}
+
+/// Every client's users pick how to sign in, whichever method their account
+/// uses, and each choice leads to its own sign-in.
#[tokio::test]
-async fn authorize_offers_chatgpt_a_sign_in_choice() {
- let harness = Harness::new();
- let redirect_uri = "https://chatgpt.com/connector/oauth/abc";
- let registration = send(&harness, register_request(redirect_uri)).await;
- assert_eq!(registration.status, StatusCode::OK);
- let client_id = registration.json()["client_id"]
- .as_str()
- .expect("registration returns a client_id")
- .to_owned();
+async fn every_client_gets_the_sign_in_choice() {
+ for redirect_uri in [
+ LOOPBACK_REDIRECT_URI,
+ TRUSTED_REDIRECT_URI,
+ GATEWAY_REDIRECT_URI,
+ ] {
+ let harness = Harness::new();
+ let client_id = register_client(&harness, redirect_uri).await;
- let choice = send(
- &harness,
- authorize_request(&client_id, redirect_uri, VICTIM_CODE_VERIFIER),
- )
- .await;
- assert_eq!(choice.status, StatusCode::OK);
- let page = choice.body;
- assert!(page.contains("&amp;sign_in=google"), "{page}");
- assert!(page.contains("&amp;sign_in=login"), "{page}");
- assert!(page.contains(&format!("client_id={client_id}")), "{page}");
-
- let code_challenge = code_challenge_for(VICTIM_CODE_VERIFIER);
- let chosen = |choice: &str| {
- Request::builder()
- .method("GET")
- .uri(format!(
- "/authorize?response_type=code&client_id={client_id}\
- &redirect_uri={}&state=x&code_challenge={code_challenge}\
- &code_challenge_method=S256&sign_in={choice}",
- urlencoding::encode(redirect_uri),
- ))
- .body(Body::empty())
- .expect("request should build")
- };
- 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"),
- "{location}"
- );
- let google = send(&harness, chosen("google")).await;
- let location = google.location.expect("redirect has a location");
- assert!(
- location.starts_with("https://upstream.example/authorize"),
- "{location}"
- );
+ let choice = send(
+ &harness,
+ get_page(&unchosen_authorize_uri(&client_id, redirect_uri, ""), None),
+ )
+ .await;
+
+ assert_eq!(choice.status, StatusCode::OK);
+ assert!(
+ !harness.inflight.has_pending(),
+ "the chooser stores nothing"
+ );
+ for method in ["google", "email", "login"] {
+ assert!(
+ choice
+ .body
+ .contains(&format!(r#"name="sign_in" value="{method}""#)),
+ "{}",
+ choice.body
+ );
+ }
+ assert!(
+ choice.body.contains(&format!(r#"value="{client_id}""#)),
+ "{}",
+ choice.body
+ );
+ }
}
-/// Whatever the query holds is re-encoded before it reaches the page.
+/// Whatever the query holds is escaped before it reaches the page.
#[tokio::test]
async fn the_sign_in_choice_escapes_the_query() {
- let response = super::sign_in_choice(Some("state=%22%3E%3Cscript%3E&a=1".to_owned()));
+ let response = super::sign_in_choice(Some("state=%22%3E%3Cscript%3E&a=1"), false);
let csp = response.headers()[axum::http::header::CONTENT_SECURITY_POLICY]
.to_str()
.expect("the policy is ascii")
@@ -594,7 +612,344 @@ async fn the_sign_in_choice_escapes_the_query() {
.expect("page should read");
let page = String::from_utf8(body.to_vec()).expect("page is utf-8");
assert!(!page.contains("<script"), "{page}");
- assert!(page.contains("state=%22%3E%3Cscript%3E&amp;a=1"), "{page}");
+}
+
+/// A browser partway through an email sign-in: the cookie that started it, and
+/// the session and token its forms carry.
+struct EmailSignIn {
+ harness: Harness,
+ client_id: String,
+ cookie: String,
+ session: String,
+ form_token: String,
+}
+
+impl EmailSignIn {
+ async fn start(redirect_uri: &str) -> Self {
+ let harness = Harness::new();
+ let client_id = register_client(&harness, redirect_uri).await;
+ let authorize = send(
+ &harness,
+ get_page(
+ &unchosen_authorize_uri(&client_id, redirect_uri, "&sign_in=email"),
+ None,
+ ),
+ )
+ .await;
+ assert_eq!(authorize.status, StatusCode::TEMPORARY_REDIRECT);
+ let session = harness.inflight.only_pending_session_id();
+ assert_eq!(
+ authorize.location.as_deref(),
+ Some(format!("email-sign-in?session={session}").as_str()),
+ );
+ let cookie = cookie_pair(
+ &authorize
+ .set_cookie
+ .expect("the flow sets its binding cookie"),
+ );
+ let secret = cookie
+ .split_once('=')
+ .expect("cookie has a name and value")
+ .1;
+ let form_token = BrowserBinding::parse(secret)
+ .expect("cookie holds a binding")
+ .form_token();
+
+ Self {
+ harness,
+ client_id,
+ cookie,
+ session,
+ form_token,
+ }
+ }
+
+ fn form(&self, email: &str, code: Option<&str>) -> String {
+ let mut form = format!(
+ "session={}&form_token={}&email={}",
+ self.session,
+ self.form_token,
+ urlencoding::encode(email),
+ );
+ if let Some(code) = code {
+ form.push_str(&format!("&code={code}"));
+ }
+ form
+ }
+
+ async fn submit(&self, email: &str, code: Option<&str>) -> Response {
+ send(
+ &self.harness,
+ post_form("/email-sign-in", &self.cookie, self.form(email, code)),
+ )
+ .await
+ }
+}
+
+/// The whole email flow over HTTP: the page, a mistyped code that costs
+/// nothing, then a code that delivers a broker code the client can redeem.
+#[tokio::test]
+async fn email_sign_in_delivers_a_code_the_client_can_redeem() {
+ let flow = EmailSignIn::start(LOOPBACK_REDIRECT_URI).await;
+
+ let page = send(
+ &flow.harness,
+ get_page(
+ &format!("/email-sign-in?session={}", flow.session),
+ Some(&flow.cookie),
+ ),
+ )
+ .await;
+ assert_eq!(page.status, StatusCode::OK);
+ assert!(page.csp.is_some());
+
+ let sent = flow.submit(EMAIL_ADDRESS, None).await;
+ assert_eq!(sent.status, StatusCode::OK);
+ assert_eq!(flow.harness.email_codes.requested(), [EMAIL_ADDRESS]);
+
+ let wrong = flow.submit(EMAIL_ADDRESS, Some("000000")).await;
+ assert_eq!(wrong.status, StatusCode::OK);
+ assert!(
+ flow.harness.inflight.has_pending(),
+ "a mistyped code must not end the sign-in"
+ );
+
+ let signed_in = flow.submit(EMAIL_ADDRESS, Some(EMAIL_CODE)).await;
+ assert_eq!(signed_in.status, StatusCode::SEE_OTHER);
+ assert!(!flow.harness.inflight.has_pending());
+ let location = signed_in.location.expect("redirect has a location");
+ assert!(location.starts_with(LOOPBACK_REDIRECT_URI), "{location}");
+ let code = query_param(&location, "code").expect("redirect carries a code");
+
+ let token = send(
+ &flow.harness,
+ token_request(&format!(
+ "grant_type=authorization_code&code={code}&client_id={}&redirect_uri={}\
+ &code_verifier={VICTIM_CODE_VERIFIER}",
+ flow.client_id,
+ urlencoding::encode(LOOPBACK_REDIRECT_URI),
+ )),
+ )
+ .await;
+ assert_eq!(token.status, StatusCode::OK, "{}", token.body);
+ assert_eq!(token.json()["access_token"], UPSTREAM_ACCESS_TOKEN);
+ assert_eq!(token.json()["refresh_token"], UPSTREAM_REFRESH_TOKEN);
+}
+
+/// An address on a single sign-on domain goes to its provider, on the same
+/// session, so the upstream callback still finishes the flow.
+#[tokio::test]
+async fn email_sign_in_sends_a_single_sign_on_address_to_its_provider() {
+ let flow = EmailSignIn::start(LOOPBACK_REDIRECT_URI).await;
+
+ let redirect = flow.submit(SSO_EMAIL_ADDRESS, None).await;
+
+ assert_eq!(redirect.status, StatusCode::SEE_OTHER);
+ let location = redirect.location.expect("redirect has a location");
+ assert!(
+ location.starts_with("https://upstream.example/sso"),
+ "{location}"
+ );
+ assert!(flow.harness.inflight.has_pending());
+}
+
+/// Someone else's sign-in link does nothing in a browser that did not start
+/// it, whether the form is shown or submitted.
+#[tokio::test]
+async fn email_sign_in_refuses_a_browser_that_did_not_start_it() {
+ let flow = EmailSignIn::start(LOOPBACK_REDIRECT_URI).await;
+ let other = BrowserBinding::generate();
+ let other_cookie = format!("__Host-macro_mcp_oauth={}", other.as_str());
+
+ let page = send(
+ &flow.harness,
+ get_page(
+ &format!("/email-sign-in?session={}", flow.session),
+ Some(&other_cookie),
+ ),
+ )
+ .await;
+ assert_eq!(page.status, StatusCode::BAD_REQUEST);
+
+ // The other browser's own valid token gets it no further.
+ let submitted = send(
+ &flow.harness,
+ post_form(
+ "/email-sign-in",
+ &other_cookie,
+ format!(
+ "session={}&form_token={}&email={EMAIL_ADDRESS}&code={EMAIL_CODE}",
+ flow.session,
+ other.form_token(),
+ ),
+ ),
+ )
+ .await;
+ assert_eq!(submitted.status, StatusCode::BAD_REQUEST);
+ assert!(flow.harness.email_codes.requested().is_empty());
+ assert!(flow.harness.inflight.has_pending());
+ assert!(!flow.harness.inflight.holds_any_issued_code());
+}
+
+/// A form posted from another site is refused even with the right cookie.
+#[tokio::test]
+async fn email_sign_in_refuses_a_cross_site_post() {
+ let flow = EmailSignIn::start(LOOPBACK_REDIRECT_URI).await;
+ let mut request = post_form(
+ "/email-sign-in",
+ &flow.cookie,
+ flow.form(EMAIL_ADDRESS, None),
+ );
+ request.headers_mut().insert(
+ "sec-fetch-site",
+ "cross-site".parse().expect("header value"),
+ );
+
+ let response = send(&flow.harness, request).await;
+
+ assert_eq!(response.status, StatusCode::FORBIDDEN);
+ assert!(flow.harness.email_codes.requested().is_empty());
+}
+
+/// Only a loopback client's users are offered the link, since a browser-based
+/// client has no listener on another machine to reach.
+#[tokio::test]
+async fn only_loopback_clients_are_offered_manual_delivery() {
+ for (redirect_uri, offered) in [
+ (LOOPBACK_REDIRECT_URI, true),
+ (TRUSTED_REDIRECT_URI, false),
+ (GATEWAY_REDIRECT_URI, false),
+ ] {
+ let harness = Harness::new();
+ let client_id = register_client(&harness, redirect_uri).await;
+
+ let choice = send(
+ &harness,
+ get_page(&unchosen_authorize_uri(&client_id, redirect_uri, ""), None),
+ )
+ .await;
+
+ assert_eq!(
+ choice.body.contains(r#"name="delivery""#),
+ offered,
+ "{redirect_uri}"
+ );
+ }
+}
+
+/// A browser on another machine than the client: the user approves carrying
+/// the code, signs in, and is shown the callback URL instead of a redirect to a
+/// loopback address that is not theirs. The client can redeem what it carries.
+#[tokio::test]
+async fn manual_delivery_shows_the_callback_url_after_consent() {
+ let harness = Harness::new();
+ let client_id = register_client(&harness, LOOPBACK_REDIRECT_URI).await;
+
+ let consent = send(
+ &harness,
+ get_page(
+ &unchosen_authorize_uri(
+ &client_id,
+ LOOPBACK_REDIRECT_URI,
+ "&sign_in=google&delivery=manual",
+ ),
+ None,
+ ),
+ )
+ .await;
+ assert_eq!(consent.status, StatusCode::OK);
+ assert!(
+ !harness.inflight.has_pending(),
+ "nothing starts until the user approves"
+ );
+ assert!(
+ consent
+ .body
+ .contains(r#"<input type="hidden" name="delivery" value="manual" />"#),
+ "{}",
+ consent.body
+ );
+ let cookie = cookie_pair(
+ &consent
+ .set_cookie
+ .expect("the flow sets its binding cookie"),
+ );
+ let binding = BrowserBinding::parse(cookie.split_once('=').expect("cookie value").1)
+ .expect("cookie holds a binding");
+
+ let approved = send(
+ &harness,
+ post_form(
+ "/authorize",
+ &cookie,
+ format!(
+ "response_type=code&client_id={client_id}&redirect_uri={}&state=client-state\
+ &code_challenge={}&code_challenge_method=S256&sign_in=google&delivery=manual\
+ &consent_token={}&decision=approve",
+ urlencoding::encode(LOOPBACK_REDIRECT_URI),
+ code_challenge_for(VICTIM_CODE_VERIFIER),
+ binding.form_token(),
+ ),
+ ),
+ )
+ .await;
+ assert_eq!(approved.status, StatusCode::SEE_OTHER);
+
+ let session_id = harness.inflight.only_pending_session_id();
+ let page = send(&harness, callback_request(&session_id, Some(&cookie))).await;
+
+ assert_eq!(page.status, StatusCode::OK);
+ assert_eq!(page.location, None, "there is no redirect to follow");
+ assert!(page.csp.is_some());
+ let page_text = page.body.replace("&#38;", "&");
+ let shown = page_text
+ .split("curl '")
+ .nth(1)
+ .and_then(|command| command.split('\'').next())
+ .expect("the page shows a curl command");
+ assert!(shown.starts_with(LOOPBACK_REDIRECT_URI), "{shown}");
+ let code = query_param(shown, "code").expect("the command carries a code");
+ assert!(harness.inflight.holds_issued_code(&code), "{code}");
+}
+
+/// Manual delivery is refused where it makes no sense or is not safe to show:
+/// on an `https` client, and on a loopback URI that could break out of the
+/// quotes of the command the page tells the user to run.
+#[tokio::test]
+async fn manual_delivery_is_refused_outside_clean_loopback_uris() {
+ for redirect_uri in [
+ TRUSTED_REDIRECT_URI,
+ "http://127.0.0.1:51000/a';touch${IFS}x;'",
+ ] {
+ let harness = Harness::new();
+ let client_id = register_client(&harness, redirect_uri).await;
+
+ let refused = send(
+ &harness,
+ get_page(
+ &unchosen_authorize_uri(
+ &client_id,
+ redirect_uri,
+ "&sign_in=google&delivery=manual",
+ ),
+ None,
+ ),
+ )
+ .await;
+
+ assert_eq!(refused.status, StatusCode::BAD_REQUEST, "{redirect_uri}");
+ assert!(!harness.inflight.has_pending());
+
+ let choice = send(
+ &harness,
+ get_page(&unchosen_authorize_uri(&client_id, redirect_uri, ""), None),
+ )
+ .await;
+ assert!(
+ !choice.body.contains(r#"name="delivery""#),
+ "{redirect_uri}"
+ );
+ }
}
/// Loopback hosts are interchangeable for the policy but not for the
diff --git a/services/mcp_auth_proxy/src/inbound/sign_in_choice.html b/services/mcp_auth_proxy/src/inbound/sign_in_choice.html
deleted file mode 100644
index 1f7a79f2ad..0000000000
--- a/services/mcp_auth_proxy/src/inbound/sign_in_choice.html
+++ /dev/null
@@ -1,21 +0,0 @@
-<!doctype html>
-<html lang="en">
-<head>
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width, initial-scale=1">
-<title>Sign in to Macro</title>
-<style>
-body {{ font: 16px system-ui, sans-serif; display: grid; place-items: center; min-height: 100vh; margin: 0; }}
-main {{ width: 20rem; padding: 1rem; }}
-h1 {{ font-size: 1.25rem; font-weight: 600; }}
-a {{ display: block; padding: .75rem; margin-top: .75rem; border: 1px solid #8888; border-radius: .5rem; color: inherit; text-align: center; text-decoration: none; }}
-</style>
-</head>
-<body>
-<main>
-<h1>Sign in to Macro</h1>
-<a href="{google}">Continue with Google</a>
-<a href="{login}">Continue with email and password</a>
-</main>
-</body>
-</html>
diff --git a/services/mcp_auth_proxy/src/outbound.rs b/services/mcp_auth_proxy/src/outbound.rs
index 1bdbe7b7e6..0145911999 100644
--- a/services/mcp_auth_proxy/src/outbound.rs
+++ b/services/mcp_auth_proxy/src/outbound.rs
@@ -1,5 +1,7 @@
//! Outbound adapters for the MCP OAuth broker.
+/// Emailed sign-in codes through the authentication service.
+pub mod email_sign_in;
/// FusionAuth-backed upstream OAuth provider.
pub mod fusionauth;
/// Postgres-backed store for all broker state.
diff --git a/services/mcp_auth_proxy/src/outbound/email_sign_in.rs b/services/mcp_auth_proxy/src/outbound/email_sign_in.rs
new file mode 100644
index 0000000000..531b10b324
--- /dev/null
+++ b/services/mcp_auth_proxy/src/outbound/email_sign_in.rs
@@ -0,0 +1,191 @@
+//! Emailed sign-in codes, through the authentication service's public login
+//! endpoints.
+//!
+//! The authentication service owns this flow for the Macro app: its address
+//! checks, per-address rate limits, single sign-on routing, and signup policy all
+//! apply here without the broker repeating them. The limits count per address,
+//! so every sign-in arriving from this one caller does not share a budget.
+
+#[cfg(test)]
+mod test;
+
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+use anyhow::Context;
+use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
+use model::{
+ authentication::login::{request::PasswordlessRequest, response::SsoRequiredResponse},
+ response::UserTokensResponse,
+};
+use reqwest::{StatusCode, header::HeaderMap};
+use tracing::Instrument;
+use url::Url;
+
+use crate::domain::{
+ models::{EmailCodeRequest, UpstreamTokens},
+ ports::{EmailCodeError, EmailCodeProvider, EmailCodeRequestFuture, EmailCodeTokensFuture},
+};
+
+const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
+
+/// Emailed sign-in codes backed by the authentication service.
+#[derive(Clone)]
+pub struct AuthServiceEmailCodes {
+ client: reqwest::Client,
+ auth_service_url: Url,
+ redirect_uri: String,
+}
+
+impl AuthServiceEmailCodes {
+ /// Creates a provider calling the authentication service at
+ /// `auth_service_url`. `redirect_uri` fills the endpoint's required field;
+ /// redeeming with redirects disabled never sends a browser there.
+ pub fn new(auth_service_url: &str, redirect_uri: String) -> anyhow::Result<Self> {
+ let client = reqwest::Client::builder()
+ .timeout(REQUEST_TIMEOUT)
+ .build()
+ .context("failed to build authentication service client")?;
+ let auth_service_url =
+ Url::parse(auth_service_url).context("invalid authentication service URL")?;
+
+ Ok(Self {
+ client,
+ auth_service_url,
+ redirect_uri,
+ })
+ }
+
+ /// The service URL with `segments` appended to its path, which already
+ /// holds a gateway prefix outside local development.
+ fn endpoint(&self, segments: &[&str]) -> Result<Url, EmailCodeError> {
+ let mut url = self.auth_service_url.clone();
+ url.path_segments_mut()
+ .map_err(|()| {
+ EmailCodeError::Unavailable(anyhow::anyhow!(
+ "authentication service URL cannot be a base"
+ ))
+ })?
+ .pop_if_empty()
+ .extend(segments);
+ Ok(url)
+ }
+}
+
+fn trace_headers() -> HeaderMap {
+ let mut headers = HeaderMap::new();
+ macro_tower_layers::inject_trace_headers(&mut headers);
+ headers
+}
+
+fn unavailable(context: &'static str) -> impl FnOnce(reqwest::Error) -> EmailCodeError {
+ move |error| EmailCodeError::Unavailable(anyhow::Error::new(error).context(context))
+}
+
+/// Seconds until an access token expires, from its `exp` claim. The service
+/// issued it over this connection, so the signature is not what is in question;
+/// the endpoint simply does not report a lifetime.
+fn seconds_until_expiry(access_token: &str) -> anyhow::Result<u64> {
+ #[derive(serde::Deserialize)]
+ struct Claims {
+ exp: u64,
+ }
+
+ let payload = access_token
+ .split('.')
+ .nth(1)
+ .context("access token is not a JWT")?;
+ let payload = URL_SAFE_NO_PAD
+ .decode(payload)
+ .context("access token payload is not base64")?;
+ let claims: Claims =
+ serde_json::from_slice(&payload).context("access token payload has no expiry")?;
+ let now = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .context("system clock is before the epoch")?
+ .as_secs();
+
+ Ok(claims.exp.saturating_sub(now))
+}
+
+impl EmailCodeProvider for AuthServiceEmailCodes {
+ fn request_code<'a>(&'a self, email: &'a str) -> EmailCodeRequestFuture<'a> {
+ let span = tracing::debug_span!("mcp_oauth.email_code.request");
+ Box::pin(
+ async move {
+ let response = self
+ .client
+ .post(self.endpoint(&["login", "passwordless"])?)
+ .headers(trace_headers())
+ .json(&PasswordlessRequest {
+ email: email.to_owned(),
+ redirect_uri: self.redirect_uri.clone(),
+ referral_code: None,
+ is_agent: false,
+ })
+ .send()
+ .await
+ .map_err(unavailable("failed to call the authentication service"))?;
+
+ match response.status() {
+ StatusCode::OK => Ok(EmailCodeRequest::Sent),
+ StatusCode::ACCEPTED => {
+ let sso: SsoRequiredResponse = response
+ .json()
+ .await
+ .map_err(unavailable("failed to read the single sign-on response"))?;
+ Ok(EmailCodeRequest::SsoRequired { idp_id: sso.idp_id })
+ }
+ StatusCode::BAD_REQUEST => Err(EmailCodeError::InvalidEmail),
+ StatusCode::FORBIDDEN => Err(EmailCodeError::NotAllowed),
+ StatusCode::TOO_MANY_REQUESTS => Err(EmailCodeError::RateLimited),
+ status => Err(EmailCodeError::Unavailable(anyhow::anyhow!(
+ "authentication service answered {status} when sending a code"
+ ))),
+ }
+ }
+ .instrument(span),
+ )
+ }
+
+ fn redeem_code<'a>(&'a self, email: &'a str, code: &'a str) -> EmailCodeTokensFuture<'a> {
+ let span = tracing::debug_span!("mcp_oauth.email_code.redeem");
+ Box::pin(
+ async move {
+ let response = self
+ .client
+ .get(self.endpoint(&["oauth", "passwordless", code])?)
+ .query(&[("email", email), ("disable_redirect", "true")])
+ .headers(trace_headers())
+ .send()
+ .await
+ .map_err(unavailable("failed to call the authentication service"))?;
+
+ match response.status() {
+ StatusCode::OK => {}
+ StatusCode::BAD_REQUEST => return Err(EmailCodeError::InvalidEmail),
+ StatusCode::UNAUTHORIZED => return Err(EmailCodeError::InvalidCode),
+ StatusCode::TOO_MANY_REQUESTS => return Err(EmailCodeError::RateLimited),
+ status => {
+ return Err(EmailCodeError::Unavailable(anyhow::anyhow!(
+ "authentication service answered {status} when redeeming a code"
+ )));
+ }
+ }
+
+ let tokens: UserTokensResponse = response
+ .json()
+ .await
+ .map_err(unavailable("failed to read the sign-in tokens"))?;
+ let expires_in = seconds_until_expiry(&tokens.access_token)
+ .map_err(EmailCodeError::Unavailable)?;
+
+ Ok(UpstreamTokens {
+ access_token: tokens.access_token.into(),
+ refresh_token: tokens.refresh_token.into(),
+ expires_in,
+ })
+ }
+ .instrument(span),
+ )
+ }
+}
diff --git a/services/mcp_auth_proxy/src/outbound/email_sign_in/test.rs b/services/mcp_auth_proxy/src/outbound/email_sign_in/test.rs
new file mode 100644
index 0000000000..5e98996e5f
--- /dev/null
+++ b/services/mcp_auth_proxy/src/outbound/email_sign_in/test.rs
@@ -0,0 +1,136 @@
+//! Pins the contract with the authentication service's login endpoints.
+
+use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
+use wiremock::{
+ Mock, MockServer, ResponseTemplate,
+ matchers::{body_partial_json, method, path, query_param},
+};
+
+use super::AuthServiceEmailCodes;
+use crate::domain::{
+ models::EmailCodeRequest,
+ ports::{EmailCodeError, EmailCodeProvider},
+};
+
+const EMAIL: &str = "[email protected]";
+
+/// A server mounted under a path prefix, as the gateway serves the real one.
+async fn provider(server: &MockServer) -> AuthServiceEmailCodes {
+ AuthServiceEmailCodes::new(
+ &format!("{}/auth", server.uri()),
+ "https://mcp.macro.com/oauth/callback".to_owned(),
+ )
+ .expect("provider should build")
+}
+
+async fn answer_code_request(status: u16, body: serde_json::Value) -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("POST"))
+ .and(path("/auth/login/passwordless"))
+ .and(body_partial_json(serde_json::json!({
+ "email": EMAIL,
+ "redirect_uri": "https://mcp.macro.com/oauth/callback",
+ })))
+ .respond_with(ResponseTemplate::new(status).set_body_json(body))
+ .mount(&server)
+ .await;
+ server
+}
+
+async fn answer_redeem(status: u16, body: serde_json::Value) -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/auth/oauth/passwordless/123456"))
+ .and(query_param("email", EMAIL))
+ .and(query_param("disable_redirect", "true"))
+ .respond_with(ResponseTemplate::new(status).set_body_json(body))
+ .mount(&server)
+ .await;
+ server
+}
+
+#[tokio::test]
+async fn requesting_a_code_reports_it_sent() {
+ let server = answer_code_request(200, serde_json::json!({})).await;
+
+ let answer = provider(&server).await.request_code(EMAIL).await;
+
+ assert_eq!(answer.expect("code request"), EmailCodeRequest::Sent);
+}
+
+#[tokio::test]
+async fn requesting_a_code_reports_the_single_sign_on_an_address_needs() {
+ let server = answer_code_request(202, serde_json::json!({ "idp_id": "idp-1" })).await;
+
+ let answer = provider(&server).await.request_code(EMAIL).await;
+
+ assert_eq!(
+ answer.expect("code request"),
+ EmailCodeRequest::SsoRequired {
+ idp_id: "idp-1".to_owned()
+ }
+ );
+}
+
+#[tokio::test]
+async fn requesting_a_code_maps_each_refusal() {
+ for (status, expected) in [
+ (400, "invalid email address"),
+ (403, "email address may not sign in"),
+ (429, "too many attempts"),
+ (500, "email sign-in is unavailable"),
+ ] {
+ let server = answer_code_request(status, serde_json::json!({})).await;
+
+ let error = provider(&server)
+ .await
+ .request_code(EMAIL)
+ .await
+ .expect_err("the request should be refused");
+
+ assert_eq!(error.to_string(), expected, "status {status}");
+ }
+}
+
+#[tokio::test]
+async fn redeeming_a_code_returns_tokens_and_their_remaining_lifetime() {
+ let exp = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .expect("clock")
+ .as_secs()
+ + 3600;
+ let payload = URL_SAFE_NO_PAD.encode(serde_json::json!({ "exp": exp }).to_string());
+ let access_token = format!("header.{payload}.signature");
+ let server = answer_redeem(
+ 200,
+ serde_json::json!({ "access_token": access_token, "refresh_token": "refresh" }),
+ )
+ .await;
+
+ let tokens = provider(&server)
+ .await
+ .redeem_code(EMAIL, "123456")
+ .await
+ .expect("code should redeem");
+
+ assert_eq!(tokens.access_token.as_str(), access_token);
+ assert_eq!(tokens.refresh_token.as_str(), "refresh");
+ assert!(
+ (3590..=3600).contains(&tokens.expires_in),
+ "expires_in {}",
+ tokens.expires_in
+ );
+}
+
+#[tokio::test]
+async fn redeeming_a_wrong_code_is_reported_as_such() {
+ let server = answer_redeem(401, serde_json::json!({})).await;
+
+ let error = provider(&server)
+ .await
+ .redeem_code(EMAIL, "123456")
+ .await
+ .expect_err("the code should be refused");
+
+ assert!(matches!(error, EmailCodeError::InvalidCode), "{error:?}");
+}
diff --git a/services/mcp_auth_proxy/src/outbound/fusionauth.rs b/services/mcp_auth_proxy/src/outbound/fusionauth.rs
index 02f1d8de75..ace059a002 100644
--- a/services/mcp_auth_proxy/src/outbound/fusionauth.rs
+++ b/services/mcp_auth_proxy/src/outbound/fusionauth.rs
@@ -10,7 +10,7 @@ use tracing::Instrument;
use upstream_error::UpstreamFailure;
use crate::domain::{
- models::{RefreshToken, SignInMethod, UpstreamTokens},
+ models::{RefreshToken, UpstreamLogin, UpstreamTokens},
ports::{OAuthProvider, UpstreamGrantError, UpstreamRevocationFuture, UpstreamTokensFuture},
};
@@ -60,21 +60,26 @@ fn grant_error(error: FusionAuthClientError) -> UpstreamGrantError {
}
impl OAuthProvider for FusionAuthOAuthProvider {
- #[tracing::instrument(skip(self), err)]
+ #[tracing::instrument(skip_all, err)]
fn construct_authorize_url(
&self,
state: &str,
- sign_in: SignInMethod,
+ login: UpstreamLogin<'_>,
) -> anyhow::Result<String> {
- match sign_in {
- SignInMethod::Google => self.client.construct_oauth2_authorize_url(
+ match login {
+ UpstreamLogin::Google => self.client.construct_oauth2_authorize_url(
&self.google_idp_id,
None,
Some(state.to_owned()),
),
- SignInMethod::Login => self
+ UpstreamLogin::LoginPage => self
.client
.construct_oauth2_login_page_url(Some(state.to_owned())),
+ UpstreamLogin::Sso { idp_id, email } => self.client.construct_oauth2_authorize_url(
+ idp_id,
+ Some(email),
+ Some(state.to_owned()),
+ ),
}
}
diff --git a/services/mcp_auth_proxy/src/outbound/postgres.rs b/services/mcp_auth_proxy/src/outbound/postgres.rs
index bbda73f548..9d1761fd30 100644
--- a/services/mcp_auth_proxy/src/outbound/postgres.rs
+++ b/services/mcp_auth_proxy/src/outbound/postgres.rs
@@ -29,7 +29,7 @@ use zeroize::Zeroizing;
use crate::domain::{
models::{
- AccessToken, IssuedAuthorizationCode, PendingAuthorization, RefreshToken,
+ AccessToken, CodeDelivery, IssuedAuthorizationCode, PendingAuthorization, RefreshToken,
RefreshTokenBinding, RegisteredClient,
},
ports::{
@@ -160,6 +160,14 @@ fn encryption_context(code_digest: &str, client_id: &str) -> HashMap<String, Str
])
}
+fn delivery_from_column(deliver_manually: bool) -> CodeDelivery {
+ if deliver_manually {
+ CodeDelivery::Manual
+ } else {
+ CodeDelivery::Redirect
+ }
+}
+
#[derive(serde::Serialize, serde::Deserialize)]
struct CodeTokens {
access_token: AccessToken,
@@ -322,8 +330,8 @@ impl InflightAuthStore for PostgresAuthStore {
r#"
INSERT INTO mcp_oauth_pending_authorizations
(session_id, client_id, code_challenge, client_state, client_redirect_uri,
- browser_binding_digest, expires_at)
- VALUES ($1, $2, $3, $4, $5, $6, $7)
+ browser_binding_digest, deliver_manually, expires_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
"#,
session_id,
pending.client_id,
@@ -331,6 +339,7 @@ impl InflightAuthStore for PostgresAuthStore {
pending.client_state,
pending.client_redirect_uri,
pending.browser_binding_digest,
+ pending.delivery == CodeDelivery::Manual,
expires_at(PENDING_AUTH_TTL)?,
)
.execute(&self.pool)
@@ -339,6 +348,29 @@ impl InflightAuthStore for PostgresAuthStore {
Ok(())
}
+ async fn find_pending(&self, session_id: &str) -> anyhow::Result<Option<PendingAuthorization>> {
+ let row = sqlx::query!(
+ r#"
+ SELECT client_id, code_challenge, client_state, client_redirect_uri,
+ browser_binding_digest, deliver_manually
+ FROM mcp_oauth_pending_authorizations
+ WHERE session_id = $1 AND expires_at > now()
+ "#,
+ session_id,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .context("failed to read pending authorization")?;
+ Ok(row.map(|row| PendingAuthorization {
+ client_id: row.client_id,
+ code_challenge: row.code_challenge,
+ client_state: row.client_state,
+ client_redirect_uri: row.client_redirect_uri,
+ browser_binding_digest: row.browser_binding_digest,
+ delivery: delivery_from_column(row.deliver_manually),
+ }))
+ }
+
async fn take_pending(&self, session_id: &str) -> anyhow::Result<Option<PendingAuthorization>> {
// DELETE ... RETURNING consumes the row atomically, so a session
// completes at most once even when callbacks race.
@@ -347,7 +379,7 @@ impl InflightAuthStore for PostgresAuthStore {
DELETE FROM mcp_oauth_pending_authorizations
WHERE session_id = $1
RETURNING client_id, code_challenge, client_state, client_redirect_uri,
- browser_binding_digest, expires_at
+ browser_binding_digest, deliver_manually, expires_at
"#,
session_id,
)
@@ -362,6 +394,7 @@ impl InflightAuthStore for PostgresAuthStore {
client_state: row.client_state,
client_redirect_uri: row.client_redirect_uri,
browser_binding_digest: row.browser_binding_digest,
+ delivery: delivery_from_column(row.deliver_manually),
}))
}
diff --git a/services/mcp_auth_proxy/src/outbound/postgres/test.rs b/services/mcp_auth_proxy/src/outbound/postgres/test.rs
index cc03f176e2..23bf088867 100644
--- a/services/mcp_auth_proxy/src/outbound/postgres/test.rs
+++ b/services/mcp_auth_proxy/src/outbound/postgres/test.rs
@@ -175,17 +175,26 @@ async fn a_pending_authorization_is_taken_once(pool: PgPool) {
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()),
+ delivery: CodeDelivery::Manual,
},
)
.await
.expect("insert");
+ let found = store
+ .find_pending("session")
+ .await
+ .expect("find")
+ .expect("reading a flow leaves it pending");
+ assert_eq!(found.delivery, CodeDelivery::Manual);
+
let pending = store
.take_pending("session")
.await
.expect("take")
.expect("pending");
assert_eq!(pending.client_state, "state");
+ assert_eq!(pending.delivery, CodeDelivery::Manual);
assert_eq!(
pending.browser_binding_digest.as_deref(),
Some("binding-digest")
diff --git a/services/mcp_auth_proxy/src/outbound/redis.rs b/services/mcp_auth_proxy/src/outbound/redis.rs
index 6b4cb97f8e..7797de618d 100644
--- a/services/mcp_auth_proxy/src/outbound/redis.rs
+++ b/services/mcp_auth_proxy/src/outbound/redis.rs
@@ -12,7 +12,8 @@ use std::{
use crate::domain::{
models::{
- IssuedAuthorizationCode, PendingAuthorization, RefreshTokenBinding, RegisteredClient,
+ CodeDelivery, IssuedAuthorizationCode, PendingAuthorization, RefreshTokenBinding,
+ RegisteredClient,
},
ports::{
ClientRegistrationStore, GrantRevokedFuture, RefreshTokenBindingFuture,
@@ -385,6 +386,8 @@ struct StoredPendingAuthorization {
client_redirect_uri: String,
#[serde(default)]
browser_binding_digest: Option<String>,
+ #[serde(default)]
+ deliver_manually: bool,
}
impl From<PendingAuthorization> for StoredPendingAuthorization {
@@ -395,6 +398,7 @@ impl From<PendingAuthorization> for StoredPendingAuthorization {
client_state: value.client_state,
client_redirect_uri: value.client_redirect_uri,
browser_binding_digest: value.browser_binding_digest,
+ deliver_manually: value.delivery == CodeDelivery::Manual,
}
}
}
@@ -407,6 +411,11 @@ impl From<StoredPendingAuthorization> for PendingAuthorization {
client_state: value.client_state,
client_redirect_uri: value.client_redirect_uri,
browser_binding_digest: value.browser_binding_digest,
+ delivery: if value.deliver_manually {
+ CodeDelivery::Manual
+ } else {
+ CodeDelivery::Redirect
+ },
}
}
}
@@ -478,6 +487,32 @@ impl InflightAuthStore for RedisInflightAuth {
}
}
+ fn find_pending(
+ &self,
+ session_id: &str,
+ ) -> impl Future<Output = anyhow::Result<Option<PendingAuthorization>>> + Send {
+ let client = self.client.clone();
+ let key = Self::pending_key(session_id);
+ async move {
+ let mut conn = client
+ .get_multiplexed_async_connection()
+ .await
+ .context("unable to connect to redis")?;
+ let value: Option<String> = redis::cmd("GET")
+ .arg(&key)
+ .query_async(&mut conn)
+ .await
+ .with_context(|| format!("failed to read pending authorization for key {key}"))?;
+ value
+ .map(|json| {
+ serde_json::from_str::<StoredPendingAuthorization>(&json)
+ .map(PendingAuthorization::from)
+ .context("failed to deserialize pending authorization")
+ })
+ .transpose()
+ }
+ }
+
fn take_pending(
&self,
session_id: &str,
diff --git a/services/mcp_auth_proxy/src/outbound/redis/test.rs b/services/mcp_auth_proxy/src/outbound/redis/test.rs
index d9927e05a7..c03b2632b4 100644
--- a/services/mcp_auth_proxy/src/outbound/redis/test.rs
+++ b/services/mcp_auth_proxy/src/outbound/redis/test.rs
@@ -211,6 +211,7 @@ async fn handshake_state_round_trips_with_its_client_id() {
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()),
+ delivery: crate::domain::models::CodeDelivery::Redirect,
},
)
.await
diff --git a/services/mcp_auth_proxy/src/outbound/redis_cutover.rs b/services/mcp_auth_proxy/src/outbound/redis_cutover.rs
index d1ab710543..1063d07b28 100644
--- a/services/mcp_auth_proxy/src/outbound/redis_cutover.rs
+++ b/services/mcp_auth_proxy/src/outbound/redis_cutover.rs
@@ -226,6 +226,12 @@ where
self.postgres.insert_pending(session_id, pending).await
}
+ /// Postgres only: the flows that need this are email sign-ins, which no
+ /// build ever wrote to Redis.
+ async fn find_pending(&self, session_id: &str) -> anyhow::Result<Option<PendingAuthorization>> {
+ self.postgres.find_pending(session_id).await
+ }
+
async fn take_pending(&self, session_id: &str) -> anyhow::Result<Option<PendingAuthorization>> {
if let Some(pending) = self.postgres.take_pending(session_id).await? {
return Ok(Some(pending));
diff --git a/services/mcp_auth_proxy/src/outbound/redis_cutover/test.rs b/services/mcp_auth_proxy/src/outbound/redis_cutover/test.rs
index c4b0f3a52b..aa52335594 100644
--- a/services/mcp_auth_proxy/src/outbound/redis_cutover/test.rs
+++ b/services/mcp_auth_proxy/src/outbound/redis_cutover/test.rs
@@ -102,6 +102,10 @@ impl InflightAuthStore for BrokenLegacy {
broken()
}
+ async fn find_pending(&self, _: &str) -> anyhow::Result<Option<PendingAuthorization>> {
+ broken()
+ }
+
async fn take_pending(&self, _: &str) -> anyhow::Result<Option<PendingAuthorization>> {
broken()
}
diff --git a/services/mcp_auth_proxy/src/test_support.rs b/services/mcp_auth_proxy/src/test_support.rs
index f7e9ef65f8..fd7a57ed31 100644
--- a/services/mcp_auth_proxy/src/test_support.rs
+++ b/services/mcp_auth_proxy/src/test_support.rs
@@ -14,11 +14,12 @@ use crate::domain::{
browser_binding::BrowserBinding,
models::{
AccessToken, AuthorizeRequest, CallbackRequest, ClientRegistrationRequest,
- IssuedAuthorizationCode, PendingAuthorization, RefreshToken, RefreshTokenBinding,
- RegisteredClient, SignInMethod, UpstreamTokens, UserConsent,
+ EmailCodeRequest, IssuedAuthorizationCode, PendingAuthorization, RefreshToken,
+ RefreshTokenBinding, RegisteredClient, UpstreamLogin, UpstreamTokens, UserConsent,
},
ports::{
- ClientRegistrationStore, GrantRevokedFuture, OAuthProvider, RefreshTokenBindingFuture,
+ ClientRegistrationStore, EmailCodeError, EmailCodeProvider, EmailCodeRequestFuture,
+ EmailCodeTokensFuture, GrantRevokedFuture, OAuthProvider, RefreshTokenBindingFuture,
RefreshTokenBindingStore, RegisteredClientFuture, StoreWriteFuture, UpstreamGrantError,
UpstreamRevocationFuture, UpstreamTokensFuture,
},
@@ -50,6 +51,12 @@ pub const REFRESHED_ACCESS_TOKEN: &str = "refreshed-access-token";
/// Upstream access token lifetime the fake provider reports, matching the one
/// hour JWT FusionAuth issues.
pub const UPSTREAM_EXPIRES_IN: u64 = 3600;
+/// An address the fake email provider sends codes to.
+pub const EMAIL_ADDRESS: &str = "[email protected]";
+/// An address whose domain the fake email provider routes to single sign-on.
+pub const SSO_EMAIL_ADDRESS: &str = "[email protected]";
+/// The only code the fake email provider accepts.
+pub const EMAIL_CODE: &str = "123456";
/// Computes the S256 challenge for a PKCE verifier.
pub fn code_challenge_for(verifier: &str) -> String {
@@ -113,6 +120,15 @@ impl InflightAuthStore for FakeInflightAuth {
Ok(())
}
+ async fn find_pending(&self, session_id: &str) -> anyhow::Result<Option<PendingAuthorization>> {
+ Ok(self
+ .pending
+ .lock()
+ .expect("pending lock")
+ .get(session_id)
+ .cloned())
+ }
+
async fn take_pending(&self, session_id: &str) -> anyhow::Result<Option<PendingAuthorization>> {
Ok(self
.pending
@@ -293,11 +309,12 @@ impl OAuthProvider for FakeOAuthProvider {
fn construct_authorize_url(
&self,
state: &str,
- sign_in: SignInMethod,
+ login: UpstreamLogin<'_>,
) -> anyhow::Result<String> {
- let page = match sign_in {
- SignInMethod::Google => "authorize",
- SignInMethod::Login => "login",
+ let page = match login {
+ UpstreamLogin::Google => "authorize",
+ UpstreamLogin::LoginPage => "login",
+ UpstreamLogin::Sso { .. } => "sso",
};
Ok(format!("https://upstream.example/{page}?state={state}"))
}
@@ -359,6 +376,51 @@ impl OAuthProvider for FakeOAuthProvider {
}
}
+/// Email provider that sends codes to one address and accepts one code,
+/// standing in for the authentication service.
+#[derive(Default)]
+pub struct FakeEmailCodes {
+ requested: Mutex<Vec<String>>,
+}
+
+impl FakeEmailCodes {
+ /// The addresses a code was requested for.
+ pub fn requested(&self) -> Vec<String> {
+ self.requested.lock().expect("requested lock").clone()
+ }
+}
+
+impl EmailCodeProvider for FakeEmailCodes {
+ fn request_code<'a>(&'a self, email: &'a str) -> EmailCodeRequestFuture<'a> {
+ Box::pin(async move {
+ self.requested
+ .lock()
+ .expect("requested lock")
+ .push(email.to_owned());
+ match email {
+ EMAIL_ADDRESS => Ok(EmailCodeRequest::Sent),
+ SSO_EMAIL_ADDRESS => Ok(EmailCodeRequest::SsoRequired {
+ idp_id: "idp-1".to_owned(),
+ }),
+ _ => Err(EmailCodeError::NotAllowed),
+ }
+ })
+ }
+
+ fn redeem_code<'a>(&'a self, _email: &'a str, code: &'a str) -> EmailCodeTokensFuture<'a> {
+ Box::pin(async move {
+ if code != EMAIL_CODE {
+ return Err(EmailCodeError::InvalidCode);
+ }
+ Ok(UpstreamTokens {
+ access_token: AccessToken::from(UPSTREAM_ACCESS_TOKEN),
+ refresh_token: RefreshToken::from(UPSTREAM_REFRESH_TOKEN),
+ expires_in: UPSTREAM_EXPIRES_IN,
+ })
+ })
+ }
+}
+
/// A broker service wired to in-memory stores, trusting only `claude.ai` for
/// `https` redirect URIs.
pub struct Harness {
@@ -370,6 +432,8 @@ pub struct Harness {
pub registry: Arc<FakeClientRegistry>,
/// The upstream provider the service was built with.
pub provider: Arc<FakeOAuthProvider>,
+ /// The email code provider the service was built with.
+ pub email_codes: Arc<FakeEmailCodes>,
/// The secret cookie of the browser the tests drive flows from.
pub browser: BrowserBinding,
}
@@ -385,6 +449,7 @@ impl Harness {
let inflight = Arc::new(FakeInflightAuth::default());
let registry = Arc::new(FakeClientRegistry::default());
let provider = Arc::new(provider);
+ let email_codes = Arc::new(FakeEmailCodes::default());
let service = McpAuthProxyServiceImpl::new(McpAuthProxyServiceDeps {
public_url: "https://mcp.macro.com".to_owned(),
redirect_uri_policy: RedirectUriPolicy::new(["claude.ai", "chatgpt.com"]),
@@ -392,6 +457,7 @@ impl Harness {
client_registrations: Arc::clone(&registry) as Arc<dyn ClientRegistrationStore>,
refresh_token_bindings: Arc::clone(&registry) as Arc<dyn RefreshTokenBindingStore>,
oauth_provider: Arc::clone(&provider) as Arc<dyn OAuthProvider>,
+ email_codes: Arc::clone(&email_codes) as Arc<dyn EmailCodeProvider>,
});
Self {
@@ -399,6 +465,7 @@ impl Harness {
inflight,
registry,
provider,
+ email_codes,
browser: BrowserBinding::generate(),
}
}
@@ -430,6 +497,7 @@ impl Harness {
code_challenge: code_challenge.to_owned(),
code_challenge_method: "S256".to_owned(),
sign_in: None,
+ delivery: None,
scope: None,
}
}
@@ -452,7 +520,7 @@ impl Harness {
.expect("authorize should succeed");
let session_id = self.inflight.only_pending_session_id();
- let redirect = self
+ let delivery = self
.service
.complete_callback(
CallbackRequest {
@@ -466,7 +534,7 @@ impl Harness {
.await
.expect("callback should succeed");
- query_param(&redirect, "code").expect("redirect carries a code")
+ query_param(&delivery.url, "code").expect("redirect carries a code")
}
}
diff --git a/services/mcp_auth_proxy/templates/broker_page.css b/services/mcp_auth_proxy/templates/broker_page.css
new file mode 100644
index 0000000000..2f895102a7
--- /dev/null
+++ b/services/mcp_auth_proxy/templates/broker_page.css
@@ -0,0 +1,119 @@
+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;
+}
+.stack {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ margin-top: 24px;
+}
+label {
+ display: block;
+ margin-bottom: 6px;
+ font-size: 14px;
+ font-weight: 600;
+}
+.option {
+ display: flex;
+ gap: 8px;
+ margin: 20px 0 0;
+ font-weight: 400;
+ line-height: 1.5;
+}
+input[type="email"],
+input[type="text"] {
+ box-sizing: border-box;
+ width: 100%;
+ padding: 10px 12px;
+ border: 1px solid #d6d3d1;
+ border-radius: 6px;
+ font: inherit;
+ font-size: 15px;
+}
+.copy {
+ 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: 13px;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ user-select: all;
+}
+code {
+ font-family: ui-monospace, "SF Mono", Menlo, monospace;
+ font-size: 13px;
+}
diff --git a/services/mcp_auth_proxy/templates/consent.html b/services/mcp_auth_proxy/templates/consent.html
index 723fe90691..d47a35d904 100644
--- a/services/mcp_auth_proxy/templates/consent.html
+++ b/services/mcp_auth_proxy/templates/consent.html
@@ -6,97 +6,31 @@
<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;
- }
+ {% include "broker_page.css" %}
</style>
</head>
<body>
<main>
<h1>Allow “{{ client_name }}” to access your Macro account?</h1>
+ {% if manual_delivery %}
+ <p>
+ If you allow it, Macro will sign you in and show you a link that gives
+ access to your account, to use in the app on your other machine.
+ </p>
+ {% else %}
<p>
If you allow it, Macro will sign you in and send access to your account
to:
</p>
<p class="destination">{{ redirect_host }}</p>
+ {% endif %}
<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
+ yourself{% if !manual_delivery %} and you recognize the address above{% endif %}. The name
“{{ client_name }}” is provided by the app and is not verified by
Macro.
</p>
@@ -113,6 +47,9 @@
{% if let Some(sign_in) = request.sign_in %}
<input type="hidden" name="sign_in" value="{{ sign_in }}" />
{% endif %}
+ {% if let Some(delivery) = request.delivery %}
+ <input type="hidden" name="delivery" value="{{ delivery }}" />
+ {% endif %}
<input type="hidden" name="consent_token" value="{{ consent_token }}" />
<div class="actions">
<button class="deny" type="submit" name="decision" value="deny">Cancel</button>
diff --git a/services/mcp_auth_proxy/templates/email_sign_in.html b/services/mcp_auth_proxy/templates/email_sign_in.html
new file mode 100644
index 0000000000..4fda652bb7
--- /dev/null
+++ b/services/mcp_auth_proxy/templates/email_sign_in.html
@@ -0,0 +1,56 @@
+<!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>Sign in to Macro</title>
+ <style>
+ {% include "broker_page.css" %}
+ </style>
+ </head>
+ <body>
+ <main>
+ {% if let Some(email) = code_sent_to %}
+ <h1>Check your email</h1>
+ <p>Enter the code we sent to <strong>{{ email }}</strong>.</p>
+ {% if let Some(error) = error %}
+ <p class="warning" role="alert">{{ error }}</p>
+ {% endif %}
+ <form method="post" action="email-sign-in">
+ <input type="hidden" name="session" value="{{ session }}" />
+ <input type="hidden" name="form_token" value="{{ form_token }}" />
+ <input type="hidden" name="email" value="{{ email }}" />
+ <label for="code">Code</label>
+ <input id="code" name="code" type="text" inputmode="numeric" autocomplete="one-time-code" required autofocus />
+ <div class="stack">
+ <button class="approve" type="submit">Continue</button>
+ </div>
+ </form>
+ <form method="post" action="email-sign-in">
+ <input type="hidden" name="session" value="{{ session }}" />
+ <input type="hidden" name="form_token" value="{{ form_token }}" />
+ <input type="hidden" name="email" value="{{ email }}" />
+ <div class="stack">
+ <button class="deny" type="submit">Send a new code</button>
+ </div>
+ </form>
+ {% else %}
+ <h1>Sign in with email</h1>
+ <p>We'll send a code to your email address.</p>
+ {% if let Some(error) = error %}
+ <p class="warning" role="alert">{{ error }}</p>
+ {% endif %}
+ <form method="post" action="email-sign-in">
+ <input type="hidden" name="session" value="{{ session }}" />
+ <input type="hidden" name="form_token" value="{{ form_token }}" />
+ <label for="email">Email</label>
+ <input id="email" name="email" type="email" autocomplete="email" required autofocus />
+ <div class="stack">
+ <button class="approve" type="submit">Send code</button>
+ </div>
+ </form>
+ {% endif %}
+ </main>
+ </body>
+</html>
diff --git a/services/mcp_auth_proxy/templates/manual_delivery.html b/services/mcp_auth_proxy/templates/manual_delivery.html
new file mode 100644
index 0000000000..b7b8e11112
--- /dev/null
+++ b/services/mcp_auth_proxy/templates/manual_delivery.html
@@ -0,0 +1,29 @@
+<!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>Finish connecting to Macro</title>
+ <style>
+ {% include "broker_page.css" %}
+ </style>
+ </head>
+ <body>
+ <main>
+ <h1>Finish connecting on your other machine</h1>
+ <p>
+ If the app is asking you to paste a URL, such as
+ <code>claude mcp login --no-browser</code>, paste this:
+ </p>
+ <pre class="copy">{{ url }}</pre>
+ <p>Otherwise, run this on the machine where the app is running, while it waits:</p>
+ <pre class="copy">curl '{{ url }}'</pre>
+ <p class="warning">
+ This link is how the app gets access to your Macro account. Use it only
+ in an app you just started connecting yourself, and never give it to
+ anyone else. It expires in 5 minutes.
+ </p>
+ </main>
+ </body>
+</html>
diff --git a/services/mcp_auth_proxy/templates/sign_in_choice.html b/services/mcp_auth_proxy/templates/sign_in_choice.html
new file mode 100644
index 0000000000..b9bec5ff55
--- /dev/null
+++ b/services/mcp_auth_proxy/templates/sign_in_choice.html
@@ -0,0 +1,36 @@
+<!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>Sign in to Macro</title>
+ <style>
+ {% include "broker_page.css" %}
+ </style>
+ </head>
+ <body>
+ <main>
+ <h1>Sign in to Macro</h1>
+ <form method="get" action="authorize">
+ {% for (name, value) in params %}
+ <input type="hidden" name="{{ name }}" value="{{ value }}" />
+ {% endfor %}
+ <div class="stack">
+ <button class="approve" type="submit" name="sign_in" value="google">Continue with Google</button>
+ <button class="deny" type="submit" name="sign_in" value="email">Continue with email</button>
+ <button class="deny" type="submit" name="sign_in" value="login">Continue with a password</button>
+ </div>
+ {% if offers_manual_delivery %}
+ <label class="option">
+ <input type="checkbox" name="delivery" value="manual" />
+ <span>
+ The app I'm connecting runs on another machine, such as over SSH or
+ in a container. Give me a link to finish there.
+ </span>
+ </label>
+ {% endif %}
+ </form>
+ </main>
+ </body>
+</html>