Skip to content

armgit / macro

Public Imported from GitHub
0

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

fix(link): sign link state (#7720)

Will Hutchinsondfd6741b4194
diff --git a/Cargo.lock b/Cargo.lock
index 0123649723..344ea537b2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1958,6 +1958,7 @@ dependencies = [
"github",
"github_pull_requests",
"gtm_invite",
+ "hmac 0.12.1",
"http-body-util",
"initiative",
"jsonwebtoken 10.3.0",
@@ -2010,6 +2011,7 @@ dependencies = [
"serde_utils",
"ses_client",
"sha1 0.10.6",
+ "sha2 0.10.9",
"sqlx",
"sqs_client",
"strum 0.27.2",
diff --git a/crates/fusionauth/src/microsoft.rs b/crates/fusionauth/src/microsoft.rs
index 9eb6e79e00..a3e3a1375e 100644
--- a/crates/fusionauth/src/microsoft.rs
+++ b/crates/fusionauth/src/microsoft.rs
@@ -46,14 +46,14 @@ impl FusionAuthClient {
}
/// Constructs a tenant-specific Microsoft OAuth authorization URL.
- pub fn construct_microsoft_authorize_url<T>(
+ ///
+ /// `state` is the opaque, already-encoded value the callback expects
+ /// back; it is placed in the URL as-is.
+ pub fn construct_microsoft_authorize_url(
&self,
redirect_uri: &str,
- state: &T,
- ) -> Result<String>
- where
- T: serde::Serialize + ?Sized,
- {
+ state: &str,
+ ) -> Result<String> {
let credentials = self.microsoft_credentials()?;
oauth::construct_authorize_url(
&credentials.client_id,
diff --git a/crates/fusionauth/src/microsoft/oauth.rs b/crates/fusionauth/src/microsoft/oauth.rs
index 8930166a31..99347ae9a6 100644
--- a/crates/fusionauth/src/microsoft/oauth.rs
+++ b/crates/fusionauth/src/microsoft/oauth.rs
@@ -78,25 +78,20 @@ pub struct MicrosoftUserInfo {
pub email: String,
}
-pub(crate) fn construct_authorize_url<T>(
+pub(crate) fn construct_authorize_url(
client_id: &str,
tenant_id: &str,
redirect_uri: &str,
- state: &T,
-) -> anyhow::Result<String>
-where
- T: serde::Serialize + ?Sized,
-{
+ state: &str,
+) -> anyhow::Result<String> {
let mut url = endpoint_url(tenant_id, "authorize")?;
- let serialized_state =
- serde_json::to_string(state).context("failed to serialize Microsoft OAuth state")?;
url.query_pairs_mut()
.append_pair("client_id", client_id)
.append_pair("redirect_uri", redirect_uri)
.append_pair("response_type", "code")
.append_pair("scope", MICROSOFT_SCOPES)
- .append_pair("state", &serialized_state)
+ .append_pair("state", state)
.append_pair("prompt", "select_account");
Ok(url.to_string())
diff --git a/crates/fusionauth/src/microsoft/test.rs b/crates/fusionauth/src/microsoft/test.rs
index 8eef8a7f26..fdbb3e8ea2 100644
--- a/crates/fusionauth/src/microsoft/test.rs
+++ b/crates/fusionauth/src/microsoft/test.rs
@@ -2,7 +2,6 @@ use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
-use serde::{Deserialize, Serialize};
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
@@ -146,7 +145,7 @@ fn authorize_url_uses_configured_tenant_and_secondary_account_parameters() {
let url = microsoft_client()
.construct_microsoft_authorize_url(
"https://auth.example.com/oauth2/microsoft/callback",
- &"state",
+ "state",
)
.unwrap();
let url = reqwest::Url::parse(&url).unwrap();
@@ -169,34 +168,23 @@ fn authorize_url_uses_configured_tenant_and_secondary_account_parameters() {
assert_eq!(query.get("prompt").unwrap(), "select_account");
}
-#[derive(Debug, Deserialize, Eq, PartialEq, Serialize)]
-struct TestState {
- identity_provider_id: String,
- link_id: String,
-}
-
#[test]
-fn authorize_url_serializes_state_as_json() {
- let state = TestState {
- identity_provider_id: "identity-provider-id".into(),
- link_id: "link-id".into(),
- };
+fn authorize_url_carries_state_through_unchanged() {
+ // Callers hand over an already-signed token; it must round-trip byte for byte.
+ let state = "eyJwcm92aWRlciI6Im1pY3Jvc29mdCJ9.c2lnbmF0dXJl+/=&?";
let url = microsoft_client()
.construct_microsoft_authorize_url(
"https://auth.example.com/oauth2/microsoft/callback",
- &state,
+ state,
)
.unwrap();
let url = reqwest::Url::parse(&url).unwrap();
- let serialized_state = url
+ let returned_state = url
.query_pairs()
.find_map(|(key, value)| (key == "state").then(|| value.into_owned()))
.unwrap();
- assert_eq!(
- serde_json::from_str::<TestState>(&serialized_state).unwrap(),
- state
- );
+ assert_eq!(returned_state, state);
}
#[test]
@@ -204,7 +192,7 @@ fn microsoft_oauth_configuration_is_optional_and_secret_is_redacted() {
let error = client()
.construct_microsoft_authorize_url(
"https://auth.example.com/oauth2/microsoft/callback",
- &"state",
+ "state",
)
.unwrap_err();
assert!(matches!(
@@ -218,7 +206,7 @@ fn microsoft_oauth_configuration_is_optional_and_secret_is_redacted() {
cloned_client
.construct_microsoft_authorize_url(
"https://auth.example.com/oauth2/microsoft/callback",
- &"state",
+ "state",
)
.unwrap();
}
diff --git a/crates/github/src/domain/ports/link.rs b/crates/github/src/domain/ports/link.rs
index f634812c5c..c33e118a22 100644
--- a/crates/github/src/domain/ports/link.rs
+++ b/crates/github/src/domain/ports/link.rs
@@ -68,12 +68,15 @@ pub trait GithubOauth: Send + Sync + 'static {
/// The error type returned by repository operations.
type Err: Into<anyhow::Error> + Send + std::fmt::Debug;
- /// Constructs the oauth url to authenticate with github
- fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(
+ /// Constructs the oauth url to authenticate with github.
+ ///
+ /// `state` is the opaque, already-encoded value the callback expects
+ /// back; it is placed in the URL as-is.
+ fn construct_oauth_url(
&self,
client_id: &str,
redirect_uri: &str,
- state: T,
+ state: &str,
) -> Result<String, Self::Err>;
/// Exchanges the oauth code for tokens
@@ -163,12 +166,11 @@ pub trait Auth: Send + Sync + 'static {
///
/// Handles OAuth URL construction and user account linking.
pub trait GithubLinkService: Send + Sync + 'static {
- /// Constructs the oauth url to authenticate with github
- fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(
- &self,
- redirect_uri: &str,
- state: T,
- ) -> Result<String, GithubError>;
+ /// Constructs the oauth url to authenticate with github.
+ ///
+ /// `state` is the opaque, already-encoded value the callback expects
+ /// back; it is placed in the URL as-is.
+ fn construct_oauth_url(&self, redirect_uri: &str, state: &str) -> Result<String, GithubError>;
/// Uses token exchange to link the user to the github account
fn link_user(
diff --git a/crates/github/src/domain/service/link.rs b/crates/github/src/domain/service/link.rs
index 3d158fbbf1..55b08ab07e 100644
--- a/crates/github/src/domain/service/link.rs
+++ b/crates/github/src/domain/service/link.rs
@@ -195,11 +195,7 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth, E: GithubPullRequestService> Github
for GithubLinkServiceImpl<R, U, F, E>
{
#[tracing::instrument(skip(self), err)]
- fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(
- &self,
- redirect_uri: &str,
- state: T,
- ) -> Result<String, GithubError> {
+ fn construct_oauth_url(&self, redirect_uri: &str, state: &str) -> Result<String, GithubError> {
self.oauth
.construct_oauth_url(&self.config.client_id, redirect_uri, state)
.map_err(|e| GithubError::Internal(e.into()))
diff --git a/crates/github/src/domain/service/link_test.rs b/crates/github/src/domain/service/link_test.rs
index 34d3fa7dd6..833fc1d86e 100644
--- a/crates/github/src/domain/service/link_test.rs
+++ b/crates/github/src/domain/service/link_test.rs
@@ -299,11 +299,11 @@ fn default_pull_request_details() -> GithubPullRequestDetails {
impl GithubOauth for StubGithubOauth {
type Err = anyhow::Error;
- fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(
+ fn construct_oauth_url(
&self,
_client_id: &str,
_redirect_uri: &str,
- _state: T,
+ _state: &str,
) -> Result<String, Self::Err> {
Ok("https://github.example/oauth".to_string())
}
diff --git a/crates/github/src/outbound/github_oauth_client.rs b/crates/github/src/outbound/github_oauth_client.rs
index 44d51f9a1c..5c872fd5c7 100644
--- a/crates/github/src/outbound/github_oauth_client.rs
+++ b/crates/github/src/outbound/github_oauth_client.rs
@@ -86,20 +86,18 @@ impl GithubOauth for GithubOauthImpl {
type Err = anyhow::Error;
#[tracing::instrument(skip(self), err)]
- fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(
+ fn construct_oauth_url(
&self,
client_id: &str,
redirect_uri: &str,
- state: T,
+ state: &str,
) -> Result<String, Self::Err> {
- let state_str = serde_json::to_string(&state)?;
-
let url = format!(
"https://github.com/login/oauth/authorize?client_id={}&redirect_uri={}&scope={}&state={}",
client_id,
urlencoding::encode(redirect_uri),
urlencoding::encode("repo user:email"),
- urlencoding::encode(&state_str)
+ urlencoding::encode(state)
);
Ok(url)
diff --git a/docs/RUNNING_LOCALLY.md b/docs/RUNNING_LOCALLY.md
index cd978520e2..a1ab0c2f99 100644
--- a/docs/RUNNING_LOCALLY.md
+++ b/docs/RUNNING_LOCALLY.md
@@ -218,7 +218,7 @@ A `--no-doppler` stack boots with deterministic stubs for every value the servic
| Stripe billing | `STRIPE_SECRET_KEY`, `STRIPE_PRICE_ID` | Checkout and subscription endpoints fail. Signup still works: the create-user webhook detects the stub key and skips the real Stripe call. It stores a placeholder customer id instead. |
| CloudFront signed URLs | `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_DISTRIBUTION_URL`, `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PUBLIC_KEY_ID`, `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY` | Document download URLs are unsigned (fine against local S3) |
-The other stubbed keys (`REDIS_HOST`, `MACRO_DB_URL`, `INTERNAL_API_KEY`, `AUTHENTICATION_SERVICE_SECRET_KEY`, `OPENSEARCH_USERNAME`, `OPENSEARCH_PASSWORD`) are internal plumbing with correct local values — you never need to override them.
+The other stubbed keys (`REDIS_HOST`, `MACRO_DB_URL`, `INTERNAL_API_KEY`, `AUTHENTICATION_SERVICE_SECRET_KEY`, `ACCOUNT_LINK_STATE_SECRET`, `OPENSEARCH_USERNAME`, `OPENSEARCH_PASSWORD`) are internal plumbing with correct local values — you never need to override them.
To turn on an integration, create a `local.env` with the real values. Then pass it
to `run_local`:
diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.toml
index 46594e5497..ea46d231fa 100644
--- a/services/authentication_service/Cargo.toml
+++ b/services/authentication_service/Cargo.toml
@@ -93,6 +93,7 @@ github_pull_requests = { path = "../../crates/github_pull_requests", default-fea
"outbound",
"service",
] }
+hmac = { workspace = true }
http-body-util = { workspace = true }
jsonwebtoken = { workspace = true }
last_online_tracker = { path = "../../crates/last_online_tracker" }
@@ -157,6 +158,7 @@ serde_json = { workspace = true }
serde_utils = { path = "../../crates/serde_utils", features = ["urlencode"] }
ses_client = { path = "../../crates/ses_client" }
sha1 = "0.10.6"
+sha2 = { workspace = true }
sqlx = { workspace = true }
sqs_client = { path = "../../crates/sqs_client", default-features = false, features = [
"email",
diff --git a/services/authentication_service/src/account_link_state.rs b/services/authentication_service/src/account_link_state.rs
new file mode 100644
index 0000000000..363ff64e6e
--- /dev/null
+++ b/services/authentication_service/src/account_link_state.rs
@@ -0,0 +1,230 @@
+//! Signed, expiring OAuth `state` for account-link flows.
+//!
+//! `/link/gmail`, `/link/github`, and `/link/outlook` send the browser to a
+//! provider's consent screen with a `state` parameter that comes back, as
+//! sent, to `/oauth2/{provider}/callback`. The callback uses it to find the
+//! pending `in_progress_user_link` row and to decide where to redirect, so a
+//! forged `state` could point another user's consent at an attacker's pending
+//! link or redirect the browser elsewhere. The state is therefore signed, and
+//! the callback refuses anything it cannot verify.
+//!
+//! The token is `base64url(payload).base64url(signature)`, without padding,
+//! where the signature is HMAC-SHA256 over the encoded payload. This mirrors
+//! the GitHub App installation state in the `github` crate.
+
+use std::sync::Arc;
+
+use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
+use hmac::{Hmac, Mac};
+use serde::{Deserialize, Serialize};
+use sha2::Sha256;
+use uuid::Uuid;
+use zeroize::Zeroizing;
+
+#[cfg(test)]
+mod test;
+
+type HmacSha256 = Hmac<Sha256>;
+
+/// How long a signed state stays valid. Consent takes minutes, and a pending
+/// link is only kept for a day, so an hour leaves room for a slow user without
+/// letting a leaked authorization URL stay live indefinitely.
+pub(crate) const ACCOUNT_LINK_STATE_TTL: chrono::Duration = chrono::Duration::hours(1);
+
+/// HMAC-SHA256 keys shorter than the digest weaken the construction (RFC 2104
+/// recommends at least the output length).
+const MIN_SECRET_LENGTH: usize = 32;
+
+/// The callback a state was issued for. The same path segment the callback
+/// router receives, so a state issued for one provider cannot complete
+/// another's callback.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub(crate) enum LinkProvider {
+ /// Gmail (and Google Calendar) linking.
+ Google,
+ /// GitHub account linking.
+ Github,
+ /// Microsoft Outlook linking.
+ Microsoft,
+}
+
+impl LinkProvider {
+ /// The `{provider}` segment of `/oauth2/{provider}/callback`.
+ pub(crate) fn as_str(self) -> &'static str {
+ match self {
+ Self::Google => "google",
+ Self::Github => "github",
+ Self::Microsoft => "microsoft",
+ }
+ }
+}
+
+impl std::fmt::Display for LinkProvider {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(self.as_str())
+ }
+}
+
+/// Authenticated context carried through an account-link OAuth flow.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub(crate) struct AccountLinkState {
+ /// Which callback may complete this state.
+ pub provider: LinkProvider,
+ /// The FusionAuth identity provider that will hold the resulting grant.
+ pub identity_provider_id: String,
+ /// The pending `in_progress_user_link` row this consent completes.
+ pub link_id: Uuid,
+ /// The FusionAuth user who began the link. The callback refuses to
+ /// complete a link whose pending row belongs to anyone else.
+ pub fusion_user_id: Uuid,
+ /// Where to send the browser once the link completes.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub original_url: Option<String>,
+ /// Expiration time in Unix seconds.
+ pub exp: i64,
+}
+
+impl AccountLinkState {
+ /// A state for a link that `fusion_user_id` just began, expiring
+ /// [`ACCOUNT_LINK_STATE_TTL`] from now.
+ pub(crate) fn new(
+ provider: LinkProvider,
+ identity_provider_id: String,
+ link_id: Uuid,
+ fusion_user_id: Uuid,
+ original_url: Option<String>,
+ ) -> Self {
+ Self {
+ provider,
+ identity_provider_id,
+ link_id,
+ fusion_user_id,
+ original_url,
+ exp: (chrono::Utc::now() + ACCOUNT_LINK_STATE_TTL).timestamp(),
+ }
+ }
+}
+
+/// An error encountered while signing or verifying account-link state.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
+pub(crate) enum AccountLinkStateError {
+ /// The payload could not be serialized.
+ #[error("account-link state payload could not be serialized")]
+ Serialization,
+ /// The token does not have the expected encoding or payload shape.
+ #[error("account-link state token is malformed")]
+ Malformed,
+ /// The token's signature is invalid.
+ #[error("account-link state signature is invalid")]
+ InvalidSignature,
+ /// The token is authentic but has reached its expiration time. Carries
+ /// the pending link it named so the caller can release that row.
+ #[error("account-link state token has expired")]
+ Expired {
+ /// The pending link the expired state was issued for.
+ link_id: Uuid,
+ },
+}
+
+/// The HMAC key that signs account-link state. Never printed.
+#[derive(Clone)]
+pub(crate) struct AccountLinkStateKey(Arc<Zeroizing<Vec<u8>>>);
+
+impl AccountLinkStateKey {
+ /// Wraps the configured secret.
+ ///
+ /// # Errors
+ /// If the secret is blank or shorter than 32 bytes. A short key is a
+ /// configuration mistake the service should refuse at startup.
+ pub(crate) fn new(secret: &str) -> anyhow::Result<Self> {
+ let secret = secret.trim();
+ if secret.len() < MIN_SECRET_LENGTH {
+ anyhow::bail!(
+ "ACCOUNT_LINK_STATE_SECRET must be at least {MIN_SECRET_LENGTH} bytes of random data"
+ );
+ }
+ Ok(Self(Arc::new(Zeroizing::new(secret.as_bytes().to_vec()))))
+ }
+
+ fn as_bytes(&self) -> &[u8] {
+ &self.0
+ }
+}
+
+impl std::fmt::Debug for AccountLinkStateKey {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("AccountLinkStateKey(<redacted>)")
+ }
+}
+
+/// Serialize and sign an account-link state.
+pub(crate) fn sign_account_link_state(
+ state: &AccountLinkState,
+ key: &AccountLinkStateKey,
+) -> Result<String, AccountLinkStateError> {
+ let json = serde_json::to_vec(state).map_err(|_| AccountLinkStateError::Serialization)?;
+ let encoded_payload = URL_SAFE_NO_PAD.encode(json);
+ let signature = signature_for(encoded_payload.as_bytes(), key);
+
+ Ok(format!(
+ "{encoded_payload}.{}",
+ URL_SAFE_NO_PAD.encode(signature)
+ ))
+}
+
+/// Verify and deserialize an account-link state token.
+///
+/// `current_timestamp` is expressed in Unix seconds. A token is expired when
+/// the current timestamp is equal to or later than its `exp` value. The
+/// signature is checked before the payload is decoded, so nothing in a
+/// rejected token is ever interpreted.
+pub(crate) fn verify_account_link_state(
+ token: &str,
+ key: &AccountLinkStateKey,
+ current_timestamp: i64,
+) -> Result<AccountLinkState, AccountLinkStateError> {
+ let (encoded_payload, encoded_signature) = split_token(token)?;
+ let signature = URL_SAFE_NO_PAD
+ .decode(encoded_signature)
+ .map_err(|_| AccountLinkStateError::Malformed)?;
+
+ let mut verifier =
+ HmacSha256::new_from_slice(key.as_bytes()).expect("HMAC-SHA256 accepts keys of any length");
+ verifier.update(encoded_payload.as_bytes());
+ verifier
+ .verify_slice(&signature)
+ .map_err(|_| AccountLinkStateError::InvalidSignature)?;
+
+ let json = URL_SAFE_NO_PAD
+ .decode(encoded_payload)
+ .map_err(|_| AccountLinkStateError::Malformed)?;
+ let state: AccountLinkState =
+ serde_json::from_slice(&json).map_err(|_| AccountLinkStateError::Malformed)?;
+
+ if current_timestamp >= state.exp {
+ return Err(AccountLinkStateError::Expired {
+ link_id: state.link_id,
+ });
+ }
+
+ Ok(state)
+}
+
+fn split_token(token: &str) -> Result<(&str, &str), AccountLinkStateError> {
+ let mut segments = token.split('.');
+ let payload = segments.next().filter(|segment| !segment.is_empty());
+ let signature = segments.next().filter(|segment| !segment.is_empty());
+
+ match (payload, signature, segments.next()) {
+ (Some(payload), Some(signature), None) => Ok((payload, signature)),
+ _ => Err(AccountLinkStateError::Malformed),
+ }
+}
+
+fn signature_for(payload: &[u8], key: &AccountLinkStateKey) -> [u8; 32] {
+ let mut signer =
+ HmacSha256::new_from_slice(key.as_bytes()).expect("HMAC-SHA256 accepts keys of any length");
+ signer.update(payload);
+ signer.finalize().into_bytes().into()
+}
diff --git a/services/authentication_service/src/account_link_state/test.rs b/services/authentication_service/src/account_link_state/test.rs
new file mode 100644
index 0000000000..d378c17d7d
--- /dev/null
+++ b/services/authentication_service/src/account_link_state/test.rs
@@ -0,0 +1,256 @@
+use super::*;
+
+const SECRET: &str = "a distinct account-link state test secret";
+const NOW: i64 = 1_730_000_000;
+
+fn key() -> AccountLinkStateKey {
+ AccountLinkStateKey::new(SECRET).unwrap()
+}
+
+fn link_id() -> Uuid {
+ Uuid::parse_str("0192b8a0-6a2e-7c3e-9b1f-4d5e6f708192").unwrap()
+}
+
+fn fusion_user_id() -> Uuid {
+ Uuid::parse_str("8c06ab3e-693c-45a7-8f92-1b5a5bf876ac").unwrap()
+}
+
+fn state(original_url: Option<&str>, exp: i64) -> AccountLinkState {
+ AccountLinkState {
+ provider: LinkProvider::Google,
+ identity_provider_id: "google-gmail-idp".into(),
+ link_id: link_id(),
+ fusion_user_id: fusion_user_id(),
+ original_url: original_url.map(str::to_owned),
+ exp,
+ }
+}
+
+fn sign_raw_payload(payload: &[u8]) -> String {
+ let encoded_payload = URL_SAFE_NO_PAD.encode(payload);
+ let signature = signature_for(encoded_payload.as_bytes(), &key());
+ format!("{encoded_payload}.{}", URL_SAFE_NO_PAD.encode(signature))
+}
+
+fn payload_json(token: &str) -> String {
+ let encoded_payload = token.split_once('.').unwrap().0;
+ String::from_utf8(URL_SAFE_NO_PAD.decode(encoded_payload).unwrap()).unwrap()
+}
+
+#[test]
+fn payload_round_trips_deterministically() {
+ let payload = state(
+ Some("https://macro.com/app/inbox-link-callback"),
+ NOW + 3_600,
+ );
+
+ let first_token = sign_account_link_state(&payload, &key()).unwrap();
+ let second_token = sign_account_link_state(&payload, &key()).unwrap();
+
+ assert_eq!(first_token, second_token);
+ assert!(!first_token.contains('='));
+ assert_eq!(
+ verify_account_link_state(&first_token, &key(), NOW).unwrap(),
+ payload
+ );
+}
+
+#[test]
+fn payload_without_original_url_omits_the_field() {
+ let payload = state(None, NOW + 3_600);
+ let token = sign_account_link_state(&payload, &key()).unwrap();
+
+ assert!(!payload_json(&token).contains("original_url"));
+ assert_eq!(
+ verify_account_link_state(&token, &key(), NOW).unwrap(),
+ payload
+ );
+}
+
+#[test]
+fn provider_serializes_as_the_callback_path_segment() {
+ for (provider, segment) in [
+ (LinkProvider::Google, "google"),
+ (LinkProvider::Github, "github"),
+ (LinkProvider::Microsoft, "microsoft"),
+ ] {
+ assert_eq!(provider.as_str(), segment);
+ assert_eq!(provider.to_string(), segment);
+ assert_eq!(
+ serde_json::to_string(&provider).unwrap(),
+ format!("\"{segment}\"")
+ );
+ }
+}
+
+#[test]
+fn new_state_expires_one_ttl_from_now() {
+ let before = chrono::Utc::now().timestamp();
+ let state = AccountLinkState::new(
+ LinkProvider::Github,
+ "github-idp".into(),
+ link_id(),
+ fusion_user_id(),
+ None,
+ );
+ let after = chrono::Utc::now().timestamp();
+ let ttl = ACCOUNT_LINK_STATE_TTL.num_seconds();
+
+ assert!(state.exp >= before + ttl);
+ assert!(state.exp <= after + ttl);
+ assert!(
+ verify_account_link_state(
+ &sign_account_link_state(&state, &key()).unwrap(),
+ &key(),
+ after
+ )
+ .is_ok()
+ );
+}
+
+#[test]
+fn expiration_boundary_is_enforced_and_names_the_pending_link() {
+ let token = sign_account_link_state(&state(None, NOW), &key()).unwrap();
+
+ assert_eq!(
+ verify_account_link_state(&token, &key(), NOW - 1),
+ Ok(state(None, NOW))
+ );
+ for current_timestamp in [NOW, NOW + 1] {
+ assert_eq!(
+ verify_account_link_state(&token, &key(), current_timestamp),
+ Err(AccountLinkStateError::Expired { link_id: link_id() })
+ );
+ }
+}
+
+#[test]
+fn malformed_tokens_are_rejected() {
+ for token in [
+ "",
+ "payload",
+ ".signature",
+ "payload.",
+ "payload.signature.extra",
+ "%%%.signature",
+ "payload.%%%",
+ r#"{"identity_provider_id":"idp","link_id":"0192b8a0-6a2e-7c3e-9b1f-4d5e6f708192"}"#,
+ ] {
+ assert!(
+ verify_account_link_state(token, &key(), NOW).is_err(),
+ "token should be rejected: {token}"
+ );
+ }
+
+ let malformed_json = sign_raw_payload(b"not json");
+ assert_eq!(
+ verify_account_link_state(&malformed_json, &key(), NOW),
+ Err(AccountLinkStateError::Malformed)
+ );
+}
+
+#[test]
+fn authentic_payloads_with_bad_fields_are_rejected() {
+ let base = serde_json::json!({
+ "provider": "google",
+ "identity_provider_id": "google-gmail-idp",
+ "link_id": link_id(),
+ "fusion_user_id": fusion_user_id(),
+ "exp": NOW + 3_600,
+ });
+
+ for (field, value) in [
+ ("provider", serde_json::json!("apple")),
+ ("link_id", serde_json::json!("not-a-uuid")),
+ ("fusion_user_id", serde_json::json!("not-a-uuid")),
+ ("exp", serde_json::json!("soon")),
+ ] {
+ let mut payload = base.clone();
+ payload[field] = value;
+ let token = sign_raw_payload(&serde_json::to_vec(&payload).unwrap());
+ assert_eq!(
+ verify_account_link_state(&token, &key(), NOW),
+ Err(AccountLinkStateError::Malformed),
+ "{field} should be validated"
+ );
+ }
+
+ for field in ["provider", "link_id", "fusion_user_id", "exp"] {
+ let mut payload = base.clone();
+ payload.as_object_mut().unwrap().remove(field);
+ let token = sign_raw_payload(&serde_json::to_vec(&payload).unwrap());
+ assert_eq!(
+ verify_account_link_state(&token, &key(), NOW),
+ Err(AccountLinkStateError::Malformed),
+ "{field} should be required"
+ );
+ }
+}
+
+#[test]
+fn payload_tampering_is_rejected() {
+ let token = sign_account_link_state(&state(None, NOW + 3_600), &key()).unwrap();
+ let (encoded_payload, encoded_signature) = token.split_once('.').unwrap();
+ let mut json: serde_json::Value =
+ serde_json::from_slice(&URL_SAFE_NO_PAD.decode(encoded_payload).unwrap()).unwrap();
+
+ for (field, value) in [
+ ("link_id", serde_json::json!(Uuid::now_v7())),
+ ("fusion_user_id", serde_json::json!(Uuid::now_v7())),
+ (
+ "original_url",
+ serde_json::json!("https://evil.example.com/"),
+ ),
+ ("provider", serde_json::json!("github")),
+ ("exp", serde_json::json!(NOW + 7_200)),
+ ] {
+ json[field] = value;
+ let tampered_payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json).unwrap());
+ let tampered_token = format!("{tampered_payload}.{encoded_signature}");
+
+ assert_eq!(
+ verify_account_link_state(&tampered_token, &key(), NOW),
+ Err(AccountLinkStateError::InvalidSignature),
+ "changing {field} should invalidate the signature"
+ );
+ }
+}
+
+#[test]
+fn signature_tampering_and_wrong_keys_are_rejected() {
+ let token = sign_account_link_state(&state(None, NOW + 3_600), &key()).unwrap();
+ let (encoded_payload, encoded_signature) = token.split_once('.').unwrap();
+ let mut signature = URL_SAFE_NO_PAD.decode(encoded_signature).unwrap();
+ signature[0] ^= 1;
+ let tampered_token = format!("{encoded_payload}.{}", URL_SAFE_NO_PAD.encode(signature));
+ let other_key = AccountLinkStateKey::new("another secret that is also long enough").unwrap();
+
+ assert_eq!(
+ verify_account_link_state(&tampered_token, &key(), NOW),
+ Err(AccountLinkStateError::InvalidSignature)
+ );
+ assert_eq!(
+ verify_account_link_state(&token, &other_key, NOW),
+ Err(AccountLinkStateError::InvalidSignature)
+ );
+}
+
+#[test]
+fn keys_must_be_at_least_32_bytes() {
+ for secret in ["", " ", "short", &"x".repeat(MIN_SECRET_LENGTH - 1)] {
+ let error = AccountLinkStateKey::new(secret).expect_err("short keys are rejected");
+ assert!(error.to_string().contains("ACCOUNT_LINK_STATE_SECRET"));
+ assert!(!error.to_string().contains(secret.trim()) || secret.trim().is_empty());
+ }
+
+ assert!(AccountLinkStateKey::new(&"x".repeat(MIN_SECRET_LENGTH)).is_ok());
+ assert!(AccountLinkStateKey::new(&format!(" {} ", "x".repeat(MIN_SECRET_LENGTH))).is_ok());
+}
+
+#[test]
+fn key_debug_output_redacts_the_secret() {
+ let debug = format!("{:?}", key());
+
+ assert!(!debug.contains(SECRET));
+ assert!(debug.contains("redacted"));
+}
diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rs
index 67b51b51f3..f6bf060d41 100644
--- a/services/authentication_service/src/api/context.rs
+++ b/services/authentication_service/src/api/context.rs
@@ -57,6 +57,7 @@ use roles_and_permissions::{
use sqlx::PgPool;
use tokio_util::task::TaskTracker;
+use crate::account_link_state::AccountLinkStateKey;
use crate::microsoft_token_cipher::MicrosoftTokenCipher;
use crate::service::signup_policy::SignupPolicy;
use cursor_api_key::cipher::CursorApiKeyCipher;
@@ -195,6 +196,8 @@ pub(crate) struct ApiContext {
pub ai_payment_gateway: Arc<ai_billing::outbound::StripePaymentGateway>,
/// Whether Gmail link consent requests the Google Calendar scope.
pub calendar_scope_enabled: bool,
+ /// Signs and verifies the `state` on account-link OAuth round trips.
+ pub account_link_state_key: AccountLinkStateKey,
}
env_var! {
diff --git a/services/authentication_service/src/api/link/github.rs b/services/authentication_service/src/api/link/github.rs
index fe6d13ef7b..9dcbeea6a4 100644
--- a/services/authentication_service/src/api/link/github.rs
+++ b/services/authentication_service/src/api/link/github.rs
@@ -1,3 +1,4 @@
+use anyhow::Context;
use axum::{
Json,
extract::{Query, State},
@@ -11,9 +12,9 @@ use model::response::{EmptyResponse, ErrorResponse};
use serde_utils::urlencode::UrlEncoded;
use url::Url;
-use crate::api::{
- context::{ApiContext, AuthorizationService},
- oauth2::OAuthState,
+use crate::{
+ account_link_state::{AccountLinkState, LinkProvider, sign_account_link_state},
+ api::context::{ApiContext, AuthorizationService},
};
pub const REAUTHENTICATION_REQUIRED_MESSAGE: &str = "ReauthenticationRequired";
@@ -172,12 +173,15 @@ pub async fn init_github_link_handler(
authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
) -> Result<Json<InitGithubLinkResponse>, InitGithubLinkError> {
let Query(InitGithubLinkQueryParams { original_url }) = query;
+ let fusion_user_id = &authorization.authorization.user.user_context.fusion_user_id;
+ let initiator =
+ macro_uuid::string_to_uuid(fusion_user_id).context("fusion user id must be a uuid")?;
// TODO: this should probably be a middleware or extractor
// Check count of in-progress links
let count =
macro_db_client::in_progress_user_link::count_existing_in_progress_user_links_for_user(
&ctx.db,
- &authorization.authorization.user.user_context.fusion_user_id,
+ fusion_user_id,
)
.await?;
@@ -188,7 +192,7 @@ pub async fn init_github_link_handler(
// Create in-progress link
let link_id = macro_db_client::in_progress_user_link::create_in_progress_user_link(
&ctx.db,
- &authorization.authorization.user.user_context.fusion_user_id,
+ fusion_user_id,
)
.await?;
@@ -199,20 +203,25 @@ pub async fn init_github_link_handler(
.await
.map_err(|_| InitGithubLinkError::IdentityProviderNotFound)?;
- // Build OAuth state
- let state = OAuthState {
- identity_provider_id: github_idp_id.clone(),
- link_id: Some(link_id),
- original_url: original_url.map(|x| x.0.to_string()),
- is_mobile: None,
- };
+ // Build the signed OAuth state. The callback refuses state it did not sign,
+ // state issued for another provider, and state whose pending link belongs
+ // to a different user.
+ let state = AccountLinkState::new(
+ LinkProvider::Github,
+ github_idp_id.clone(),
+ link_id,
+ initiator,
+ original_url.map(|x| x.0.to_string()),
+ );
+ let state = sign_account_link_state(&state, &ctx.account_link_state_key)
+ .context("failed to sign OAuth state")?;
// Build Github OAuth URL
- let redirect_uri = crate::api::oauth2::format_redirect_uri("github");
+ let redirect_uri = crate::api::oauth2::format_redirect_uri(LinkProvider::Github.as_str());
let authorization_url = ctx
.github_link_service
- .construct_oauth_url(&redirect_uri, state)
+ .construct_oauth_url(&redirect_uri, &state)
.map_err(InitGithubLinkError::GithubServiceError)?;
Ok(Json(InitGithubLinkResponse {
diff --git a/services/authentication_service/src/api/link/gmail.rs b/services/authentication_service/src/api/link/gmail.rs
index 2d83645d7b..e99333365b 100644
--- a/services/authentication_service/src/api/link/gmail.rs
+++ b/services/authentication_service/src/api/link/gmail.rs
@@ -14,11 +14,13 @@ use roles_and_permissions::domain::model::PermissionId;
use serde_utils::urlencode::UrlEncoded;
use url::Url;
-use crate::api::{
- context::{ApiContext, AuthorizationService},
- link::github::REAUTHENTICATION_REQUIRED_MESSAGE,
- oauth2::OAuthState,
- permissions_extractor::DbPermissionsExtractor,
+use crate::{
+ account_link_state::{AccountLinkState, LinkProvider, sign_account_link_state},
+ api::{
+ context::{ApiContext, AuthorizationService},
+ link::github::REAUTHENTICATION_REQUIRED_MESSAGE,
+ permissions_extractor::DbPermissionsExtractor,
+ },
};
#[cfg(test)]
@@ -134,6 +136,9 @@ pub async fn init_gmail_link_handler(
scopes,
}) = query;
let authorization = &db_permissions.authorization;
+ let fusion_user_id = &authorization.authorization.user.user_context.fusion_user_id;
+ let initiator =
+ macro_uuid::string_to_uuid(fusion_user_id).context("fusion user id must be a uuid")?;
enforce_inbox_paywall(
db_permissions
@@ -146,7 +151,7 @@ pub async fn init_gmail_link_handler(
let count =
macro_db_client::in_progress_user_link::count_existing_in_progress_user_links_for_user(
&ctx.db,
- &authorization.authorization.user.user_context.fusion_user_id,
+ fusion_user_id,
)
.await?;
@@ -161,7 +166,7 @@ pub async fn init_gmail_link_handler(
.collect();
let link_id = macro_db_client::in_progress_user_link::create_in_progress_google_link(
&ctx.db,
- &authorization.authorization.user.user_context.fusion_user_id,
+ fusion_user_id,
&requested_google_scopes,
)
.await?;
@@ -172,15 +177,20 @@ pub async fn init_gmail_link_handler(
.await
.map_err(|_| InitGmailLinkError::IdentityProviderNotFound)?;
- let state = OAuthState {
- identity_provider_id: gmail_idp_id,
- link_id: Some(link_id),
- original_url: original_url.map(|x| x.0.to_string()),
- is_mobile: None,
- };
+ // The state is signed and bound to this user, this link, and the Google
+ // callback: the callback refuses anything else, so the authorization URL
+ // cannot be rewritten to point another user's consent at this link.
+ let state = AccountLinkState::new(
+ LinkProvider::Google,
+ gmail_idp_id,
+ link_id,
+ initiator,
+ original_url.map(|x| x.0.to_string()),
+ );
- let redirect_uri = crate::api::oauth2::format_redirect_uri("google");
- let state_str = serde_json::to_string(&state).context("failed to serialize OAuth state")?;
+ let redirect_uri = crate::api::oauth2::format_redirect_uri(LinkProvider::Google.as_str());
+ let state_str = sign_account_link_state(&state, &ctx.account_link_state_key)
+ .context("failed to sign OAuth state")?;
let authorization_url = google_authorization_url(
ctx.auth_client.google_client_id(),
diff --git a/services/authentication_service/src/api/link/outlook.rs b/services/authentication_service/src/api/link/outlook.rs
index dcd27968d7..685b8c11f2 100644
--- a/services/authentication_service/src/api/link/outlook.rs
+++ b/services/authentication_service/src/api/link/outlook.rs
@@ -11,9 +11,9 @@ use model::response::ErrorResponse;
use serde_utils::urlencode::UrlEncoded;
use url::Url;
-use crate::api::{
- context::{ApiContext, AuthorizationService},
- oauth2::OAuthState,
+use crate::{
+ account_link_state::{AccountLinkState, LinkProvider, sign_account_link_state},
+ api::context::{ApiContext, AuthorizationService},
};
#[cfg(test)]
@@ -103,6 +103,9 @@ pub async fn init_outlook_link_handler(
.map_err(map_identity_provider_lookup_error)?;
let fusion_user_id = &authorization.authorization.user.user_context.fusion_user_id;
+ let initiator = macro_uuid::string_to_uuid(fusion_user_id).map_err(|error| {
+ InitOutlookLinkError::InternalError(error.context("fusion user id must be a uuid"))
+ })?;
let count =
macro_db_client::in_progress_user_link::count_existing_in_progress_user_links_for_user(
&ctx.db,
@@ -119,18 +122,24 @@ pub async fn init_outlook_link_handler(
fusion_user_id,
)
.await?;
- let state = OAuthState {
- identity_provider_id: microsoft_idp_id,
- link_id: Some(link_id),
- original_url: original_url.map(|url| url.0.to_string()),
- is_mobile: None,
- };
- let redirect_uri = crate::api::oauth2::format_redirect_uri("microsoft");
-
- let authorization_url = match ctx
- .auth_client
- .construct_microsoft_authorize_url(&redirect_uri, &state)
- {
+ // Signed and bound to this user, this link, and the Microsoft callback;
+ // see `account_link_state` for what the callback refuses.
+ let state = AccountLinkState::new(
+ LinkProvider::Microsoft,
+ microsoft_idp_id,
+ link_id,
+ initiator,
+ original_url.map(|url| url.0.to_string()),
+ );
+ let redirect_uri = crate::api::oauth2::format_redirect_uri(LinkProvider::Microsoft.as_str());
+
+ let authorization_url = match sign_account_link_state(&state, &ctx.account_link_state_key)
+ .map_err(|error| InitOutlookLinkError::InternalError(error.into()))
+ .and_then(|state| {
+ ctx.auth_client
+ .construct_microsoft_authorize_url(&redirect_uri, &state)
+ .map_err(map_microsoft_oauth_error)
+ }) {
Ok(authorization_url) => authorization_url,
Err(error) => {
let _ = macro_db_client::in_progress_user_link::delete_in_progress_user_link(
@@ -144,7 +153,7 @@ pub async fn init_outlook_link_handler(
"failed to clean up pending Outlook link"
);
});
- return Err(map_microsoft_oauth_error(error));
+ return Err(error);
}
};
diff --git a/services/authentication_service/src/api/oauth2.rs b/services/authentication_service/src/api/oauth2.rs
index 8eaf8ed2e4..00b93e91da 100644
--- a/services/authentication_service/src/api/oauth2.rs
+++ b/services/authentication_service/src/api/oauth2.rs
@@ -1,4 +1,8 @@
use crate::{
+ account_link_state::{
+ AccountLinkState, AccountLinkStateError, AccountLinkStateKey, LinkProvider,
+ verify_account_link_state,
+ },
api::login::sso::{is_allowed_original_url, redact_original_url_for_logging},
config::BASE_URL,
};
@@ -35,23 +39,105 @@ pub(in crate::api) fn format_redirect_uri(provider: &str) -> String {
format!("{}/oauth2/{provider}/callback", *BASE_URL)
}
-#[derive(Debug, serde::Serialize, serde::Deserialize)]
+/// The state the provider handlers complete a callback with.
+///
+/// Account-link flows never arrive in this shape. Their `state` is a signed
+/// [`AccountLinkState`] token that [`parse_callback_state`] verifies before
+/// converting it into this struct. Plain JSON is accepted only for sign-in,
+/// which carries no `link_id`.
+#[derive(Debug, serde::Deserialize)]
pub(in crate::api) struct OAuthState {
/// The identity provider id to use to complete the login
pub identity_provider_id: String,
- /// The link id to use to complete the login
- /// If the link id is provided, this means we need to link this idp to a specific user before
- /// performing the login process
- #[serde(skip_serializing_if = "Option::is_none")]
+ /// The pending account link to complete instead of signing in. Populated
+ /// only from a verified [`AccountLinkState`]; unsigned state that names a
+ /// link is rejected.
+ #[serde(default)]
pub link_id: Option<uuid::Uuid>,
/// The original url you came from
- #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(default)]
pub original_url: Option<String>,
/// If the authentication request is from a mobile device
- #[serde(skip_serializing_if = "Option::is_none")]
+ #[serde(default)]
pub is_mobile: Option<bool>,
}
+impl From<&AccountLinkState> for OAuthState {
+ fn from(state: &AccountLinkState) -> Self {
+ Self {
+ identity_provider_id: state.identity_provider_id.clone(),
+ link_id: Some(state.link_id),
+ original_url: state.original_url.clone(),
+ is_mobile: None,
+ }
+ }
+}
+
+/// What a callback's `state` parameter verified as.
+#[derive(Debug)]
+enum CallbackState {
+ /// A signed token issued by one of the `/link/*` handlers.
+ AccountLink(AccountLinkState),
+ /// Unsigned sign-in state. Never carries a `link_id`.
+ Login(OAuthState),
+}
+
+impl CallbackState {
+ fn original_url(&self) -> Option<&str> {
+ match self {
+ Self::AccountLink(state) => state.original_url.as_deref(),
+ Self::Login(state) => state.original_url.as_deref(),
+ }
+ }
+}
+
+#[derive(Debug, PartialEq, Eq)]
+enum CallbackStateError {
+ /// A signed token that failed verification.
+ Signed(AccountLinkStateError),
+ /// Unsigned state that is not valid sign-in state.
+ Unparseable,
+ /// Unsigned state naming a pending link. Only a signed token may do that.
+ UnsignedAccountLink,
+ /// A verified token presented to a different provider's callback.
+ ProviderMismatch {
+ /// The callback the token was issued for.
+ issued_for: LinkProvider,
+ },
+}
+
+/// Verifies the raw `state` for the `provider` callback that received it.
+///
+/// Signed tokens never start with `{`, so a leading brace selects the legacy
+/// sign-in JSON. That path refuses any `link_id`: the pending links it would
+/// name are reachable only through a token this service signed, bound to the
+/// user who created them and to the provider that will call back.
+fn parse_callback_state(
+ raw: &str,
+ provider: &str,
+ key: &AccountLinkStateKey,
+ current_timestamp: i64,
+) -> Result<CallbackState, CallbackStateError> {
+ if raw.trim_start().starts_with('{') {
+ let state: OAuthState =
+ serde_json::from_str(raw).map_err(|_| CallbackStateError::Unparseable)?;
+ if state.link_id.is_some() {
+ return Err(CallbackStateError::UnsignedAccountLink);
+ }
+ return Ok(CallbackState::Login(state));
+ }
+
+ let state = verify_account_link_state(raw, key, current_timestamp)
+ .map_err(CallbackStateError::Signed)?;
+ if state.provider.as_str() != provider {
+ return Err(CallbackStateError::ProviderMismatch {
+ issued_for: state.provider,
+ });
+ }
+
+ Ok(CallbackState::AccountLink(state))
+}
+
#[derive(Debug, serde::Deserialize)]
pub(in crate::api) struct Params {
/// The code to complete the login
@@ -82,7 +168,8 @@ fn validate_original_url(original_url: Option<&str>) -> Result<(), OriginalUrlVa
return Ok(());
};
- // OAuth state is client-visible and may be forged. Decode it exactly as the
+ // Sign-in state is client-visible and may be forged, and a signed link state
+ // still carries whatever URL the caller asked for. Decode it exactly as the
// redirect handlers do before validating the resulting destination.
let decoded_url =
urlencoding::decode(original_url).map_err(|_| OriginalUrlValidationError::Invalid)?;
@@ -95,6 +182,58 @@ fn validate_original_url(original_url: Option<&str>) -> Result<(), OriginalUrlVa
Ok(())
}
+fn error_response(status: StatusCode, message: &'static str) -> Response {
+ (
+ status,
+ Json(ErrorResponse {
+ message: message.into(),
+ }),
+ )
+ .into_response()
+}
+
+/// The pending row must still belong to the user named in the signed state.
+/// Completing a link against anyone else's row would attach this consent to
+/// their account.
+async fn verify_pending_link_owner(
+ ctx: &ApiContext,
+ state: &AccountLinkState,
+) -> Result<(), Response> {
+ let owner = macro_db_client::in_progress_user_link::get_macro_user_id_by_link_id(
+ &ctx.db,
+ &state.link_id,
+ )
+ .await
+ .map_err(|error| {
+ if matches!(
+ error.downcast_ref::<sqlx::Error>(),
+ Some(sqlx::Error::RowNotFound)
+ ) {
+ tracing::warn!(link_id = %state.link_id, "pending account link not found");
+ error_response(StatusCode::NOT_FOUND, "pending account link not found")
+ } else {
+ tracing::error!(error=?error, "unable to load pending account link");
+ error_response(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "unable to load pending account link",
+ )
+ }
+ })?;
+
+ if owner != state.fusion_user_id {
+ tracing::error!(
+ link_id = %state.link_id,
+ "account-link state and pending link name different users"
+ );
+ return Err(error_response(
+ StatusCode::FORBIDDEN,
+ "pending account link belongs to another user",
+ ));
+ }
+
+ Ok(())
+}
+
/// Custom OAuth2 callback
#[utoipa::path(
get,
@@ -121,27 +260,43 @@ pub(in crate::api) async fn handler(
) -> Result<Response, Response> {
tracing::info!("oauth2_callback");
- let state: OAuthState = serde_json::from_str(&params.state).map_err(|e| {
- tracing::error!(error=?e, "unable to deserialize state");
- (
- StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: "unable to deserialize state".into(),
- }),
- )
- .into_response()
- })?;
+ let state = match parse_callback_state(
+ &params.state,
+ &provider,
+ &ctx.account_link_state_key,
+ chrono::Utc::now().timestamp(),
+ ) {
+ Ok(state) => state,
+ Err(CallbackStateError::Signed(AccountLinkStateError::Expired { link_id })) => {
+ // The token is authentic, so the pending row it names is safe to
+ // release instead of counting toward the user's in-progress cap
+ // for the rest of the day.
+ tracing::warn!(%link_id, "account-link state expired before the provider called back");
+ account_link::cleanup_pending_link(&ctx, &link_id).await;
+ return Err(error_response(
+ StatusCode::BAD_REQUEST,
+ "account link request expired; start it again",
+ ));
+ }
+ Err(error) => {
+ tracing::error!(error=?error, "rejected oauth2 callback state");
+ return Err(error_response(
+ StatusCode::BAD_REQUEST,
+ "unable to verify state",
+ ));
+ }
+ };
- // Clean up failed Microsoft account-link callbacks before validating the
- // redirect so an invalid original_url cannot leave the pending link behind.
+ // Provider errors arrive without a code. Release the pending link before
+ // validating the redirect so an invalid original_url cannot leave it
+ // behind. The state is verified, so the row it names is the caller's own.
if params.code.is_none()
- && provider == "microsoft"
- && let Some(link_id) = state.link_id.as_ref()
+ && let CallbackState::AccountLink(link_state) = &state
{
- account_link::cleanup_pending_link(&ctx, link_id).await;
+ account_link::cleanup_pending_link(&ctx, &link_state.link_id).await;
}
- validate_original_url(state.original_url.as_deref()).map_err(|error| {
+ validate_original_url(state.original_url()).map_err(|error| {
match error {
OriginalUrlValidationError::Invalid => {
tracing::error!(
@@ -159,13 +314,10 @@ pub(in crate::api) async fn handler(
}
}
- (
+ error_response(
StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: "provided original_url is not allowed".into(),
- }),
+ "provided original_url is not allowed",
)
- .into_response()
})?;
let code = match params.code {
@@ -177,13 +329,18 @@ pub(in crate::api) async fn handler(
error_description = ?params.error_description,
"oauth2 callback received without code",
);
- return Err((
+ return Err(error_response(
StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: "Sign-in failed. Please try again or contact support.".into(),
- }),
- )
- .into_response());
+ "Sign-in failed. Please try again or contact support.",
+ ));
+ }
+ };
+
+ let state = match state {
+ CallbackState::Login(state) => state,
+ CallbackState::AccountLink(link_state) => {
+ verify_pending_link_owner(&ctx, &link_state).await?;
+ OAuthState::from(&link_state)
}
};
@@ -194,12 +351,9 @@ pub(in crate::api) async fn handler(
.map(|r| r.into_response())
.map_err(|e| e.into_response()),
"microsoft" => microsoft::handler(&ctx, &code, &state).await,
- _ => Err((
+ _ => Err(error_response(
StatusCode::NOT_IMPLEMENTED,
- Json(ErrorResponse {
- message: "oauth2 callback not implemented for this provider".into(),
- }),
- )
- .into_response()),
+ "oauth2 callback not implemented for this provider",
+ )),
}
}
diff --git a/services/authentication_service/src/api/oauth2/test.rs b/services/authentication_service/src/api/oauth2/test.rs
index 9a89273eee..ba52e023f1 100644
--- a/services/authentication_service/src/api/oauth2/test.rs
+++ b/services/authentication_service/src/api/oauth2/test.rs
@@ -52,3 +52,123 @@ fn callback_original_url_rejects_invalid_urls() {
));
assert!(validate_original_url(None).is_ok());
}
+
+use crate::account_link_state::{AccountLinkState, AccountLinkStateKey, sign_account_link_state};
+use uuid::Uuid;
+
+const NOW: i64 = 1_730_000_000;
+
+fn key() -> AccountLinkStateKey {
+ AccountLinkStateKey::new("oauth2 callback state test secret value").unwrap()
+}
+
+fn link_state(provider: LinkProvider, exp: i64) -> AccountLinkState {
+ AccountLinkState {
+ provider,
+ identity_provider_id: "idp-for-linking".into(),
+ link_id: Uuid::parse_str("0192b8a0-6a2e-7c3e-9b1f-4d5e6f708192").unwrap(),
+ fusion_user_id: Uuid::parse_str("8c06ab3e-693c-45a7-8f92-1b5a5bf876ac").unwrap(),
+ original_url: Some("https://macro.com/app/inbox-link-callback".into()),
+ exp,
+ }
+}
+
+#[test]
+fn callback_accepts_signed_state_issued_for_its_provider() {
+ for provider in [
+ LinkProvider::Google,
+ LinkProvider::Github,
+ LinkProvider::Microsoft,
+ ] {
+ let state = link_state(provider, NOW + 60);
+ let token = sign_account_link_state(&state, &key()).unwrap();
+
+ match parse_callback_state(&token, provider.as_str(), &key(), NOW).unwrap() {
+ CallbackState::AccountLink(verified) => assert_eq!(verified, state),
+ other => panic!("expected an account link for {provider}, got {other:?}"),
+ }
+ }
+}
+
+#[test]
+fn callback_rejects_signed_state_issued_for_another_provider() {
+ let token =
+ sign_account_link_state(&link_state(LinkProvider::Github, NOW + 60), &key()).unwrap();
+
+ assert_eq!(
+ parse_callback_state(&token, "google", &key(), NOW).unwrap_err(),
+ CallbackStateError::ProviderMismatch {
+ issued_for: LinkProvider::Github
+ }
+ );
+}
+
+#[test]
+fn callback_rejects_expired_foreign_and_garbage_tokens() {
+ let state = link_state(LinkProvider::Google, NOW);
+ let expired = sign_account_link_state(&state, &key()).unwrap();
+ let other_key = AccountLinkStateKey::new("a different signing key of enough length").unwrap();
+ let foreign =
+ sign_account_link_state(&link_state(LinkProvider::Google, NOW + 60), &other_key).unwrap();
+
+ assert_eq!(
+ parse_callback_state(&expired, "google", &key(), NOW).unwrap_err(),
+ CallbackStateError::Signed(AccountLinkStateError::Expired {
+ link_id: state.link_id
+ })
+ );
+ assert_eq!(
+ parse_callback_state(&foreign, "google", &key(), NOW).unwrap_err(),
+ CallbackStateError::Signed(AccountLinkStateError::InvalidSignature)
+ );
+ assert_eq!(
+ parse_callback_state("not-a-token", "google", &key(), NOW).unwrap_err(),
+ CallbackStateError::Signed(AccountLinkStateError::Malformed)
+ );
+}
+
+#[test]
+fn callback_accepts_unsigned_state_only_for_sign_in() {
+ let login = parse_callback_state(
+ r#"{"identity_provider_id":"google-login","is_mobile":true}"#,
+ "google",
+ &key(),
+ NOW,
+ )
+ .unwrap();
+ match login {
+ CallbackState::Login(state) => {
+ assert_eq!(state.identity_provider_id, "google-login");
+ assert_eq!(state.is_mobile, Some(true));
+ assert!(state.link_id.is_none());
+ assert!(state.original_url.is_none());
+ }
+ other => panic!("expected sign-in state, got {other:?}"),
+ }
+
+ // The pre-signing wire format: an attacker-chosen link_id in plain JSON.
+ let forged = format!(
+ r#"{{"identity_provider_id":"google-gmail","link_id":"{}","original_url":"https://macro.com/app"}}"#,
+ Uuid::now_v7()
+ );
+ assert_eq!(
+ parse_callback_state(&forged, "google", &key(), NOW).unwrap_err(),
+ CallbackStateError::UnsignedAccountLink
+ );
+ assert_eq!(
+ parse_callback_state("{not json", "google", &key(), NOW).unwrap_err(),
+ CallbackStateError::Unparseable
+ );
+}
+
+#[test]
+fn verified_link_state_converts_to_provider_handler_state() {
+ let link = link_state(LinkProvider::Microsoft, NOW + 60);
+
+ let state = OAuthState::from(&link);
+
+ assert_eq!(state.identity_provider_id, link.identity_provider_id);
+ assert_eq!(state.link_id, Some(link.link_id));
+ assert_eq!(state.original_url, link.original_url);
+ assert_eq!(state.is_mobile, None);
+}
diff --git a/services/authentication_service/src/config.rs b/services/authentication_service/src/config.rs
index 75a644a3a8..2b0e116eba 100644
--- a/services/authentication_service/src/config.rs
+++ b/services/authentication_service/src/config.rs
@@ -1,5 +1,6 @@
use std::sync::LazyLock;
+use crate::account_link_state::AccountLinkStateKey;
use crate::service::signup_policy::SignupPolicy;
use anyhow::Context;
use database_env_vars::{DatabaseUrl, RedisUri};
@@ -30,6 +31,9 @@ env_vars! {
pub struct GithubClientId;
pub struct GithubClientSecret;
pub struct GithubIdpId;
+ /// HMAC-SHA256 key for the signed `state` on account-link OAuth requests:
+ /// at least 32 bytes of random data. See `account_link_state`.
+ pub struct AccountLinkStateSecret;
pub struct StripePriceId;
/// Comma-separated Kafka bootstrap servers for the macro event broker.
pub struct KafkaBrokers;
@@ -159,6 +163,9 @@ pub struct Config {
pub github_client_secret: GithubClientSecret,
/// The github idp id
pub github_idp_id: GithubIdpId,
+ /// Signs the `state` carried through account-link OAuth flows. Checked
+ /// for length by [`Config::account_link_state_key`] at startup.
+ pub account_link_state_secret: AccountLinkStateSecret,
/// GA4 Measurement ID (optional, e.g., "G-XXXXXXXXXX")
pub ga_measurement_id: GaMeasurementId,
/// GA4 Measurement Protocol API secret (optional)
@@ -272,6 +279,20 @@ impl Config {
.map(str::to_owned)
}
+ /// The key that signs and verifies account-link OAuth state.
+ ///
+ /// # Errors
+ /// If the configured secret is blank or shorter than 32 bytes.
+ pub(crate) fn account_link_state_key(&self) -> anyhow::Result<AccountLinkStateKey> {
+ AccountLinkStateKey::new(self.account_link_state_secret.as_ref())
+ }
+
+ /// Checks the account-link signing secret without exposing it. Public for
+ /// the Doppler config check binary.
+ pub fn validate_account_link_state_secret(&self) -> anyhow::Result<()> {
+ self.account_link_state_key().map(drop)
+ }
+
/// Resolves Microsoft credentials, enforcing that all values are configured together.
pub(crate) fn microsoft_credentials(&self) -> anyhow::Result<Option<MicrosoftCredentials>> {
resolve_microsoft_credentials(
diff --git a/services/authentication_service/src/config/test.rs b/services/authentication_service/src/config/test.rs
index 28490f8fb3..1ad98e9775 100644
--- a/services/authentication_service/src/config/test.rs
+++ b/services/authentication_service/src/config/test.rs
@@ -24,6 +24,7 @@ fn config_values() -> serde_json::Value {
"GITHUB_CLIENT_ID",
"GITHUB_CLIENT_SECRET",
"GITHUB_IDP_ID",
+ "ACCOUNT_LINK_STATE_SECRET",
"STRIPE_PRICE_ID",
"INTERNAL_API_KEY",
"KAFKA_BROKERS",
@@ -122,6 +123,32 @@ fn billing_settlement_config_defaults_off_and_requires_a_boolean() {
assert!(serde_json::from_value::<Config>(values).is_err());
}
+#[test]
+fn account_link_state_secret_is_mandatory_and_must_be_long_enough() {
+ let mut values = config_values();
+ values
+ .as_object_mut()
+ .unwrap()
+ .remove("ACCOUNT_LINK_STATE_SECRET");
+ assert!(
+ serde_json::from_value::<Config>(values).is_err(),
+ "ACCOUNT_LINK_STATE_SECRET must be mandatory"
+ );
+
+ // The placeholder value every other key uses is far too short to sign with.
+ let config: Config = serde_json::from_value(config_values()).unwrap();
+ let error = config
+ .validate_account_link_state_secret()
+ .expect_err("a short signing secret must be rejected");
+ assert!(error.to_string().contains("ACCOUNT_LINK_STATE_SECRET"));
+
+ let mut values = config_values();
+ values["ACCOUNT_LINK_STATE_SECRET"] = serde_json::json!("x".repeat(32));
+ let config: Config = serde_json::from_value(values).unwrap();
+ config.validate_account_link_state_secret().unwrap();
+ config.account_link_state_key().unwrap();
+}
+
#[test]
fn complete_microsoft_credentials_are_resolved() {
let credentials = resolve(
diff --git a/services/authentication_service/src/doppler_config.rs b/services/authentication_service/src/doppler_config.rs
index e053ffe5d3..b82eda0d4a 100644
--- a/services/authentication_service/src/doppler_config.rs
+++ b/services/authentication_service/src/doppler_config.rs
@@ -14,6 +14,7 @@ async fn main() -> anyhow::Result<()> {
let dev_config = dev.load::<Config>().await?;
dev_config.signup_policy_for_environment(Environment::Develop)?;
+ dev_config.validate_account_link_state_secret()?;
let prd = doppler_config::DopplerConfig::builder()
.token_from_env("DOPPLER_TOKEN")
@@ -24,6 +25,7 @@ async fn main() -> anyhow::Result<()> {
let prd_config = prd.load::<Config>().await?;
prd_config.signup_policy_for_environment(Environment::Production)?;
+ prd_config.validate_account_link_state_secret()?;
Ok(())
}
diff --git a/services/authentication_service/src/lib.rs b/services/authentication_service/src/lib.rs
index 601b1458ea..4f082042e1 100644
--- a/services/authentication_service/src/lib.rs
+++ b/services/authentication_service/src/lib.rs
@@ -3,6 +3,7 @@
//! Doppler config check all link this library, so the service compiles once
//! and caches as one rlib.
+mod account_link_state;
mod api;
mod config;
mod generate_password;
diff --git a/services/authentication_service/src/server.rs b/services/authentication_service/src/server.rs
index 2c735960b7..131a0c7631 100644
--- a/services/authentication_service/src/server.rs
+++ b/services/authentication_service/src/server.rs
@@ -453,6 +453,8 @@ pub async fn run() -> anyhow::Result<()> {
let foreign_entity_service =
ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone()));
+ let account_link_state_key = config.account_link_state_key()?;
+
let github_link_service_impl = GithubLinkServiceImpl::new(
PgGithubRepo::new(db.clone()),
GithubOauthImpl::default(),
@@ -597,6 +599,7 @@ pub async fn run() -> anyhow::Result<()> {
signup_policy,
rate_limit_service: rate_limit,
calendar_scope_enabled: config.calendar_scope_enabled,
+ account_link_state_key,
jwt_args,
authorization_state,
token_context: MacroApiTokenContext {
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
index 6c27511545..4a42eabf95 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs
@@ -712,6 +712,12 @@ impl BootStubEnv {
"local-github-client-secret".into(),
);
env.insert("GITHUB_IDP_ID".into(), identity::GITHUB_IDP_ID.into());
+ // HMAC key for signed account-link OAuth state; the loader rejects
+ // anything under 32 bytes.
+ env.insert(
+ "ACCOUNT_LINK_STATE_SECRET".into(),
+ "local-account-link-state-secret-0123456789".into(),
+ );
env.insert("STRIPE_SECRET_KEY".into(), "local-stripe-secret".into());
env.insert("STRIPE_PRICE_ID".into(), "local-stripe-price".into());
env.insert(
diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
index 4f3b189490..451f7e4654 100644
--- a/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/local_env/test.rs
@@ -82,6 +82,7 @@ fn emits_required_keys() {
"GITHUB_CLIENT_ID",
"GITHUB_CLIENT_SECRET",
"GITHUB_IDP_ID",
+ "ACCOUNT_LINK_STATE_SECRET",
"STRIPE_SECRET_KEY",
"STRIPE_PRICE_ID",
"STRIPE_WEBHOOK_SECRET_KEY",