Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(auth): validate original url in redirect (#5568)
Will Hutchinsonb67694378a38
diff --git a/services/authentication_service/src/api/login/sso.rs b/services/authentication_service/src/api/login/sso.rsindex 40cc1d401a..bc763c3f9f 100644--- a/services/authentication_service/src/api/login/sso.rs+++ b/services/authentication_service/src/api/login/sso.rs@@ -35,7 +35,7 @@ pub(crate) struct LoginQueryParams {referral_code: Option<String>,}-fn is_allowed_original_url(url: &Url) -> bool {+pub(crate) fn is_allowed_original_url(url: &Url) -> bool {match url.scheme() {// The app owns the custom scheme and handles all macro URI routes itself."macro" => true,@@ -49,6 +49,20 @@ fn is_allowed_original_url(url: &Url) -> bool {}}+/// Strips the userinfo, query, and fragment from an `original_url` so it is+/// safe to log — all are client-controlled and may carry credentials, tokens,+/// or PII. The path is kept because it distinguishes e.g. macro://login from+/// macro:///login.+pub(crate) fn redact_original_url_for_logging(url: &Url) -> Url {+ let mut redacted_url = url.clone();+ redacted_url.set_query(None);+ redacted_url.set_fragment(None);+ // These only fail for cannot-be-a-base URLs, which carry no userinfo.+ let _ = redacted_url.set_username("");+ let _ = redacted_url.set_password(None);+ redacted_url+}+/// Initiates an SSO login#[utoipa::path(get,@@ -89,12 +103,7 @@ pub async fn handler(.as_ref().filter(|url| !is_allowed_original_url(url)){- // Log scheme://host/path only — the query and fragment are- // client-controlled and may carry tokens or PII. The path is kept- // because it distinguishes e.g. macro://login from macro:///login.- let mut redacted_url = url.clone();- redacted_url.set_query(None);- redacted_url.set_fragment(None);+ let redacted_url = redact_original_url_for_logging(url);tracing::error!(auth_handoff_failure = "original_url_rejected",original_url = %redacted_url,diff --git a/services/authentication_service/src/api/login/sso/tests.rs b/services/authentication_service/src/api/login/sso/tests.rsindex 123e5eed7f..199af73e5f 100644--- a/services/authentication_service/src/api/login/sso/tests.rs+++ b/services/authentication_service/src/api/login/sso/tests.rs@@ -49,6 +49,22 @@ fn untrusted_original_urls_are_rejected() {}}+#[test]+fn redacted_url_strips_credentials_query_and_fragment_but_keeps_path() {+ let url =+ Url::parse("https://alice:[email protected]/app/login?token=abc123#access_token=xyz")+ .expect("test URL should parse");+ let redacted = redact_original_url_for_logging(&url);+ assert_eq!(redacted.as_str(), "https://evil.example.com/app/login");+}++#[test]+fn redacted_url_handles_cannot_be_a_base_urls() {+ let url = Url::parse("mailto:[email protected]?subject=hi").expect("test URL should parse");+ let redacted = redact_original_url_for_logging(&url);+ assert_eq!(redacted.as_str(), "mailto:[email protected]");+}+#[tokio::test]async fn it_works_with_no_params() {let request = Request::builder()diff --git a/services/authentication_service/src/api/oauth/oauth_redirect.rs b/services/authentication_service/src/api/oauth/oauth_redirect.rsindex 4a541c9c29..1f0d2130f5 100644--- a/services/authentication_service/src/api/oauth/oauth_redirect.rs+++ b/services/authentication_service/src/api/oauth/oauth_redirect.rs@@ -1,6 +1,6 @@use crate::api::{context::ApiContext,- login::sso::SsoState,+ login::sso::{SsoState, is_allowed_original_url, redact_original_url_for_logging},utils::{append_signed_up_param_if_new_user, create_access_token_cookie,create_refresh_token_cookie, default_redirect_url, generate_session_code,@@ -187,6 +187,8 @@ enum InnerErr {MacroCacheErr(anyhow::Error),#[error("Failed to parse url {0}")]ParseErr(#[from] url::ParseError),+ #[error("original_url is not allowed")]+ DisallowedOriginalUrl,}impl IntoResponse for InnerErr {@@ -221,6 +223,14 @@ impl IntoResponse for InnerErr {}),).into_response(),++ InnerErr::DisallowedOriginalUrl => (+ StatusCode::BAD_REQUEST,+ Json(ErrorResponse {+ message: "provided original_url is not allowed".into(),+ }),+ )+ .into_response(),}}}@@ -245,6 +255,23 @@ async fn get_redirect_url(return Ok(default_redirect_url());};+ // The state round-trips through the identity provider as a client-visible+ // query param, so re-validate original_url here — /login/sso checking it+ // on the way in does not prevent a forged state on the way back.+ if let Some(url) = state+ .original_url+ .as_ref()+ .filter(|url| !is_allowed_original_url(url))+ {+ let redacted_url = redact_original_url_for_logging(url);+ tracing::error!(+ auth_handoff_failure = "original_url_rejected",+ original_url = %redacted_url,+ "original_url in oauth state is not allowed"+ );+ return Err(InnerErr::DisallowedOriginalUrl);+ }+// Generate the session code if necessarylet session_code = state.is_mobile.then(generate_session_code).map(SessionCode);let res = update_url_with_session_code(diff --git a/services/authentication_service/src/api/oauth/oauth_redirect/tests.rs b/services/authentication_service/src/api/oauth/oauth_redirect/tests.rsindex a1782ed3bc..6558be5118 100644--- a/services/authentication_service/src/api/oauth/oauth_redirect/tests.rs+++ b/services/authentication_service/src/api/oauth/oauth_redirect/tests.rs@@ -104,7 +104,7 @@ async fn it_writes_session_code_to_db() {let mut dummy = DummyCb::default();let res = get_redirect_url(&Some(SsoState {- original_url: Some("https://example.com".parse().unwrap()),+ original_url: Some("https://macro.com".parse().unwrap()),is_mobile: true,referral_code: None,}),@@ -113,7 +113,7 @@ async fn it_writes_session_code_to_db() {.await.unwrap();assert_eq!(dummy.called, 1);- assert_eq!(res.domain(), Some("example.com"));+ assert_eq!(res.domain(), Some("macro.com"));assert_eq!(res.scheme(), "https");let query = res.query_pairs();let p = query.collect::<Vec<_>>();@@ -124,6 +124,39 @@ async fn it_writes_session_code_to_db() {);}+#[tokio::test]+async fn it_rejects_disallowed_original_url_without_side_effects() {+ let mut dummy = DummyCb::default();+ let res = get_redirect_url(+ &Some(SsoState {+ original_url: Some("https://evil.example.com/phish".parse().unwrap()),+ is_mobile: true,+ referral_code: None,+ }),+ async |x| dummy.cb(x).await,+ )+ .await;+ assert_eq!(dummy.called, 0, "must not mint a session code");+ assert_matches!(res, Err(InnerErr::DisallowedOriginalUrl));+}++#[tokio::test]+async fn it_allows_macro_scheme_original_url() {+ let mut dummy = DummyCb::default();+ let res = get_redirect_url(+ &Some(SsoState {+ original_url: Some("macro://login".parse().unwrap()),+ is_mobile: false,+ referral_code: None,+ }),+ async |x| dummy.cb(x).await,+ )+ .await+ .unwrap();+ assert_eq!(dummy.called, 0);+ assert_eq!(res.as_str(), "macro://login");+}+#[tokio::test]async fn update_url_replaces_existing_token_and_preserves_other_params() {let url: Url = "https://example.com?token=old_token&other=param"