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(outlook): support outlook account linking (#5635)

Will Hutchinson827d55a571c2
diff --git a/Cargo.lock b/Cargo.lock
index 178df37956..64c512a6e3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5903,6 +5903,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"base64 0.22.1",
+ "jsonwebtoken 10.3.0",
"reqwest 0.13.4",
"serde",
"serde_json",
@@ -5911,6 +5912,7 @@ dependencies = [
"tokio",
"tracing",
"urlencoding",
+ "wiremock",
"workspace-hack",
]
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
index 573cfc8a56..eabed46444 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts
@@ -29,6 +29,8 @@ import type {
InitGithubLinkResponse,
InitGmailLinkParams,
InitGmailLinkResponse,
+ InitOutlookLinkParams,
+ InitOutlookLinkResponse,
InviteToTeamRequest,
MacroApiTokenParams,
MacroApiTokenResponse,
@@ -950,6 +952,91 @@ export const checkGmailLinkStatus = async (
} as checkGmailLinkStatusResponse;
};
+/**
+ * @summary Initiates a Microsoft Outlook account link for an authenticated user.
+ */
+export type initOutlookLinkResponse200 = {
+ data: InitOutlookLinkResponse;
+ status: 200;
+};
+
+export type initOutlookLinkResponse400 = {
+ data: ErrorResponse;
+ status: 400;
+};
+
+export type initOutlookLinkResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type initOutlookLinkResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type initOutlookLinkResponse429 = {
+ data: ErrorResponse;
+ status: 429;
+};
+
+export type initOutlookLinkResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type initOutlookLinkResponseSuccess = initOutlookLinkResponse200 & {
+ headers: Headers;
+};
+export type initOutlookLinkResponseError = (
+ | initOutlookLinkResponse400
+ | initOutlookLinkResponse401
+ | initOutlookLinkResponse404
+ | initOutlookLinkResponse429
+ | initOutlookLinkResponse500
+) & {
+ headers: Headers;
+};
+
+export type initOutlookLinkResponse =
+ | initOutlookLinkResponseSuccess
+ | initOutlookLinkResponseError;
+
+export const getInitOutlookLinkUrl = (params?: InitOutlookLinkParams) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/link/outlook?${stringifiedParams}`
+ : `/link/outlook`;
+};
+
+export const initOutlookLink = async (
+ params?: InitOutlookLinkParams,
+ options?: RequestInit
+): Promise<initOutlookLinkResponse> => {
+ const res = await fetch(getInitOutlookLinkUrl(params), {
+ ...options,
+ method: 'POST',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: initOutlookLinkResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as initOutlookLinkResponse;
+};
+
/**
* @summary Completes the apple login flow
*/
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
index 885702e958..1cd3624e13 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
@@ -69,6 +69,8 @@ export * from './initGithubLinkParams';
export * from './initGithubLinkResponse';
export * from './initGmailLinkParams';
export * from './initGmailLinkResponse';
+export * from './initOutlookLinkParams';
+export * from './initOutlookLinkResponse';
export * from './inviteEntry';
export * from './inviteToTeamRequest';
export * from './macroApiTokenParams';
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/initOutlookLinkParams.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/initOutlookLinkParams.ts
new file mode 100644
index 0000000000..16dc3eb3c1
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/initOutlookLinkParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type InitOutlookLinkParams = {
+ /**
+ * **OPTIONAL**. The original URL to redirect to.
+ */
+ original_url?: string;
+};
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/initOutlookLinkResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/initOutlookLinkResponse.ts
new file mode 100644
index 0000000000..1d1d01bdd8
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/initOutlookLinkResponse.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Response returned when a Microsoft Outlook link is initiated.
+ */
+export interface InitOutlookLinkResponse {
+ /** The OAuth authorization URL to redirect the user to. */
+ authorization_url: string;
+ /** The link ID for tracking the OAuth flow. */
+ link_id: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index 7bb832ad8a..da2bdcb59d 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -758,6 +758,86 @@
}
}
},
+ "/link/outlook": {
+ "post": {
+ "tags": ["link::outlook"],
+ "summary": "Initiates a Microsoft Outlook account link for an authenticated user.",
+ "operationId": "init_outlook_link",
+ "parameters": [
+ {
+ "name": "original_url",
+ "in": "query",
+ "description": "**OPTIONAL**. The original URL to redirect to.",
+ "required": false,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/InitOutlookLinkResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/login/apple": {
"post": {
"tags": ["login::apple"],
@@ -4067,6 +4147,22 @@
}
}
},
+ "InitOutlookLinkResponse": {
+ "type": "object",
+ "description": "Response returned when a Microsoft Outlook link is initiated.",
+ "required": ["authorization_url", "link_id"],
+ "properties": {
+ "authorization_url": {
+ "type": "string",
+ "description": "The OAuth authorization URL to redirect the user to."
+ },
+ "link_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The link ID for tracking the OAuth flow."
+ }
+ }
+ },
"InviteEntry": {
"type": "object",
"description": "A single invite entry with email and tier",
diff --git a/crates/fusionauth/Cargo.toml b/crates/fusionauth/Cargo.toml
index 89a09a5a7f..6c140d7690 100644
--- a/crates/fusionauth/Cargo.toml
+++ b/crates/fusionauth/Cargo.toml
@@ -7,6 +7,7 @@ version = "0.1.0"
[dependencies]
anyhow = { workspace = true }
base64 = { workspace = true }
+jsonwebtoken = { workspace = true }
reqwest = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
@@ -18,3 +19,4 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
tokio = { workspace = true }
+wiremock = { workspace = true }
diff --git a/crates/fusionauth/src/error.rs b/crates/fusionauth/src/error.rs
index e0cedb27e3..388a9470d4 100644
--- a/crates/fusionauth/src/error.rs
+++ b/crates/fusionauth/src/error.rs
@@ -29,6 +29,9 @@ pub enum FusionAuthClientError {
/// The refresh token was not found or has expired.
#[error("refresh token was not found or has expired")]
InvalidRefreshToken,
+ /// Microsoft OAuth credentials were not configured.
+ #[error("Microsoft OAuth not configured")]
+ MicrosoftOAuthNotConfigured,
/// A generic error occurred.
#[error("an unknown error occurred")]
Generic(GenericErrorResponse),
diff --git a/crates/fusionauth/src/lib.rs b/crates/fusionauth/src/lib.rs
index 373de8d01a..df4d11b488 100644
--- a/crates/fusionauth/src/lib.rs
+++ b/crates/fusionauth/src/lib.rs
@@ -13,6 +13,8 @@ pub mod identity_provider;
pub mod jwt;
/// Logout operations.
pub mod logout;
+/// Microsoft identity provider and OAuth.
+pub mod microsoft;
/// OAuth authorization code grant.
pub mod oauth;
/// Password-based login.
@@ -93,6 +95,8 @@ pub struct FusionAuthClient {
google_client_id: String,
/// The client secret for Google identity provider
google_client_secret: String,
+ /// Optional Microsoft OAuth credentials.
+ microsoft_credentials: Option<microsoft::MicrosoftOAuthCredentials>,
}
impl FusionAuthClient {
@@ -120,6 +124,7 @@ impl FusionAuthClient {
unauth_client,
google_client_id,
google_client_secret,
+ microsoft_credentials: None,
}
}
diff --git a/crates/fusionauth/src/microsoft/mod.rs b/crates/fusionauth/src/microsoft/mod.rs
new file mode 100644
index 0000000000..9eb6e79e00
--- /dev/null
+++ b/crates/fusionauth/src/microsoft/mod.rs
@@ -0,0 +1,127 @@
+use std::fmt;
+
+use crate::{
+ FusionAuthClient, Result,
+ error::{FusionAuthClientError, GenericErrorResponse},
+};
+
+/// Microsoft OAuth token and ID-token operations.
+pub mod oauth;
+
+#[cfg(test)]
+mod test;
+
+#[derive(Clone)]
+pub(crate) struct MicrosoftOAuthCredentials {
+ client_id: String,
+ client_secret: String,
+ tenant_id: String,
+}
+
+impl fmt::Debug for MicrosoftOAuthCredentials {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter
+ .debug_struct("MicrosoftOAuthCredentials")
+ .field("client_id", &self.client_id)
+ .field("client_secret", &"[REDACTED]")
+ .field("tenant_id", &self.tenant_id)
+ .finish()
+ }
+}
+
+impl FusionAuthClient {
+ /// Configures the Microsoft OAuth application used for secondary account linking.
+ pub fn with_microsoft_credentials(
+ mut self,
+ client_id: String,
+ client_secret: String,
+ tenant_id: String,
+ ) -> Self {
+ self.microsoft_credentials = Some(MicrosoftOAuthCredentials {
+ client_id,
+ client_secret,
+ tenant_id,
+ });
+ self
+ }
+
+ /// Constructs a tenant-specific Microsoft OAuth authorization URL.
+ pub fn construct_microsoft_authorize_url<T>(
+ &self,
+ redirect_uri: &str,
+ state: &T,
+ ) -> Result<String>
+ where
+ T: serde::Serialize + ?Sized,
+ {
+ let credentials = self.microsoft_credentials()?;
+ oauth::construct_authorize_url(
+ &credentials.client_id,
+ &credentials.tenant_id,
+ redirect_uri,
+ state,
+ )
+ .map_err(FusionAuthClientError::from)
+ }
+
+ /// Exchanges a Microsoft authorization code for a refresh token and ID token.
+ #[tracing::instrument(skip(self, code, redirect_uri), err)]
+ pub async fn exchange_microsoft_code_for_tokens(
+ &self,
+ code: &str,
+ redirect_uri: &str,
+ ) -> Result<oauth::MicrosoftExchangeTokenResponse> {
+ let credentials = self.microsoft_credentials()?;
+ oauth::exchange_code_for_tokens(
+ &self.unauth_client,
+ &credentials.client_id,
+ &credentials.client_secret,
+ &credentials.tenant_id,
+ redirect_uri,
+ code,
+ )
+ .await
+ }
+
+ /// Verifies a Microsoft ID token against the tenant's OIDC signing keys and extracts the
+ /// identity claims. The signature, issuer, audience, tenant, expiration, and not-before
+ /// claims are all validated before any claim is trusted.
+ #[tracing::instrument(skip(self, id_token), err)]
+ pub async fn parse_microsoft_id_token(
+ &self,
+ id_token: &str,
+ ) -> Result<oauth::MicrosoftUserInfo> {
+ let credentials = self.microsoft_credentials()?;
+ let signing_keys = oauth::fetch_microsoft_signing_keys(
+ &self.unauth_client,
+ oauth::MICROSOFT_LOGIN_BASE_URL,
+ &credentials.tenant_id,
+ )
+ .await
+ .map_err(|error| {
+ tracing::error!(error=?error, "unable to fetch Microsoft OIDC signing keys");
+ FusionAuthClientError::Generic(GenericErrorResponse {
+ message: error.to_string(),
+ })
+ })?;
+
+ oauth::decode_microsoft_id_token(
+ id_token,
+ &signing_keys,
+ &credentials.client_id,
+ &credentials.tenant_id,
+ )
+ .map_err(|error| {
+ tracing::error!(error=?error, "unable to parse Microsoft ID token");
+ FusionAuthClientError::Generic(GenericErrorResponse {
+ message: error.to_string(),
+ })
+ })
+ }
+
+ fn microsoft_credentials(&self) -> Result<&MicrosoftOAuthCredentials> {
+ self.microsoft_credentials
+ .as_ref()
+ .ok_or(FusionAuthClientError::MicrosoftOAuthNotConfigured)
+ }
+}
diff --git a/crates/fusionauth/src/microsoft/oauth.rs b/crates/fusionauth/src/microsoft/oauth.rs
new file mode 100644
index 0000000000..8930166a31
--- /dev/null
+++ b/crates/fusionauth/src/microsoft/oauth.rs
@@ -0,0 +1,298 @@
+use std::time::Duration;
+
+use anyhow::Context;
+use jsonwebtoken::{Algorithm, DecodingKey, Validation};
+use reqwest::Url;
+
+use crate::{
+ Result, UnauthedClient,
+ error::{FusionAuthClientError, GenericErrorResponse},
+};
+
+pub(crate) const MICROSOFT_LOGIN_BASE_URL: &str = "https://login.microsoftonline.com/";
+const MICROSOFT_SCOPES: &str = "openid email offline_access profile Mail.ReadWrite Mail.Send";
+
+#[derive(serde::Serialize)]
+struct MicrosoftTokenExchangeRequest<'a> {
+ client_id: &'a str,
+ client_secret: &'a str,
+ code: &'a str,
+ grant_type: &'static str,
+ redirect_uri: &'a str,
+}
+
+#[derive(serde::Deserialize)]
+struct MicrosoftTokenExchangePayload {
+ refresh_token: String,
+ id_token: String,
+}
+
+/// Tokens returned by a Microsoft authorization-code exchange.
+pub struct MicrosoftExchangeTokenResponse {
+ /// The refresh token used to request future Microsoft Graph access tokens.
+ pub refresh_token: String,
+ /// The ID token containing the linked Microsoft identity.
+ pub id_token: String,
+}
+
+#[derive(serde::Deserialize)]
+struct MicrosoftIdTokenClaims {
+ tid: String,
+ sub: String,
+ email: Option<String>,
+ preferred_username: Option<String>,
+}
+
+#[derive(serde::Deserialize)]
+struct MicrosoftOpenIdConfiguration {
+ issuer: String,
+ jwks_uri: String,
+}
+
+#[derive(serde::Deserialize)]
+struct MicrosoftJsonWebKeySet {
+ keys: Vec<MicrosoftJsonWebKey>,
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub(crate) struct MicrosoftJsonWebKey {
+ pub(crate) kid: String,
+ pub(crate) kty: String,
+ pub(crate) n: String,
+ pub(crate) e: String,
+}
+
+/// The tenant's OIDC issuer and current signing keys, resolved through Microsoft OIDC discovery.
+#[derive(Debug)]
+pub(crate) struct MicrosoftSigningKeys {
+ pub(crate) issuer: String,
+ pub(crate) keys: Vec<MicrosoftJsonWebKey>,
+}
+
+/// Validated identity details extracted from a Microsoft ID token.
+#[derive(Debug, Eq, PartialEq)]
+pub struct MicrosoftUserInfo {
+ /// The tenant-specific Microsoft subject identifier.
+ pub sub: String,
+ /// The email claim, or `preferred_username` when the email claim is absent.
+ pub email: String,
+}
+
+pub(crate) fn construct_authorize_url<T>(
+ client_id: &str,
+ tenant_id: &str,
+ redirect_uri: &str,
+ state: &T,
+) -> anyhow::Result<String>
+where
+ T: serde::Serialize + ?Sized,
+{
+ 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("prompt", "select_account");
+
+ Ok(url.to_string())
+}
+
+pub(crate) async fn exchange_code_for_tokens(
+ client: &UnauthedClient,
+ client_id: &str,
+ client_secret: &str,
+ tenant_id: &str,
+ redirect_uri: &str,
+ code: &str,
+) -> Result<MicrosoftExchangeTokenResponse> {
+ let token_endpoint = endpoint_url(tenant_id, "token").map_err(FusionAuthClientError::from)?;
+ let request = MicrosoftTokenExchangeRequest {
+ client_id,
+ client_secret,
+ code,
+ grant_type: "authorization_code",
+ redirect_uri,
+ };
+
+ let response = client
+ .client()
+ .post(token_endpoint)
+ .form(&request)
+ .timeout(Duration::from_secs(30))
+ .send()
+ .await
+ .map_err(|error| {
+ tracing::error!(error=?error, "failed to send Microsoft token request");
+ generic_error(error.to_string())
+ })?;
+ let status = response.status();
+
+ if !status.is_success() {
+ let error_body = response.text().await.map_err(|error| {
+ tracing::error!(error=?error, "failed to read Microsoft token error response");
+ generic_error(error.to_string())
+ })?;
+ tracing::error!(?status, body=?error_body, "Microsoft token exchange failed");
+ return Err(generic_error(format!(
+ "Microsoft token exchange failed with status {status}: {error_body}"
+ )));
+ }
+
+ let payload = response
+ .json::<MicrosoftTokenExchangePayload>()
+ .await
+ .map_err(|error| {
+ tracing::error!(error=?error, "failed to parse Microsoft token response");
+ generic_error(error.to_string())
+ })?;
+
+ if payload.refresh_token.trim().is_empty() {
+ return Err(generic_error(
+ "Microsoft token response did not include a refresh token",
+ ));
+ }
+ if payload.id_token.trim().is_empty() {
+ return Err(generic_error(
+ "Microsoft token response did not include an ID token",
+ ));
+ }
+
+ Ok(MicrosoftExchangeTokenResponse {
+ refresh_token: payload.refresh_token,
+ id_token: payload.id_token,
+ })
+}
+
+pub(crate) async fn fetch_microsoft_signing_keys(
+ client: &UnauthedClient,
+ login_base_url: &str,
+ tenant_id: &str,
+) -> anyhow::Result<MicrosoftSigningKeys> {
+ let discovery_url = discovery_url(login_base_url, tenant_id)?;
+ let configuration: MicrosoftOpenIdConfiguration =
+ fetch_json(client, discovery_url, "OpenID configuration").await?;
+
+ let jwks_uri = Url::parse(&configuration.jwks_uri)
+ .context("Microsoft OpenID configuration contains an invalid JWKS URI")?;
+ let jwks: MicrosoftJsonWebKeySet = fetch_json(client, jwks_uri, "JWKS").await?;
+ if jwks.keys.is_empty() {
+ anyhow::bail!("Microsoft JWKS response did not contain any signing keys");
+ }
+
+ Ok(MicrosoftSigningKeys {
+ issuer: configuration.issuer,
+ keys: jwks.keys,
+ })
+}
+
+async fn fetch_json<T: serde::de::DeserializeOwned>(
+ client: &UnauthedClient,
+ url: Url,
+ resource: &str,
+) -> anyhow::Result<T> {
+ let response = client
+ .client()
+ .get(url)
+ .timeout(Duration::from_secs(30))
+ .send()
+ .await
+ .with_context(|| format!("failed to fetch Microsoft {resource}"))?;
+ let status = response.status();
+ if !status.is_success() {
+ anyhow::bail!("Microsoft {resource} request failed with status {status}");
+ }
+
+ response
+ .json::<T>()
+ .await
+ .with_context(|| format!("failed to parse Microsoft {resource} response"))
+}
+
+pub(crate) fn decode_microsoft_id_token(
+ id_token: &str,
+ signing_keys: &MicrosoftSigningKeys,
+ expected_audience: &str,
+ expected_tenant_id: &str,
+) -> anyhow::Result<MicrosoftUserInfo> {
+ let header = jsonwebtoken::decode_header(id_token)
+ .context("failed to decode Microsoft ID-token header")?;
+ if header.alg != Algorithm::RS256 {
+ anyhow::bail!("Microsoft ID token is not signed with an approved algorithm");
+ }
+ let kid = header
+ .kid
+ .context("Microsoft ID-token header does not contain a key ID")?;
+ let signing_key = signing_keys
+ .keys
+ .iter()
+ .find(|key| key.kid == kid)
+ .context("Microsoft ID token is not signed with a known signing key")?;
+ if signing_key.kty != "RSA" {
+ anyhow::bail!("Microsoft ID-token signing key is not an RSA key");
+ }
+
+ let decoding_key = DecodingKey::from_rsa_components(&signing_key.n, &signing_key.e)
+ .context("failed to construct a decoding key from the Microsoft signing key")?;
+ let mut validation = Validation::new(Algorithm::RS256);
+ validation.set_required_spec_claims(&["exp", "nbf", "aud", "iss"]);
+ validation.validate_nbf = true;
+ validation.set_audience(&[expected_audience]);
+ validation.set_issuer(&[&signing_keys.issuer]);
+
+ let claims =
+ jsonwebtoken::decode::<MicrosoftIdTokenClaims>(id_token, &decoding_key, &validation)
+ .context("Microsoft ID token failed signature or claims validation")?
+ .claims;
+
+ if claims.tid != expected_tenant_id {
+ anyhow::bail!("Microsoft ID-token tenant does not match the configured tenant");
+ }
+ if claims.sub.trim().is_empty() {
+ anyhow::bail!("Microsoft ID token does not contain a subject");
+ }
+
+ let email = claims
+ .email
+ .filter(|email| !email.trim().is_empty())
+ .or_else(|| {
+ claims
+ .preferred_username
+ .filter(|username| !username.trim().is_empty())
+ })
+ .context("Microsoft ID token does not contain an email or preferred username")?;
+
+ Ok(MicrosoftUserInfo {
+ sub: claims.sub,
+ email,
+ })
+}
+
+fn endpoint_url(tenant_id: &str, endpoint: &str) -> anyhow::Result<Url> {
+ let mut url =
+ Url::parse(MICROSOFT_LOGIN_BASE_URL).context("invalid Microsoft OAuth base URL")?;
+ url.path_segments_mut()
+ .expect("Microsoft OAuth base URL must support path segments")
+ .pop_if_empty()
+ .extend([tenant_id, "oauth2", "v2.0", endpoint]);
+ Ok(url)
+}
+
+fn discovery_url(login_base_url: &str, tenant_id: &str) -> anyhow::Result<Url> {
+ let mut url = Url::parse(login_base_url).context("invalid Microsoft OAuth base URL")?;
+ url.path_segments_mut()
+ .map_err(|()| anyhow::anyhow!("Microsoft OAuth base URL must support path segments"))?
+ .pop_if_empty()
+ .extend([tenant_id, "v2.0", ".well-known", "openid-configuration"]);
+ Ok(url)
+}
+
+fn generic_error(message: impl Into<String>) -> FusionAuthClientError {
+ FusionAuthClientError::Generic(GenericErrorResponse {
+ message: message.into(),
+ })
+}
diff --git a/crates/fusionauth/src/microsoft/test.rs b/crates/fusionauth/src/microsoft/test.rs
new file mode 100644
index 0000000000..8eef8a7f26
--- /dev/null
+++ b/crates/fusionauth/src/microsoft/test.rs
@@ -0,0 +1,388 @@
+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};
+
+use super::*;
+use crate::UnauthedClient;
+
+const TEST_KEY_ID: &str = "test-signing-key";
+
+const TEST_PRIVATE_KEY: &str = r#"-----BEGIN RSA PRIVATE KEY-----
+MIIEpAIBAAKCAQEAsAR6nHqp4SETFWaUoKS3zR5P6t8ztZGK005KQ9uwFhHUXUV4
+dX6+NZ7xS9WtHNzdr2VJBv3Pn3aTcEz6fdWK/zt7Ew/WncN5j8vZfcLDMp6fX3Xh
+37hU9UnlV7NhXtmpYP86i9vPIUw0bDyvv7oEwksbhFY0QawdqFm5//l7IoM1FYxY
+EaLtjcAEIrBkL7NSOgE01VcedY4VlYRnOArvHT+qwtMCrXv1a2jez0AfdyhO2U72
+kRkw0fGbUk/Yv3/gx3P1L40LwMSaT1ejl+pYmDLp46PCOjuMdKwuEgbuW3lIj8hc
+G06HBSK7OgwOXvUaDLVeICgOS2f1uRhZ4xXY2wIDAQABAoIBAARj0DUH4CXDv+iY
+Otu4z/a3K1IVyAHew+IaQULo/z7FqhC7c1Im25KVyLnV9e/S2FqQAZ7BhMSa3fl+
+if7KbSGJd7vVeMpNfkImWOHIkjq4dwwX8g6017WYZrZlvGdzsURAiVLEpClV77bF
+WrLC7mx0GBcYWUxMAR9aQYfPTpFhPsEgjmBttPl3AseOEb9Ql8cSHOVt019du1q8
+3LRd9jR14UVK9k62WPUA/sJ1cC9w5CsZyJH1GXcsjf9rwu//ss9nipXGqMCgbe2i
+8ABd+RhcfDf6Gx/TRyJ9AxJNJNA2g6txKkH6pcWFPmczDhmpsLgcnJvv0tNWJeVS
+xvRI040CgYEA2zxtEvQpuUsF2edRfl5nTFlOGW/JPtA+LUkM0kNfQd3q5FPDUXlR
+UyEE+SuU2Zp2g/fBfox03NbFFhHhDxtuptlQeDQlqMR/zlnnlehhiNz6k9m+YX6l
+d1hCNpJM4d1IRxKf99mBlJPlTLwU7felLELH1XlYtG/x4FP19YjremUCgYEAzYi5
+2ymFM3NcY0+FORSreFfoIQdPkZ4XVP/sRl+eMidu0Q6fnOTQFFXUx+NiL4/v9GMq
+YMzbjLbODNAD6i17hliWS1x4xHA4LhKXMARFeDSDCFwSeCicbpRJJRr8DB+yUPtX
+5Tad68JyTcRLp+0t4cKDx18WVp8WWcPxP00fMj8CgYEArM+dvsH9nZQ4gYHn5+9s
+B2+hs0U9YajuSe36EEeQ76+ItwAbxr4VT6yIagxjYX9zCiUiPaljeKxGYFYpjCn4
+d8Z2urmIMdbqU3LkrHKnZyWg0yhg/CLDNSa50qBRv/wYPAW/WLP3g3Fs3qam7Mk3
+RoNBV9E2Dczr4QLtruSFkU0CgYEAxEkbFc6lQumdBcrftA+lYhyxtzlAKBUOu0Jd
+5ydR8RvvnP+WN0Pd5E3EE9F352xTANXjluaNlejPBzVxR6eAHGFlxzrcqt1xCa7/
+a//oSE/+A3HKwa4nFwPOhv0qUHnE1cnzuxdZ4dmlR9d7WTgNZVlaeIC62Ka9taSH
+NKj2bgkCgYBklT3jCD3vvUpLLgyIL92Dv3Sk6YvkFftkKvZDxqmH2CjmqkcXFW7+
+zA9/aondVhZwdixoc6nnqzVyKBiTmLn804nICpDHxyNayRXAbum+aFqM7tfhG+/T
+m5UIYS903JMnauKzKOF5xn+3qIBkMkXluyq2wIRIi+V6DmZKlpxTDw==
+-----END RSA PRIVATE KEY-----"#;
+
+const TEST_MODULUS: &str = "sAR6nHqp4SETFWaUoKS3zR5P6t8ztZGK005KQ9uwFhHUXUV4dX6-NZ7xS9WtHNzdr2VJBv3Pn3aTcEz6fdWK_zt7Ew_WncN5j8vZfcLDMp6fX3Xh37hU9UnlV7NhXtmpYP86i9vPIUw0bDyvv7oEwksbhFY0QawdqFm5__l7IoM1FYxYEaLtjcAEIrBkL7NSOgE01VcedY4VlYRnOArvHT-qwtMCrXv1a2jez0AfdyhO2U72kRkw0fGbUk_Yv3_gx3P1L40LwMSaT1ejl-pYmDLp46PCOjuMdKwuEgbuW3lIj8hcG06HBSK7OgwOXvUaDLVeICgOS2f1uRhZ4xXY2w";
+
+/// A second key pair whose private key does not match `TEST_MODULUS`, used to forge signatures.
+const OTHER_PRIVATE_KEY: &str = r#"-----BEGIN RSA PRIVATE KEY-----
+MIIEpQIBAAKCAQEAptcayMug1gOK1fjWp163qoLbrEouZOl16fFEGy8enPch1USS
+BYcjenMPISXZo7yIQbzdIRHEz43JpxJo6gac8SdnV++ibg5SyI1rSYfeRrzrnLCs
+yszBBQ4BSbAeRe5hk0fSxWRT8yl+p+e11onFPRN5Du3OHT9x1KxvuOcCVrh/M5uN
+yj8UZHZvoT3SAnz8r6uvwvvzutybTIjzxEq14NLwVJlf16COzAzWldIN3vq6b0KK
+/KLK6OPib/EiFrUj6pBXQNMlnWO9z7AP8fS71N1xYcTes2GnMQbfPz0jcU36NXcn
++DgLoBEbpqerGSvq1kPOdygyFXT0WxVK4lJ0LQIDAQABAoIBAALJS963m9+HHp31
+MmyIJewYlF+bu4ue5IO8LkV/83RuoieEJiYmfB6y5jlI/wn/f40NgOno+I740LnU
+EmF6K8vROyYaT+2jmplT10talAk9ZXfv8WrPoZeahMX8xXyofwOtKuV2B/rjIgTe
+10gWc+9RsG9h5FPTt+xz1sfRP9Y/5qSX8/SlbuiJNu+UWLqsWXUtPaKTd36kpAu9
+EB+UFL3fcqmJWfP1n+K5rnJk74UOuwwPb8cghartawwvz8Prp4suts+rEaxS6zkL
+DW+X8OW/qMAGD79YgTtfF2PjigRrKt25IyJjciPDSqAgtbdr1yhPGNWhPO9yDx05
+bD+5rjcCgYEA0aSZJBrOYddx0ji3C+f3JAyhQsV2pDwx2r99FVKGVFyG3HdwQciW
+WjQSNnE12tm3LuCmiEErJr5xuptMXDaICuAJhyM16uyIkCJ6KCiYX77IcOqPBNtn
+aT8sGgoOLTb7tkdCaoDItfL8sWlRvE1g24ry/rZyJZ4zDfWzh869nM8CgYEAy7uL
+WQ4xxDed8Nc14+u5n61JJ3LpwKzUdWGiEB1IVzxyT77AN5kFVHBRXGmFLjou0iA2
+xW+7SRMnMpC6xTyVioTpSPNsf7cmXYRyuTT7aV+/C4hyIgXDJCDKzd3W6/I86gXU
+LI+9zOoklHoSBa/yOBMBBOlGdvZ/on/rpoGldkMCgYEA0R5MOEyZA9Yhzp4OUU0R
+JJ+ImI9aWldFL7wFbKiGIE6vo+lsS+JnwBDi/fWN0AGOja8/zviar6oWzhqtX+px
+Z8+1EV0ZIn7Rdl091yMvY4pubNw8z46AJ+cA+fR/0bBgA6IvaQePrpd0Yw/4nUne
+TQDchSG+2TFmIg2uCNE8KNcCgYEAlvTv25zY4zsSnFHabHdNozMS8VgEO+/TvOYK
+30XTRFBVoyED7C5F9LsEjiThuc8Cwk98Re70JsE6Wg1DVsH9TBYPhS5ZRoi+tKxf
+FTxczUdUl4cSioMahLqHiuLFTS7AU+bdv+cCC8OyNxH8KJqmL0Zliu4OeDdNe2qt
+gUKvB2ECgYEAk7nhlRphHCzNG496WURcVh9IWnle42X8WD6Ea+UWFY7mGLpTGDDd
+ShsvpFNoypKKPZfrQrZdKJ6QnwX8jRSL0X9uKT8z7ey0zFM4OOxCmUmoM2Fk5BwD
+8SMSuhPm1cKUhmSvOh7yK+f9/WVipjeLZoMUWoZZAqiFoh2+NQVRmrA=
+-----END RSA PRIVATE KEY-----"#;
+
+fn client() -> FusionAuthClient {
+ FusionAuthClient::new(
+ "api-key".into(),
+ "fusionauth-client-id".into(),
+ "fusionauth-client-secret".into(),
+ "http://fusionauth:9011".into(),
+ "http://localhost:28011/oauth/redirect".into(),
+ "google-client-id".into(),
+ "google-client-secret".into(),
+ )
+}
+
+fn microsoft_client() -> FusionAuthClient {
+ client().with_microsoft_credentials(
+ "microsoft-client-id".into(),
+ "microsoft-client-secret".into(),
+ "microsoft-tenant-id".into(),
+ )
+}
+
+fn signing_keys() -> oauth::MicrosoftSigningKeys {
+ oauth::MicrosoftSigningKeys {
+ issuer: "https://login.microsoftonline.com/microsoft-tenant-id/v2.0".into(),
+ keys: vec![oauth::MicrosoftJsonWebKey {
+ kid: TEST_KEY_ID.into(),
+ kty: "RSA".into(),
+ n: TEST_MODULUS.into(),
+ e: "AQAB".into(),
+ }],
+ }
+}
+
+fn now() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs()
+}
+
+fn valid_claims() -> serde_json::Value {
+ serde_json::json!({
+ "iss": "https://login.microsoftonline.com/microsoft-tenant-id/v2.0",
+ "aud": "microsoft-client-id",
+ "tid": "microsoft-tenant-id",
+ "sub": "microsoft-user-id",
+ "email": "[email protected]",
+ "exp": now() + 3600,
+ "nbf": now() - 300,
+ })
+}
+
+fn signed_id_token(private_key: &str, kid: &str, claims: &serde_json::Value) -> String {
+ let mut header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::RS256);
+ header.kid = Some(kid.to_string());
+ jsonwebtoken::encode(
+ &header,
+ claims,
+ &jsonwebtoken::EncodingKey::from_rsa_pem(private_key.as_bytes()).unwrap(),
+ )
+ .unwrap()
+}
+
+fn decode_id_token(token: &str) -> anyhow::Result<oauth::MicrosoftUserInfo> {
+ oauth::decode_microsoft_id_token(
+ token,
+ &signing_keys(),
+ "microsoft-client-id",
+ "microsoft-tenant-id",
+ )
+}
+
+#[test]
+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",
+ )
+ .unwrap();
+ let url = reqwest::Url::parse(&url).unwrap();
+ let query: HashMap<_, _> = url.query_pairs().into_owned().collect();
+
+ assert_eq!(
+ url.as_str().split('?').next().unwrap(),
+ "https://login.microsoftonline.com/microsoft-tenant-id/oauth2/v2.0/authorize"
+ );
+ assert_eq!(query.get("client_id").unwrap(), "microsoft-client-id");
+ assert_eq!(
+ query.get("redirect_uri").unwrap(),
+ "https://auth.example.com/oauth2/microsoft/callback"
+ );
+ assert_eq!(query.get("response_type").unwrap(), "code");
+ assert_eq!(
+ query.get("scope").unwrap(),
+ "openid email offline_access profile Mail.ReadWrite Mail.Send"
+ );
+ 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(),
+ };
+ let url = microsoft_client()
+ .construct_microsoft_authorize_url(
+ "https://auth.example.com/oauth2/microsoft/callback",
+ &state,
+ )
+ .unwrap();
+ let url = reqwest::Url::parse(&url).unwrap();
+ let serialized_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
+ );
+}
+
+#[test]
+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",
+ )
+ .unwrap_err();
+ assert!(matches!(
+ error,
+ FusionAuthClientError::MicrosoftOAuthNotConfigured
+ ));
+
+ let client = microsoft_client();
+ let cloned_client = client.clone();
+ assert!(!format!("{client:?}").contains("microsoft-client-secret"));
+ cloned_client
+ .construct_microsoft_authorize_url(
+ "https://auth.example.com/oauth2/microsoft/callback",
+ &"state",
+ )
+ .unwrap();
+}
+
+#[test]
+fn id_token_claims_are_validated_and_email_is_preferred() {
+ let mut claims = valid_claims();
+ claims["preferred_username"] = serde_json::json!("[email protected]");
+ let token = signed_id_token(TEST_PRIVATE_KEY, TEST_KEY_ID, &claims);
+
+ let user = decode_id_token(&token).unwrap();
+
+ assert_eq!(user.sub, "microsoft-user-id");
+ assert_eq!(user.email, "[email protected]");
+}
+
+#[test]
+fn id_token_uses_preferred_username_when_email_is_absent() {
+ let mut claims = valid_claims();
+ claims["email"] = serde_json::Value::Null;
+ claims["preferred_username"] = serde_json::json!("[email protected]");
+ let token = signed_id_token(TEST_PRIVATE_KEY, TEST_KEY_ID, &claims);
+
+ let user = decode_id_token(&token).unwrap();
+
+ assert_eq!(user.email, "[email protected]");
+}
+
+#[test]
+fn id_token_rejects_invalid_claims() {
+ for (claim, invalid_value) in [
+ ("iss", serde_json::json!("https://evil.example.com/v2.0")),
+ ("aud", serde_json::json!("another-client")),
+ ("tid", serde_json::json!("another-tenant")),
+ ("sub", serde_json::json!("")),
+ ("email", serde_json::Value::Null),
+ ("exp", serde_json::json!(now() - 3600)),
+ ("exp", serde_json::Value::Null),
+ ("nbf", serde_json::json!(now() + 3600)),
+ ("nbf", serde_json::Value::Null),
+ ] {
+ let mut claims = valid_claims();
+ claims[claim] = invalid_value;
+ let token = signed_id_token(TEST_PRIVATE_KEY, TEST_KEY_ID, &claims);
+
+ assert!(
+ decode_id_token(&token).is_err(),
+ "claim {claim} should have been rejected"
+ );
+ }
+}
+
+#[test]
+fn id_token_rejects_invalid_signatures() {
+ // Signed by a key the tenant does not advertise, while claiming the trusted key ID.
+ let forged = signed_id_token(OTHER_PRIVATE_KEY, TEST_KEY_ID, &valid_claims());
+ assert!(decode_id_token(&forged).is_err());
+
+ // Signed with an unknown key ID.
+ let unknown_kid = signed_id_token(TEST_PRIVATE_KEY, "unknown-key", &valid_claims());
+ assert!(decode_id_token(&unknown_kid).is_err());
+
+ // Valid token whose signature has been stripped.
+ let valid = signed_id_token(TEST_PRIVATE_KEY, TEST_KEY_ID, &valid_claims());
+ let mut parts = valid.split('.');
+ let (header, payload) = (parts.next().unwrap(), parts.next().unwrap());
+ assert!(decode_id_token(&format!("{header}.{payload}.")).is_err());
+
+ // Unsigned token claiming the "none" algorithm.
+ let none_header = URL_SAFE_NO_PAD.encode(format!(r#"{{"alg":"none","kid":"{TEST_KEY_ID}"}}"#));
+ assert!(decode_id_token(&format!("{none_header}.{payload}.signature")).is_err());
+
+ // Token signed with a symmetric algorithm using the trusted key ID.
+ let mut header = jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS256);
+ header.kid = Some(TEST_KEY_ID.to_string());
+ let symmetric = jsonwebtoken::encode(
+ &header,
+ &valid_claims(),
+ &jsonwebtoken::EncodingKey::from_secret(TEST_MODULUS.as_bytes()),
+ )
+ .unwrap();
+ assert!(decode_id_token(&symmetric).is_err());
+}
+
+#[tokio::test]
+async fn signing_keys_are_fetched_through_oidc_discovery() {
+ let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path(
+ "/microsoft-tenant-id/v2.0/.well-known/openid-configuration",
+ ))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "issuer": "https://login.microsoftonline.com/microsoft-tenant-id/v2.0",
+ "jwks_uri": format!("{}/microsoft-tenant-id/discovery/v2.0/keys", server.uri()),
+ })))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/microsoft-tenant-id/discovery/v2.0/keys"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "keys": [{
+ "kid": TEST_KEY_ID,
+ "kty": "RSA",
+ "use": "sig",
+ "n": TEST_MODULUS,
+ "e": "AQAB",
+ }]
+ })))
+ .mount(&server)
+ .await;
+
+ let signing_keys = oauth::fetch_microsoft_signing_keys(
+ &UnauthedClient::default(),
+ &server.uri(),
+ "microsoft-tenant-id",
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ signing_keys.issuer,
+ "https://login.microsoftonline.com/microsoft-tenant-id/v2.0"
+ );
+ let token = signed_id_token(TEST_PRIVATE_KEY, TEST_KEY_ID, &valid_claims());
+ let user = oauth::decode_microsoft_id_token(
+ &token,
+ &signing_keys,
+ "microsoft-client-id",
+ "microsoft-tenant-id",
+ )
+ .unwrap();
+ assert_eq!(user.sub, "microsoft-user-id");
+}
+
+#[tokio::test]
+async fn signing_key_fetch_rejects_an_empty_key_set() {
+ let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path(
+ "/microsoft-tenant-id/v2.0/.well-known/openid-configuration",
+ ))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "issuer": "https://login.microsoftonline.com/microsoft-tenant-id/v2.0",
+ "jwks_uri": format!("{}/microsoft-tenant-id/discovery/v2.0/keys", server.uri()),
+ })))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/microsoft-tenant-id/discovery/v2.0/keys"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ "keys": [] })))
+ .mount(&server)
+ .await;
+
+ let error = oauth::fetch_microsoft_signing_keys(
+ &UnauthedClient::default(),
+ &server.uri(),
+ "microsoft-tenant-id",
+ )
+ .await
+ .unwrap_err();
+
+ assert!(
+ error
+ .to_string()
+ .contains("did not contain any signing keys")
+ );
+}
diff --git a/packages/sdk/generated/auth/index.ts b/packages/sdk/generated/auth/index.ts
index c60efc8a9b..e7cadf72ac 100644
--- a/packages/sdk/generated/auth/index.ts
+++ b/packages/sdk/generated/auth/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AbGroup, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, ClientOptions, CreateAccountMergeRequest, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreateUserData, CreateUserError, CreateUserErrors, CreateUserRequest, CreateUserResponse, CreateUserResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestRef, GithubPullRequestStatus, GmailLinkStatusResponse, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StripeSessionResponse, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';
+export type { AbGroup, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, ClientOptions, CreateAccountMergeRequest, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreateUserData, CreateUserError, CreateUserErrors, CreateUserRequest, CreateUserResponse, CreateUserResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestRef, GithubPullRequestStatus, GmailLinkStatusResponse, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StripeSessionResponse, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';
diff --git a/packages/sdk/generated/auth/sdk.gen.ts b/packages/sdk/generated/auth/sdk.gen.ts
index 9b9d856a84..834d514222 100644
--- a/packages/sdk/generated/auth/sdk.gen.ts
+++ b/packages/sdk/generated/auth/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamResponses, CreateUserData, CreateUserErrors, CreateUserResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetTeamData, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';
+import type { AppleLoginData, AppleLoginErrors, AppleLoginResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Responses, CreateInProgressLinkData, CreateInProgressLinkErrors, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestErrors, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionErrors, CreatePortalSessionResponses, CreateTeamData, CreateTeamErrors, CreateTeamResponses, CreateUserData, CreateUserErrors, CreateUserResponses, DeleteGithubLinkData, DeleteGithubLinkErrors, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserErrors, DeleteUserResponses, EnrichGithubPullRequestsData, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsResponses, GenerateEmailLinkData, GenerateEmailLinkErrors, GenerateEmailLinkResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponses, GetPermissionsData, GetPermissionsErrors, GetPermissionsResponses, GetReferralCodeData, GetReferralCodeErrors, GetReferralCodeResponses, GetTeamData, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesErrors, GetTeamInvitesResponses, GetTeamResponses, GetUserInfoData, GetUserInfoErrors, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesErrors, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsErrors, GetUserLinkExistsResponses, GetUserNameData, GetUserNameErrors, GetUserNameResponses, GetUserNamesData, GetUserNamesErrors, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationErrors, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsErrors, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaErrors, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsErrors, GetUserTeamsResponses, HealthHandlerData, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkErrors, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkErrors, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkErrors, InitOutlookLinkResponses, InviteToTeamData, InviteToTeamErrors, InviteToTeamResponses, JoinTeamData, JoinTeamErrors, JoinTeamResponses, LogoutData, LogoutResponses, MacroApiTokenData, MacroApiTokenErrors, MacroApiTokenResponses, Oauth2CallbackData, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackErrors, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginErrors, PasswordlessLoginResponses, PasswordLoginData, PasswordLoginErrors, PasswordLoginResponses, PatchTeamCrmSettingsData, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamErrors, PatchTeamResponses, PatchUserGroupData, PatchUserGroupErrors, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingErrors, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialErrors, PatchUserTutorialResponses, PostProfilePicturesData, PostProfilePicturesErrors, PostProfilePicturesResponses, PutProfilePictureData, PutProfilePictureErrors, PutProfilePictureResponses, PutUserNameData, PutUserNameErrors, PutUserNameResponses, RefreshData, RefreshErrors, RefreshResponses, RejectInvitationData, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailResponses, SendMobileWelcomeEmailData, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeErrors, SendReferralCodeResponses, SessionCreationData, SessionCreationErrors, SessionCreationResponses, SessionLoginData, SessionLoginErrors, SessionLoginResponses, SsoLoginData, SsoLoginErrors, SsoLoginResponses, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponses, VerifyEmailLinkData, VerifyEmailLinkErrors, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestErrors, VerifyMergeRequestResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -185,6 +185,13 @@ export class Sdk extends HeyApiClient {
return (options?.client ?? this.client).get<CheckGmailLinkStatusResponses, CheckGmailLinkStatusErrors, ThrowOnError>({ url: '/link/gmail/status', ...options });
}
+ /**
+ * Initiates a Microsoft Outlook account link for an authenticated user.
+ */
+ public initOutlookLink<ThrowOnError extends boolean = false>(options?: Options<InitOutlookLinkData, ThrowOnError>): RequestResult<InitOutlookLinkResponses, InitOutlookLinkErrors, ThrowOnError> {
+ return (options?.client ?? this.client).post<InitOutlookLinkResponses, InitOutlookLinkErrors, ThrowOnError>({ url: '/link/outlook', ...options });
+ }
+
/**
* Completes the apple login flow
*/
diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.ts
index 8e21965640..9b3196d156 100644
--- a/packages/sdk/generated/auth/types.gen.ts
+++ b/packages/sdk/generated/auth/types.gen.ts
@@ -471,6 +471,20 @@ export type InitGmailLinkResponse = {
link_id: string;
};
+/**
+ * Response returned when a Microsoft Outlook link is initiated.
+ */
+export type InitOutlookLinkResponse = {
+ /**
+ * The OAuth authorization URL to redirect the user to.
+ */
+ authorization_url: string;
+ /**
+ * The link ID for tracking the OAuth flow.
+ */
+ link_id: string;
+};
+
/**
* A single invite entry with email and tier
*/
@@ -1246,6 +1260,34 @@ export type CheckGmailLinkStatusResponses = {
export type CheckGmailLinkStatusResponse = CheckGmailLinkStatusResponses[keyof CheckGmailLinkStatusResponses];
+export type InitOutlookLinkData = {
+ body?: never;
+ path?: never;
+ query?: {
+ /**
+ * **OPTIONAL**. The original URL to redirect to.
+ */
+ original_url?: string;
+ };
+ url: '/link/outlook';
+};
+
+export type InitOutlookLinkErrors = {
+ 400: ErrorResponse;
+ 401: ErrorResponse;
+ 404: ErrorResponse;
+ 429: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type InitOutlookLinkError = InitOutlookLinkErrors[keyof InitOutlookLinkErrors];
+
+export type InitOutlookLinkResponses = {
+ 200: InitOutlookLinkResponse;
+};
+
+export type InitOutlookLinkResponse2 = InitOutlookLinkResponses[keyof InitOutlookLinkResponses];
+
export type AppleLoginData = {
body: AppleLoginRequest;
path?: never;
diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.json
index 7bb832ad8a..da2bdcb59d 100644
--- a/packages/sdk/specs/auth.json
+++ b/packages/sdk/specs/auth.json
@@ -758,6 +758,86 @@
}
}
},
+ "/link/outlook": {
+ "post": {
+ "tags": ["link::outlook"],
+ "summary": "Initiates a Microsoft Outlook account link for an authenticated user.",
+ "operationId": "init_outlook_link",
+ "parameters": [
+ {
+ "name": "original_url",
+ "in": "query",
+ "description": "**OPTIONAL**. The original URL to redirect to.",
+ "required": false,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/InitOutlookLinkResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "429": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/login/apple": {
"post": {
"tags": ["login::apple"],
@@ -4067,6 +4147,22 @@
}
}
},
+ "InitOutlookLinkResponse": {
+ "type": "object",
+ "description": "Response returned when a Microsoft Outlook link is initiated.",
+ "required": ["authorization_url", "link_id"],
+ "properties": {
+ "authorization_url": {
+ "type": "string",
+ "description": "The OAuth authorization URL to redirect the user to."
+ },
+ "link_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The link ID for tracking the OAuth flow."
+ }
+ }
+ },
"InviteEntry": {
"type": "object",
"description": "A single invite entry with email and tier",
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index 772066f6f0..5bb6096e5b 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -52,6 +52,7 @@ export const authExcluded = [
'healthHandler',
'initGithubLink',
'initGmailLink',
+ 'initOutlookLink',
'inviteToTeam',
'joinTeam',
'logout',
diff --git a/services/authentication_service/src/api/link/mod.rs b/services/authentication_service/src/api/link/mod.rs
index df22aa4fb3..5d360b8f54 100644
--- a/services/authentication_service/src/api/link/mod.rs
+++ b/services/authentication_service/src/api/link/mod.rs
@@ -6,6 +6,7 @@ use axum::{
pub(in crate::api) mod create_in_progress_link;
pub(in crate::api) mod github;
pub(in crate::api) mod gmail;
+pub(in crate::api) mod outlook;
/// Routes for authenticated account-link operations.
pub fn router() -> Router<ApiContext> {
@@ -19,4 +20,5 @@ pub fn router() -> Router<ApiContext> {
)
.route("/gmail", post(gmail::init_gmail_link_handler))
.route("/gmail/status", get(gmail::check_gmail_link_status_handler))
+ .route("/outlook", post(outlook::init_outlook_link_handler))
}
diff --git a/services/authentication_service/src/api/link/outlook.rs b/services/authentication_service/src/api/link/outlook.rs
new file mode 100644
index 0000000000..dcd27968d7
--- /dev/null
+++ b/services/authentication_service/src/api/link/outlook.rs
@@ -0,0 +1,168 @@
+use axum::{
+ Json,
+ extract::{Query, State},
+ http::StatusCode,
+ response::{IntoResponse, Response},
+};
+use fusionauth::error::FusionAuthClientError;
+use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
+use macro_middleware::tracking::ClientIp;
+use model::response::ErrorResponse;
+use serde_utils::urlencode::UrlEncoded;
+use url::Url;
+
+use crate::api::{
+ context::{ApiContext, AuthorizationService},
+ oauth2::OAuthState,
+};
+
+#[cfg(test)]
+mod test;
+
+const MICROSOFT_IDENTITY_PROVIDER_NAME: &str = "microsoft";
+const MAX_IN_PROGRESS_LINKS: i64 = 5;
+
+/// Response returned when a Microsoft Outlook link is initiated.
+#[derive(Debug, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
+pub struct InitOutlookLinkResponse {
+ /// The OAuth authorization URL to redirect the user to.
+ pub authorization_url: String,
+ /// The link ID for tracking the OAuth flow.
+ pub link_id: uuid::Uuid,
+}
+
+/// Errors that can occur while initiating a Microsoft Outlook link.
+#[derive(Debug, thiserror::Error)]
+pub enum InitOutlookLinkError {
+ /// Too many account-link attempts are already in progress.
+ #[error("too many in progress links")]
+ TooManyInProgressLinks,
+ /// The Microsoft identity provider does not exist in FusionAuth.
+ #[error("identity provider not found")]
+ IdentityProviderNotFound,
+ /// An internal operation failed.
+ #[error("internal error occurred")]
+ InternalError(#[from] anyhow::Error),
+}
+
+impl IntoResponse for InitOutlookLinkError {
+ fn into_response(self) -> Response {
+ let status_code = match &self {
+ Self::TooManyInProgressLinks => StatusCode::TOO_MANY_REQUESTS,
+ Self::IdentityProviderNotFound => StatusCode::NOT_FOUND,
+ Self::InternalError(error) => {
+ tracing::error!(error=?error, "failed to initiate Outlook link");
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ };
+
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: self.to_string().into(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+#[derive(Debug, serde::Deserialize)]
+pub(crate) struct InitOutlookLinkQueryParams {
+ /// Once the frontend is updated to not double-urlencode this, change this to `Option<Url>`.
+ original_url: Option<UrlEncoded<Url>>,
+}
+
+/// Initiates a Microsoft Outlook account link for an authenticated user.
+#[utoipa::path(
+ post,
+ operation_id = "init_outlook_link",
+ path = "/link/outlook",
+ params(
+ ("original_url" = Option<String>, Query, description = "**OPTIONAL**. The original URL to redirect to.")
+ ),
+ responses(
+ (status = 200, body = InitOutlookLinkResponse),
+ (status = 400, body = ErrorResponse),
+ (status = 401, body = ErrorResponse),
+ (status = 404, body = ErrorResponse),
+ (status = 429, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(ctx, ip_context, authorization), fields(client_ip=%ip_context, user_id=%authorization.authorization.user.user_context.user_id, fusion_user_id=%authorization.authorization.user.user_context.fusion_user_id), err)]
+pub async fn init_outlook_link_handler(
+ State(ctx): State<ApiContext>,
+ Query(InitOutlookLinkQueryParams { original_url }): Query<InitOutlookLinkQueryParams>,
+ ip_context: ClientIp,
+ authorization: MacroAuthorizationExtractor<AuthorizationService, UserOrInternal>,
+) -> Result<Json<InitOutlookLinkResponse>, InitOutlookLinkError> {
+ let microsoft_idp_id = ctx
+ .auth_client
+ .get_identity_provider_id_by_name(MICROSOFT_IDENTITY_PROVIDER_NAME)
+ .await
+ .map_err(map_identity_provider_lookup_error)?;
+
+ let fusion_user_id = &authorization.authorization.user.user_context.fusion_user_id;
+ let count =
+ macro_db_client::in_progress_user_link::count_existing_in_progress_user_links_for_user(
+ &ctx.db,
+ fusion_user_id,
+ )
+ .await?;
+
+ if count >= MAX_IN_PROGRESS_LINKS {
+ return Err(InitOutlookLinkError::TooManyInProgressLinks);
+ }
+
+ let link_id = macro_db_client::in_progress_user_link::create_in_progress_user_link(
+ &ctx.db,
+ 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)
+ {
+ Ok(authorization_url) => authorization_url,
+ Err(error) => {
+ let _ = macro_db_client::in_progress_user_link::delete_in_progress_user_link(
+ &ctx.db, &link_id,
+ )
+ .await
+ .inspect_err(|cleanup_error| {
+ tracing::warn!(
+ error=?cleanup_error,
+ %link_id,
+ "failed to clean up pending Outlook link"
+ );
+ });
+ return Err(map_microsoft_oauth_error(error));
+ }
+ };
+
+ Ok(Json(InitOutlookLinkResponse {
+ authorization_url,
+ link_id,
+ }))
+}
+
+fn map_identity_provider_lookup_error(error: FusionAuthClientError) -> InitOutlookLinkError {
+ match error {
+ FusionAuthClientError::NoIdentityProviderFound => {
+ InitOutlookLinkError::IdentityProviderNotFound
+ }
+ error => InitOutlookLinkError::InternalError(error.into()),
+ }
+}
+
+fn map_microsoft_oauth_error(error: FusionAuthClientError) -> InitOutlookLinkError {
+ InitOutlookLinkError::InternalError(error.into())
+}
diff --git a/services/authentication_service/src/api/link/outlook/test.rs b/services/authentication_service/src/api/link/outlook/test.rs
new file mode 100644
index 0000000000..ab4893fbb9
--- /dev/null
+++ b/services/authentication_service/src/api/link/outlook/test.rs
@@ -0,0 +1,77 @@
+use axum::response::IntoResponse;
+use fusionauth::error::{FusionAuthClientError, GenericErrorResponse};
+use http_body_util::BodyExt;
+use utoipa::OpenApi;
+
+use super::*;
+use crate::api::swagger::ApiDoc;
+
+#[tokio::test]
+async fn missing_microsoft_identity_provider_maps_to_not_found() {
+ let response =
+ map_identity_provider_lookup_error(FusionAuthClientError::NoIdentityProviderFound)
+ .into_response();
+
+ assert_eq!(response.status(), StatusCode::NOT_FOUND);
+ let body = response.into_body().collect().await.unwrap().to_bytes();
+ let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(body["message"], "identity provider not found");
+}
+
+#[test]
+fn other_identity_provider_lookup_errors_map_to_internal_server_error() {
+ let response =
+ map_identity_provider_lookup_error(FusionAuthClientError::Generic(GenericErrorResponse {
+ message: "FusionAuth unavailable".into(),
+ }))
+ .into_response();
+
+ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
+}
+
+#[test]
+fn disabled_microsoft_oauth_maps_to_internal_server_error() {
+ let response = map_microsoft_oauth_error(FusionAuthClientError::MicrosoftOAuthNotConfigured)
+ .into_response();
+
+ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
+}
+
+#[test]
+fn original_url_is_optional() {
+ let params: InitOutlookLinkQueryParams = serde_json::from_value(serde_json::json!({})).unwrap();
+
+ assert!(params.original_url.is_none());
+}
+
+#[test]
+fn outlook_link_openapi_includes_path_schema_and_error_responses() {
+ let openapi = serde_json::to_value(ApiDoc::openapi()).unwrap();
+ let operation = &openapi["paths"]["/link/outlook"]["post"];
+
+ assert_eq!(operation["operationId"], "init_outlook_link");
+ assert_eq!(
+ operation["responses"]["200"]["content"]["application/json"]["schema"]["$ref"].as_str(),
+ Some("#/components/schemas/InitOutlookLinkResponse")
+ );
+
+ for status in ["401", "404", "429", "500"] {
+ assert!(
+ operation["responses"].get(status).is_some(),
+ "missing documented {status} response"
+ );
+ }
+
+ let original_url = operation["parameters"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|parameter| parameter["name"] == "original_url")
+ .unwrap();
+ assert_ne!(original_url["required"].as_bool(), Some(true));
+ assert!(
+ openapi["components"]["schemas"]
+ .get("InitOutlookLinkResponse")
+ .is_some()
+ );
+}
diff --git a/services/authentication_service/src/api/oauth2/account_link.rs b/services/authentication_service/src/api/oauth2/account_link.rs
new file mode 100644
index 0000000000..39eae1a5df
--- /dev/null
+++ b/services/authentication_service/src/api/oauth2/account_link.rs
@@ -0,0 +1,201 @@
+use std::borrow::Cow;
+
+use axum::{
+ Json,
+ response::{IntoResponse, Redirect, Response},
+};
+use fusionauth::{
+ FusionAuthClient,
+ identity_provider::{IdentityProviderLink, LinkUserRequest},
+};
+use model::response::ErrorResponse;
+use reqwest::StatusCode;
+use url::Url;
+use uuid::Uuid;
+
+use crate::api::context::ApiContext;
+
+#[cfg(test)]
+mod test;
+
+type AccountLinkResult<T> = Result<T, (StatusCode, String)>;
+
+#[derive(Debug)]
+pub(super) enum CallbackRedirectError {
+ UnableToDecode,
+ UnableToParse,
+}
+
+impl IntoResponse for CallbackRedirectError {
+ fn into_response(self) -> Response {
+ let message = match self {
+ Self::UnableToDecode => "unable to decode original url",
+ Self::UnableToParse => "unable to parse to original url",
+ };
+
+ (
+ StatusCode::BAD_REQUEST,
+ Json(ErrorResponse {
+ message: message.into(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+/// Replaces the refresh token on an existing identity-provider link.
+///
+/// FusionAuth does not update a link when `link_user` reports that it already
+/// exists, so reconnects must unlink and recreate it. The stale link is restored
+/// if the replacement fails. Deactivated stub users are activated only for the
+/// swap and then returned to their previous state.
+#[tracing::instrument(skip(auth_client, display_name, fresh_refresh_token), err(Debug))]
+pub(super) async fn replace_identity_provider_grant(
+ auth_client: &FusionAuthClient,
+ identity_provider_id: &str,
+ link_owner_id: &str,
+ display_name: &str,
+ fresh_refresh_token: &str,
+) -> AccountLinkResult<()> {
+ let server_error = |message: String| (StatusCode::INTERNAL_SERVER_ERROR, message);
+
+ if fresh_refresh_token.is_empty() {
+ tracing::info!(
+ fusion_user_id = %link_owner_id,
+ "identity-provider link already exists and no fresh refresh token was returned; leaving existing grant"
+ );
+ return Ok(());
+ }
+
+ let existing_links = auth_client
+ .get_links(link_owner_id, Some(identity_provider_id.to_string()))
+ .await
+ .map_err(|error| server_error(format!("unable to read existing links {error}")))?;
+
+ let Some(existing_link) = existing_links
+ .into_iter()
+ .find(|link| link.display_name == display_name)
+ else {
+ tracing::warn!(
+ fusion_user_id = %link_owner_id,
+ "grant replacement found no matching link on the resolved owner; skipping"
+ );
+ return Ok(());
+ };
+
+ if existing_link.token == fresh_refresh_token {
+ return Ok(());
+ }
+
+ let identity_provider_user_id = existing_link.identity_provider_user_id;
+ let stale_refresh_token = existing_link.token;
+ let was_active = auth_client
+ .get_user_active(link_owner_id)
+ .await
+ .map_err(|error| server_error(format!("unable to read user active state {error}")))?;
+
+ if !was_active {
+ auth_client
+ .reactivate_user(link_owner_id)
+ .await
+ .map_err(|error| {
+ server_error(format!("unable to reactivate user for relink {error}"))
+ })?;
+ }
+
+ let link_with_token = |refresh_token: &str| LinkUserRequest {
+ identity_provider_link: IdentityProviderLink {
+ display_name: Cow::Owned(display_name.to_string()),
+ identity_provider_id: Cow::Borrowed(identity_provider_id),
+ identity_provider_user_id: Cow::Borrowed(&identity_provider_user_id),
+ user_id: Cow::Borrowed(link_owner_id),
+ token: Cow::Owned(refresh_token.to_string()),
+ },
+ };
+
+ let swap_result: AccountLinkResult<()> = async {
+ auth_client
+ .unlink_user(
+ link_owner_id,
+ identity_provider_id,
+ &identity_provider_user_id,
+ )
+ .await
+ .map_err(|error| server_error(format!("unable to unlink stale grant {error}")))?;
+
+ let link_result = auth_client
+ .link_user(link_with_token(fresh_refresh_token))
+ .await;
+
+ if let Err(error) = &link_result {
+ tracing::error!(error=?error, "failed to attach fresh grant; rolling back to stale token");
+ if let Err(rollback_error) = auth_client
+ .link_user(link_with_token(&stale_refresh_token))
+ .await
+ {
+ tracing::error!(error=?rollback_error, "grant rollback also failed; identity-provider link is detached");
+ }
+ }
+
+ link_result.map_err(|error| {
+ server_error(format!("unable to attach fresh grant {error}"))
+ })
+ }
+ .await;
+
+ if !was_active && let Err(error) = auth_client.deactivate_user(link_owner_id).await {
+ tracing::error!(
+ error=?error,
+ %link_owner_id,
+ "failed to re-deactivate stub after grant replacement"
+ );
+ }
+
+ swap_result
+}
+
+/// Builds the redirect back to an account-link caller with fresh link identifiers.
+pub(super) fn build_callback_redirect(
+ original_url: &str,
+ link_id: &Uuid,
+) -> Result<Response, CallbackRedirectError> {
+ let decoded_url = urlencoding::decode(original_url).map_err(|error| {
+ tracing::error!(error=?error, "unable to decode original url");
+ CallbackRedirectError::UnableToDecode
+ })?;
+
+ let mut url: Url = decoded_url
+ .parse()
+ .inspect_err(|error| tracing::error!(error=?error, "unable to parse string to url"))
+ .map_err(|_| CallbackRedirectError::UnableToParse)?;
+
+ let preserved_query_pairs: Vec<(String, String)> = url
+ .query_pairs()
+ .filter(|(key, _)| key != "link_id" && key != "token")
+ .map(|(key, value)| (key.into_owned(), value.into_owned()))
+ .collect();
+ url.query_pairs_mut()
+ .clear()
+ .extend_pairs(preserved_query_pairs);
+
+ let link_id = link_id.to_string();
+ url.query_pairs_mut()
+ .append_pair("link_id", &link_id)
+ .append_pair("token", &link_id);
+
+ Ok(Redirect::to(url.as_str()).into_response())
+}
+
+/// Removes a pending account-link row after a callback failure.
+pub(super) async fn cleanup_pending_link(ctx: &ApiContext, link_id: &Uuid) {
+ macro_db_client::in_progress_user_link::delete_in_progress_user_link(&ctx.db, link_id)
+ .await
+ .inspect_err(|error| {
+ tracing::warn!(
+ error=?error,
+ ?link_id,
+ "failed to clean up in_progress_user_link after account-link callback error"
+ );
+ })
+ .ok();
+}
diff --git a/services/authentication_service/src/api/oauth2/account_link/test.rs b/services/authentication_service/src/api/oauth2/account_link/test.rs
new file mode 100644
index 0000000000..9e42cb4927
--- /dev/null
+++ b/services/authentication_service/src/api/oauth2/account_link/test.rs
@@ -0,0 +1,47 @@
+use axum::http::{StatusCode, header::LOCATION};
+use url::Url;
+use uuid::Uuid;
+
+use super::build_callback_redirect;
+
+#[test]
+fn callback_redirect_appends_link_identifiers_and_preserves_query_parameters() {
+ let link_id = Uuid::parse_str("694d20f7-ff85-46fd-b17d-5f68ff2d3707").unwrap();
+ let original_url = urlencoding::encode("https://app.macro.com/inbox?view=shared&sort=newest");
+
+ let response = build_callback_redirect(&original_url, &link_id).unwrap();
+ let redirect_url = Url::parse(response.headers()[LOCATION].to_str().unwrap()).unwrap();
+ let query_pairs: Vec<_> = redirect_url.query_pairs().collect();
+
+ assert_eq!(response.status(), StatusCode::SEE_OTHER);
+ assert_eq!(
+ query_pairs,
+ vec![
+ ("view".into(), "shared".into()),
+ ("sort".into(), "newest".into()),
+ ("link_id".into(), link_id.to_string().into()),
+ ("token".into(), link_id.to_string().into()),
+ ]
+ );
+}
+
+#[test]
+fn callback_redirect_replaces_stale_link_identifiers() {
+ let link_id = Uuid::parse_str("694d20f7-ff85-46fd-b17d-5f68ff2d3707").unwrap();
+ let original_url = urlencoding::encode(
+ "https://app.macro.com/inbox?link_id=stale-link&view=shared&token=stale-token",
+ );
+
+ let response = build_callback_redirect(&original_url, &link_id).unwrap();
+ let redirect_url = Url::parse(response.headers()[LOCATION].to_str().unwrap()).unwrap();
+ let query_pairs: Vec<_> = redirect_url.query_pairs().collect();
+
+ assert_eq!(
+ query_pairs,
+ vec![
+ ("view".into(), "shared".into()),
+ ("link_id".into(), link_id.to_string().into()),
+ ("token".into(), link_id.to_string().into()),
+ ]
+ );
+}
diff --git a/services/authentication_service/src/api/oauth2/google.rs b/services/authentication_service/src/api/oauth2/google.rs
index da847d9b21..d35ccaec06 100644
--- a/services/authentication_service/src/api/oauth2/google.rs
+++ b/services/authentication_service/src/api/oauth2/google.rs
@@ -4,17 +4,20 @@ use std::borrow::Cow;
use axum::{
Json,
- response::{IntoResponse, Redirect, Response},
+ response::{IntoResponse, Response},
};
use model::response::ErrorResponse;
use reqwest::StatusCode;
use tower_cookies::Cookies;
-use url::Url;
use crate::api::{
context::ApiContext,
oauth2::{
- OAuthState, format_redirect_uri,
+ OAuthState,
+ account_link::{
+ build_callback_redirect, cleanup_pending_link, replace_identity_provider_grant,
+ },
+ format_redirect_uri,
login::{self},
},
};
@@ -106,26 +109,16 @@ async fn link_user(
{
Ok(()) => {}
Err(FusionAuthClientError::IdentityProviderLinkAlreadyExists) => {
- // The link already exists but its stored refresh token may be dead (this
- // is the reconnect path). A plain `link_user` no-ops and leaves the dead
- // token in place, so swap in the freshly minted token. With no fresh token
- // (Google withheld a refresh token) there is nothing to swap, so leave the
- // existing grant untouched.
- if token_response.refresh_token.is_empty() {
- tracing::info!(
- fusion_user_id = %idp_link_owner,
- "idp link already exists and no fresh refresh token returned, leaving existing grant"
- );
- } else {
- relink_with_fresh_token(
- ctx,
- identity_provider_id,
- &idp_link_owner,
- &user_info_email,
- &token_response.refresh_token,
- )
- .await?;
- }
+ // A plain `link_user` leaves the existing grant untouched. Reconnects
+ // replace a stale token when Google returns a fresh one.
+ replace_identity_provider_grant(
+ &ctx.auth_client,
+ identity_provider_id,
+ &idp_link_owner,
+ &user_info_email,
+ &token_response.refresh_token,
+ )
+ .await?;
}
Err(e) => {
return Err((
@@ -165,103 +158,6 @@ fn resolved_granted_scopes(returned: &str, requested: Vec<String>) -> Vec<String
}
}
-/// Replaces a stale Google grant on an existing IdP link with a freshly minted
-/// refresh token. Used on reconnect, when the mailbox's FusionAuth link already
-/// exists but its stored token has gone dead — a plain `link_user` no-ops and
-/// leaves the dead token in place.
-///
-/// A Google identity binds to exactly one FusionAuth user, so the grant is swapped
-/// by unlinking the old link and re-linking with the new token, rolling back to the
-/// old token if the re-link fails. A shared mailbox's grant lives on a deactivated
-/// stub user; links are only created against active users, so the stub is
-/// reactivated for the swap and returned to its prior state afterward (a human's own
-/// active account is left active). Idempotent when the stored token already matches.
-async fn relink_with_fresh_token(
- ctx: &ApiContext,
- identity_provider_id: &str,
- idp_link_owner: &str,
- email: &str,
- fresh_refresh_token: &str,
-) -> Result<(), (StatusCode, String)> {
- let server_error = |message: String| (StatusCode::INTERNAL_SERVER_ERROR, message);
- let auth = &ctx.auth_client;
-
- let existing_links = auth
- .get_links(idp_link_owner, Some(identity_provider_id.to_string()))
- .await
- .map_err(|e| server_error(format!("unable to read existing links {e}")))?;
-
- let Some(existing) = existing_links.into_iter().find(|l| l.display_name == email) else {
- // Owner resolution and the already-exists error disagree about where the
- // link lives; there is nothing to relink on this user.
- tracing::warn!(
- fusion_user_id = %idp_link_owner,
- "relink: no existing grant found for mailbox on resolved owner, skipping"
- );
- return Ok(());
- };
-
- if existing.token == fresh_refresh_token {
- // Stored token already current; nothing to do.
- return Ok(());
- }
-
- let sub = existing.identity_provider_user_id;
- let stale_token = existing.token;
-
- let was_active = auth
- .get_user_active(idp_link_owner)
- .await
- .map_err(|e| server_error(format!("unable to read user active state {e}")))?;
-
- if !was_active {
- auth.reactivate_user(idp_link_owner)
- .await
- .map_err(|e| server_error(format!("unable to reactivate user for relink {e}")))?;
- }
-
- let link_with = |token: &str| LinkUserRequest {
- identity_provider_link: IdentityProviderLink {
- display_name: Cow::Owned(email.to_string()),
- identity_provider_id: Cow::Borrowed(identity_provider_id),
- identity_provider_user_id: Cow::Borrowed(&sub),
- user_id: Cow::Borrowed(idp_link_owner),
- token: Cow::Owned(token.to_string()),
- },
- };
-
- // Swap the grant, capturing the outcome so the stub is re-deactivated below on
- // every path — including an unlink failure — rather than leaking an active stub.
- let swap_result: Result<(), (StatusCode, String)> = async {
- auth.unlink_user(idp_link_owner, identity_provider_id, &sub)
- .await
- .map_err(|e| server_error(format!("unable to unlink stale grant {e}")))?;
-
- let link_result = auth.link_user(link_with(fresh_refresh_token)).await;
-
- if let Err(e) = &link_result {
- tracing::error!(error=?e, "relink: failed to attach fresh grant, rolling back to stale token");
- if let Err(rollback) = auth.link_user(link_with(&stale_token)).await {
- tracing::error!(error=?rollback, "relink: rollback re-link also failed, grant is detached");
- }
- }
-
- link_result.map_err(|e| server_error(format!("unable to attach fresh grant {e}")))
- }
- .await;
-
- // Restore the stub's deactivated state on every path; a human's own account was
- // active and is left as-is. Best-effort (logged) so a deactivation blip can't fail
- // a reconnect whose grant swap already succeeded.
- if !was_active && let Err(e) = auth.deactivate_user(idp_link_owner).await {
- tracing::error!(error=?e, %idp_link_owner, "relink: failed to re-deactivate stub after relink");
- }
-
- swap_result?;
-
- Ok(())
-}
-
pub(in crate::api::oauth2) async fn handler(
ctx: &ApiContext,
cookies: Cookies,
@@ -274,20 +170,7 @@ pub(in crate::api::oauth2) async fn handler(
let link_result = link_user(ctx, &state.identity_provider_id, code, link_id).await;
if link_result.is_err() {
- // The OAuth callback failed; the in_progress_user_link row will never be
- // consumed by /email/init (no redirect carrying link_id is emitted on
- // error). Best-effort delete so a failed attempt doesn't burn one of
- // the user's 5 in-flight link slots.
- macro_db_client::in_progress_user_link::delete_in_progress_user_link(&ctx.db, link_id)
- .await
- .inspect_err(|e| {
- tracing::warn!(
- error=?e,
- ?link_id,
- "failed to clean up in_progress_user_link after link_user error"
- );
- })
- .ok();
+ cleanup_pending_link(ctx, link_id).await;
}
link_result.map_err(|(status_code, error)| {
@@ -302,47 +185,8 @@ pub(in crate::api::oauth2) async fn handler(
})?;
if let Some(original_url) = &state.original_url {
- let decoded = urlencoding::decode(original_url).map_err(|e| {
- tracing::error!(error=?e, "unable to decode original url");
- (
- StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: "unable to decode original url".into(),
- }),
- )
- .into_response()
- })?;
-
- let mut url: Url = decoded
- .parse()
- .inspect_err(|e| tracing::error!(error=?e, "unable to parse string to url"))
- .map_err(|_| {
- (
- StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: "unable to parse to original url".into(),
- }),
- )
- .into_response()
- })?;
-
- // Strip any stale identifiers embedded in the original_url
- // before appending fresh ones; consumers read the first
- // occurrence of each param.
- let filtered: Vec<(String, String)> = url
- .query_pairs()
- .filter(|(k, _)| k != "link_id" && k != "token")
- .map(|(k, v)| (k.into_owned(), v.into_owned()))
- .collect();
- url.query_pairs_mut().clear().extend_pairs(filtered);
-
- // `token` mirrors link_id for callback consumers that only
- // surface a `token` query param from the redirect URL.
- url.query_pairs_mut()
- .append_pair("link_id", &link_id.to_string())
- .append_pair("token", &link_id.to_string());
-
- return Ok(Redirect::to(url.as_str()).into_response());
+ return build_callback_redirect(original_url, link_id)
+ .map_err(IntoResponse::into_response);
}
return Ok(StatusCode::OK.into_response());
diff --git a/services/authentication_service/src/api/oauth2/microsoft.rs b/services/authentication_service/src/api/oauth2/microsoft.rs
new file mode 100644
index 0000000000..77f17e52ea
--- /dev/null
+++ b/services/authentication_service/src/api/oauth2/microsoft.rs
@@ -0,0 +1,241 @@
+use std::borrow::Cow;
+
+use axum::{
+ Json,
+ response::{IntoResponse, Response},
+};
+use email_validator::normalize_email;
+use fusionauth::{
+ error::FusionAuthClientError,
+ identity_provider::{IdentityProviderLink, LinkUserRequest},
+ microsoft::oauth::MicrosoftUserInfo,
+};
+use model::response::ErrorResponse;
+use reqwest::StatusCode;
+use uuid::Uuid;
+
+use crate::api::{
+ context::ApiContext,
+ oauth2::{
+ OAuthState,
+ account_link::{
+ build_callback_redirect, cleanup_pending_link, replace_identity_provider_grant,
+ },
+ format_redirect_uri,
+ },
+};
+
+#[cfg(test)]
+mod test;
+
+const MICROSOFT_IDENTITY_PROVIDER_NAME: &str = "microsoft";
+
+type MicrosoftCallbackResult<T> = Result<T, (StatusCode, String)>;
+
+#[derive(Debug, Eq, PartialEq)]
+struct MicrosoftLinkIdentity {
+ subject: String,
+ email: String,
+}
+
+fn extract_identity(
+ user_info: MicrosoftUserInfo,
+) -> MicrosoftCallbackResult<MicrosoftLinkIdentity> {
+ if user_info.sub.trim().is_empty() {
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "Microsoft identity does not contain a subject".into(),
+ ));
+ }
+
+ let email = normalize_email(&user_info.email)
+ .map(Cow::into_owned)
+ .ok_or_else(|| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "Microsoft identity does not contain a usable email".into(),
+ )
+ })?;
+
+ Ok(MicrosoftLinkIdentity {
+ subject: user_info.sub,
+ email,
+ })
+}
+
+fn require_link_id(state: &OAuthState) -> MicrosoftCallbackResult<Uuid> {
+ state.link_id.ok_or_else(|| {
+ (
+ StatusCode::BAD_REQUEST,
+ "Microsoft OAuth callback requires link_id".into(),
+ )
+ })
+}
+
+fn verify_identity_provider(
+ state: &OAuthState,
+ microsoft_identity_provider_id: &str,
+) -> MicrosoftCallbackResult<()> {
+ if state.identity_provider_id != microsoft_identity_provider_id {
+ return Err((
+ StatusCode::BAD_REQUEST,
+ "Microsoft identity provider does not match callback state".into(),
+ ));
+ }
+
+ Ok(())
+}
+
+#[tracing::instrument(skip(ctx, code, state), fields(%link_id), err(Debug))]
+async fn link_user(
+ ctx: &ApiContext,
+ code: &str,
+ state: &OAuthState,
+ link_id: &Uuid,
+) -> MicrosoftCallbackResult<()> {
+ let microsoft_identity_provider_id = ctx
+ .auth_client
+ .get_identity_provider_id_by_name(MICROSOFT_IDENTITY_PROVIDER_NAME)
+ .await
+ .map_err(|error| match error {
+ FusionAuthClientError::NoIdentityProviderFound => {
+ (StatusCode::NOT_FOUND, "identity provider not found".into())
+ }
+ error => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ format!("unable to resolve Microsoft identity provider {error}"),
+ ),
+ })?;
+ verify_identity_provider(state, &microsoft_identity_provider_id)?;
+
+ let pending_link =
+ macro_db_client::in_progress_user_link::get_in_progress_user_link(&ctx.db, link_id)
+ .await
+ .map_err(|error| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ format!("unable to load pending Microsoft link {error}"),
+ )
+ })?;
+
+ let token_response = ctx
+ .auth_client
+ .exchange_microsoft_code_for_tokens(code, &format_redirect_uri("microsoft"))
+ .await
+ .map_err(|error| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ format!("unable to exchange Microsoft code for tokens {error}"),
+ )
+ })?;
+ let user_info = ctx
+ .auth_client
+ .parse_microsoft_id_token(&token_response.id_token)
+ .await
+ .map_err(|error| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ format!("unable to decode Microsoft ID token {error}"),
+ )
+ })?;
+ let identity = extract_identity(user_info)?;
+
+ // The identity-provider link is also a login identity. If the mailbox already belongs to a
+ // Macro account, keep its Microsoft login attached to that owner rather than the requester.
+ let link_owner_id = match macro_db_client::user::get::get_macro_user_id_by_email(
+ &ctx.db,
+ &identity.email,
+ )
+ .await
+ {
+ Ok(Some(mailbox_owner_id)) => mailbox_owner_id.to_string(),
+ Ok(None) => pending_link.macro_user_id.to_string(),
+ Err(error) => {
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ format!("unable to look up mailbox owner for linked email {error}"),
+ ));
+ }
+ };
+
+ match ctx
+ .auth_client
+ .link_user(LinkUserRequest {
+ identity_provider_link: IdentityProviderLink {
+ display_name: Cow::Borrowed(&identity.email),
+ identity_provider_id: Cow::Borrowed(&microsoft_identity_provider_id),
+ identity_provider_user_id: Cow::Borrowed(&identity.subject),
+ user_id: Cow::Borrowed(&link_owner_id),
+ token: Cow::Borrowed(&token_response.refresh_token),
+ },
+ })
+ .await
+ {
+ Ok(()) => {}
+ Err(FusionAuthClientError::IdentityProviderLinkAlreadyExists) => {
+ replace_identity_provider_grant(
+ &ctx.auth_client,
+ &microsoft_identity_provider_id,
+ &link_owner_id,
+ &identity.email,
+ &token_response.refresh_token,
+ )
+ .await?;
+ }
+ Err(error) => {
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ format!("unable to link Microsoft user {error}"),
+ ));
+ }
+ }
+
+ macro_db_client::in_progress_user_link::set_linked_email(&ctx.db, link_id, &identity.email)
+ .await
+ .map_err(|error| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ format!("unable to record linked Microsoft email {error}"),
+ )
+ })?;
+
+ Ok(())
+}
+
+pub(in crate::api::oauth2) async fn handler(
+ ctx: &ApiContext,
+ code: &str,
+ state: &OAuthState,
+) -> Result<Response, Response> {
+ let link_id = require_link_id(state).map_err(callback_error_response)?;
+ let link_result = link_user(ctx, code, state, &link_id).await;
+
+ if link_result.is_err() {
+ cleanup_pending_link(ctx, &link_id).await;
+ }
+
+ link_result.map_err(callback_error_response)?;
+
+ if let Some(original_url) = &state.original_url {
+ return match build_callback_redirect(original_url, &link_id) {
+ Ok(response) => Ok(response),
+ Err(error) => {
+ cleanup_pending_link(ctx, &link_id).await;
+ Err(error.into_response())
+ }
+ };
+ }
+
+ Ok(StatusCode::OK.into_response())
+}
+
+fn callback_error_response((status_code, message): (StatusCode, String)) -> Response {
+ tracing::error!(error=?message, "unable to link Microsoft user");
+ (
+ status_code,
+ Json(ErrorResponse {
+ message: message.into(),
+ }),
+ )
+ .into_response()
+}
diff --git a/services/authentication_service/src/api/oauth2/microsoft/test.rs b/services/authentication_service/src/api/oauth2/microsoft/test.rs
new file mode 100644
index 0000000000..02666d885d
--- /dev/null
+++ b/services/authentication_service/src/api/oauth2/microsoft/test.rs
@@ -0,0 +1,66 @@
+use fusionauth::microsoft::oauth::MicrosoftUserInfo;
+use reqwest::StatusCode;
+use uuid::Uuid;
+
+use super::{extract_identity, require_link_id, verify_identity_provider};
+use crate::api::oauth2::OAuthState;
+
+fn state(identity_provider_id: &str, link_id: Option<Uuid>) -> OAuthState {
+ OAuthState {
+ identity_provider_id: identity_provider_id.to_string(),
+ link_id,
+ original_url: None,
+ is_mobile: None,
+ }
+}
+
+#[test]
+fn extracts_subject_and_normalizes_email() {
+ let identity = extract_identity(MicrosoftUserInfo {
+ sub: "microsoft-user-id".into(),
+ email: "[email protected]".into(),
+ })
+ .unwrap();
+
+ assert_eq!(identity.subject, "microsoft-user-id");
+ assert_eq!(identity.email, "[email protected]");
+}
+
+#[test]
+fn rejects_identity_without_subject_or_usable_email() {
+ for user_info in [
+ MicrosoftUserInfo {
+ sub: "".into(),
+ email: "[email protected]".into(),
+ },
+ MicrosoftUserInfo {
+ sub: "microsoft-user-id".into(),
+ email: "not-an-email".into(),
+ },
+ ] {
+ assert!(extract_identity(user_info).is_err());
+ }
+}
+
+#[test]
+fn microsoft_callback_requires_link_id() {
+ let error = require_link_id(&state("microsoft-idp-id", None)).unwrap_err();
+
+ assert_eq!(error.0, StatusCode::BAD_REQUEST);
+ assert!(error.1.contains("link_id"));
+}
+
+#[test]
+fn microsoft_callback_rejects_identity_provider_mismatch() {
+ let callback_state = state("unexpected-idp-id", Some(Uuid::now_v7()));
+ let error = verify_identity_provider(&callback_state, "microsoft-idp-id").unwrap_err();
+
+ assert_eq!(error.0, StatusCode::BAD_REQUEST);
+}
+
+#[test]
+fn microsoft_callback_accepts_resolved_identity_provider() {
+ let callback_state = state("microsoft-idp-id", Some(Uuid::now_v7()));
+
+ verify_identity_provider(&callback_state, "microsoft-idp-id").unwrap();
+}
diff --git a/services/authentication_service/src/api/oauth2/mod.rs b/services/authentication_service/src/api/oauth2/mod.rs
index 9c98c0bd22..686e419aae 100644
--- a/services/authentication_service/src/api/oauth2/mod.rs
+++ b/services/authentication_service/src/api/oauth2/mod.rs
@@ -2,9 +2,11 @@ use crate::config::BASE_URL;
use axum::{Router, extract::State, routing::get};
use tower_cookies::CookieManagerLayer;
+mod account_link;
mod github;
mod google;
mod login;
+mod microsoft;
pub fn router() -> Router<ApiContext> {
Router::new().route(
@@ -108,6 +110,11 @@ pub(in crate::api) async fn handler(
error_description = ?params.error_description,
"oauth2 callback received without code",
);
+ if provider == "microsoft"
+ && let Some(link_id) = state.link_id.as_ref()
+ {
+ account_link::cleanup_pending_link(&ctx, link_id).await;
+ }
return Err((
StatusCode::BAD_REQUEST,
Json(ErrorResponse {
@@ -124,6 +131,7 @@ pub(in crate::api) async fn handler(
.await
.map(|r| r.into_response())
.map_err(|e| e.into_response()),
+ "microsoft" => microsoft::handler(&ctx, &code, &state).await,
_ => Err((
StatusCode::NOT_IMPLEMENTED,
Json(ErrorResponse {
diff --git a/services/authentication_service/src/api/swagger.rs b/services/authentication_service/src/api/swagger.rs
index 6b34c941a4..ae13ac3915 100644
--- a/services/authentication_service/src/api/swagger.rs
+++ b/services/authentication_service/src/api/swagger.rs
@@ -24,6 +24,7 @@ use crate::api::jwt::macro_api_token::MacroApiTokenResponse;
use crate::api::link::create_in_progress_link::CreateInProgressLinkResponse;
use crate::api::link::github::{GithubLinkStatusResponse, InitGithubLinkResponse};
use crate::api::link::gmail::{GmailLinkStatusResponse, InitGmailLinkResponse};
+use crate::api::link::outlook::InitOutlookLinkResponse;
use crate::api::merge::create_merge_request::CreateAccountMergeRequest;
use crate::api::user::create_user::CreateUserRequest;
use crate::api::user::get_legacy_user_permissions::GetLegacyUserPermissionsResponse;
@@ -80,6 +81,7 @@ use model::user::{
link::github::check_github_link_status_handler,
link::gmail::init_gmail_link_handler,
link::gmail::check_gmail_link_status_handler,
+ link::outlook::init_outlook_link_handler,
/// /github_pull_requests
github_pull_requests::handler,
@@ -181,6 +183,7 @@ use model::user::{
GithubLinkStatusResponse,
InitGmailLinkResponse,
GmailLinkStatusResponse,
+ InitOutlookLinkResponse,
// GitHub pull requests
EnrichGithubPullRequestsProxyRequest,
diff --git a/services/authentication_service/src/config.rs b/services/authentication_service/src/config.rs
index ebc6b149b8..d5cb22ea34 100644
--- a/services/authentication_service/src/config.rs
+++ b/services/authentication_service/src/config.rs
@@ -36,6 +36,9 @@ env_vars! {
maybe_env_vars! {
/// Browser-reachable FusionAuth origin used for OAuth authorization redirects.
pub struct FusionAuthPublicUrl;
+ pub struct MicrosoftClientId;
+ pub struct MicrosoftClientSecret;
+ pub struct MicrosoftTenantId;
pub struct GaMeasurementId;
pub struct GaApiSecret;
pub struct MetaPixelId;
@@ -79,6 +82,12 @@ pub struct Config {
pub google_client_id: GoogleClientId,
/// Google client secret key
pub google_client_secret_key: GoogleClientSecretKey,
+ /// Microsoft OAuth client ID.
+ pub microsoft_client_id: MicrosoftClientId,
+ /// Microsoft OAuth client secret.
+ pub microsoft_client_secret: MicrosoftClientSecret,
+ /// Microsoft Entra tenant ID.
+ pub microsoft_tenant_id: MicrosoftTenantId,
/// Stripe secret key
pub stripe_secret_key: StripeSecretKey,
/// The port to listen for HTTP requests on.
@@ -125,9 +134,54 @@ pub struct Config {
pub calendar_scope_enabled: bool,
}
+/// Complete Microsoft OAuth credentials used to enable Outlook account linking.
+pub(crate) struct MicrosoftCredentials {
+ pub(crate) client_id: String,
+ pub(crate) client_secret: String,
+ pub(crate) tenant_id: String,
+}
+
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
macro_config::ConfigLoader::load::<Config>()
.context("failed to load authentication service config")
}
+
+ /// Resolves Microsoft credentials, enforcing that all values are configured together.
+ pub(crate) fn microsoft_credentials(&self) -> anyhow::Result<Option<MicrosoftCredentials>> {
+ resolve_microsoft_credentials(
+ &self.microsoft_client_id,
+ &self.microsoft_client_secret,
+ &self.microsoft_tenant_id,
+ )
+ }
}
+
+fn resolve_microsoft_credentials(
+ client_id: &MicrosoftClientId,
+ client_secret: &MicrosoftClientSecret,
+ tenant_id: &MicrosoftTenantId,
+) -> anyhow::Result<Option<MicrosoftCredentials>> {
+ let client_id = nonblank_value(client_id.value());
+ let client_secret = nonblank_value(client_secret.value());
+ let tenant_id = nonblank_value(tenant_id.value());
+
+ match (client_id, client_secret, tenant_id) {
+ (None, None, None) => Ok(None),
+ (Some(client_id), Some(client_secret), Some(tenant_id)) => Ok(Some(MicrosoftCredentials {
+ client_id: client_id.to_owned(),
+ client_secret: client_secret.to_owned(),
+ tenant_id: tenant_id.to_owned(),
+ })),
+ _ => anyhow::bail!(
+ "MICROSOFT_CLIENT_ID, MICROSOFT_CLIENT_SECRET, and MICROSOFT_TENANT_ID must all be set to nonblank values or all be unset"
+ ),
+ }
+}
+
+fn nonblank_value(value: Option<&str>) -> Option<&str> {
+ value.filter(|value| !value.trim().is_empty())
+}
+
+#[cfg(test)]
+mod test;
diff --git a/services/authentication_service/src/config/test.rs b/services/authentication_service/src/config/test.rs
new file mode 100644
index 0000000000..11e4c33112
--- /dev/null
+++ b/services/authentication_service/src/config/test.rs
@@ -0,0 +1,94 @@
+use super::*;
+
+#[test]
+fn complete_microsoft_credentials_are_resolved() {
+ let credentials = resolve(
+ Some("microsoft-client-id"),
+ Some("microsoft-client-secret"),
+ Some("microsoft-tenant-id"),
+ )
+ .expect("complete credentials should be valid");
+ let Some(credentials) = credentials else {
+ panic!("complete credentials should enable Microsoft OAuth");
+ };
+
+ assert_eq!(credentials.client_id, "microsoft-client-id");
+ assert_eq!(credentials.client_secret, "microsoft-client-secret");
+ assert_eq!(credentials.tenant_id, "microsoft-tenant-id");
+}
+
+#[test]
+fn absent_or_blank_microsoft_credentials_are_disabled() {
+ let missing_values = [None, Some(""), Some(" \t ")];
+
+ for client_id in missing_values {
+ for client_secret in missing_values {
+ for tenant_id in missing_values {
+ let credentials = resolve(client_id, client_secret, tenant_id)
+ .expect("absent or blank credentials should be valid");
+ assert!(credentials.is_none());
+ }
+ }
+ }
+}
+
+#[test]
+fn every_partial_microsoft_credential_combination_is_rejected() {
+ for configured_fields in 1_u8..=6 {
+ let client_id = (configured_fields & 0b001 != 0).then_some("microsoft-client-id");
+ let client_secret = (configured_fields & 0b010 != 0).then_some("microsoft-client-secret");
+ let tenant_id = (configured_fields & 0b100 != 0).then_some("microsoft-tenant-id");
+
+ let error = resolve(client_id, client_secret, tenant_id)
+ .err()
+ .expect("partial credentials should be rejected");
+
+ assert!(error.to_string().contains("must all be set"));
+ }
+}
+
+#[test]
+fn blank_values_are_rejected_when_other_credentials_are_configured() {
+ let partial_credentials = [
+ (Some(" "), Some("client-secret"), Some("tenant-id")),
+ (Some("client-id"), Some(" "), Some("tenant-id")),
+ (Some("client-id"), Some("client-secret"), Some(" ")),
+ ];
+
+ for (client_id, client_secret, tenant_id) in partial_credentials {
+ assert!(resolve(client_id, client_secret, tenant_id).is_err());
+ }
+}
+
+fn resolve(
+ client_id: Option<&'static str>,
+ client_secret: Option<&'static str>,
+ tenant_id: Option<&'static str>,
+) -> anyhow::Result<Option<MicrosoftCredentials>> {
+ resolve_microsoft_credentials(
+ &microsoft_client_id(client_id),
+ &microsoft_client_secret(client_secret),
+ &microsoft_tenant_id(tenant_id),
+ )
+}
+
+fn microsoft_client_id(value: Option<&'static str>) -> MicrosoftClientId {
+ match value {
+ Some(value) => MicrosoftClientId::new_testing(value),
+ None => MicrosoftClientId::new_unset(),
+ }
+}
+
+fn microsoft_client_secret(value: Option<&'static str>) -> MicrosoftClientSecret {
+ match value {
+ Some(value) => MicrosoftClientSecret::new_testing(value),
+ None => MicrosoftClientSecret::new_unset(),
+ }
+}
+
+fn microsoft_tenant_id(value: Option<&'static str>) -> MicrosoftTenantId {
+ match value {
+ Some(value) => MicrosoftTenantId::new_testing(value),
+ None => MicrosoftTenantId::new_unset(),
+ }
+}
diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rs
index 38f688ea71..489b7a3470 100644
--- a/services/authentication_service/src/main.rs
+++ b/services/authentication_service/src/main.rs
@@ -92,6 +92,9 @@ async fn main() -> anyhow::Result<()> {
// Parse our configuration from the environment.
let config = Config::from_env().context("expected to be able to generate config")?;
+ let microsoft_credentials = config
+ .microsoft_credentials()
+ .context("invalid Microsoft OAuth configuration")?;
let internal_api_key = config.internal_api_key.clone();
@@ -176,6 +179,14 @@ async fn main() -> anyhow::Result<()> {
google_client_secret,
)
.with_public_url(fusionauth_public_url);
+ let auth_client = match microsoft_credentials {
+ Some(credentials) => auth_client.with_microsoft_credentials(
+ credentials.client_id,
+ credentials.client_secret,
+ credentials.tenant_id,
+ ),
+ None => auth_client,
+ };
tracing::trace!("initialized auth client");
let document_storage_service_client = DocumentStorageServiceClient::new(