Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(mcp): let ChatGPT users pick how to sign in (#9514)

Eric Hayesdd8d3c468261
diff --git a/crates/fusionauth/src/lib.rs b/crates/fusionauth/src/lib.rs
index df4d11b488..8341f02a77 100644
--- a/crates/fusionauth/src/lib.rs
+++ b/crates/fusionauth/src/lib.rs
@@ -150,6 +150,27 @@ impl FusionAuthClient {
login_hint: Option<&str>,
state: Option<T>,
) -> anyhow::Result<String>
+ where
+ T: serde::Serialize + std::fmt::Debug + 'static,
+ {
+ self.oauth2_authorize_url(Some(idp_id), login_hint, state)
+ }
+
+ /// The authorize URL with no identity provider picked, which lands on
+ /// FusionAuth's own login page (password and every provider).
+ pub fn construct_oauth2_login_page_url<T>(&self, state: Option<T>) -> anyhow::Result<String>
+ where
+ T: serde::Serialize + std::fmt::Debug + 'static,
+ {
+ self.oauth2_authorize_url(None, None, state)
+ }
+
+ fn oauth2_authorize_url<T>(
+ &self,
+ idp_id: Option<&str>,
+ login_hint: Option<&str>,
+ state: Option<T>,
+ ) -> anyhow::Result<String>
where
T: serde::Serialize + std::fmt::Debug + 'static,
{
@@ -159,11 +180,14 @@ impl FusionAuthClient {
url.query_pairs_mut()
.append_pair("client_id", &self.client_id)
.append_pair("redirect_uri", &self.oauth_redirect_uri)
- .append_pair("idp_hint", idp_id)
.append_pair("response_type", "code")
.append_pair("scope", "openid profile email offline_access")
.append_pair("access_type", "offline"); // Explicitly request offline access
+ if let Some(idp_id) = idp_id {
+ url.query_pairs_mut().append_pair("idp_hint", idp_id);
+ }
+
if let Some(state) = state {
tracing::trace!(state=?state, "state provided");
let state_str = serde_json::to_string(&state)
diff --git a/services/mcp_auth_proxy/README.md b/services/mcp_auth_proxy/README.md
index 20a9753cf0..4a9612f179 100644
--- a/services/mcp_auth_proxy/README.md
+++ b/services/mcp_auth_proxy/README.md
@@ -28,6 +28,15 @@ with `Referrer-Policy: no-referrer`, so FusionAuth sees no client origin and
third-party clients need no entry in the FusionAuth origin list. Whether a
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.
+
## Which redirect URIs are usable
Dynamic client registration is open, because MCP clients require it. That means
diff --git a/services/mcp_auth_proxy/src/domain/models.rs b/services/mcp_auth_proxy/src/domain/models.rs
index e55eabbfd9..9b3418817d 100644
--- a/services/mcp_auth_proxy/src/domain/models.rs
+++ b/services/mcp_auth_proxy/src/domain/models.rs
@@ -182,6 +182,17 @@ pub struct IssuedAuthorizationCode {
pub access_token_expires_at: SystemTime,
}
+/// How a user signs in upstream during an authorize flow.
+#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum SignInMethod {
+ /// Straight to Google, the default for every client.
+ #[default]
+ Google,
+ /// FusionAuth's login page: password and every other provider.
+ Login,
+}
+
/// OAuth authorize request from the MCP client.
#[derive(Deserialize)]
pub struct AuthorizeRequest {
@@ -197,6 +208,9 @@ pub struct AuthorizeRequest {
pub code_challenge: String,
/// Expected to be `S256`.
pub code_challenge_method: String,
+ /// The sign-in the user picked on the chooser, when it was shown.
+ #[serde(default)]
+ pub sign_in: Option<SignInMethod>,
/// Optional requested scopes.
#[serde(default)]
#[allow(dead_code)]
diff --git a/services/mcp_auth_proxy/src/domain/ports.rs b/services/mcp_auth_proxy/src/domain/ports.rs
index 052b92d76c..ce2c64a2da 100644
--- a/services/mcp_auth_proxy/src/domain/ports.rs
+++ b/services/mcp_auth_proxy/src/domain/ports.rs
@@ -2,7 +2,9 @@
use std::{future::Future, pin::Pin};
-use super::models::{RefreshToken, RefreshTokenBinding, RegisteredClient, UpstreamTokens};
+use super::models::{
+ RefreshToken, RefreshTokenBinding, RegisteredClient, SignInMethod, UpstreamTokens,
+};
/// Boxed future returning a token grant from the upstream provider.
pub type UpstreamTokensFuture<'a> =
@@ -74,7 +76,8 @@ 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) -> anyhow::Result<String>;
+ fn construct_authorize_url(&self, state: &str, sign_in: SignInMethod)
+ -> anyhow::Result<String>;
/// Exchanges an upstream authorization code for tokens.
fn exchange_authorization_code<'a>(&'a self, code: &'a str) -> UpstreamTokensFuture<'a>;
diff --git a/services/mcp_auth_proxy/src/domain/service.rs b/services/mcp_auth_proxy/src/domain/service.rs
index 2d069d356c..10d040c30b 100644
--- a/services/mcp_auth_proxy/src/domain/service.rs
+++ b/services/mcp_auth_proxy/src/domain/service.rs
@@ -496,6 +496,7 @@ 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");
service
@@ -514,7 +515,7 @@ where
service
.oauth_provider
- .construct_authorize_url(&session_id)
+ .construct_authorize_url(&session_id, sign_in)
.map_err(StartAuthorizationError::ConstructAuthorizeUrl)
}
}
diff --git a/services/mcp_auth_proxy/src/inbound/axum_router.rs b/services/mcp_auth_proxy/src/inbound/axum_router.rs
index f6b8f377be..04660c5ee4 100644
--- a/services/mcp_auth_proxy/src/inbound/axum_router.rs
+++ b/services/mcp_auth_proxy/src/inbound/axum_router.rs
@@ -7,10 +7,10 @@ use std::time::Duration;
use axum::{
Router,
- extract::{Query, State},
+ extract::{Query, RawQuery, State},
http::{HeaderName, Method, header},
middleware as axum_mw,
- response::{IntoResponse, Json, Redirect, Response},
+ response::{Html, IntoResponse, Json, Redirect, Response},
routing,
};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
@@ -84,10 +84,59 @@ async fn register<I: InflightAuthStore + 'static>(
}
}
+/// 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),
+ )
+ .into_response()
+}
+
async fn authorize<I: InflightAuthStore + 'static>(
State(auth_proxy): State<McpAuthProxyServiceImpl<I>>,
+ RawQuery(query): RawQuery,
Query(params): Query<AuthorizeRequest>,
) -> Response {
+ if params.sign_in.is_none() && offers_sign_in_choice(&params.redirect_uri) {
+ return sign_in_choice(query);
+ }
match auth_proxy.start_authorization(params).await {
// The browser carries the MCP client page's Referer across this
// redirect, and FusionAuth rejects any Referer outside its first-party
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 a679ef5cdb..6ad3e5bfc1 100644
--- a/services/mcp_auth_proxy/src/inbound/axum_router/test.rs
+++ b/services/mcp_auth_proxy/src/inbound/axum_router/test.rs
@@ -201,6 +201,75 @@ 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.
+#[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();
+
+ 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);
+ 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}"
+ );
+}
+
+/// Whatever the query holds is re-encoded 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 csp = response.headers()[axum::http::header::CONTENT_SECURITY_POLICY]
+ .to_str()
+ .expect("the policy is ascii")
+ .to_owned();
+ assert!(csp.contains("default-src 'none'"), "{csp}");
+ let body = axum::body::to_bytes(response.into_body(), 64 * 1024)
+ .await
+ .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}");
+}
+
/// Loopback hosts are interchangeable for the policy but not for the
/// registration: a client registered on `localhost` cannot have its code sent
/// to `127.0.0.1`.
diff --git a/services/mcp_auth_proxy/src/inbound/sign_in_choice.html b/services/mcp_auth_proxy/src/inbound/sign_in_choice.html
new file mode 100644
index 0000000000..1f7a79f2ad
--- /dev/null
+++ b/services/mcp_auth_proxy/src/inbound/sign_in_choice.html
@@ -0,0 +1,21 @@
+<!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/fusionauth.rs b/services/mcp_auth_proxy/src/outbound/fusionauth.rs
index d8d16d5071..4db317b90e 100644
--- a/services/mcp_auth_proxy/src/outbound/fusionauth.rs
+++ b/services/mcp_auth_proxy/src/outbound/fusionauth.rs
@@ -5,7 +5,7 @@ use std::sync::Arc;
use tracing::Instrument;
use crate::domain::{
- models::{RefreshToken, UpstreamTokens},
+ models::{RefreshToken, SignInMethod, UpstreamTokens},
ports::{OAuthProvider, UpstreamRevocationFuture, UpstreamTokensFuture},
};
@@ -35,12 +35,21 @@ impl FusionAuthOAuthProvider {
impl OAuthProvider for FusionAuthOAuthProvider {
#[tracing::instrument(skip(self), err)]
- fn construct_authorize_url(&self, state: &str) -> anyhow::Result<String> {
- self.client.construct_oauth2_authorize_url(
- &self.google_idp_id,
- None,
- Some(state.to_owned()),
- )
+ fn construct_authorize_url(
+ &self,
+ state: &str,
+ sign_in: SignInMethod,
+ ) -> anyhow::Result<String> {
+ match sign_in {
+ SignInMethod::Google => self.client.construct_oauth2_authorize_url(
+ &self.google_idp_id,
+ None,
+ Some(state.to_owned()),
+ ),
+ SignInMethod::Login => self
+ .client
+ .construct_oauth2_login_page_url(Some(state.to_owned())),
+ }
}
fn exchange_authorization_code<'a>(&'a self, code: &'a str) -> UpstreamTokensFuture<'a> {
diff --git a/services/mcp_auth_proxy/src/test_support.rs b/services/mcp_auth_proxy/src/test_support.rs
index 14928be6eb..13a3d48f5f 100644
--- a/services/mcp_auth_proxy/src/test_support.rs
+++ b/services/mcp_auth_proxy/src/test_support.rs
@@ -14,7 +14,7 @@ use crate::domain::{
models::{
AccessToken, AuthorizeRequest, CallbackRequest, ClientRegistrationRequest,
IssuedAuthorizationCode, PendingAuthorization, RefreshToken, RefreshTokenBinding,
- RegisteredClient, UpstreamTokens,
+ RegisteredClient, SignInMethod, UpstreamTokens,
},
ports::{
ClientRegistrationStore, GrantRevokedFuture, OAuthProvider, RefreshTokenBindingFuture,
@@ -255,8 +255,16 @@ impl FakeOAuthProvider {
}
impl OAuthProvider for FakeOAuthProvider {
- fn construct_authorize_url(&self, state: &str) -> anyhow::Result<String> {
- Ok(format!("https://upstream.example/authorize?state={state}"))
+ fn construct_authorize_url(
+ &self,
+ state: &str,
+ sign_in: SignInMethod,
+ ) -> anyhow::Result<String> {
+ let page = match sign_in {
+ SignInMethod::Google => "authorize",
+ SignInMethod::Login => "login",
+ };
+ Ok(format!("https://upstream.example/{page}?state={state}"))
}
fn exchange_authorization_code<'a>(&'a self, _code: &'a str) -> UpstreamTokensFuture<'a> {
@@ -334,7 +342,7 @@ impl Harness {
let provider = Arc::new(provider);
let service = McpAuthProxyServiceImpl::new(McpAuthProxyServiceDeps {
public_url: "https://mcp.macro.com".to_owned(),
- redirect_uri_policy: RedirectUriPolicy::new(["claude.ai"]),
+ redirect_uri_policy: RedirectUriPolicy::new(["claude.ai", "chatgpt.com"]),
inflight_auth: Arc::clone(&inflight),
client_registrations: Arc::clone(&registry) as Arc<dyn ClientRegistrationStore>,
refresh_token_bindings: Arc::clone(&registry) as Arc<dyn RefreshTokenBindingStore>,
@@ -375,6 +383,7 @@ impl Harness {
state: "client-state".to_owned(),
code_challenge: code_challenge.to_owned(),
code_challenge_method: "S256".to_owned(),
+ sign_in: None,
scope: None,
}
}