Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(email): store outlook refresh token in db (#5739)
Will Hutchinson78c8473b1d82
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 02a0573edf..439b36c40c 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -450,6 +450,7 @@"crates/macro_user_id","crates/macro_uuid","crates/mention_utils",+ "crates/microsoft_oauth_grant_db_utils","crates/mobile_welcome_email_db_client","crates/model","crates/model-entity",@@ -4212,6 +4213,10 @@"crates/mention_utils","crates/workspace-hack"],+ "microsoft_oauth_grant_db_utils": [+ "crates/microsoft_oauth_grant_db_utils",+ "crates/workspace-hack"+ ],"mobile_welcome_email_db_client": ["crates/mobile_welcome_email_db_client","crates/workspace-hack"diff --git a/.sqlx/query-3885b8b814d7d3ff9f8f13c57123ba4865de811150067f17f51757053fc32fb1.json b/.sqlx/query-3885b8b814d7d3ff9f8f13c57123ba4865de811150067f17f51757053fc32fb1.jsonnew file mode 100644index 0000000000..72047b4c83--- /dev/null+++ b/.sqlx/query-3885b8b814d7d3ff9f8f13c57123ba4865de811150067f17f51757053fc32fb1.json@@ -0,0 +1,82 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO microsoft_oauth_grants (\n fusionauth_user_id,\n email_address,\n refresh_token_ciphertext,\n encrypted_data_key,\n nonce,\n encryption_version,\n kms_key_id\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n ON CONFLICT (fusionauth_user_id, email_address) DO UPDATE SET\n refresh_token_ciphertext = EXCLUDED.refresh_token_ciphertext,\n encrypted_data_key = EXCLUDED.encrypted_data_key,\n nonce = EXCLUDED.nonce,\n encryption_version = EXCLUDED.encryption_version,\n kms_key_id = EXCLUDED.kms_key_id,\n updated_at = now(),\n last_refreshed_at = now()\n RETURNING\n fusionauth_user_id,\n email_address,\n refresh_token_ciphertext,\n encrypted_data_key,\n nonce,\n encryption_version,\n kms_key_id,\n created_at,\n updated_at,\n last_refreshed_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "fusionauth_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "email_address",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "refresh_token_ciphertext",+ "type_info": "Bytea"+ },+ {+ "ordinal": 3,+ "name": "encrypted_data_key",+ "type_info": "Bytea"+ },+ {+ "ordinal": 4,+ "name": "nonce",+ "type_info": "Bytea"+ },+ {+ "ordinal": 5,+ "name": "encryption_version",+ "type_info": "Int4"+ },+ {+ "ordinal": 6,+ "name": "kms_key_id",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "last_refreshed_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Bytea",+ "Bytea",+ "Bytea",+ "Int4",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "3885b8b814d7d3ff9f8f13c57123ba4865de811150067f17f51757053fc32fb1"+}diff --git a/.sqlx/query-9e9f6d63c5fa062986b777ceac5c9c0f824a9141b257c3a6cc45b2bf3bdf8981.json b/.sqlx/query-9e9f6d63c5fa062986b777ceac5c9c0f824a9141b257c3a6cc45b2bf3bdf8981.jsonnew file mode 100644index 0000000000..cdcbae964d--- /dev/null+++ b/.sqlx/query-9e9f6d63c5fa062986b777ceac5c9c0f824a9141b257c3a6cc45b2bf3bdf8981.json@@ -0,0 +1,77 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n fusionauth_user_id,\n email_address,\n refresh_token_ciphertext,\n encrypted_data_key,\n nonce,\n encryption_version,\n kms_key_id,\n created_at,\n updated_at,\n last_refreshed_at\n FROM microsoft_oauth_grants\n WHERE fusionauth_user_id = $1\n AND email_address = $2\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "fusionauth_user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "email_address",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "refresh_token_ciphertext",+ "type_info": "Bytea"+ },+ {+ "ordinal": 3,+ "name": "encrypted_data_key",+ "type_info": "Bytea"+ },+ {+ "ordinal": 4,+ "name": "nonce",+ "type_info": "Bytea"+ },+ {+ "ordinal": 5,+ "name": "encryption_version",+ "type_info": "Int4"+ },+ {+ "ordinal": 6,+ "name": "kms_key_id",+ "type_info": "Text"+ },+ {+ "ordinal": 7,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 8,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 9,+ "name": "last_refreshed_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "9e9f6d63c5fa062986b777ceac5c9c0f824a9141b257c3a6cc45b2bf3bdf8981"+}diff --git a/Cargo.lock b/Cargo.lockindex 782d448b2a..a6af9c7749 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -81,6 +81,7 @@ dependencies = ["ctr","ghash","subtle",+ "zeroize",][[package]]@@ -1185,10 +1186,13 @@ dependencies = [name = "authentication_service"version = "0.1.0"dependencies = [+ "aes-gcm","analytics_client","anyhow","async-stripe","async-stripe-webhook",+ "async-trait",+ "aws-sdk-kms","aws-sdk-secretsmanager","aws-sdk-sesv2","aws-sdk-sqs",@@ -1239,6 +1243,7 @@ dependencies = ["macro_uuid","maud","mention_utils",+ "microsoft_oauth_grant_db_utils","miniserde","mobile_welcome_email_db_client","mockall",@@ -1283,6 +1288,7 @@ dependencies = ["utoipa-swagger-ui","uuid","workspace-hack",+ "zeroize",][[package]]@@ -1517,6 +1523,31 @@ dependencies = ["tracing",]+[[package]]+name = "aws-sdk-kms"+version = "1.109.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35ae42a03fd0308c178015426a5e2ab0909a11f33c0efc56aea95caf92dc38b0"+dependencies = [+ "arc-swap",+ "aws-credential-types",+ "aws-runtime",+ "aws-smithy-async",+ "aws-smithy-http",+ "aws-smithy-json",+ "aws-smithy-observability",+ "aws-smithy-runtime",+ "aws-smithy-runtime-api",+ "aws-smithy-types",+ "aws-types",+ "bytes",+ "fastrand 2.4.1",+ "http 0.2.12",+ "http 1.4.0",+ "regex-lite",+ "tracing",+]+[[package]]name = "aws-sdk-lambda"version = "1.123.0"@@ -5667,7 +5698,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -7368,7 +7399,7 @@ dependencies = ["libc","percent-encoding","pin-project-lite",- "socket2 0.5.10",+ "socket2 0.6.3","system-configuration","tokio","tower-service",@@ -7946,7 +7977,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"dependencies = ["hermit-abi","libc",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -9574,6 +9605,18 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "microsoft_oauth_grant_db_utils"+version = "0.1.0"+dependencies = [+ "anyhow",+ "chrono",+ "macro_db_migrator",+ "sqlx",+ "tokio",+ "workspace-hack",+]+[[package]]name = "miette"version = "7.6.0"@@ -10431,7 +10474,7 @@ version = "0.50.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"dependencies = [- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -12095,7 +12138,7 @@ dependencies = ["quinn-udp","rustc-hash 2.1.2","rustls 0.23.40",- "socket2 0.5.10",+ "socket2 0.6.3","thiserror 2.0.18","tokio","tracing",@@ -12133,7 +12176,7 @@ dependencies = ["cfg_aliases","libc","once_cell",- "socket2 0.5.10",+ "socket2 0.6.3","tracing","windows-sys 0.59.0",]@@ -13086,7 +13129,7 @@ dependencies = ["errno","libc","linux-raw-sys 0.12.1",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -13157,7 +13200,7 @@ dependencies = ["security-framework","security-framework-sys","webpki-root-certs",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -15291,7 +15334,7 @@ dependencies = ["getrandom 0.4.2","once_cell","rustix 1.1.4",- "windows-sys 0.52.0",+ "windows-sys 0.61.2",][[package]]@@ -16929,7 +16972,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.48.0",+ "windows-sys 0.61.2",][[package]]@@ -17465,6 +17508,7 @@ dependencies = [name = "workspace-hack"version = "0.1.0"dependencies = [+ "aes-gcm","ahash","aho-corasick","aws-config",diff --git a/Cargo.toml b/Cargo.tomlindex f7f39393f7..e874f7d43b 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -108,6 +108,7 @@ members = [][workspace.dependencies]+aes-gcm = { version = "0.10.3", features = ["zeroize"] }anyhow = "1.0.100"apollo-compiler = "1"apollo-parser = "0.8"@@ -127,6 +128,7 @@ automod = "1"aws-config = { version = "1.8.16", features = ["behavior-version-latest"] }aws-msk-iam-sasl-signer = "1.0.1"aws-sdk-dynamodb = "1.111.0"+aws-sdk-kms = "1.104.0"aws-sdk-lambda = "1.122.0"aws-sdk-s3 = "1.132.0"aws-sdk-secretsmanager = "1.104.0"@@ -283,6 +285,7 @@ utoipa = { version = "5.4.0", features = [utoipa-swagger-ui = { version = "9", features = ["axum", "vendored"] }uuid = { version = "1.15.1", features = ["fast-rng", "serde", "v4", "v5", "v7"] }wiremock = "0.6.5"+zeroize = "1.8.2"# worker-build (see services/sync-service/wrangler.toml) refuses to build against# anything older than 0.2.123, so keep this floor above that.wasm-bindgen = "0.2.123"diff --git a/crates/fusionauth/src/identity_provider/mod.rs b/crates/fusionauth/src/identity_provider/mod.rsindex 61150fc5aa..9c195ed355 100644--- a/crates/fusionauth/src/identity_provider/mod.rs+++ b/crates/fusionauth/src/identity_provider/mod.rs@@ -33,7 +33,7 @@ impl FusionAuthClient {}/// This API is used to create a link between a FusionAuth User and a user in a 3rd party identity provider. This API may be useful when you already know the unique Id of a user in a 3rd party identity provider and the corresponding FusionAuth User.- #[tracing::instrument(skip(self), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url, user_id=%request.identity_provider_link.user_id, idp_id=%request.identity_provider_link.identity_provider_id))]+ #[tracing::instrument(skip(self, request), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url, user_id=%request.identity_provider_link.user_id, idp_id=%request.identity_provider_link.identity_provider_id))]pub async fn link_user(&self, request: LinkUserRequest<'_>) -> Result<()> {link::link_user(&self.auth_client, &self.fusion_auth_base_url, request).await}diff --git a/crates/macro_db_client/migrations/20260819123655_add_microsoft_oauth_grants.sql b/crates/macro_db_client/migrations/20260819123655_add_microsoft_oauth_grants.sqlnew file mode 100644index 0000000000..51fdf11335--- /dev/null+++ b/crates/macro_db_client/migrations/20260819123655_add_microsoft_oauth_grants.sql@@ -0,0 +1,34 @@+CREATE TABLE microsoft_oauth_grants (+ fusionauth_user_id text NOT NULL,+ email_address text NOT NULL,+ refresh_token_ciphertext bytea NOT NULL,+ encrypted_data_key bytea NOT NULL,+ nonce bytea NOT NULL,+ encryption_version integer NOT NULL,+ kms_key_id text NOT NULL,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ last_refreshed_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY (fusionauth_user_id, email_address),+ CONSTRAINT microsoft_oauth_grants_lowercase_email CHECK (+ email_address = lower(email_address)+ ),+ CONSTRAINT microsoft_oauth_grants_email_not_empty CHECK (email_address <> ''),+ CONSTRAINT microsoft_oauth_grants_user_not_empty CHECK (fusionauth_user_id <> ''),+ CONSTRAINT microsoft_oauth_grants_ciphertext_not_empty CHECK (+ octet_length(refresh_token_ciphertext) > 0+ ),+ CONSTRAINT microsoft_oauth_grants_data_key_not_empty CHECK (+ octet_length(encrypted_data_key) > 0+ ),+ CONSTRAINT microsoft_oauth_grants_aes_gcm_nonce_length CHECK (+ octet_length(nonce) = 12+ ),+ CONSTRAINT microsoft_oauth_grants_encryption_version_positive CHECK (+ encryption_version > 0+ ),+ CONSTRAINT microsoft_oauth_grants_kms_key_id_not_empty CHECK (kms_key_id <> '')+);++-- The primary key's leading fusionauth_user_id column supports both exact grant+-- lookup and user-wide grant lifecycle operations without a redundant index.diff --git a/crates/microsoft_oauth_grant_db_utils/Cargo.toml b/crates/microsoft_oauth_grant_db_utils/Cargo.tomlnew file mode 100644index 0000000000..fe1b42396c--- /dev/null+++ b/crates/microsoft_oauth_grant_db_utils/Cargo.toml@@ -0,0 +1,15 @@+[package]+edition = "2024"+name = "microsoft_oauth_grant_db_utils"+publish = false+version = "0.1.0"++[dependencies]+anyhow = { workspace = true }+chrono = { workspace = true }+sqlx = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }++[dev-dependencies]+macro_db_migrator = { path = "../macro_db_migrator" }+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }diff --git a/crates/microsoft_oauth_grant_db_utils/src/lib.rs b/crates/microsoft_oauth_grant_db_utils/src/lib.rsnew file mode 100644index 0000000000..ec3af96a99--- /dev/null+++ b/crates/microsoft_oauth_grant_db_utils/src/lib.rs@@ -0,0 +1,233 @@+#![deny(missing_docs)]++//! Database utilities for encrypted Microsoft OAuth grants stored in MacroDB.++use chrono::{DateTime, Utc};+use sqlx::{Pool, Postgres};++#[cfg(test)]+mod test;++/// An encrypted Microsoft OAuth refresh-token envelope.+///+/// This type intentionally exposes only opaque encrypted bytes and envelope metadata.+/// Encryption, decryption, and plaintext token handling belong to the calling service.+#[derive(Clone, PartialEq, Eq)]+pub struct EncryptedMicrosoftOAuthGrant {+ refresh_token_ciphertext: Vec<u8>,+ encrypted_data_key: Vec<u8>,+ nonce: Vec<u8>,+ encryption_version: i32,+ kms_key_id: String,+}++impl EncryptedMicrosoftOAuthGrant {+ /// Creates an opaque encrypted grant envelope.+ pub fn new(+ refresh_token_ciphertext: Vec<u8>,+ encrypted_data_key: Vec<u8>,+ nonce: Vec<u8>,+ encryption_version: i32,+ kms_key_id: String,+ ) -> Self {+ Self {+ refresh_token_ciphertext,+ encrypted_data_key,+ nonce,+ encryption_version,+ kms_key_id,+ }+ }++ /// Returns the encrypted refresh-token bytes.+ pub fn refresh_token_ciphertext(&self) -> &[u8] {+ &self.refresh_token_ciphertext+ }++ /// Returns the KMS-encrypted data-key bytes.+ pub fn encrypted_data_key(&self) -> &[u8] {+ &self.encrypted_data_key+ }++ /// Returns the AES-GCM nonce.+ pub fn nonce(&self) -> &[u8] {+ &self.nonce+ }++ /// Returns the envelope encryption format version.+ pub fn encryption_version(&self) -> i32 {+ self.encryption_version+ }++ /// Returns the KMS key identifier used to create the data key.+ pub fn kms_key_id(&self) -> &str {+ &self.kms_key_id+ }+}++/// An encrypted Microsoft OAuth grant as stored in MacroDB.+pub struct StoredMicrosoftOAuthGrant {+ fusionauth_user_id: String,+ email_address: String,+ encrypted_grant: EncryptedMicrosoftOAuthGrant,+ created_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+ last_refreshed_at: DateTime<Utc>,+}++impl StoredMicrosoftOAuthGrant {+ /// Returns the FusionAuth user that owns the grant.+ pub fn fusionauth_user_id(&self) -> &str {+ &self.fusionauth_user_id+ }++ /// Returns the normalized mailbox email address.+ pub fn email_address(&self) -> &str {+ &self.email_address+ }++ /// Returns the opaque encrypted grant envelope.+ pub fn encrypted_grant(&self) -> &EncryptedMicrosoftOAuthGrant {+ &self.encrypted_grant+ }++ /// Returns when the grant was first stored.+ pub fn created_at(&self) -> DateTime<Utc> {+ self.created_at+ }++ /// Returns when the stored envelope was last replaced.+ pub fn updated_at(&self) -> DateTime<Utc> {+ self.updated_at+ }++ /// Returns when the refresh-token grant was last received from Microsoft.+ pub fn last_refreshed_at(&self) -> DateTime<Utc> {+ self.last_refreshed_at+ }+}++struct MicrosoftOAuthGrantRow {+ fusionauth_user_id: String,+ email_address: String,+ refresh_token_ciphertext: Vec<u8>,+ encrypted_data_key: Vec<u8>,+ nonce: Vec<u8>,+ encryption_version: i32,+ kms_key_id: String,+ created_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+ last_refreshed_at: DateTime<Utc>,+}++impl From<MicrosoftOAuthGrantRow> for StoredMicrosoftOAuthGrant {+ fn from(row: MicrosoftOAuthGrantRow) -> Self {+ Self {+ fusionauth_user_id: row.fusionauth_user_id,+ email_address: row.email_address,+ encrypted_grant: EncryptedMicrosoftOAuthGrant::new(+ row.refresh_token_ciphertext,+ row.encrypted_data_key,+ row.nonce,+ row.encryption_version,+ row.kms_key_id,+ ),+ created_at: row.created_at,+ updated_at: row.updated_at,+ last_refreshed_at: row.last_refreshed_at,+ }+ }+}++/// Inserts an encrypted Microsoft OAuth grant or atomically replaces its complete envelope.+pub async fn upsert_microsoft_oauth_grant(+ db: &Pool<Postgres>,+ fusionauth_user_id: &str,+ email_address: &str,+ encrypted_grant: &EncryptedMicrosoftOAuthGrant,+) -> anyhow::Result<StoredMicrosoftOAuthGrant> {+ let email_address = normalize_email_address(email_address);+ let row = sqlx::query_as!(+ MicrosoftOAuthGrantRow,+ r#"+ INSERT INTO microsoft_oauth_grants (+ fusionauth_user_id,+ email_address,+ refresh_token_ciphertext,+ encrypted_data_key,+ nonce,+ encryption_version,+ kms_key_id+ )+ VALUES ($1, $2, $3, $4, $5, $6, $7)+ ON CONFLICT (fusionauth_user_id, email_address) DO UPDATE SET+ refresh_token_ciphertext = EXCLUDED.refresh_token_ciphertext,+ encrypted_data_key = EXCLUDED.encrypted_data_key,+ nonce = EXCLUDED.nonce,+ encryption_version = EXCLUDED.encryption_version,+ kms_key_id = EXCLUDED.kms_key_id,+ updated_at = now(),+ last_refreshed_at = now()+ RETURNING+ fusionauth_user_id,+ email_address,+ refresh_token_ciphertext,+ encrypted_data_key,+ nonce,+ encryption_version,+ kms_key_id,+ created_at,+ updated_at,+ last_refreshed_at+ "#,+ fusionauth_user_id,+ email_address,+ encrypted_grant.refresh_token_ciphertext,+ encrypted_grant.encrypted_data_key,+ encrypted_grant.nonce,+ encrypted_grant.encryption_version,+ encrypted_grant.kms_key_id,+ )+ .fetch_one(db)+ .await?;++ Ok(row.into())+}++/// Fetches an encrypted Microsoft OAuth grant by owner and normalized mailbox.+pub async fn get_microsoft_oauth_grant(+ db: &Pool<Postgres>,+ fusionauth_user_id: &str,+ email_address: &str,+) -> anyhow::Result<Option<StoredMicrosoftOAuthGrant>> {+ let email_address = normalize_email_address(email_address);+ let row = sqlx::query_as!(+ MicrosoftOAuthGrantRow,+ r#"+ SELECT+ fusionauth_user_id,+ email_address,+ refresh_token_ciphertext,+ encrypted_data_key,+ nonce,+ encryption_version,+ kms_key_id,+ created_at,+ updated_at,+ last_refreshed_at+ FROM microsoft_oauth_grants+ WHERE fusionauth_user_id = $1+ AND email_address = $2+ "#,+ fusionauth_user_id,+ email_address,+ )+ .fetch_optional(db)+ .await?;++ Ok(row.map(Into::into))+}++fn normalize_email_address(email_address: &str) -> String {+ email_address.to_lowercase()+}diff --git a/crates/microsoft_oauth_grant_db_utils/src/test.rs b/crates/microsoft_oauth_grant_db_utils/src/test.rsnew file mode 100644index 0000000000..1626bc32e7--- /dev/null+++ b/crates/microsoft_oauth_grant_db_utils/src/test.rs@@ -0,0 +1,242 @@+use super::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};++const OWNER_ID: &str = "fusionauth-user-1";++fn encrypted_grant(seed: u8) -> EncryptedMicrosoftOAuthGrant {+ EncryptedMicrosoftOAuthGrant::new(+ vec![seed, 0, 255, seed.wrapping_add(1)],+ vec![seed.wrapping_add(2), 0, 128],+ vec![seed; 12],+ i32::from(seed) + 1,+ format!("arn:aws:kms:us-east-1:123456789012:key/{seed}"),+ )+}++fn assert_envelopes_equal(+ actual: &EncryptedMicrosoftOAuthGrant,+ expected: &EncryptedMicrosoftOAuthGrant,+) {+ assert_eq!(+ actual.refresh_token_ciphertext(),+ expected.refresh_token_ciphertext()+ );+ assert_eq!(actual.encrypted_data_key(), expected.encrypted_data_key());+ assert_eq!(actual.nonce(), expected.nonce());+ assert_eq!(actual.encryption_version(), expected.encryption_version());+ assert_eq!(actual.kms_key_id(), expected.kms_key_id());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn normalizes_email_addresses_for_upsert_and_fetch(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let envelope = encrypted_grant(1);++ let inserted =+ upsert_microsoft_oauth_grant(&pool, OWNER_ID, "[email protected]", &envelope).await?;+ let fetched = get_microsoft_oauth_grant(&pool, OWNER_ID, "[email protected]")+ .await?+ .expect("normalized grant should exist");++ assert_eq!(inserted.email_address(), "[email protected]");+ assert_eq!(fetched.email_address(), "[email protected]");++ let uppercase_update = sqlx::query!(+ r#"+ UPDATE microsoft_oauth_grants+ SET email_address = '[email protected]'+ WHERE fusionauth_user_id = $1+ AND email_address = '[email protected]'+ "#,+ OWNER_ID,+ )+ .execute(&pool)+ .await;+ assert!(+ uppercase_update.is_err(),+ "the database must reject non-normalized mailbox keys"+ );++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn first_insert_stores_encrypted_envelope_and_metadata(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let before_insert = Utc::now();+ let envelope = encrypted_grant(2);++ let inserted =+ upsert_microsoft_oauth_grant(&pool, OWNER_ID, "[email protected]", &envelope).await?;++ assert_eq!(inserted.fusionauth_user_id(), OWNER_ID);+ assert_envelopes_equal(inserted.encrypted_grant(), &envelope);+ assert!(inserted.created_at() >= before_insert);+ assert_eq!(inserted.updated_at(), inserted.created_at());+ assert_eq!(inserted.last_refreshed_at(), inserted.created_at());++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn reconnect_atomically_replaces_the_complete_envelope(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let initial = encrypted_grant(3);+ let replacement = encrypted_grant(20);+ let first =+ upsert_microsoft_oauth_grant(&pool, OWNER_ID, "[email protected]", &initial).await?;++ tokio::time::sleep(std::time::Duration::from_millis(2)).await;+ let reconnected =+ upsert_microsoft_oauth_grant(&pool, OWNER_ID, "[email protected]", &replacement).await?;++ assert_eq!(reconnected.created_at(), first.created_at());+ assert!(reconnected.updated_at() > first.updated_at());+ assert!(reconnected.last_refreshed_at() > first.last_refreshed_at());+ assert_envelopes_equal(reconnected.encrypted_grant(), &replacement);+ assert_ne!(+ reconnected.encrypted_grant().refresh_token_ciphertext(),+ initial.refresh_token_ciphertext()+ );+ assert_ne!(+ reconnected.encrypted_grant().encrypted_data_key(),+ initial.encrypted_data_key()+ );+ assert_ne!(reconnected.encrypted_grant().nonce(), initial.nonce());+ assert_ne!(+ reconnected.encrypted_grant().encryption_version(),+ initial.encryption_version()+ );+ assert_ne!(+ reconnected.encrypted_grant().kms_key_id(),+ initial.kms_key_id()+ );++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn owner_and_normalized_mailbox_form_a_unique_key(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let owner_one_envelope = encrypted_grant(4);+ let owner_two_envelope = encrypted_grant(5);++ upsert_microsoft_oauth_grant(+ &pool,+ "fusionauth-user-1",+ "[email protected]",+ &owner_one_envelope,+ )+ .await?;+ upsert_microsoft_oauth_grant(+ &pool,+ "fusionauth-user-2",+ "[email protected]",+ &owner_two_envelope,+ )+ .await?;++ let duplicate_result = sqlx::query!(+ r#"+ INSERT INTO microsoft_oauth_grants (+ fusionauth_user_id,+ email_address,+ refresh_token_ciphertext,+ encrypted_data_key,+ nonce,+ encryption_version,+ kms_key_id+ )+ VALUES ($1, $2, $3, $4, $5, $6, $7)+ "#,+ "fusionauth-user-1",+ "[email protected]",+ owner_one_envelope.refresh_token_ciphertext,+ owner_one_envelope.encrypted_data_key,+ owner_one_envelope.nonce,+ owner_one_envelope.encryption_version,+ owner_one_envelope.kms_key_id,+ )+ .execute(&pool)+ .await;++ assert!(duplicate_result.is_err(), "duplicate owner key must fail");+ let grant_count = sqlx::query_scalar!(+ r#"+ SELECT COUNT(*) AS "count!"+ FROM microsoft_oauth_grants+ WHERE email_address = '[email protected]'+ "#+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(grant_count, 2, "ownership must be scoped to the user");++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn opaque_binary_values_round_trip_without_interpretation(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let envelope = EncryptedMicrosoftOAuthGrant::new(+ vec![0, 255, 0, 17, 128, 42],+ vec![255, 254, 0, 1, 2],+ vec![0, 1, 2, 3, 4, 5, 255, 128, 10, 11, 12, 13],+ i32::MAX,+ "alias/microsoft-oauth-grants".to_string(),+ );++ upsert_microsoft_oauth_grant(&pool, OWNER_ID, "[email protected]", &envelope).await?;+ let fetched = get_microsoft_oauth_grant(&pool, OWNER_ID, "[email protected]")+ .await?+ .expect("grant should exist");++ assert_envelopes_equal(fetched.encrypted_grant(), &envelope);++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn schema_has_no_plaintext_secret_columns(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let columns = sqlx::query_scalar!(+ r#"+ SELECT column_name AS "column_name!"+ FROM information_schema.columns+ WHERE table_schema = 'public'+ AND table_name = 'microsoft_oauth_grants'+ ORDER BY ordinal_position+ "#+ )+ .fetch_all(&pool)+ .await?;++ assert_eq!(+ columns,+ vec![+ "fusionauth_user_id",+ "email_address",+ "refresh_token_ciphertext",+ "encrypted_data_key",+ "nonce",+ "encryption_version",+ "kms_key_id",+ "created_at",+ "updated_at",+ "last_refreshed_at",+ ]+ );+ assert!(!columns.iter().any(|column| {+ matches!(+ column.as_str(),+ "refresh_token" | "plaintext_refresh_token" | "data_key"+ )+ }));++ Ok(())+}diff --git a/crates/workspace-hack/Cargo.toml b/crates/workspace-hack/Cargo.tomlindex fb5b677721..837fa0d60d 100644--- a/crates/workspace-hack/Cargo.toml+++ b/crates/workspace-hack/Cargo.toml@@ -15,6 +15,7 @@ publish = false### BEGIN HAKARI SECTION[dependencies]+aes-gcm = { version = "0.10", features = ["zeroize"] }ahash = { version = "0.8" }aho-corasick = { version = "1" }aws-config = { version = "1", features = ["behavior-version-latest"] }@@ -142,6 +143,7 @@ zerocopy = { version = "0.8", default-features = false, features = ["derive", "szeroize = { version = "1", features = ["derive"] }[build-dependencies]+aes-gcm = { version = "0.10", features = ["zeroize"] }ahash = { version = "0.8" }aho-corasick = { version = "1" }aws-config = { version = "1", features = ["behavior-version-latest"] }diff --git a/infra/stacks/authentication-service/Pulumi.dev.yaml b/infra/stacks/authentication-service/Pulumi.dev.yamlindex 94de172dc9..ec4bdebd74 100644--- a/infra/stacks/authentication-service/Pulumi.dev.yaml+++ b/infra/stacks/authentication-service/Pulumi.dev.yaml@@ -4,6 +4,9 @@ config:authentication-service:macro_db_secret_key: macro-db-devauthentication-service:fusionauth_api_key_secret_key: fusionauth-api-key-devauthentication-service:authentication_service_internal_api_key: authentication-service-internal-api-key-dev+ # Keep Microsoft OAuth credentials in the authentication_service Doppler config.+ # Pulumi injects MICROSOFT_TOKEN_KMS_KEY_ID from the per-stack key; it is not a secret config value.+ authentication-service:microsoft_token_kms_deletion_window_days: 7authentication-service:service_internal_auth_key: document-storage-service-auth-key-devauthentication-service:fusionauth_client_secret_key: fusionauth-client-secret-devauthentication-service:stripe_secret_key: stripe-devdiff --git a/infra/stacks/authentication-service/Pulumi.prod.yaml b/infra/stacks/authentication-service/Pulumi.prod.yamlindex 8d314fd194..d8bb8d729f 100644--- a/infra/stacks/authentication-service/Pulumi.prod.yaml+++ b/infra/stacks/authentication-service/Pulumi.prod.yaml@@ -4,6 +4,9 @@ config:authentication-service:macro_db_secret_key: macro-db-prodauthentication-service:fusionauth_api_key_secret_key: fusionauth-api-key-prodauthentication-service:authentication_service_internal_api_key: authentication-service-internal-api-key-prod+ # Keep Microsoft OAuth credentials in the authentication_service Doppler config.+ # Pulumi injects MICROSOFT_TOKEN_KMS_KEY_ID from the per-stack key; it is not a secret config value.+ authentication-service:microsoft_token_kms_deletion_window_days: 30authentication-service:fusionauth_client_secret_key: fusionauth-client-secret-prodauthentication-service:service_internal_auth_key: document-storage-service-auth-key-prodauthentication-service:stripe_secret_key: stripe-proddiff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.tsindex 616eb60d10..af0d295656 100644--- a/infra/stacks/authentication-service/index.ts+++ b/infra/stacks/authentication-service/index.ts@@ -32,6 +32,9 @@ const FUSIONAUTH_API_KEY_SECRET_KEY = config.require(const AUTHENTICATION_SERVICE_INTERNAL_API_KEY = config.require(`authentication_service_internal_api_key`);+const MICROSOFT_TOKEN_KMS_DELETION_WINDOW_IN_DAYS = config.requireNumber(+ 'microsoft_token_kms_deletion_window_days'+);const FUSIONAUTH_CLIENT_SECRET_KEY = config.require(`fusionauth_client_secret_key`@@ -148,7 +151,12 @@ const service = new AuthenticationService('authentication-service', {backfillQueueArn,contactsQueueArn,],+ microsoftTokenKmsDeletionWindowInDays:+ MICROSOFT_TOKEN_KMS_DELETION_WINDOW_IN_DAYS,containerEnvVars: [+ // Configure MICROSOFT_CLIENT_ID, MICROSOFT_CLIENT_SECRET, and+ // MICROSOFT_TENANT_ID together in the authentication_service Doppler+ // config.{ name: 'ENVIRONMENT', value: stack },{ name: 'DOPPLER_PROJECT', value: 'authentication_service' },// OpenTelemetry / Datadog tracing configurationdiff --git a/infra/stacks/authentication-service/service.ts b/infra/stacks/authentication-service/service.tsindex de75ee4ce8..59200acb55 100644--- a/infra/stacks/authentication-service/service.ts+++ b/infra/stacks/authentication-service/service.ts@@ -21,6 +21,8 @@ import {const BASE_NAME = pulumi.getProject();const REPO_ROOT = '../../..';+const MICROSOFT_TOKEN_KMS_ACTIONS = ['kms:GenerateDataKey', 'kms:Decrypt'];+export const SERVICE_DOMAIN_NAME = `auth-service${stack === 'prod' ? '' : `-${stack}`}.${BASE_DOMAIN}`;@@ -41,6 +43,7 @@ type Args = {healthCheckPath: string;tags: { [key: string]: string };queueArns: pulumi.Output<string>[];+ microsoftTokenKmsDeletionWindowInDays: number;};export class AuthenticationService extends pulumi.ComponentResource {@@ -70,6 +73,7 @@ export class AuthenticationService extends pulumi.ComponentResource {tags,secretKeyArns,queueArns,+ microsoftTokenKmsDeletionWindowInDays,}: Args,opts?: pulumi.ComponentResourceOptions) {@@ -162,6 +166,80 @@ export class AuthenticationService extends pulumi.ComponentResource {{ parent: this });+ const accountRootArn = pulumi.interpolate`arn:aws:iam::${aws.getCallerIdentityOutput().accountId}:root`;+ const microsoftTokenKmsKeyPolicy = aws.iam.getPolicyDocumentOutput({+ statements: [+ {+ sid: 'AllowAccountKeyAdministration',+ effect: 'Allow',+ principals: [{ type: 'AWS', identifiers: [accountRootArn] }],+ actions: [+ 'kms:CancelKeyDeletion',+ 'kms:Create*',+ 'kms:Delete*',+ 'kms:Describe*',+ 'kms:Disable*',+ 'kms:Enable*',+ 'kms:Get*',+ 'kms:List*',+ 'kms:Put*',+ 'kms:Revoke*',+ 'kms:ScheduleKeyDeletion',+ 'kms:TagResource',+ 'kms:UntagResource',+ 'kms:Update*',+ ],+ resources: ['*'],+ },+ {+ sid: 'AllowAuthenticationServiceTokenEncryption',+ effect: 'Allow',+ principals: [{ type: 'AWS', identifiers: [this.role.arn] }],+ actions: MICROSOFT_TOKEN_KMS_ACTIONS,+ resources: ['*'],+ },+ ],+ });++ const microsoftTokenKmsKey = new aws.kms.Key(+ `${BASE_NAME}-microsoft-token-key`,+ {+ description: `Microsoft refresh-token envelope key for ${stack}`,+ deletionWindowInDays: microsoftTokenKmsDeletionWindowInDays,+ enableKeyRotation: true,+ policy: microsoftTokenKmsKeyPolicy.json,+ tags: this.tags,+ },+ { parent: this, protect: stack === 'prod' }+ );++ new aws.kms.Alias(+ `${BASE_NAME}-microsoft-token-key-alias`,+ {+ name: `alias/${BASE_NAME}-microsoft-token-${stack}`,+ targetKeyId: microsoftTokenKmsKey.keyId,+ },+ { parent: this }+ );++ new aws.iam.RolePolicy(+ `${BASE_NAME}-microsoft-token-kms-policy`,+ {+ role: this.role.id,+ policy: {+ Version: '2012-10-17',+ Statement: [+ {+ Action: MICROSOFT_TOKEN_KMS_ACTIONS,+ Resource: microsoftTokenKmsKey.arn,+ Effect: 'Allow',+ },+ ],+ },+ },+ { parent: this }+ );+// ecr imageconst image = new EcrImage(`${BASE_NAME}-ecr-image-${stack}`,diff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.tomlindex 56befdd8d7..1ae4d10d77 100644--- a/services/authentication_service/Cargo.toml+++ b/services/authentication_service/Cargo.toml@@ -28,15 +28,18 @@ rate_limit = []return_passwordless_code = [][dependencies]+aes-gcm = { workspace = true }calendar_events = { path = "../../crates/calendar_events" }analytics_client = { path = "../../crates/analytics_client" }anyhow = { workspace = true }+async-trait = { workspace = true }async-stripe = { workspace = true, default-features = false, features = ["billing","checkout","runtime-tokio-hyper-rustls-webpki",] }async-stripe-webhook = { version = "1.0.0-alpha.4", default-features = false }+aws-sdk-kms = { workspace = true }aws-sdk-secretsmanager = { workspace = true }aws-sdk-sesv2 = { workspace = true }aws-sdk-sqs = { workspace = true }@@ -104,6 +107,7 @@ macro_user_id = { path = "../../crates/macro_user_id" }macro_uuid = { path = "../../crates/macro_uuid" }maud = { version = "0.27.0" }miniserde = "0.1.45"+microsoft_oauth_grant_db_utils = { path = "../../crates/microsoft_oauth_grant_db_utils" }mobile_welcome_email_db_client = { path = "../../crates/mobile_welcome_email_db_client" }mockall = { workspace = true }model = { path = "../../crates/model" }@@ -149,6 +153,7 @@ user_quota = { path = "../../crates/user_quota" }utoipa = { workspace = true }utoipa-swagger-ui = { workspace = true }uuid = { workspace = true }+zeroize = { workspace = true }doppler-config = { workspace = true }workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }database_env_vars = { path = "../../crates/database_env_vars" }diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rsindex 4b99f6dc0c..29b7737484 100644--- a/services/authentication_service/src/api/context.rs+++ b/services/authentication_service/src/api/context.rs@@ -50,6 +50,8 @@ use roles_and_permissions::{use sqlx::PgPool;use tokio_util::task::TaskTracker;+use crate::microsoft_token_cipher::MicrosoftTokenCipher;+pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsQueue>;pub(crate) type AuthenticationEventBroker =MacroEventBrokerService<KafkaEventPublisher, TaskTracker>;@@ -111,6 +113,7 @@ pub(crate) struct ApiContext {pub db: PgPool,pub github_link_service: Arc<GithubLinkServiceType>,pub auth_client: Arc<fusionauth::FusionAuthClient>,+ pub microsoft_token_cipher: Option<Arc<dyn MicrosoftTokenCipher>>,pub macro_cache_client: Arc<MacroCache>,pub stripe_client: Arc<stripe::Client>,pub document_storage_service_client:diff --git a/services/authentication_service/src/api/oauth2/microsoft.rs b/services/authentication_service/src/api/oauth2/microsoft.rsindex 77f17e52ea..7901347adf 100644--- a/services/authentication_service/src/api/oauth2/microsoft.rs+++ b/services/authentication_service/src/api/oauth2/microsoft.rs@@ -8,27 +8,32 @@ use email_validator::normalize_email;use fusionauth::{error::FusionAuthClientError,identity_provider::{IdentityProviderLink, LinkUserRequest},- microsoft::oauth::MicrosoftUserInfo,+ microsoft::oauth::{MicrosoftExchangeTokenResponse, MicrosoftUserInfo},};+use microsoft_oauth_grant_db_utils::EncryptedMicrosoftOAuthGrant;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,+use crate::{+ api::{+ context::ApiContext,+ oauth2::{+ OAuthState,+ account_link::{+ build_callback_redirect, cleanup_pending_link, replace_identity_provider_grant,+ },+ format_redirect_uri,},- format_redirect_uri,},+ microsoft_token_cipher::{EncryptedMicrosoftToken, MicrosoftRefreshToken},};#[cfg(test)]mod test;const MICROSOFT_IDENTITY_PROVIDER_NAME: &str = "microsoft";+const GRANT_STORAGE_ERROR: &str = "unable to securely store Microsoft grant";type MicrosoftCallbackResult<T> = Result<T, (StatusCode, String)>;@@ -38,6 +43,312 @@ struct MicrosoftLinkIdentity {email: String,}+enum FusionLinkChange {+ Fresh,+ Replaced {+ previous_refresh_token: MicrosoftRefreshToken,+ },+ Unchanged,+}++struct GrantEncryptionFailed;+struct GrantPersistenceFailed;++#[async_trait::async_trait]+trait MicrosoftCallbackDependencies: Send + Sync {+ async fn identity_provider_id(&self) -> MicrosoftCallbackResult<String>;++ async fn pending_link_owner(&self, link_id: &Uuid) -> MicrosoftCallbackResult<String>;++ async fn exchange_tokens(+ &self,+ code: &str,+ ) -> MicrosoftCallbackResult<MicrosoftExchangeTokenResponse>;++ async fn parse_identity(&self, id_token: &str) -> MicrosoftCallbackResult<MicrosoftUserInfo>;++ async fn mailbox_owner(+ &self,+ email: &str,+ pending_link_owner: &str,+ ) -> MicrosoftCallbackResult<String>;++ async fn link_identity(+ &self,+ identity_provider_id: &str,+ link_owner_id: &str,+ identity: &MicrosoftLinkIdentity,+ refresh_token: &str,+ ) -> MicrosoftCallbackResult<FusionLinkChange>;++ async fn encrypt_grant(+ &self,+ link_owner_id: &str,+ email: &str,+ refresh_token: MicrosoftRefreshToken,+ ) -> Result<EncryptedMicrosoftToken, GrantEncryptionFailed>;++ async fn persist_grant(+ &self,+ link_owner_id: &str,+ email: &str,+ encrypted_token: &EncryptedMicrosoftToken,+ ) -> Result<(), GrantPersistenceFailed>;++ async fn mark_link_consumable(+ &self,+ link_id: &Uuid,+ email: &str,+ ) -> MicrosoftCallbackResult<()>;++ async fn compensate_link(+ &self,+ identity_provider_id: &str,+ link_owner_id: &str,+ identity: &MicrosoftLinkIdentity,+ change: FusionLinkChange,+ );++ async fn cleanup_pending_link(&self, link_id: &Uuid);+}++#[async_trait::async_trait]+impl MicrosoftCallbackDependencies for ApiContext {+ async fn identity_provider_id(&self) -> MicrosoftCallbackResult<String> {+ self.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}"),+ ),+ })+ }++ async fn pending_link_owner(&self, link_id: &Uuid) -> MicrosoftCallbackResult<String> {+ macro_db_client::in_progress_user_link::get_in_progress_user_link(&self.db, link_id)+ .await+ .map(|link| link.macro_user_id.to_string())+ .map_err(|error| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ format!("unable to load pending Microsoft link {error}"),+ )+ })+ }++ async fn exchange_tokens(+ &self,+ code: &str,+ ) -> MicrosoftCallbackResult<MicrosoftExchangeTokenResponse> {+ self.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}"),+ )+ })+ }++ async fn parse_identity(&self, id_token: &str) -> MicrosoftCallbackResult<MicrosoftUserInfo> {+ self.auth_client+ .parse_microsoft_id_token(id_token)+ .await+ .map_err(|error| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ format!("unable to decode Microsoft ID token {error}"),+ )+ })+ }++ async fn mailbox_owner(+ &self,+ email: &str,+ pending_link_owner: &str,+ ) -> MicrosoftCallbackResult<String> {+ match macro_db_client::user::get::get_macro_user_id_by_email(&self.db, email).await {+ Ok(Some(mailbox_owner_id)) => Ok(mailbox_owner_id.to_string()),+ Ok(None) => Ok(pending_link_owner.to_owned()),+ Err(error) => Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ format!("unable to look up mailbox owner for linked email {error}"),+ )),+ }+ }++ async fn link_identity(+ &self,+ identity_provider_id: &str,+ link_owner_id: &str,+ identity: &MicrosoftLinkIdentity,+ refresh_token: &str,+ ) -> MicrosoftCallbackResult<FusionLinkChange> {+ let link_request = LinkUserRequest {+ identity_provider_link: IdentityProviderLink {+ display_name: Cow::Borrowed(&identity.email),+ identity_provider_id: Cow::Borrowed(identity_provider_id),+ identity_provider_user_id: Cow::Borrowed(&identity.subject),+ user_id: Cow::Borrowed(link_owner_id),+ token: Cow::Borrowed(refresh_token),+ },+ };++ match self.auth_client.link_user(link_request).await {+ Ok(()) => Ok(FusionLinkChange::Fresh),+ Err(FusionAuthClientError::IdentityProviderLinkAlreadyExists) => {+ let previous_refresh_token = self+ .auth_client+ .get_links(link_owner_id, Some(identity_provider_id.to_owned()))+ .await+ .map_err(|error| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ format!("unable to read existing Microsoft links {error}"),+ )+ })?+ .into_iter()+ .find(|link| link.display_name == identity.email)+ .and_then(|link| {+ (!refresh_token.is_empty() && link.token != refresh_token)+ .then(|| MicrosoftRefreshToken::new(link.token))+ });++ replace_identity_provider_grant(+ &self.auth_client,+ identity_provider_id,+ link_owner_id,+ &identity.email,+ refresh_token,+ )+ .await+ .map_err(|_| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ "unable to replace Microsoft identity-provider grant".into(),+ )+ })?;++ match previous_refresh_token {+ Some(previous_refresh_token) => Ok(FusionLinkChange::Replaced {+ previous_refresh_token,+ }),+ None => Ok(FusionLinkChange::Unchanged),+ }+ }+ Err(_) => Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ "unable to link Microsoft user".into(),+ )),+ }+ }++ async fn encrypt_grant(+ &self,+ link_owner_id: &str,+ email: &str,+ refresh_token: MicrosoftRefreshToken,+ ) -> Result<EncryptedMicrosoftToken, GrantEncryptionFailed> {+ let Some(cipher) = &self.microsoft_token_cipher else {+ tracing::error!("Microsoft token cipher is not configured");+ return Err(GrantEncryptionFailed);+ };++ cipher+ .encrypt(link_owner_id, email, refresh_token)+ .await+ .inspect_err(+ |error| tracing::error!(error=?error, "failed to encrypt Microsoft refresh token"),+ )+ .map_err(|_| GrantEncryptionFailed)+ }++ async fn persist_grant(+ &self,+ link_owner_id: &str,+ email: &str,+ encrypted_token: &EncryptedMicrosoftToken,+ ) -> Result<(), GrantPersistenceFailed> {+ let encrypted_grant = EncryptedMicrosoftOAuthGrant::new(+ encrypted_token.refresh_token_ciphertext.clone(),+ encrypted_token.encrypted_data_key.clone(),+ encrypted_token.nonce.clone(),+ i32::from(encrypted_token.encryption_version),+ encrypted_token.kms_key_id.clone(),+ );++ microsoft_oauth_grant_db_utils::upsert_microsoft_oauth_grant(+ &self.db,+ link_owner_id,+ email,+ &encrypted_grant,+ )+ .await+ .inspect_err(+ |error| tracing::error!(error=?error, "failed to persist encrypted Microsoft grant"),+ )+ .map(|_| ())+ .map_err(|_| GrantPersistenceFailed)+ }++ async fn mark_link_consumable(+ &self,+ link_id: &Uuid,+ email: &str,+ ) -> MicrosoftCallbackResult<()> {+ macro_db_client::in_progress_user_link::set_linked_email(&self.db, link_id, email)+ .await+ .map_err(|error| {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ format!("unable to record linked Microsoft email {error}"),+ )+ })+ }++ async fn compensate_link(+ &self,+ identity_provider_id: &str,+ link_owner_id: &str,+ identity: &MicrosoftLinkIdentity,+ change: FusionLinkChange,+ ) {+ let compensation_failed = match change {+ FusionLinkChange::Fresh => self+ .auth_client+ .unlink_user(link_owner_id, identity_provider_id, &identity.subject)+ .await+ .is_err(),+ FusionLinkChange::Replaced {+ previous_refresh_token,+ } => replace_identity_provider_grant(+ &self.auth_client,+ identity_provider_id,+ link_owner_id,+ &identity.email,+ previous_refresh_token.as_str(),+ )+ .await+ .is_err(),+ FusionLinkChange::Unchanged => false,+ };++ if compensation_failed {+ tracing::warn!("failed to compensate Microsoft identity-provider link");+ }+ }++ async fn cleanup_pending_link(&self, link_id: &Uuid) {+ cleanup_pending_link(self, link_id).await;+ }+}+fn extract_identity(user_info: MicrosoftUserInfo,) -> MicrosoftCallbackResult<MicrosoftLinkIdentity> {@@ -86,132 +397,95 @@ fn verify_identity_provider(Ok(())}-#[tracing::instrument(skip(ctx, code, state), fields(%link_id), err(Debug))]-async fn link_user(- ctx: &ApiContext,+#[tracing::instrument(skip(dependencies, code, state), fields(%link_id), err(Debug))]+async fn link_user<D: MicrosoftCallbackDependencies + ?Sized>(+ dependencies: &D,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, µsoft_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 identity_provider_id = dependencies.identity_provider_id().await?;+ verify_identity_provider(state, &identity_provider_id)?;- 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 pending_link_owner = dependencies.pending_link_owner(link_id).await?;+ let token_response = dependencies.exchange_tokens(code).await?;+ let user_info = dependencies+ .parse_identity(&token_response.id_token)+ .await?;let identity = extract_identity(user_info)?;+ let link_owner_id = dependencies+ .mailbox_owner(&identity.email, &pending_link_owner)+ .await?;- // 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+ let link_change = dependencies+ .link_identity(+ &identity_provider_id,+ &link_owner_id,+ &identity,+ &token_response.refresh_token,+ )+ .await?;++ let encrypted_token = match dependencies+ .encrypt_grant(+ &link_owner_id,+ &identity.email,+ MicrosoftRefreshToken::new(token_response.refresh_token),+ )+ .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}"),- ));+ Ok(encrypted_token) => encrypted_token,+ Err(_) => {+ dependencies+ .compensate_link(+ &identity_provider_id,+ &link_owner_id,+ &identity,+ link_change,+ )+ .await;+ return Err(grant_storage_error());}};- match ctx- .auth_client- .link_user(LinkUserRequest {- identity_provider_link: IdentityProviderLink {- display_name: Cow::Borrowed(&identity.email),- identity_provider_id: Cow::Borrowed(µsoft_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),- },- })+ if dependencies+ .persist_grant(&link_owner_id, &identity.email, &encrypted_token).await+ .is_err(){- Ok(()) => {}- Err(FusionAuthClientError::IdentityProviderLinkAlreadyExists) => {- replace_identity_provider_grant(- &ctx.auth_client,- µsoft_identity_provider_id,+ dependencies+ .compensate_link(+ &identity_provider_id,&link_owner_id,- &identity.email,- &token_response.refresh_token,+ &identity,+ link_change,)- .await?;- }- Err(error) => {- return Err((- StatusCode::INTERNAL_SERVER_ERROR,- format!("unable to link Microsoft user {error}"),- ));- }+ .await;+ return Err(grant_storage_error());}- macro_db_client::in_progress_user_link::set_linked_email(&ctx.db, link_id, &identity.email)+ dependencies+ .mark_link_consumable(link_id, &identity.email).await- .map_err(|error| {- (- StatusCode::INTERNAL_SERVER_ERROR,- format!("unable to record linked Microsoft email {error}"),- )- })?;+}- Ok(())+fn grant_storage_error() -> (StatusCode, String) {+ (+ StatusCode::INTERNAL_SERVER_ERROR,+ GRANT_STORAGE_ERROR.into(),+ )}-pub(in crate::api::oauth2) async fn handler(- ctx: &ApiContext,+async fn handler_with_dependencies<D: MicrosoftCallbackDependencies + ?Sized>(+ dependencies: &D,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;+ let link_result = link_user(dependencies, code, state, &link_id).await;if link_result.is_err() {- cleanup_pending_link(ctx, &link_id).await;+ dependencies.cleanup_pending_link(&link_id).await;}link_result.map_err(callback_error_response)?;@@ -220,7 +494,7 @@ pub(in crate::api::oauth2) async fn handler(return match build_callback_redirect(original_url, &link_id) {Ok(response) => Ok(response),Err(error) => {- cleanup_pending_link(ctx, &link_id).await;+ dependencies.cleanup_pending_link(&link_id).await;Err(error.into_response())}};@@ -229,6 +503,14 @@ pub(in crate::api::oauth2) async fn handler(Ok(StatusCode::OK.into_response())}+pub(in crate::api::oauth2) async fn handler(+ ctx: &ApiContext,+ code: &str,+ state: &OAuthState,+) -> Result<Response, Response> {+ handler_with_dependencies(ctx, code, state).await+}+fn callback_error_response((status_code, message): (StatusCode, String)) -> Response {tracing::error!(error=?message, "unable to link Microsoft user");(diff --git a/services/authentication_service/src/api/oauth2/microsoft/test.rs b/services/authentication_service/src/api/oauth2/microsoft/test.rsindex 02666d885d..f3d34c1a63 100644--- a/services/authentication_service/src/api/oauth2/microsoft/test.rs+++ b/services/authentication_service/src/api/oauth2/microsoft/test.rs@@ -1,10 +1,20 @@-use fusionauth::microsoft::oauth::MicrosoftUserInfo;+use std::{+ collections::{HashMap, VecDeque},+ sync::Mutex,+};++use fusionauth::microsoft::oauth::{MicrosoftExchangeTokenResponse, MicrosoftUserInfo};+use http_body_util::BodyExt;use reqwest::StatusCode;use uuid::Uuid;-use super::{extract_identity, require_link_id, verify_identity_provider};+use super::*;use crate::api::oauth2::OAuthState;+const IDENTITY_PROVIDER_ID: &str = "microsoft-idp-id";+const PENDING_OWNER: &str = "pending-owner";+const REFRESH_TOKEN: &str = "private-microsoft-refresh-token";+fn state(identity_provider_id: &str, link_id: Option<Uuid>) -> OAuthState {OAuthState {identity_provider_id: identity_provider_id.to_string(),@@ -44,7 +54,7 @@ fn rejects_identity_without_subject_or_usable_email() {#[test]fn microsoft_callback_requires_link_id() {- let error = require_link_id(&state("microsoft-idp-id", None)).unwrap_err();+ let error = require_link_id(&state(IDENTITY_PROVIDER_ID, None)).unwrap_err();assert_eq!(error.0, StatusCode::BAD_REQUEST);assert!(error.1.contains("link_id"));@@ -53,14 +63,452 @@ fn microsoft_callback_requires_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();+ let error = verify_identity_provider(&callback_state, IDENTITY_PROVIDER_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()));+ let callback_state = state(IDENTITY_PROVIDER_ID, Some(Uuid::now_v7()));++ verify_identity_provider(&callback_state, IDENTITY_PROVIDER_ID).unwrap();+}++#[tokio::test]+async fn first_link_persists_encrypted_grant_before_making_link_consumable() {+ let dependencies = FakeDependencies::new(+ [REFRESH_TOKEN],+ [LinkScenario::Fresh],+ "[email protected]",+ );+ let link_id = Uuid::now_v7();++ let response = handler_with_dependencies(+ &dependencies,+ "authorization-code",+ &state(IDENTITY_PROVIDER_ID, Some(link_id)),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ let recorded = dependencies.recorded();+ assert_eq!(recorded.events, ["link", "encrypt", "persist", "mark"]);+ assert_eq!(+ recorded.grants.keys().collect::<Vec<_>>(),+ [&(+ PENDING_OWNER.to_owned(),+ "[email protected]".to_owned()+ )]+ );+ assert_eq!(recorded.fusion_token_lengths, [REFRESH_TOKEN.len()]);+ assert!(recorded.compensations.is_empty());+ assert!(recorded.cleaned_links.is_empty());+}++#[tokio::test]+async fn reconnect_replaces_the_encrypted_grant() {+ let dependencies = FakeDependencies::new(+ ["first-refresh-token", "replacement-refresh-token"],+ [+ LinkScenario::Fresh,+ LinkScenario::Reconnect("first-refresh-token".into()),+ ],+ "[email protected]",+ );++ for _ in 0..2 {+ handler_with_dependencies(+ &dependencies,+ "authorization-code",+ &state(IDENTITY_PROVIDER_ID, Some(Uuid::now_v7())),+ )+ .await+ .unwrap();+ }++ let recorded = dependencies.recorded();+ assert_eq!(recorded.grants.len(), 1);+ assert_eq!(+ recorded+ .grants+ .get(&(PENDING_OWNER.to_owned(), "[email protected]".to_owned())),+ Some(&vec![2])+ );+ assert_eq!(+ recorded.events,+ [+ "link", "encrypt", "persist", "mark", "link", "encrypt", "persist", "mark"+ ]+ );+}++#[tokio::test]+async fn grant_is_keyed_by_resolved_owner_and_normalized_mailbox() {+ let dependencies = FakeDependencies::new(+ [REFRESH_TOKEN],+ [LinkScenario::Fresh],+ "[email protected]",+ )+ .with_mailbox_owner("mailbox-owner");++ handler_with_dependencies(+ &dependencies,+ "authorization-code",+ &state(IDENTITY_PROVIDER_ID, Some(Uuid::now_v7())),+ )+ .await+ .unwrap();++ let recorded = dependencies.recorded();+ assert_eq!(+ recorded.encryption_identities,+ [("mailbox-owner".into(), "[email protected]".into())]+ );+ assert!(+ recorded+ .grants+ .contains_key(&("mailbox-owner".into(), "[email protected]".into()))+ );+}++#[tokio::test]+async fn encryption_failure_compensates_fresh_link_and_cleans_pending_link() {+ let dependencies =+ FakeDependencies::new([REFRESH_TOKEN], [LinkScenario::Fresh], "[email protected]")+ .with_failure(Failure::Encryption);+ let link_id = Uuid::now_v7();++ let response = callback_error(+ handler_with_dependencies(+ &dependencies,+ "authorization-code",+ &state(IDENTITY_PROVIDER_ID, Some(link_id)),+ )+ .await,+ );++ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);+ let recorded = dependencies.recorded();+ assert_eq!(recorded.compensations, [Compensation::Fresh]);+ assert_eq!(recorded.cleaned_links, [link_id]);+ assert!(recorded.grants.is_empty());+ assert!(recorded.marked_emails.is_empty());+}++#[tokio::test]+async fn database_failure_restores_replaced_link_and_cleans_pending_link() {+ let dependencies = FakeDependencies::new(+ [REFRESH_TOKEN],+ [LinkScenario::Reconnect("stale-refresh-token".into())],+ "[email protected]",+ )+ .with_failure(Failure::Persistence);+ let link_id = Uuid::now_v7();++ let response = callback_error(+ handler_with_dependencies(+ &dependencies,+ "authorization-code",+ &state(IDENTITY_PROVIDER_ID, Some(link_id)),+ )+ .await,+ );++ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);+ let recorded = dependencies.recorded();+ assert_eq!(recorded.compensations, [Compensation::Replaced]);+ assert_eq!(recorded.cleaned_links, [link_id]);+ assert!(recorded.marked_emails.is_empty());+}++#[tokio::test]+async fn callback_failure_before_linking_still_cleans_pending_link() {+ let dependencies =+ FakeDependencies::new([REFRESH_TOKEN], [LinkScenario::Fresh], "not-an-email");+ let link_id = Uuid::now_v7();++ let response = callback_error(+ handler_with_dependencies(+ &dependencies,+ "authorization-code",+ &state(IDENTITY_PROVIDER_ID, Some(link_id)),+ )+ .await,+ );++ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);+ assert_eq!(dependencies.recorded().cleaned_links, [link_id]);+}++#[tokio::test]+async fn grant_failure_error_and_response_never_contain_refresh_token() {+ let dependencies =+ FakeDependencies::new([REFRESH_TOKEN], [LinkScenario::Fresh], "[email protected]")+ .with_failure(Failure::Persistence);++ let result = link_user(+ &dependencies,+ "authorization-code",+ &state(IDENTITY_PROVIDER_ID, Some(Uuid::now_v7())),+ &Uuid::now_v7(),+ )+ .await;+ let error = result.unwrap_err();+ assert!(!error.1.contains(REFRESH_TOKEN));++ let response = callback_error_response(error);+ let body = response.into_body().collect().await.unwrap().to_bytes();+ let body = String::from_utf8(body.to_vec()).unwrap();+ assert!(!body.contains(REFRESH_TOKEN));+ assert!(body.contains(GRANT_STORAGE_ERROR));+}++fn callback_error(result: Result<Response, Response>) -> Response {+ match result {+ Ok(_) => panic!("callback unexpectedly succeeded"),+ Err(response) => response,+ }+}++#[derive(Clone, Copy, Eq, PartialEq)]+enum Failure {+ None,+ Encryption,+ Persistence,+}++enum LinkScenario {+ Fresh,+ Reconnect(String),+}++#[derive(Clone, Debug, Eq, PartialEq)]+enum Compensation {+ Fresh,+ Replaced,+ Unchanged,+}++struct FakeDependencies {+ state: Mutex<FakeState>,+ user_email: String,+ mailbox_owner: Option<String>,+ failure: Failure,+}++struct FakeState {+ refresh_tokens: VecDeque<String>,+ link_scenarios: VecDeque<LinkScenario>,+ events: Vec<&'static str>,+ grants: HashMap<(String, String), Vec<u8>>,+ encryption_count: u8,+ encryption_identities: Vec<(String, String)>,+ fusion_token_lengths: Vec<usize>,+ marked_emails: Vec<String>,+ compensations: Vec<Compensation>,+ cleaned_links: Vec<Uuid>,+}++struct RecordedState {+ events: Vec<&'static str>,+ grants: HashMap<(String, String), Vec<u8>>,+ encryption_identities: Vec<(String, String)>,+ fusion_token_lengths: Vec<usize>,+ marked_emails: Vec<String>,+ compensations: Vec<Compensation>,+ cleaned_links: Vec<Uuid>,+}++impl FakeDependencies {+ fn new(+ refresh_tokens: impl IntoIterator<Item = &'static str>,+ link_scenarios: impl IntoIterator<Item = LinkScenario>,+ user_email: &str,+ ) -> Self {+ Self {+ state: Mutex::new(FakeState {+ refresh_tokens: refresh_tokens.into_iter().map(str::to_owned).collect(),+ link_scenarios: link_scenarios.into_iter().collect(),+ events: Vec::new(),+ grants: HashMap::new(),+ encryption_count: 0,+ encryption_identities: Vec::new(),+ fusion_token_lengths: Vec::new(),+ marked_emails: Vec::new(),+ compensations: Vec::new(),+ cleaned_links: Vec::new(),+ }),+ user_email: user_email.to_owned(),+ mailbox_owner: None,+ failure: Failure::None,+ }+ }- verify_identity_provider(&callback_state, "microsoft-idp-id").unwrap();+ fn with_mailbox_owner(mut self, mailbox_owner: &str) -> Self {+ self.mailbox_owner = Some(mailbox_owner.to_owned());+ self+ }++ fn with_failure(mut self, failure: Failure) -> Self {+ self.failure = failure;+ self+ }++ fn recorded(&self) -> RecordedState {+ let state = self.state.lock().unwrap();+ RecordedState {+ events: state.events.clone(),+ grants: state.grants.clone(),+ encryption_identities: state.encryption_identities.clone(),+ fusion_token_lengths: state.fusion_token_lengths.clone(),+ marked_emails: state.marked_emails.clone(),+ compensations: state.compensations.clone(),+ cleaned_links: state.cleaned_links.clone(),+ }+ }+}++#[async_trait::async_trait]+impl MicrosoftCallbackDependencies for FakeDependencies {+ async fn identity_provider_id(&self) -> MicrosoftCallbackResult<String> {+ Ok(IDENTITY_PROVIDER_ID.into())+ }++ async fn pending_link_owner(&self, _link_id: &Uuid) -> MicrosoftCallbackResult<String> {+ Ok(PENDING_OWNER.into())+ }++ async fn exchange_tokens(+ &self,+ _code: &str,+ ) -> MicrosoftCallbackResult<MicrosoftExchangeTokenResponse> {+ let refresh_token = self+ .state+ .lock()+ .unwrap()+ .refresh_tokens+ .pop_front()+ .expect("a refresh token fixture");+ Ok(MicrosoftExchangeTokenResponse {+ refresh_token,+ id_token: "microsoft-id-token".into(),+ })+ }++ async fn parse_identity(&self, _id_token: &str) -> MicrosoftCallbackResult<MicrosoftUserInfo> {+ Ok(MicrosoftUserInfo {+ sub: "microsoft-user-id".into(),+ email: self.user_email.clone(),+ })+ }++ async fn mailbox_owner(+ &self,+ _email: &str,+ pending_link_owner: &str,+ ) -> MicrosoftCallbackResult<String> {+ Ok(self+ .mailbox_owner+ .clone()+ .unwrap_or_else(|| pending_link_owner.to_owned()))+ }++ async fn link_identity(+ &self,+ _identity_provider_id: &str,+ _link_owner_id: &str,+ _identity: &MicrosoftLinkIdentity,+ refresh_token: &str,+ ) -> MicrosoftCallbackResult<FusionLinkChange> {+ let mut state = self.state.lock().unwrap();+ state.events.push("link");+ state.fusion_token_lengths.push(refresh_token.len());+ Ok(+ match state+ .link_scenarios+ .pop_front()+ .expect("a link scenario fixture")+ {+ LinkScenario::Fresh => FusionLinkChange::Fresh,+ LinkScenario::Reconnect(previous_refresh_token) => FusionLinkChange::Replaced {+ previous_refresh_token: MicrosoftRefreshToken::new(previous_refresh_token),+ },+ },+ )+ }++ async fn encrypt_grant(+ &self,+ link_owner_id: &str,+ email: &str,+ _refresh_token: MicrosoftRefreshToken,+ ) -> Result<EncryptedMicrosoftToken, GrantEncryptionFailed> {+ let mut state = self.state.lock().unwrap();+ state.events.push("encrypt");+ state+ .encryption_identities+ .push((link_owner_id.to_owned(), email.to_owned()));+ if self.failure == Failure::Encryption {+ return Err(GrantEncryptionFailed);+ }+ state.encryption_count += 1;++ Ok(EncryptedMicrosoftToken {+ refresh_token_ciphertext: vec![state.encryption_count],+ encrypted_data_key: vec![10, state.encryption_count],+ nonce: vec![state.encryption_count; 12],+ encryption_version: 1,+ kms_key_id: "fake-kms-key".into(),+ })+ }++ async fn persist_grant(+ &self,+ link_owner_id: &str,+ email: &str,+ encrypted_token: &EncryptedMicrosoftToken,+ ) -> Result<(), GrantPersistenceFailed> {+ let mut state = self.state.lock().unwrap();+ state.events.push("persist");+ if self.failure == Failure::Persistence {+ return Err(GrantPersistenceFailed);+ }+ state.grants.insert(+ (link_owner_id.to_owned(), email.to_owned()),+ encrypted_token.refresh_token_ciphertext.clone(),+ );+ Ok(())+ }++ async fn mark_link_consumable(+ &self,+ _link_id: &Uuid,+ email: &str,+ ) -> MicrosoftCallbackResult<()> {+ let mut state = self.state.lock().unwrap();+ state.events.push("mark");+ state.marked_emails.push(email.to_owned());+ Ok(())+ }++ async fn compensate_link(+ &self,+ _identity_provider_id: &str,+ _link_owner_id: &str,+ _identity: &MicrosoftLinkIdentity,+ change: FusionLinkChange,+ ) {+ let compensation = match change {+ FusionLinkChange::Fresh => Compensation::Fresh,+ FusionLinkChange::Replaced { .. } => Compensation::Replaced,+ FusionLinkChange::Unchanged => Compensation::Unchanged,+ };+ self.state.lock().unwrap().compensations.push(compensation);+ }++ async fn cleanup_pending_link(&self, link_id: &Uuid) {+ self.state.lock().unwrap().cleaned_links.push(*link_id);+ }}diff --git a/services/authentication_service/src/config.rs b/services/authentication_service/src/config.rsindex d5cb22ea34..67d1e6cf5f 100644--- a/services/authentication_service/src/config.rs+++ b/services/authentication_service/src/config.rs@@ -39,6 +39,7 @@ maybe_env_vars! {pub struct MicrosoftClientId;pub struct MicrosoftClientSecret;pub struct MicrosoftTenantId;+ pub struct MicrosoftTokenKmsKeyId;pub struct GaMeasurementId;pub struct GaApiSecret;pub struct MetaPixelId;@@ -88,6 +89,8 @@ pub struct Config {pub microsoft_client_secret: MicrosoftClientSecret,/// Microsoft Entra tenant ID.pub microsoft_tenant_id: MicrosoftTenantId,+ /// KMS key used to encrypt Microsoft refresh-token data keys.+ pub microsoft_token_kms_key_id: MicrosoftTokenKmsKeyId,/// Stripe secret keypub stripe_secret_key: StripeSecretKey,/// The port to listen for HTTP requests on.@@ -139,6 +142,7 @@ pub(crate) struct MicrosoftCredentials {pub(crate) client_id: String,pub(crate) client_secret: String,pub(crate) tenant_id: String,+ pub(crate) token_kms_key_id: String,}impl Config {@@ -153,6 +157,7 @@ impl Config {&self.microsoft_client_id,&self.microsoft_client_secret,&self.microsoft_tenant_id,+ &self.microsoft_token_kms_key_id,)}}@@ -161,18 +166,26 @@ fn resolve_microsoft_credentials(client_id: &MicrosoftClientId,client_secret: &MicrosoftClientSecret,tenant_id: &MicrosoftTenantId,+ token_kms_key_id: &MicrosoftTokenKmsKeyId,) -> 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());+ let token_kms_key_id = nonblank_value(token_kms_key_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(),- })),+ (Some(client_id), Some(client_secret), Some(tenant_id)) => {+ let token_kms_key_id = token_kms_key_id.context(+ "MICROSOFT_TOKEN_KMS_KEY_ID must be set to a nonblank value when Microsoft OAuth is enabled",+ )?;+ Ok(Some(MicrosoftCredentials {+ client_id: client_id.to_owned(),+ client_secret: client_secret.to_owned(),+ tenant_id: tenant_id.to_owned(),+ token_kms_key_id: token_kms_key_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"),diff --git a/services/authentication_service/src/config/test.rs b/services/authentication_service/src/config/test.rsindex 11e4c33112..7b3149dbbc 100644--- a/services/authentication_service/src/config/test.rs+++ b/services/authentication_service/src/config/test.rs@@ -15,6 +15,7 @@ fn complete_microsoft_credentials_are_resolved() {assert_eq!(credentials.client_id, "microsoft-client-id");assert_eq!(credentials.client_secret, "microsoft-client-secret");assert_eq!(credentials.tenant_id, "microsoft-tenant-id");+ assert_eq!(credentials.token_kms_key_id, "microsoft-kms-key");}#[test]@@ -47,6 +48,30 @@ fn every_partial_microsoft_credential_combination_is_rejected() {}}+#[test]+fn kms_key_is_required_when_microsoft_oauth_is_enabled() {+ for kms_key_id in [None, Some(""), Some(" \t ")] {+ let error = resolve_with_kms(+ Some("microsoft-client-id"),+ Some("microsoft-client-secret"),+ Some("microsoft-tenant-id"),+ kms_key_id,+ )+ .err()+ .expect("a KMS key is required with Microsoft credentials");++ assert!(error.to_string().contains("MICROSOFT_TOKEN_KMS_KEY_ID"));+ }+}++#[test]+fn kms_key_alone_does_not_enable_microsoft_oauth() {+ let credentials = resolve_with_kms(None, None, None, Some("microsoft-kms-key"))+ .expect("an unused KMS key should not enable Microsoft OAuth");++ assert!(credentials.is_none());+}+#[test]fn blank_values_are_rejected_when_other_credentials_are_configured() {let partial_credentials = [@@ -64,11 +89,26 @@ fn resolve(client_id: Option<&'static str>,client_secret: Option<&'static str>,tenant_id: Option<&'static str>,+) -> anyhow::Result<Option<MicrosoftCredentials>> {+ resolve_with_kms(+ client_id,+ client_secret,+ tenant_id,+ Some("microsoft-kms-key"),+ )+}++fn resolve_with_kms(+ client_id: Option<&'static str>,+ client_secret: Option<&'static str>,+ tenant_id: Option<&'static str>,+ token_kms_key_id: Option<&'static str>,) -> anyhow::Result<Option<MicrosoftCredentials>> {resolve_microsoft_credentials(µsoft_client_id(client_id),µsoft_client_secret(client_secret),µsoft_tenant_id(tenant_id),+ µsoft_token_kms_key_id(token_kms_key_id),)}@@ -92,3 +132,10 @@ fn microsoft_tenant_id(value: Option<&'static str>) -> MicrosoftTenantId {None => MicrosoftTenantId::new_unset(),}}++fn microsoft_token_kms_key_id(value: Option<&'static str>) -> MicrosoftTokenKmsKeyId {+ match value {+ Some(value) => MicrosoftTokenKmsKeyId::new_testing(value),+ None => MicrosoftTokenKmsKeyId::new_unset(),+ }+}diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rsindex 489b7a3470..de1120a4e9 100644--- a/services/authentication_service/src/main.rs+++ b/services/authentication_service/src/main.rs@@ -67,9 +67,14 @@ use referral::{outbound::{pg_referral_repo::PgReferralRepo, stripe_discount_client::StripeDiscountClient},};-use crate::api::context::{- ApiContext, AuthorizationService, MacroApiTokenContext, MacroApiTokenExpirySeconds,- MacroApiTokenIssuer, MacroApiTokenPrivateSecretKey, StripeWebhookSecretKey,+use crate::{+ api::context::{+ ApiContext, AuthorizationService, MacroApiTokenContext, MacroApiTokenExpirySeconds,+ MacroApiTokenIssuer, MacroApiTokenPrivateSecretKey, StripeWebhookSecretKey,+ },+ microsoft_token_cipher::{+ EnvelopeMicrosoftTokenCipher, KmsDataKeyProvider, MicrosoftTokenCipher,+ },};use std::{sync::Arc, time::Duration};use tokio_util::task::TaskTracker;@@ -77,6 +82,7 @@ use tokio_util::task::TaskTracker;mod api;mod config;mod generate_password;+mod microsoft_token_cipher;mod rate_limit_config;#[tokio::main]@@ -95,6 +101,12 @@ async fn main() -> anyhow::Result<()> {let microsoft_credentials = config.microsoft_credentials().context("invalid Microsoft OAuth configuration")?;+ let microsoft_token_cipher = microsoft_credentials.as_ref().map(|credentials| {+ Arc::new(EnvelopeMicrosoftTokenCipher::new(KmsDataKeyProvider::new(+ aws_sdk_kms::Client::new(&aws_config),+ credentials.token_kms_key_id.clone(),+ ))) as Arc<dyn MicrosoftTokenCipher>+ });let internal_api_key = config.internal_api_key.clone();@@ -412,6 +424,7 @@ async fn main() -> anyhow::Result<()> {db,github_link_service: Arc::new(github_link_service_impl),auth_client: Arc::new(auth_client),+ microsoft_token_cipher,macro_cache_client: Arc::new(macro_cache_client),stripe_client: Arc::new(stripe_client),document_storage_service_client: Arc::new(document_storage_service_client),diff --git a/services/authentication_service/src/microsoft_token_cipher.rs b/services/authentication_service/src/microsoft_token_cipher.rsnew file mode 100644index 0000000000..9d483e5139--- /dev/null+++ b/services/authentication_service/src/microsoft_token_cipher.rs@@ -0,0 +1,364 @@+#![allow(+ dead_code,+ reason = "cipher wiring is consumed by Microsoft grant persistence in the follow-up task"+)]++use std::collections::HashMap;++use aes_gcm::{+ Aes256Gcm, Nonce,+ aead::{Aead, AeadCore, KeyInit, OsRng, Payload},+};+use aws_sdk_kms::{Client, primitives::Blob, types::DataKeySpec};+use zeroize::Zeroizing;++const ENCRYPTION_VERSION: i16 = 1;+const AES_256_KEY_LENGTH: usize = 32;+const AES_GCM_NONCE_LENGTH: usize = 12;+const AES_GCM_TAG_LENGTH: usize = 16;+const ENCRYPTION_PURPOSE: &str = "microsoft-refresh-token";++/// An encrypted Microsoft refresh-token envelope suitable for persistence.+#[derive(Clone, Debug, Eq, PartialEq)]+pub(crate) struct EncryptedMicrosoftToken {+ pub(crate) refresh_token_ciphertext: Vec<u8>,+ pub(crate) encrypted_data_key: Vec<u8>,+ pub(crate) nonce: Vec<u8>,+ pub(crate) encryption_version: i16,+ pub(crate) kms_key_id: String,+}++/// A Microsoft refresh token that clears its allocation when dropped.+pub(crate) struct MicrosoftRefreshToken(Zeroizing<String>);++impl MicrosoftRefreshToken {+ pub(crate) fn new(value: String) -> Self {+ Self(Zeroizing::new(value))+ }++ pub(crate) fn as_str(&self) -> &str {+ self.0.as_str()+ }+}++/// Encrypts and decrypts Microsoft refresh-token envelopes.+#[async_trait::async_trait]+pub(crate) trait MicrosoftTokenCipher: Send + Sync {+ async fn encrypt(+ &self,+ fusionauth_user_id: &str,+ email_address: &str,+ refresh_token: MicrosoftRefreshToken,+ ) -> Result<EncryptedMicrosoftToken, MicrosoftTokenCipherError>;++ async fn decrypt(+ &self,+ fusionauth_user_id: &str,+ email_address: &str,+ envelope: &EncryptedMicrosoftToken,+ ) -> Result<MicrosoftRefreshToken, MicrosoftTokenCipherError>;+}++/// AES-256-GCM envelope cipher backed by an external data-key provider.+pub(crate) struct EnvelopeMicrosoftTokenCipher<P> {+ data_key_provider: P,+}++impl<P> EnvelopeMicrosoftTokenCipher<P> {+ pub(crate) fn new(data_key_provider: P) -> Self {+ Self { data_key_provider }+ }+}++#[async_trait::async_trait]+impl<P> MicrosoftTokenCipher for EnvelopeMicrosoftTokenCipher<P>+where+ P: DataKeyProvider,+{+ async fn encrypt(+ &self,+ fusionauth_user_id: &str,+ email_address: &str,+ refresh_token: MicrosoftRefreshToken,+ ) -> Result<EncryptedMicrosoftToken, MicrosoftTokenCipherError> {+ let identity = EncryptionIdentity::new(fusionauth_user_id, email_address)?;+ let data_key = self+ .data_key_provider+ .generate_data_key(identity.kms_encryption_context())+ .await?;+ validate_plaintext_data_key(&data_key.plaintext)?;++ let cipher = Aes256Gcm::new_from_slice(&data_key.plaintext)+ .map_err(|_| MicrosoftTokenCipherError::InvalidDataKey)?;+ let nonce = Aes256Gcm::generate_nonce(&mut OsRng);+ let ciphertext = cipher+ .encrypt(+ &nonce,+ Payload {+ msg: refresh_token.as_str().as_bytes(),+ aad: &identity.aad(),+ },+ )+ .map_err(|_| MicrosoftTokenCipherError::EncryptionFailed)?;++ Ok(EncryptedMicrosoftToken {+ refresh_token_ciphertext: ciphertext,+ encrypted_data_key: data_key.encrypted,+ nonce: nonce.to_vec(),+ encryption_version: ENCRYPTION_VERSION,+ kms_key_id: data_key.key_id,+ })+ }++ async fn decrypt(+ &self,+ fusionauth_user_id: &str,+ email_address: &str,+ envelope: &EncryptedMicrosoftToken,+ ) -> Result<MicrosoftRefreshToken, MicrosoftTokenCipherError> {+ validate_envelope(envelope)?;+ let identity = EncryptionIdentity::new(fusionauth_user_id, email_address)?;+ let plaintext_data_key = self+ .data_key_provider+ .decrypt_data_key(+ &envelope.kms_key_id,+ &envelope.encrypted_data_key,+ identity.kms_encryption_context(),+ )+ .await?;+ validate_plaintext_data_key(&plaintext_data_key)?;++ let cipher = Aes256Gcm::new_from_slice(&plaintext_data_key)+ .map_err(|_| MicrosoftTokenCipherError::InvalidDataKey)?;+ let nonce_bytes: [u8; AES_GCM_NONCE_LENGTH] = envelope+ .nonce+ .as_slice()+ .try_into()+ .map_err(|_| MicrosoftTokenCipherError::MalformedEnvelope)?;+ let nonce = Nonce::from(nonce_bytes);+ let plaintext = cipher+ .decrypt(+ &nonce,+ Payload {+ msg: &envelope.refresh_token_ciphertext,+ aad: &identity.aad(),+ },+ )+ .map_err(|_| MicrosoftTokenCipherError::DecryptionFailed)?;+ let mut plaintext = Zeroizing::new(plaintext);+ if std::str::from_utf8(&plaintext).is_err() {+ return Err(MicrosoftTokenCipherError::MalformedPlaintext);+ }++ // UTF-8 was validated above. Moving the allocation into String avoids another plaintext+ // copy, and the returned wrapper zeroizes that allocation on drop.+ let plaintext = String::from_utf8(std::mem::take(&mut *plaintext))+ .map_err(|_| MicrosoftTokenCipherError::MalformedPlaintext)?;+ Ok(MicrosoftRefreshToken::new(plaintext))+ }+}++#[derive(Debug, thiserror::Error)]+pub(crate) enum MicrosoftTokenCipherError {+ #[error("Microsoft token data-key operation failed")]+ DataKey(#[from] DataKeyProviderError),+ #[error("Microsoft token identity is malformed")]+ MalformedIdentity,+ #[error("Microsoft token envelope is malformed")]+ MalformedEnvelope,+ #[error("Microsoft token plaintext is malformed")]+ MalformedPlaintext,+ #[error("Microsoft token envelope uses unsupported encryption version {0}")]+ UnsupportedVersion(i16),+ #[error("Microsoft token data key is invalid")]+ InvalidDataKey,+ #[error("Microsoft token encryption failed")]+ EncryptionFailed,+ #[error("Microsoft token decryption failed")]+ DecryptionFailed,+}++#[derive(Debug, thiserror::Error)]+pub(crate) enum DataKeyProviderError {+ #[error("KMS GenerateDataKey failed")]+ GenerateFailed,+ #[error("KMS Decrypt failed")]+ DecryptFailed,+ #[error("KMS returned a malformed data key")]+ MalformedResponse,+}++struct GeneratedDataKey {+ plaintext: Zeroizing<Vec<u8>>,+ encrypted: Vec<u8>,+ key_id: String,+}++#[async_trait::async_trait]+trait DataKeyProvider: Send + Sync {+ async fn generate_data_key(+ &self,+ encryption_context: HashMap<String, String>,+ ) -> Result<GeneratedDataKey, DataKeyProviderError>;++ async fn decrypt_data_key(+ &self,+ key_id: &str,+ encrypted_data_key: &[u8],+ encryption_context: HashMap<String, String>,+ ) -> Result<Zeroizing<Vec<u8>>, DataKeyProviderError>;+}++/// KMS implementation of the envelope data-key provider.+pub(crate) struct KmsDataKeyProvider {+ client: Client,+ key_id: String,+}++impl KmsDataKeyProvider {+ pub(crate) fn new(client: Client, key_id: String) -> Self {+ Self { client, key_id }+ }+}++#[async_trait::async_trait]+impl DataKeyProvider for KmsDataKeyProvider {+ async fn generate_data_key(+ &self,+ encryption_context: HashMap<String, String>,+ ) -> Result<GeneratedDataKey, DataKeyProviderError> {+ let output = self+ .client+ .generate_data_key()+ .key_id(&self.key_id)+ .key_spec(DataKeySpec::Aes256)+ .set_encryption_context(Some(encryption_context))+ .send()+ .await+ .map_err(|_| DataKeyProviderError::GenerateFailed)?;++ let plaintext = output+ .plaintext()+ .map(|value| Zeroizing::new(value.as_ref().to_vec()))+ .ok_or(DataKeyProviderError::MalformedResponse)?;+ let encrypted = output+ .ciphertext_blob()+ .map(|value| value.as_ref().to_vec())+ .ok_or(DataKeyProviderError::MalformedResponse)?;+ let key_id = output+ .key_id()+ .filter(|value| !value.trim().is_empty())+ .map(str::to_owned)+ .ok_or(DataKeyProviderError::MalformedResponse)?;++ Ok(GeneratedDataKey {+ plaintext,+ encrypted,+ key_id,+ })+ }++ async fn decrypt_data_key(+ &self,+ key_id: &str,+ encrypted_data_key: &[u8],+ encryption_context: HashMap<String, String>,+ ) -> Result<Zeroizing<Vec<u8>>, DataKeyProviderError> {+ let output = self+ .client+ .decrypt()+ .key_id(key_id)+ .ciphertext_blob(Blob::new(encrypted_data_key))+ .set_encryption_context(Some(encryption_context))+ .send()+ .await+ .map_err(|_| DataKeyProviderError::DecryptFailed)?;++ output+ .plaintext()+ .map(|value| Zeroizing::new(value.as_ref().to_vec()))+ .ok_or(DataKeyProviderError::MalformedResponse)+ }+}++struct EncryptionIdentity {+ fusionauth_user_id: String,+ email_address: String,+}++impl EncryptionIdentity {+ fn new(+ fusionauth_user_id: &str,+ email_address: &str,+ ) -> Result<Self, MicrosoftTokenCipherError> {+ let fusionauth_user_id = fusionauth_user_id.trim().to_ascii_lowercase();+ let email_address = email_validator::normalize_email(email_address)+ .map(|email| email.into_owned())+ .ok_or(MicrosoftTokenCipherError::MalformedIdentity)?;+ if fusionauth_user_id.is_empty() || fusionauth_user_id.contains('\0') {+ return Err(MicrosoftTokenCipherError::MalformedIdentity);+ }++ Ok(Self {+ fusionauth_user_id,+ email_address,+ })+ }++ fn aad(&self) -> Vec<u8> {+ let mut aad = ENCRYPTION_PURPOSE.as_bytes().to_vec();+ append_length_prefixed(&mut aad, &ENCRYPTION_VERSION.to_be_bytes());+ append_length_prefixed(&mut aad, self.fusionauth_user_id.as_bytes());+ append_length_prefixed(&mut aad, self.email_address.as_bytes());+ aad+ }++ fn kms_encryption_context(&self) -> HashMap<String, String> {+ HashMap::from([+ ("macro:purpose".to_owned(), ENCRYPTION_PURPOSE.to_owned()),+ (+ "macro:encryption-version".to_owned(),+ ENCRYPTION_VERSION.to_string(),+ ),+ (+ "macro:fusionauth-user-id".to_owned(),+ self.fusionauth_user_id.clone(),+ ),+ (+ "macro:microsoft-mailbox".to_owned(),+ self.email_address.clone(),+ ),+ ])+ }+}++fn append_length_prefixed(output: &mut Vec<u8>, value: &[u8]) {+ output.extend_from_slice(&(value.len() as u64).to_be_bytes());+ output.extend_from_slice(value);+}++fn validate_plaintext_data_key(data_key: &[u8]) -> Result<(), MicrosoftTokenCipherError> {+ if data_key.len() != AES_256_KEY_LENGTH {+ return Err(MicrosoftTokenCipherError::InvalidDataKey);+ }+ Ok(())+}++fn validate_envelope(envelope: &EncryptedMicrosoftToken) -> Result<(), MicrosoftTokenCipherError> {+ if envelope.encryption_version != ENCRYPTION_VERSION {+ return Err(MicrosoftTokenCipherError::UnsupportedVersion(+ envelope.encryption_version,+ ));+ }+ if envelope.nonce.len() != AES_GCM_NONCE_LENGTH+ || envelope.refresh_token_ciphertext.len() < AES_GCM_TAG_LENGTH+ || envelope.encrypted_data_key.is_empty()+ || envelope.kms_key_id.trim().is_empty()+ {+ return Err(MicrosoftTokenCipherError::MalformedEnvelope);+ }+ Ok(())+}++#[cfg(test)]+mod test;diff --git a/services/authentication_service/src/microsoft_token_cipher/test.rs b/services/authentication_service/src/microsoft_token_cipher/test.rsnew file mode 100644index 0000000000..3b6bd81bff--- /dev/null+++ b/services/authentication_service/src/microsoft_token_cipher/test.rs@@ -0,0 +1,202 @@+use std::sync::{Arc, Mutex};++use super::*;++const OWNER: &str = "fusionauth-user-id";+const MAILBOX: &str = "[email protected]";+const REFRESH_TOKEN: &str = "private-microsoft-refresh-token";++#[tokio::test]+async fn round_trip_uses_normalized_identity_and_stable_kms_context() {+ let provider = FakeDataKeyProvider::default();+ let calls = provider.calls.clone();+ let cipher = EnvelopeMicrosoftTokenCipher::new(provider);++ let envelope = cipher+ .encrypt(+ " FUSIONAUTH-USER-ID ",+ "[email protected]",+ token(),+ )+ .await+ .expect("token should encrypt");+ let plaintext = cipher+ .decrypt(OWNER, MAILBOX, &envelope)+ .await+ .expect("token should decrypt");++ assert_eq!(plaintext.as_str(), REFRESH_TOKEN);+ assert_ne!(envelope.refresh_token_ciphertext, REFRESH_TOKEN.as_bytes());+ assert_eq!(envelope.encryption_version, ENCRYPTION_VERSION);+ assert_eq!(envelope.kms_key_id, "fake-kms-key");++ let calls = calls.lock().expect("fake call lock should be available");+ assert_eq!(calls.len(), 2);+ assert_eq!(calls[0], calls[1]);+ assert_eq!(+ calls[0],+ HashMap::from([+ ("macro:purpose".to_owned(), ENCRYPTION_PURPOSE.to_owned()),+ (+ "macro:encryption-version".to_owned(),+ ENCRYPTION_VERSION.to_string(),+ ),+ ("macro:fusionauth-user-id".to_owned(), OWNER.to_owned()),+ ("macro:microsoft-mailbox".to_owned(), MAILBOX.to_owned()),+ ])+ );+}++#[tokio::test]+async fn wrong_owner_aad_is_rejected() {+ let cipher = test_cipher();+ let envelope = encrypt(&cipher).await;++ let error = cipher+ .decrypt("another-owner", MAILBOX, &envelope)+ .await+ .err()+ .expect("an envelope must be bound to its owner");++ assert!(matches!(error, MicrosoftTokenCipherError::DecryptionFailed));+}++#[tokio::test]+async fn wrong_mailbox_aad_is_rejected() {+ let cipher = test_cipher();+ let envelope = encrypt(&cipher).await;++ let error = cipher+ .decrypt(OWNER, "[email protected]", &envelope)+ .await+ .err()+ .expect("an envelope must be bound to its mailbox");++ assert!(matches!(error, MicrosoftTokenCipherError::DecryptionFailed));+}++#[tokio::test]+async fn tampered_ciphertext_is_rejected() {+ let cipher = test_cipher();+ let mut envelope = encrypt(&cipher).await;+ envelope.refresh_token_ciphertext[0] ^= 1;++ let error = cipher+ .decrypt(OWNER, MAILBOX, &envelope)+ .await+ .err()+ .expect("tampered ciphertext must not authenticate");++ assert!(matches!(error, MicrosoftTokenCipherError::DecryptionFailed));+}++#[tokio::test]+async fn malformed_envelopes_are_rejected_before_decryption() {+ let cipher = test_cipher();+ let envelope = encrypt(&cipher).await;+ let malformed_envelopes = [+ EncryptedMicrosoftToken {+ nonce: vec![0; AES_GCM_NONCE_LENGTH - 1],+ ..envelope.clone()+ },+ EncryptedMicrosoftToken {+ refresh_token_ciphertext: vec![0; AES_GCM_TAG_LENGTH - 1],+ ..envelope.clone()+ },+ EncryptedMicrosoftToken {+ encrypted_data_key: Vec::new(),+ ..envelope.clone()+ },+ EncryptedMicrosoftToken {+ kms_key_id: " ".to_owned(),+ ..envelope+ },+ ];++ for malformed in malformed_envelopes {+ let error = cipher+ .decrypt(OWNER, MAILBOX, &malformed)+ .await+ .err()+ .expect("malformed envelope must be rejected");+ assert!(matches!(+ error,+ MicrosoftTokenCipherError::MalformedEnvelope+ ));+ }+}++#[tokio::test]+async fn unsupported_encryption_version_is_rejected() {+ let cipher = test_cipher();+ let mut envelope = encrypt(&cipher).await;+ envelope.encryption_version += 1;++ let error = cipher+ .decrypt(OWNER, MAILBOX, &envelope)+ .await+ .err()+ .expect("unknown encryption versions must be rejected");++ assert!(matches!(+ error,+ MicrosoftTokenCipherError::UnsupportedVersion(version)+ if version == ENCRYPTION_VERSION + 1+ ));+}++type TestCipher = EnvelopeMicrosoftTokenCipher<FakeDataKeyProvider>;++fn test_cipher() -> TestCipher {+ EnvelopeMicrosoftTokenCipher::new(FakeDataKeyProvider::default())+}++async fn encrypt(cipher: &TestCipher) -> EncryptedMicrosoftToken {+ cipher+ .encrypt(OWNER, MAILBOX, token())+ .await+ .expect("token should encrypt")+}++fn token() -> MicrosoftRefreshToken {+ MicrosoftRefreshToken::new(REFRESH_TOKEN.to_owned())+}++#[derive(Clone, Default)]+struct FakeDataKeyProvider {+ calls: Arc<Mutex<Vec<HashMap<String, String>>>>,+}++#[async_trait::async_trait]+impl DataKeyProvider for FakeDataKeyProvider {+ async fn generate_data_key(+ &self,+ encryption_context: HashMap<String, String>,+ ) -> Result<GeneratedDataKey, DataKeyProviderError> {+ self.record(encryption_context);+ Ok(GeneratedDataKey {+ plaintext: Zeroizing::new(vec![42; AES_256_KEY_LENGTH]),+ encrypted: vec![7; 48],+ key_id: "fake-kms-key".to_owned(),+ })+ }++ async fn decrypt_data_key(+ &self,+ _key_id: &str,+ _encrypted_data_key: &[u8],+ encryption_context: HashMap<String, String>,+ ) -> Result<Zeroizing<Vec<u8>>, DataKeyProviderError> {+ self.record(encryption_context);+ Ok(Zeroizing::new(vec![42; AES_256_KEY_LENGTH]))+ }+}++impl FakeDataKeyProvider {+ fn record(&self, encryption_context: HashMap<String, String>) {+ self.calls+ .lock()+ .expect("fake call lock should be available")+ .push(encryption_context);+ }+}diff --git a/services/authentication_service/src/openapi.rs b/services/authentication_service/src/openapi.rsindex db25019c23..196a3f0025 100644--- a/services/authentication_service/src/openapi.rs+++ b/services/authentication_service/src/openapi.rs@@ -3,6 +3,7 @@mod api;mod config;mod generate_password;+mod microsoft_token_cipher;mod rate_limit_config;mod service;