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(auth): lock down dev (#6092)
Will Hutchinson90512859dc1d
diff --git a/.sqlx/query-c3f9152d242ae679d87961e306f319ac0035e078be790795eed823a95095c7cc.json b/.sqlx/query-66c5645ff47fc80c380a5e47c61a3776c6b89f53a720380fa12f9e7305c8dbc2.jsonsimilarity index 79%rename from .sqlx/query-c3f9152d242ae679d87961e306f319ac0035e078be790795eed823a95095c7cc.jsonrename to .sqlx/query-66c5645ff47fc80c380a5e47c61a3776c6b89f53a720380fa12f9e7305c8dbc2.jsonindex 736ecd78b6..f4e619ae12 100644--- a/.sqlx/query-c3f9152d242ae679d87961e306f319ac0035e078be790795eed823a95095c7cc.json+++ b/.sqlx/query-66c5645ff47fc80c380a5e47c61a3776c6b89f53a720380fa12f9e7305c8dbc2.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT id, \"organizationId\" as \"organization_id?\"\n FROM \"User\"\n WHERE \"macro_user_id\" = $1\n AND email = $2\n ",+ "query": "\n SELECT id, \"organizationId\" as \"organization_id?\"\n FROM \"User\"\n WHERE \"macro_user_id\" = $1\n AND LOWER(email) = LOWER($2)\n ","describe": {"columns": [{@@ -25,5 +25,5 @@true]},- "hash": "c3f9152d242ae679d87961e306f319ac0035e078be790795eed823a95095c7cc"+ "hash": "66c5645ff47fc80c380a5e47c61a3776c6b89f53a720380fa12f9e7305c8dbc2"}diff --git a/.sqlx/query-0f43991b34ee9e8bb85f7a8c87ed522daaa36ef9bb9e1eed4ccca12de09f44f0.json b/.sqlx/query-a3757dda5b286deef7e3f3a2fca93c2fc17732ac062ef2bbf835fb91fcb3edc1.jsonsimilarity index 57%rename from .sqlx/query-0f43991b34ee9e8bb85f7a8c87ed522daaa36ef9bb9e1eed4ccca12de09f44f0.jsonrename to .sqlx/query-a3757dda5b286deef7e3f3a2fca93c2fc17732ac062ef2bbf835fb91fcb3edc1.jsonindex b9e67bdaa7..e4c50a2c0f 100644--- a/.sqlx/query-0f43991b34ee9e8bb85f7a8c87ed522daaa36ef9bb9e1eed4ccca12de09f44f0.json+++ b/.sqlx/query-a3757dda5b286deef7e3f3a2fca93c2fc17732ac062ef2bbf835fb91fcb3edc1.json@@ -1,15 +1,16 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE email_links\n SET macro_id = $1, updated_at = NOW()\n WHERE id = $2\n ",+ "query": "\n UPDATE email_links\n SET macro_id = $1, email_address = $2, updated_at = NOW()\n WHERE id = $3\n ","describe": {"columns": [],"parameters": {"Left": ["Text",+ "Varchar","Uuid"]},"nullable": []},- "hash": "0f43991b34ee9e8bb85f7a8c87ed522daaa36ef9bb9e1eed4ccca12de09f44f0"+ "hash": "a3757dda5b286deef7e3f3a2fca93c2fc17732ac062ef2bbf835fb91fcb3edc1"}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.tsindex bb366c349f..d8ccf80f0c 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@@ -3420,6 +3420,11 @@ export type createUserResponse400 = {status: 400;};+export type createUserResponse403 = {+ data: ErrorResponse;+ status: 403;+};+export type createUserResponse500 = {data: ErrorResponse;status: 500;@@ -3430,6 +3435,7 @@ export type createUserResponseSuccess = createUserResponse200 & {};export type createUserResponseError = (| createUserResponse400+ | createUserResponse403| createUserResponse500) & {headers: Headers;diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.jsonindex 9757c8c8b6..af9f0f2ec1 100644--- a/apps/web/src/lib/service-clients/service-auth/openapi.json+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json@@ -2906,6 +2906,16 @@}}},+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },"500": {"description": "","content": {diff --git a/crates/fusionauth/src/user.rs b/crates/fusionauth/src/user.rsindex ec9cdc1063..1f6de24b0e 100644--- a/crates/fusionauth/src/user.rs+++ b/crates/fusionauth/src/user.rs@@ -9,6 +9,9 @@ mod get;mod register;mod verify;+#[cfg(test)]+mod test;+impl FusionAuthClient {/// Gets a user's FusionAuth ID by their email address.#[tracing::instrument(skip(self), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]@@ -30,11 +33,7 @@ impl FusionAuthClient {&self.auth_client,&self.fusion_auth_base_url,None,- create::CreateUserRequest {- application_id: Cow::Borrowed(&self.client_id),- skip_verification,- user,- },+ create::CreateUserRequest::new(Cow::Borrowed(&self.client_id), skip_verification, user),client_ip,).await@@ -55,11 +54,7 @@ impl FusionAuthClient {&self.auth_client,&self.fusion_auth_base_url,Some(user_id),- create::CreateUserRequest {- application_id: Cow::Borrowed(&self.client_id),- skip_verification,- user,- },+ create::CreateUserRequest::new(Cow::Borrowed(&self.client_id), skip_verification, user),client_ip,).awaitdiff --git a/crates/fusionauth/src/user/create.rs b/crates/fusionauth/src/user/create.rsindex 722711190f..1c8e474e98 100644--- a/crates/fusionauth/src/user/create.rs+++ b/crates/fusionauth/src/user/create.rs@@ -31,6 +31,20 @@ pub(crate) struct CreateUserRequest<'a> {pub user: User<'a>,}+impl<'a> CreateUserRequest<'a> {+ pub(crate) fn new(+ application_id: Cow<'a, str>,+ skip_verification: bool,+ user: User<'a>,+ ) -> Self {+ Self {+ application_id,+ skip_verification,+ user,+ }+ }+}+#[derive(serde::Serialize, serde::Deserialize, Debug)]#[serde(rename_all = "camelCase")]pub(crate) struct UserResponse<'a> {@@ -38,8 +52,6 @@ pub(crate) struct UserResponse<'a> {pub id: Cow<'a, str>,/// The email address of the userpub email: Cow<'a, str>,- /// The additional data associated with the user- pub data: Option<serde_json::Value>,}#[derive(serde::Serialize, serde::Deserialize, Debug)]diff --git a/crates/fusionauth/src/user/test.rs b/crates/fusionauth/src/user/test.rsnew file mode 100644index 0000000000..3acf6a07a5--- /dev/null+++ b/crates/fusionauth/src/user/test.rs@@ -0,0 +1,86 @@+use std::{borrow::Cow, net::IpAddr};++use serde_json::json;+use wiremock::matchers::{body_json, method, path};+use wiremock::{Mock, MockServer, ResponseTemplate};++use super::*;++fn client(base_url: String) -> FusionAuthClient {+ FusionAuthClient::new(+ "api-key".into(),+ "application-id".into(),+ "client-secret".into(),+ base_url,+ "http://localhost:28011/oauth/redirect".into(),+ "google-client-id".into(),+ "google-client-secret".into(),+ )+}++fn user() -> create::User<'static> {+ create::User {+ email: Cow::Borrowed("[email protected]"),+ password: Cow::Borrowed("unused-password"),+ username: None,+ }+}++fn success_response() -> ResponseTemplate {+ ResponseTemplate::new(200).set_body_json(json!({+ "user": {+ "id": "created-user-id",+ "email": "[email protected]"+ }+ }))+}++fn expected_body() -> serde_json::Value {+ json!({+ "applicationId": "application-id",+ "skipVerification": true,+ "user": {+ "email": "[email protected]",+ "password": "unused-password",+ "username": null+ }+ })+}++#[tokio::test]+async fn create_user_posts_user() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/api/user"))+ .and(body_json(expected_body()))+ .respond_with(success_response())+ .expect(1)+ .mount(&server)+ .await;++ let user_id = client(server.uri())+ .create_user(user(), true, IpAddr::from([127, 0, 0, 1]))+ .await+ .unwrap();++ assert_eq!(user_id, "created-user-id");+}++#[tokio::test]+async fn create_user_with_id_posts_user_to_id_endpoint() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/api/user/caller-user-id"))+ .and(body_json(expected_body()))+ .respond_with(success_response())+ .expect(1)+ .mount(&server)+ .await;++ let user_id = client(server.uri())+ .create_user_with_id("caller-user-id", user(), true, IpAddr::from([127, 0, 0, 1]))+ .await+ .unwrap();++ assert_eq!(user_id, "created-user-id");+}diff --git a/crates/macro_db_client/src/shared_inbox.rs b/crates/macro_db_client/src/shared_inbox.rsindex 615851401a..b1385d6cda 100644--- a/crates/macro_db_client/src/shared_inbox.rs+++ b/crates/macro_db_client/src/shared_inbox.rs@@ -37,6 +37,7 @@ pub async fn promote_link_to_shared(mailbox_email: &str,organization_id: Option<i32>,) -> anyhow::Result<PromotedSharedInbox> {+ let mailbox_email = mailbox_email.to_lowercase();let mailbox_macro_id = format!("macro|{mailbox_email}");let fusionauth_user_id = macro_uuid::generate_uuid_v7();let stripe_customer_id = format!("cus_shared_{fusionauth_user_id}");@@ -48,7 +49,7 @@ pub async fn promote_link_to_shared("#,&fusionauth_user_id,&mailbox_macro_id,- mailbox_email,+ &mailbox_email,stripe_customer_id,).execute(&mut *conn)@@ -60,7 +61,7 @@ pub async fn promote_link_to_shared(VALUES ($1, $2, true)"#,&fusionauth_user_id,- mailbox_email,+ &mailbox_email,).execute(&mut *conn).await?;@@ -71,7 +72,7 @@ pub async fn promote_link_to_shared(VALUES ($1, $2, $3, $4)"#,&mailbox_macro_id,- mailbox_email,+ &mailbox_email,&fusionauth_user_id,organization_id,)@@ -94,10 +95,11 @@ pub async fn promote_link_to_shared(let rehomed = sqlx::query!(r#"UPDATE email_links- SET macro_id = $1, updated_at = NOW()- WHERE id = $2+ SET macro_id = $1, email_address = $2, updated_at = NOW()+ WHERE id = $3"#,&mailbox_macro_id,+ &mailbox_email,existing_link_id,).execute(&mut *conn)diff --git a/crates/macro_db_client/src/shared_inbox/test.rs b/crates/macro_db_client/src/shared_inbox/test.rsindex a00291b9c4..be50e171b9 100644--- a/crates/macro_db_client/src/shared_inbox/test.rs+++ b/crates/macro_db_client/src/shared_inbox/test.rs@@ -105,6 +105,48 @@ async fn promote_dedups_to_single_link_with_two_edges(pool: Pool<Postgres>) -> aOk(())}+#[sqlx::test]+async fn promote_normalizes_mailbox_email_for_fusionauth_webhook(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ insert_user(&pool, OWNER, "[email protected]").await;+ insert_user(&pool, CONNECTOR, "[email protected]").await;+ let mixed_case_mailbox = "[email protected]";+ let link_id = insert_data_source_link(&pool, OWNER, mixed_case_mailbox).await;++ let mut conn = pool.acquire().await?;+ let result = promote_link_to_shared(+ &mut conn,+ link_id,+ OWNER,+ CONNECTOR,+ mixed_case_mailbox,+ None,+ )+ .await?;++ assert_eq!(result.mailbox_macro_id, "macro|[email protected]");++ let mailbox_user = sqlx::query!(+ r#"SELECT email, macro_user_id FROM "User" WHERE id = $1"#,+ result.mailbox_macro_id+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(mailbox_user.email, "[email protected]");+ assert_eq!(mailbox_user.macro_user_id, result.mailbox_fusion_id);++ let link = sqlx::query!(+ r#"SELECT email_address FROM email_links WHERE id = $1"#,+ link_id+ )+ .fetch_one(&pool)+ .await?;+ assert_eq!(link.email_address, "[email protected]");++ Ok(())+}+#[sqlx::test]async fn promote_is_atomic_on_rollback(pool: Pool<Postgres>) -> anyhow::Result<()> {insert_user(&pool, OWNER, "[email protected]").await;diff --git a/crates/macro_db_client/src/user/get.rs b/crates/macro_db_client/src/user/get.rsindex 55510636aa..fc4acc679c 100644--- a/crates/macro_db_client/src/user/get.rs+++ b/crates/macro_db_client/src/user/get.rs@@ -128,7 +128,7 @@ pub async fn get_user_profile_by_fusionauth_user_id_and_email(SELECT id, "organizationId" as "organization_id?"FROM "User"WHERE "macro_user_id" = $1- AND email = $2+ AND LOWER(email) = LOWER($2)"#,&fusionauth_user_id,diff --git a/crates/macro_db_client/src/user/get/test.rs b/crates/macro_db_client/src/user/get/test.rsindex 9850b5d88e..6d29649cfe 100644--- a/crates/macro_db_client/src/user/get/test.rs+++ b/crates/macro_db_client/src/user/get/test.rs@@ -1,6 +1,8 @@use sqlx::{Pool, Postgres};-use super::get_user_macro_user_id_and_id_by_email;+use super::{+ get_user_macro_user_id_and_id_by_email, get_user_profile_by_fusionauth_user_id_and_email,+};#[sqlx::test(fixtures(path = "../../../fixtures", scripts("users")))]async fn test_get_user_macro_user_id_and_id_by_email_success(pool: Pool<Postgres>) {@@ -21,3 +23,39 @@ async fn test_get_user_macro_user_id_and_id_by_email_not_found(pool: Pool<Postgrassert!(matches!(result, Err(sqlx::Error::RowNotFound)));}++#[sqlx::test]+async fn get_user_profile_by_fusionauth_user_id_and_email_matches_email_case_insensitively(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let fusionauth_user_id = uuid::Uuid::now_v7();+ sqlx::query!(+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, 'macro|[email protected]', '[email protected]', 'cus_test')"#,+ fusionauth_user_id,+ )+ .execute(&pool)+ .await?;++ sqlx::query!(+ r#"INSERT INTO "User" (id, email, macro_user_id)+ VALUES ('macro|[email protected]', '[email protected]', $1)"#,+ fusionauth_user_id,+ )+ .execute(&pool)+ .await?;++ let profile = get_user_profile_by_fusionauth_user_id_and_email(+ &pool,+ &fusionauth_user_id.to_string(),+ "[email protected]",+ )+ .await?;++ assert_eq!(+ profile,+ Some(("macro|[email protected]".to_string(), None))+ );++ Ok(())+}diff --git a/crates/model/src/authentication/webhooks.rs b/crates/model/src/authentication/webhooks.rsindex 90ac0cd8ca..ac4ed032d7 100644--- a/crates/model/src/authentication/webhooks.rs+++ b/crates/model/src/authentication/webhooks.rs@@ -1,4 +1,8 @@pub mod populate_jwt;++#[cfg(test)]+mod test;+pub mod update_name;pub mod update_profile_picture;@@ -44,4 +48,7 @@ pub struct User {pub last_name: Option<String>,/// Display name, set by the identity provider reconcile lambda on SSO signuppub full_name: Option<String>,+ /// Caller-provided FusionAuth user metadata.+ #[serde(default)]+ pub data: Option<serde_json::Value>,}diff --git a/crates/model/src/authentication/webhooks/test.rs b/crates/model/src/authentication/webhooks/test.rsnew file mode 100644index 0000000000..eeff7ab695--- /dev/null+++ b/crates/model/src/authentication/webhooks/test.rs@@ -0,0 +1,53 @@+use serde_json::json;++use super::FusionAuthUserWebhook;++#[test]+fn user_create_payload_without_user_data_defaults_to_none() {+ let webhook = deserialize_user_create_payload(None);++ assert_eq!(webhook.event.user.data, None);+}++#[test]+fn user_create_payload_retains_user_data() {+ let data = json!({+ "custom": {+ "source": "test"+ },+ "arbitrary": ["metadata", 42]+ });++ let webhook = deserialize_user_create_payload(Some(data.clone()));++ assert_eq!(webhook.event.user.data, Some(data));+}++fn deserialize_user_create_payload(data: Option<serde_json::Value>) -> FusionAuthUserWebhook {+ let mut payload = json!({+ "event": {+ "createInstant": 1,+ "id": "event-id",+ "linkedObjectId": "linked-object-id",+ "info": {+ "ipAddress": "127.0.0.1"+ },+ "user": {+ "id": "0f1e2d3c-4b5a-6978-8796-a5b4c3d2e1f0",+ "email": "[email protected]",+ "username": null,+ "verified": true,+ "firstName": null,+ "lastName": null,+ "fullName": null+ },+ "type": "user.create"+ }+ });++ if let Some(data) = data {+ payload["event"]["user"]["data"] = data;+ }++ serde_json::from_value(payload).expect("valid FusionAuth user.create payload")+}diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.tsindex 58fd1c7c60..0467e2d34d 100644--- a/packages/sdk/generated/auth/types.gen.ts+++ b/packages/sdk/generated/auth/types.gen.ts@@ -2204,6 +2204,7 @@ export type CreateUserData = {export type CreateUserErrors = {400: ErrorResponse;+ 403: ErrorResponse;500: ErrorResponse;};diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.jsonindex 9757c8c8b6..af9f0f2ec1 100644--- a/packages/sdk/specs/auth.json+++ b/packages/sdk/specs/auth.json@@ -2906,6 +2906,16 @@}}},+ "403": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },"500": {"description": "","content": {diff --git a/services/authentication_service/README.md b/services/authentication_service/README.mdnew file mode 100644index 0000000000..525f6eb6dd--- /dev/null+++ b/services/authentication_service/README.md@@ -0,0 +1,118 @@+# Authentication Service Configuration++## Development signup allowlist++The authentication service gates new signups with a startup-built `SignupPolicy`.+The policy is enforced authoritatively by the existing FusionAuth `user.create`+webhook at `/webhooks/user`. FusionAuth is configured for `user.create` with+`AbsoluteMajority`, so a non-2xx response from this service rejects the+transaction and aborts FusionAuth user creation.++Public prechecks in user creation and passwordless signup exist only for a+faster user-facing `403` response. They are advisory. The transactional webhook+is the enforcement boundary for all signup paths, including SSO and future+FusionAuth-created users.++### Setting++- Doppler project: `authentication-service`+- Develop Doppler config: `dev`+- Production Doppler config: `prd`+- Setting name: `DEVELOPMENT_SIGNUP_ALLOWLIST_JSON`+- Format: JSON array of exact email-address strings++Synthetic example only:++```json+["[email protected]", "[email protected]"]+```++Do not commit or paste operational allowlist values into source, docs, logs, PRs,+or generated files.++### Environment behavior++| Runtime environment | Doppler slug | Effective signup policy |+| --- | --- | --- |+| `Environment::Develop` | `dev` | Requires `DEVELOPMENT_SIGNUP_ALLOWLIST_JSON` to be present, nonblank, valid, and non-empty. |+| `Environment::Production` | `prd` | Allows all public signups. The allowlist setting is ignored even if present or malformed. |+| `Environment::Local` | `lcl` | Allows all public signups. The allowlist setting is ignored even if present or malformed. |++Develop startup fails if the setting is missing, blank, malformed JSON, not a+JSON array, empty, contains a non-string entry, contains a blank entry, or+contains an invalid email address. Production and Local do not require the+setting and do not parse it.++### Matching and validation semantics++The allowlist is parsed once at service startup and stored in memory. Request+handlers perform hash lookups only.++Normalization rules:++- Trim leading and trailing whitespace from each configured entry.+- Validate each entry with the service email parser.+- Lowercase the address after validation.+- Deduplicate normalized addresses.++Matching rules:++- Matching is exact after normalization.+- Case differences do not matter.+- `+` aliases remain distinct addresses.+- Domains, wildcards, suffixes, patterns, and regular expressions are not+ supported.+- Denial responses and policy errors must not disclose configured addresses.++## Shared mailboxes++Internal shared-mailbox grant relocation creates ordinary FusionAuth users for+mailbox grants. In Develop, those mailbox addresses must be listed explicitly in+`DEVELOPMENT_SIGNUP_ALLOWLIST_JSON` before relocation creates the FusionAuth+user. There is no metadata-based signup-policy bypass for shared mailboxes.++## Rollout++1. Configure `DEVELOPMENT_SIGNUP_ALLOWLIST_JSON` in Doppler project+ `authentication-service`, config `dev`, using only the approved operational+ addresses for the deployment. Keep values out of source control and chat.+2. Validate the Doppler configs and semantic policy resolution:++ ```bash+ nix develop --command cargo check -p authentication_service --bin authentication_service_doppler_config+ ```++3. Deploy the authentication service build that contains the signup policy.+4. Restart or replace all Develop authentication service tasks. The setting is+ loaded once at startup; changing Doppler after deployment does not update+ running tasks.+5. Confirm Develop signups for allowed synthetic/test accounts succeed and+ unlisted synthetic/test accounts receive a generic `403` without onboarding+ side effects.++Production and Local remain allow-all and can deploy independently of the+Develop allowlist value.++## Rollback++- If Develop startup fails, fix the Doppler JSON value and restart the service+ tasks. The service will not accept traffic until the Develop value is valid.+- If a legitimate Develop signup is denied, add the address to the Doppler JSON+ array and restart or replace the authentication service tasks.+- If the release must be reverted, roll Develop back to the previous+ authentication service deployment or task definition. Keep a valid Develop+ allowlist configured so the forward version can be redeployed safely.++## Focused verification++Useful checks after editing signup configuration behavior:++```bash+nix develop --command env -u DATABASE_URL cargo test -p authentication_service --bin authentication_service config::test+nix develop --command cargo check -p authentication_service --bin authentication_service_doppler_config+cargo fmt --check+```++Review this README and related logs before rollout to confirm they contain only+placeholders or reserved synthetic examples, never operational email addresses+or copied Doppler values.diff --git a/services/authentication_service/src/api.rs b/services/authentication_service/src/api.rsindex 684dae6eb3..84ef94898e 100644--- a/services/authentication_service/src/api.rs+++ b/services/authentication_service/src/api.rs@@ -35,6 +35,7 @@ mod oauth2;mod permissions;mod permissions_extractor;mod session;+pub(crate) mod signup_policy;mod user;mod webhooks;diff --git a/services/authentication_service/src/api/context.rs b/services/authentication_service/src/api/context.rsindex 367e4c9926..603a2c5fb3 100644--- a/services/authentication_service/src/api/context.rs+++ b/services/authentication_service/src/api/context.rs@@ -51,6 +51,7 @@ use sqlx::PgPool;use tokio_util::task::TaskTracker;use crate::microsoft_token_cipher::MicrosoftTokenCipher;+use authentication_service::service::signup_policy::SignupPolicy;use cursor_api_key::cipher::CursorApiKeyCipher;pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsQueue>;@@ -126,6 +127,7 @@ pub(crate) struct ApiContext {pub notification_ingress_service: Arc<NotificationIngressType>,pub sqs_client: Arc<sqs_client::SQS>,pub environment: Environment,+ pub signup_policy: Arc<SignupPolicy>,pub jwt_args: JwtValidationArgs,pub authorization_state: MacroAuthorizationState<AuthorizationService>,pub token_context: MacroApiTokenContext,diff --git a/services/authentication_service/src/api/internal/relocate_inbox_grant.rs b/services/authentication_service/src/api/internal/relocate_inbox_grant.rsindex e161b8d87b..4feb75a5fd 100644--- a/services/authentication_service/src/api/internal/relocate_inbox_grant.rs+++ b/services/authentication_service/src/api/internal/relocate_inbox_grant.rs@@ -76,10 +76,11 @@ pub async fn handler(server_error("unable to get identity provider id")})?;- // Get-or-create the dedicated mailbox user. The signup webhook no-ops here because the- // verified MacroDB User for this mailbox already exists (created during promotion), so no- // Stripe customer is provisioned. Freshly created users start active; they are- // deactivated once the grant is in place.+ // Get-or-create the dedicated mailbox user. In Develop, the mailbox email must be on+ // the signup allowlist; the create-user webhook then no-ops because the verified+ // MacroDB User for this mailbox already exists (created during promotion), so no Stripe+ // customer is provisioned. Freshly created users start active; they are deactivated once+ // the grant is in place.let shared_user_id = match auth.get_user_id_by_email(&email).await {Ok(id) => id,Err(fusionauth::error::FusionAuthClientError::UserDoesNotExist) => {@@ -88,7 +89,7 @@ pub async fn handler(password: Cow::Owned(uuid::Uuid::new_v4().to_string()),username: Some(Cow::Borrowed(&email)),};- let created = match &desired_user_id {+ let created = match desired_user_id.as_deref() {Some(id) => {auth.create_user_with_id(id, user, true, IpAddr::V4(Ipv4Addr::LOCALHOST)).awaitdiff --git a/services/authentication_service/src/api/login/passwordless.rs b/services/authentication_service/src/api/login/passwordless.rsindex 47db48c92f..9a62d4aec0 100644--- a/services/authentication_service/src/api/login/passwordless.rs+++ b/services/authentication_service/src/api/login/passwordless.rs@@ -8,7 +8,10 @@ use macro_middleware::tracking::ClientIp;use std::borrow::Cow;-use crate::{api::context::ApiContext, generate_password::generate_random_password};+use crate::{+ api::{context::ApiContext, signup_policy::signup_forbidden_response},+ generate_password::generate_random_password,+};use fusionauth::error::FusionAuthClientError;use macro_user_id::user_id::MacroUserId;use model::{@@ -99,18 +102,29 @@ pub async fn handler(match e {FusionAuthClientError::UserDoesNotExist => {tracing::trace!(email=%lowercase_email, "user does not exist, we need to create user");+ ctx.signup_policy+ .authorize_public_email(&lowercase_email)+ .map_err(|denial| {+ tracing::warn!(error=?denial, "signup policy denied passwordless user creation");+ signup_forbidden_response()+ })?;+let fusionauth_user_id = ctx- .auth_client- .create_user(fusionauth::user::create::User {- email: (&lowercase_email).into(),- password: generate_random_password().into(),- username: None,- }, true, ip_context.origin_ip())- .await- .map_err(|e| {- tracing::error!(error=?e, email=%lowercase_email, "unable to create user");- (StatusCode::INTERNAL_SERVER_ERROR, "unable to create user").into_response()- })?;+ .auth_client+ .create_user(+ fusionauth::user::create::User {+ email: (&lowercase_email).into(),+ password: generate_random_password().into(),+ username: None,+ },+ true,+ ip_context.origin_ip(),+ )+ .await+ .map_err(|e| {+ tracing::error!(error=?e, email=%lowercase_email, "unable to create user");+ (StatusCode::INTERNAL_SERVER_ERROR, "unable to create user").into_response()+ })?;tracing::trace!(fusionauth_user_id, "created new fusionauth user");diff --git a/services/authentication_service/src/api/signup_policy.rs b/services/authentication_service/src/api/signup_policy.rsnew file mode 100644index 0000000000..52d7caa6a1--- /dev/null+++ b/services/authentication_service/src/api/signup_policy.rs@@ -0,0 +1,22 @@+#[cfg(test)]+mod test;++use axum::{+ Json,+ http::StatusCode,+ response::{IntoResponse, Response},+};+use model::response::ErrorResponse;++const SIGNUP_FORBIDDEN_MESSAGE: &str = "signup is not allowed";++/// Map an expected signup-policy rejection to a generic API response.+pub(crate) fn signup_forbidden_response() -> Response {+ (+ StatusCode::FORBIDDEN,+ Json(ErrorResponse {+ message: SIGNUP_FORBIDDEN_MESSAGE.into(),+ }),+ )+ .into_response()+}diff --git a/services/authentication_service/src/api/signup_policy/test.rs b/services/authentication_service/src/api/signup_policy/test.rsnew file mode 100644index 0000000000..24ab342f35--- /dev/null+++ b/services/authentication_service/src/api/signup_policy/test.rs@@ -0,0 +1,29 @@+use axum::body::Body;+use axum::http::StatusCode;+use http_body_util::BodyExt;++use super::*;++const ALLOWED_EMAIL: &str = "[email protected]";+const DENIED_EMAIL: &str = "[email protected]";++#[tokio::test]+async fn forbidden_response_is_generic_and_redacted() {+ let response = signup_forbidden_response();+ assert_eq!(response.status(), StatusCode::FORBIDDEN);++ let body = response_body(response.into_body()).await;+ assert!(body.contains("signup is not allowed"));+ assert_redacted(&body);+}++async fn response_body(body: Body) -> String {+ let bytes = body.collect().await.unwrap().to_bytes();+ String::from_utf8(bytes.to_vec()).unwrap()+}++fn assert_redacted(diagnostic: &str) {+ assert!(!diagnostic.contains(ALLOWED_EMAIL));+ assert!(!diagnostic.contains(DENIED_EMAIL));+ assert!(!diagnostic.contains("example.test"));+}diff --git a/services/authentication_service/src/api/user/create_user.rs b/services/authentication_service/src/api/user/create_user.rsindex 2e733eb4f6..b88eb31f73 100644--- a/services/authentication_service/src/api/user/create_user.rs+++ b/services/authentication_service/src/api/user/create_user.rs@@ -6,7 +6,7 @@ use axum::{};use macro_middleware::tracking::ClientIp;-use crate::api::context::ApiContext;+use crate::api::{context::ApiContext, signup_policy::signup_forbidden_response};use model::response::{EmptyResponse, ErrorResponse};@@ -32,6 +32,7 @@ pub struct CreateUserRequest {responses((status = 200, body=EmptyResponse),(status = 400, body=ErrorResponse),+ (status = 403, body=ErrorResponse),(status = 500, body=ErrorResponse),),)]@@ -44,6 +45,13 @@ pub async fn handler(tracing::info!("create_user");let email = req.email.to_lowercase();+ ctx.signup_policy+ .authorize_public_email(&email)+ .map_err(|denial| {+ tracing::warn!(error=?denial, "signup policy denied public user creation");+ signup_forbidden_response()+ })?;+let username_exists =macro_db_client::macro_user::check_username_exists(&ctx.db, &req.username).awaitdiff --git a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rsindex 83d61078c3..763759b7c7 100644--- a/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs+++ b/services/authentication_service/src/api/webhooks/user/create_user_webhook.rs@@ -2,7 +2,10 @@mod test;use analytics_client::{MetaActionSource, MetaUserData};+use std::{collections::HashSet, future::Future};+use anyhow::Context;+use authentication_service::service::signup_policy::SignupPolicy;use axum::{extract::{self, State},http::StatusCode,@@ -12,7 +15,10 @@ use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};use rand::Rng;use crate::{- api::context::{ApiContext, AuthorizationService},+ api::{+ context::{ApiContext, AuthorizationService},+ signup_policy::signup_forbidden_response,+ },rate_limit_config::RATE_LIMIT_CONFIG,};use authentication_service::service::user::create_user::create_user;@@ -29,7 +35,6 @@ use macro_user_id::{};use model::authentication::webhooks::{FusionAuthUserWebhook, User as FusionAuthWebhookUser};use model_entity::EntityType;-use std::collections::HashSet;use teams::domain::team_repo::TeamService;/// Macro support team members added to every new user's support channel.@@ -88,10 +93,11 @@ pub async fn handler(})?;}"user.create" => {- create_user_webhook(&ctx, req).await.map_err(|e| {- tracing::error!(error=?e, "unable to user.create");- (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()- })?;+ dispatch_user_create_webhook(&ctx.signup_policy, req, |req| {+ create_user_webhook(&ctx, req)+ })+ .await+ .map_err(user_create_webhook_error_response)?;}"user.email.verified" => {verify_user_email_webhook(&ctx, req).await.map_err(|e| {@@ -108,6 +114,39 @@ pub async fn handler(Ok(StatusCode::OK.into_response())}+enum UserCreateWebhookError {+ Forbidden,+ Onboarding(anyhow::Error),+}++fn user_create_webhook_error_response(error: UserCreateWebhookError) -> Response {+ match error {+ UserCreateWebhookError::Forbidden => signup_forbidden_response(),+ UserCreateWebhookError::Onboarding(e) => {+ tracing::error!(error=?e, "unable to user.create");+ (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()+ }+ }+}++async fn dispatch_user_create_webhook<F, Fut>(+ signup_policy: &SignupPolicy,+ req: FusionAuthUserWebhook,+ onboard_user: F,+) -> Result<(), UserCreateWebhookError>+where+ F: FnOnce(FusionAuthUserWebhook) -> Fut,+ Fut: Future<Output = anyhow::Result<()>>,+{+ signup_policy+ .authorize_public_email(&req.event.user.email)+ .map_err(|_| UserCreateWebhookError::Forbidden)?;++ onboard_user(req)+ .await+ .map_err(UserCreateWebhookError::Onboarding)+}+#[tracing::instrument(skip(ctx, req), err)]async fn verify_user_email_webhook(ctx: &ApiContext,@@ -174,6 +213,18 @@ async fn create_user_webhook(ctx: &ApiContext, req: FusionAuthUserWebhook) -> ananyhow::bail!("rate limit exceeded")}+ if let Some((user_id, organization_id)) =+ macro_db_client::user::get::get_user_profile_by_fusionauth_user_id_and_email(+ &ctx.db,+ &fusionauth_user_id,+ &email,+ )+ .await?+ {+ tracing::info!(user_id=?user_id, organization_id=?organization_id, "user profile already exists for FusionAuth user");+ return Ok(());+ }+// check if user existsif let Ok((user_id, _stripe_customer_id)) =macro_db_client::user::get::get_user_id_and_stripe_customer_id_by_email(&ctx.db, &email)diff --git a/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rs b/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rsindex 6c3413f738..f5bde3eafc 100644--- a/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rs+++ b/services/authentication_service/src/api/webhooks/user/create_user_webhook/test.rs@@ -1,7 +1,20 @@+use std::sync::{+ Arc,+ atomic::{AtomicUsize, Ordering},+};++use authentication_service::service::signup_policy::SignupPolicy;+use axum::http::StatusCode;use macro_user_id::email::Email;-use model::authentication::webhooks::User as FusionAuthWebhookUser;+use model::authentication::webhooks::{+ Event, EventInfo, FusionAuthUserWebhook, User as FusionAuthWebhookUser,+};+use serde_json::Value;-use super::{identity_provider_name, support_channel_name};+use super::{+ UserCreateWebhookError, dispatch_user_create_webhook, identity_provider_name,+ support_channel_name, user_create_webhook_error_response,+};#[test]fn support_channel_name_uses_email_local_part() {@@ -26,6 +39,118 @@ fn webhook_user(first_name: first_name.map(str::to_string),last_name: last_name.map(str::to_string),full_name: full_name.map(str::to_string),+ data: None,+ }+}++fn user_create_webhook(email: &str, data: Option<Value>) -> FusionAuthUserWebhook {+ FusionAuthUserWebhook {+ event: Event {+ create_instant: 0,+ id: "event-id".to_string(),+ linked_object_id: "linked-object-id".to_string(),+ info: EventInfo {+ ip_address: "198.51.100.42".to_string(),+ },+ user: FusionAuthWebhookUser {+ email: email.to_string(),+ data,+ ..webhook_user(None, None, None)+ },+ event_type: "user.create".to_string(),+ },+ }+}++async fn dispatch_with_invocation_count(+ policy: &SignupPolicy,+ req: FusionAuthUserWebhook,+) -> (bool, usize) {+ let invocation_count = Arc::new(AtomicUsize::new(0));+ let spy_count = invocation_count.clone();++ let result = dispatch_user_create_webhook(policy, req, move |_| {+ spy_count.fetch_add(1, Ordering::SeqCst);+ async { Ok(()) }+ })+ .await;++ (result.is_ok(), invocation_count.load(Ordering::SeqCst))+}++#[tokio::test]+async fn allowed_develop_public_signup_invokes_onboarding() {+ let policy = SignupPolicy::from_allowlist_json(r#"["[email protected]"]"#).unwrap();+ let req = user_create_webhook("[email protected]", None);++ let (is_ok, invocation_count) = dispatch_with_invocation_count(&policy, req).await;++ assert!(is_ok);+ assert_eq!(invocation_count, 1);+}++#[tokio::test]+async fn denied_develop_public_signup_does_not_invoke_onboarding() {+ let policy = SignupPolicy::from_allowlist_json(r#"["[email protected]"]"#).unwrap();+ let req = user_create_webhook("[email protected]", None);++ let (is_ok, invocation_count) = dispatch_with_invocation_count(&policy, req).await;++ assert!(!is_ok);+ assert_eq!(invocation_count, 0);+}++#[test]+fn denied_signup_maps_to_generic_forbidden_status() {+ let response = user_create_webhook_error_response(UserCreateWebhookError::Forbidden);++ assert_eq!(response.status(), StatusCode::FORBIDDEN);+}++#[tokio::test]+async fn allow_all_environment_policy_invokes_onboarding() {+ let policy = SignupPolicy::allow_all();+ let req = user_create_webhook("[email protected]", None);++ let (is_ok, invocation_count) = dispatch_with_invocation_count(&policy, req).await;++ assert!(is_ok);+ assert_eq!(invocation_count, 1);+}++#[tokio::test]+async fn allowlisted_shared_mailbox_email_invokes_onboarding() {+ let policy = SignupPolicy::from_allowlist_json(r#"["[email protected]"]"#).unwrap();+ let req = user_create_webhook("[email protected]", None);++ let (is_ok, invocation_count) = dispatch_with_invocation_count(&policy, req).await;++ assert!(is_ok);+ assert_eq!(invocation_count, 1);+}++#[tokio::test]+async fn non_allowlisted_shared_mailbox_email_is_denied() {+ let policy = SignupPolicy::from_allowlist_json(r#"["[email protected]"]"#).unwrap();+ let req = user_create_webhook("[email protected]", None);++ let (is_ok, invocation_count) = dispatch_with_invocation_count(&policy, req).await;++ assert!(!is_ok);+ assert_eq!(invocation_count, 0);+}++#[tokio::test]+async fn complete_and_verified_events_do_not_use_user_create_dispatch() {+ for event_type in ["user.create.complete", "user.email.verified"] {+ let req = FusionAuthUserWebhook {+ event: Event {+ event_type: event_type.to_string(),+ ..user_create_webhook("[email protected]", None).event+ },+ };++ assert_ne!(req.event.event_type, "user.create");}}diff --git a/services/authentication_service/src/config.rs b/services/authentication_service/src/config.rsindex 432baed463..b29f395b4f 100644--- a/services/authentication_service/src/config.rs+++ b/services/authentication_service/src/config.rs@@ -1,6 +1,7 @@use std::sync::LazyLock;use anyhow::Context;+use authentication_service::service::signup_policy::SignupPolicy;use database_env_vars::{DatabaseUrl, RedisUri};use macro_auth::InternalApiKey;pub use macro_env::Environment;@@ -60,6 +61,8 @@ maybe_env_vars! {pub struct PosthogApiKey;pub struct PosthogHost;pub struct LoopsApiKey;+ /// JSON array of exact email addresses allowed to sign up in Develop.+ pub struct DevelopmentSignupAllowlistJson;}/// The configuration parameters for the application.@@ -140,6 +143,10 @@ pub struct Config {/// Loops API key (optional). When set, Macro sign-ups are added to our/// Loops audience.pub loops_api_key: LoopsApiKey,+ /// JSON array of exact non-Macro email addresses allowed to sign up in Develop.+ ///+ /// All `@macro.com` email addresses are allowed by the Develop policy automatically.+ pub development_signup_allowlist_json: DevelopmentSignupAllowlistJson,/// The stripe price idpub stripe_price_id: StripePriceId,/// The internal api key@@ -196,6 +203,19 @@ impl Config {&self.microsoft_token_kms_key_id,)}++ /// Resolves the signup policy for the configured environment.+ pub(crate) fn signup_policy(&self) -> anyhow::Result<SignupPolicy> {+ self.signup_policy_for_environment(self.environment)+ }++ /// Resolves the signup policy for an explicit environment.+ pub(crate) fn signup_policy_for_environment(+ &self,+ environment: Environment,+ ) -> anyhow::Result<SignupPolicy> {+ resolve_signup_policy(environment, &self.development_signup_allowlist_json)+ }}fn resolve_microsoft_credentials(@@ -228,6 +248,21 @@ fn resolve_microsoft_credentials(}}+fn resolve_signup_policy(+ environment: Environment,+ development_signup_allowlist_json: &DevelopmentSignupAllowlistJson,+) -> anyhow::Result<SignupPolicy> {+ match environment {+ Environment::Production | Environment::Local => Ok(SignupPolicy::allow_all()),+ Environment::Develop => {+ let raw_allowlist = nonblank_value(development_signup_allowlist_json.value())+ .context("DEVELOPMENT_SIGNUP_ALLOWLIST_JSON is required in Develop")?;+ SignupPolicy::from_allowlist_json(raw_allowlist)+ .context("DEVELOPMENT_SIGNUP_ALLOWLIST_JSON is invalid")+ }+ }+}+fn nonblank_value(value: Option<&str>) -> Option<&str> {value.filter(|value| !value.trim().is_empty())}diff --git a/services/authentication_service/src/config/test.rs b/services/authentication_service/src/config/test.rsindex 483e9bb831..bf6312a1e6 100644--- a/services/authentication_service/src/config/test.rs+++ b/services/authentication_service/src/config/test.rs@@ -140,6 +140,74 @@ fn microsoft_token_kms_key_id(value: Option<&'static str>) -> MicrosoftTokenKmsK}}+fn development_allowlist(value: Option<&'static str>) -> DevelopmentSignupAllowlistJson {+ match value {+ Some(value) => DevelopmentSignupAllowlistJson::new_testing(value),+ None => DevelopmentSignupAllowlistJson::new_unset(),+ }+}++#[test]+fn develop_signup_policy_requires_configured_allowlist() {+ for value in [None, Some(""), Some(" \t ")] {+ let error = resolve_signup_policy(Environment::Develop, &development_allowlist(value))+ .expect_err("Develop should require a nonblank allowlist setting");++ assert!(+ error+ .to_string()+ .contains("DEVELOPMENT_SIGNUP_ALLOWLIST_JSON")+ );+ }+}++#[test]+fn develop_signup_policy_uses_configured_allowlist() {+ let policy = resolve_signup_policy(+ Environment::Develop,+ &development_allowlist(Some(+ r#"["[email protected]", "[email protected]"]"#,+ )),+ )+ .expect("valid Develop allowlist should resolve");++ assert_eq!(policy.allowed_email_count(), Some(1));+ policy+ .authorize_public_email("[email protected]")+ .expect("configured email should be allowed");+}++#[test]+fn develop_signup_policy_rejects_malformed_allowlist_without_leaking_value() {+ let configured_value = "[email protected]";+ let error = resolve_signup_policy(+ Environment::Develop,+ &development_allowlist(Some(configured_value)),+ )+ .expect_err("malformed Develop allowlist should be rejected");+ let message = error.to_string();++ assert!(message.contains("DEVELOPMENT_SIGNUP_ALLOWLIST_JSON"));+ assert!(!message.contains(configured_value));+ assert!(!format!("{error:?}").contains(configured_value));+}++#[test]+fn production_and_local_signup_policy_ignore_allowlist_setting() {+ for environment in [Environment::Production, Environment::Local] {+ let policy = resolve_signup_policy(+ environment,+ &development_allowlist(Some("[email protected]")),+ )+ .expect("non-Develop environments should not parse the allowlist setting");++ assert_eq!(policy.allowed_email_count(), None);+ policy+ .authorize_public_email("[email protected]")+ .expect("non-Develop environments should allow all public signups");+ }+}+#[test]fn cursor_kms_key_from_config_field() {let configured = CursorApiKeyKmsKeyId::new_testing("arn:aws:kms:from-config");diff --git a/services/authentication_service/src/doppler_config.rs b/services/authentication_service/src/doppler_config.rsindex 4793cbfb33..1593ecc815 100644--- a/services/authentication_service/src/doppler_config.rs+++ b/services/authentication_service/src/doppler_config.rs@@ -16,7 +16,8 @@ async fn main() -> anyhow::Result<()> {.build().expect("able to grab doppler project");- dev.load::<config::Config>().await?;+ let dev_config = dev.load::<config::Config>().await?;+ dev_config.signup_policy_for_environment(Environment::Develop)?;let prd = doppler_config::DopplerConfig::builder().token_from_env("DOPPLER_TOKEN")@@ -25,7 +26,8 @@ async fn main() -> anyhow::Result<()> {.build().expect("able to grab doppler project");- prd.load::<config::Config>().await?;+ let prd_config = prd.load::<config::Config>().await?;+ prd_config.signup_policy_for_environment(Environment::Production)?;Ok(())}diff --git a/services/authentication_service/src/main.rs b/services/authentication_service/src/main.rsindex bcab0e67c3..f3c95ded73 100644--- a/services/authentication_service/src/main.rs+++ b/services/authentication_service/src/main.rs@@ -101,6 +101,11 @@ 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 signup_policy = Arc::new(+ config+ .signup_policy()+ .context("invalid signup policy configuration")?,+ );let microsoft_credentials = config.microsoft_credentials().context("invalid Microsoft OAuth configuration")?;@@ -448,6 +453,7 @@ async fn main() -> anyhow::Result<()> {notification_ingress_service,sqs_client,environment: config.environment,+ signup_policy,rate_limit_service: rate_limit,calendar_scope_enabled: config.calendar_scope_enabled,jwt_args,diff --git a/services/authentication_service/src/service/mod.rs b/services/authentication_service/src/service/mod.rsindex 22d12a3827..e8dcd1a633 100644--- a/services/authentication_service/src/service/mod.rs+++ b/services/authentication_service/src/service/mod.rs@@ -1 +1,2 @@+pub mod signup_policy;pub mod user;diff --git a/services/authentication_service/src/service/signup_policy.rs b/services/authentication_service/src/service/signup_policy.rsnew file mode 100644index 0000000000..f2f1bfb00a--- /dev/null+++ b/services/authentication_service/src/service/signup_policy.rs@@ -0,0 +1,168 @@+#[cfg(test)]+mod test;++use std::{collections::HashSet, fmt};++use macro_user_id::email::Email;+use serde_json::Value;++const MACRO_EMAIL_DOMAIN: &str = "macro.com";++/// The configured signup admission policy.+#[derive(Clone, Eq, PartialEq)]+pub enum SignupPolicy {+ /// Admit every signup origin.+ AllowAll,+ /// Admit public signups when their normalized email is a Macro address or present.+ EmailAllowlist { allowed_emails: HashSet<String> },+}++impl SignupPolicy {+ /// Create a policy that admits every signup origin.+ pub fn allow_all() -> Self {+ Self::AllowAll+ }++ /// Create an exact-address allowlist from a JSON array of email strings.+ ///+ /// The resulting policy also admits every `@macro.com` address.+ pub fn from_allowlist_json(raw_json: &str) -> Result<Self, SignupPolicyConfigError> {+ let value = serde_json::from_str::<Value>(raw_json)+ .map_err(|_| SignupPolicyConfigError::MalformedJson)?;+ let Value::Array(entries) = value else {+ return Err(SignupPolicyConfigError::ExpectedArray);+ };++ let allowed_emails = entries+ .iter()+ .enumerate()+ .map(|(index, entry)| normalize_allowlist_entry(index, entry))+ .collect::<Result<HashSet<_>, _>>()?;++ if allowed_emails.is_empty() {+ return Err(SignupPolicyConfigError::EmptyAllowlist);+ }++ Ok(Self::EmailAllowlist { allowed_emails })+ }++ /// Authorize a public signup email address.+ pub fn authorize_public_email(&self, email: &str) -> Result<(), SignupPolicyDenial> {+ match self {+ Self::AllowAll => Ok(()),+ Self::EmailAllowlist { allowed_emails } => {+ let normalized_email = normalize_public_email(email)?;+ if is_macro_email(&normalized_email) || allowed_emails.contains(&normalized_email) {+ Ok(())+ } else {+ Err(SignupPolicyDenial::PublicEmailNotAllowed)+ }+ }+ }+ }++ /// Return the number of configured addresses for allowlist policies.+ pub fn allowed_email_count(&self) -> Option<usize> {+ match self {+ Self::AllowAll => None,+ Self::EmailAllowlist { allowed_emails } => Some(allowed_emails.len()),+ }+ }+}++impl fmt::Debug for SignupPolicy {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::AllowAll => formatter.write_str("SignupPolicy::AllowAll"),+ Self::EmailAllowlist { allowed_emails } => formatter+ .debug_struct("SignupPolicy::EmailAllowlist")+ .field("allowed_email_count", &allowed_emails.len())+ .finish(),+ }+ }+}++/// A redacted policy configuration error.+#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]+pub enum SignupPolicyConfigError {+ /// The setting was not valid JSON.+ #[error("signup allowlist must be valid JSON")]+ MalformedJson,+ /// The setting was valid JSON, but not an array.+ #[error("signup allowlist must be a JSON array")]+ ExpectedArray,+ /// An array entry was not a string.+ #[error("signup allowlist entry at index {index} must be a string")]+ NonStringEntry {+ /// The zero-based array index of the invalid entry.+ index: usize,+ },+ /// An array entry was blank after trimming whitespace.+ #[error("signup allowlist entry at index {index} must not be blank")]+ BlankEntry {+ /// The zero-based array index of the blank entry.+ index: usize,+ },+ /// An array entry was not a valid email address.+ #[error("signup allowlist entry at index {index} must be a valid email address")]+ InvalidEmail {+ /// The zero-based array index of the invalid entry.+ index: usize,+ },+ /// The allowlist did not contain any usable email addresses.+ #[error("signup allowlist must contain at least one email address")]+ EmptyAllowlist,+}++/// A redacted policy denial.+#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]+pub enum SignupPolicyDenial {+ /// The public signup email was not admitted by the configured policy.+ #[error("signup is not allowed for this email address")]+ PublicEmailNotAllowed,+ /// The public signup email could not be parsed.+ #[error("signup email address is invalid")]+ InvalidPublicEmail,+}++fn normalize_allowlist_entry(+ index: usize,+ entry: &Value,+) -> Result<String, SignupPolicyConfigError> {+ let Some(email) = entry.as_str() else {+ return Err(SignupPolicyConfigError::NonStringEntry { index });+ };++ normalize_config_email(index, email)+}++fn normalize_config_email(index: usize, email: &str) -> Result<String, SignupPolicyConfigError> {+ let trimmed_email = email.trim();+ if trimmed_email.is_empty() {+ return Err(SignupPolicyConfigError::BlankEntry { index });+ }++ normalize_email(trimmed_email).map_err(|_| SignupPolicyConfigError::InvalidEmail { index })+}++fn normalize_public_email(email: &str) -> Result<String, SignupPolicyDenial> {+ let trimmed_email = email.trim();+ if trimmed_email.is_empty() {+ return Err(SignupPolicyDenial::InvalidPublicEmail);+ }++ normalize_email(trimmed_email).map_err(|_| SignupPolicyDenial::InvalidPublicEmail)+}++fn normalize_email(email: &str) -> Result<String, ()> {+ Email::parse_from_str(email).map_err(|_| ())?;+ let lowercased_email = email.to_lowercase();+ Email::parse_from_str(&lowercased_email).map_err(|_| ())?;+ Ok(lowercased_email)+}++fn is_macro_email(normalized_email: &str) -> bool {+ normalized_email+ .rsplit_once('@')+ .is_some_and(|(_, domain)| domain == MACRO_EMAIL_DOMAIN)+}diff --git a/services/authentication_service/src/service/signup_policy/test.rs b/services/authentication_service/src/service/signup_policy/test.rsnew file mode 100644index 0000000000..f16132a66a--- /dev/null+++ b/services/authentication_service/src/service/signup_policy/test.rs@@ -0,0 +1,174 @@+use super::*;++#[test]+fn allow_all_accepts_public_signups() {+ let policy = SignupPolicy::allow_all();++ assert!(+ policy+ .authorize_public_email("[email protected]")+ .is_ok()+ );+}++#[test]+fn allowlist_matching_trims_and_ignores_case() {+ let policy = SignupPolicy::from_allowlist_json(+ r#"[" [email protected] ", "[email protected]"]"#,+ )+ .expect("valid allowlist");++ assert_eq!(policy.allowed_email_count(), Some(2));+ assert!(+ policy+ .authorize_public_email("[email protected]")+ .is_ok()+ );+ assert!(+ policy+ .authorize_public_email(" [email protected] ")+ .is_ok()+ );+ assert!(+ policy+ .authorize_public_email("[email protected]")+ .is_ok()+ );+}++#[test]+fn duplicate_allowlist_entries_are_collapsed() {+ let policy = SignupPolicy::from_allowlist_json(+ r#"["[email protected]", " [email protected] "]"#,+ )+ .expect("valid allowlist");++ assert_eq!(policy.allowed_email_count(), Some(1));+ assert!(!format!("{policy:?}").contains("[email protected]"));+}++#[test]+fn plus_aliases_remain_distinct_addresses() {+ let policy =+ SignupPolicy::from_allowlist_json(r#"["[email protected]"]"#).expect("valid allowlist");++ assert!(policy.authorize_public_email("[email protected]").is_ok());+ assert_eq!(+ policy.authorize_public_email("[email protected]"),+ Err(SignupPolicyDenial::PublicEmailNotAllowed)+ );+}++#[test]+fn allowlist_policy_accepts_macro_domain_addresses() {+ let policy =+ SignupPolicy::from_allowlist_json(r#"["[email protected]"]"#).expect("valid allowlist");++ assert!(policy.authorize_public_email("[email protected]").is_ok());+ assert!(+ policy+ .authorize_public_email(" [email protected] ")+ .is_ok()+ );+ assert!(+ policy+ .authorize_public_email("[email protected]")+ .is_ok()+ );+}++#[test]+fn macro_domain_match_does_not_include_subdomains_or_similar_domains() {+ let policy =+ SignupPolicy::from_allowlist_json(r#"["[email protected]"]"#).expect("valid allowlist");++ for email in [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ] {+ assert_eq!(+ policy.authorize_public_email(email),+ Err(SignupPolicyDenial::PublicEmailNotAllowed),+ "{email}"+ );+ }+}++#[test]+fn malformed_json_is_rejected() {+ assert_eq!(+ SignupPolicy::from_allowlist_json("not json"),+ Err(SignupPolicyConfigError::MalformedJson)+ );+}++#[test]+fn non_array_json_is_rejected() {+ assert_eq!(+ SignupPolicy::from_allowlist_json(r#"{"email":"[email protected]"}"#),+ Err(SignupPolicyConfigError::ExpectedArray)+ );+}++#[test]+fn non_string_entries_are_rejected_by_index() {+ assert_eq!(+ SignupPolicy::from_allowlist_json(r#"["[email protected]", 42]"#),+ Err(SignupPolicyConfigError::NonStringEntry { index: 1 })+ );+}++#[test]+fn invalid_emails_are_rejected_by_index() {+ assert_eq!(+ SignupPolicy::from_allowlist_json(r#"["[email protected]", "not-an-email"]"#),+ Err(SignupPolicyConfigError::InvalidEmail { index: 1 })+ );+}++#[test]+fn blank_entries_are_rejected_by_index() {+ assert_eq!(+ SignupPolicy::from_allowlist_json(r#"["[email protected]", " "]"#),+ Err(SignupPolicyConfigError::BlankEntry { index: 1 })+ );+}++#[test]+fn empty_arrays_are_rejected() {+ assert_eq!(+ SignupPolicy::from_allowlist_json("[]"),+ Err(SignupPolicyConfigError::EmptyAllowlist)+ );+}++#[test]+fn diagnostics_do_not_reveal_allowlist_or_denied_email() {+ let policy = SignupPolicy::from_allowlist_json(r#"["[email protected]"]"#)+ .expect("valid allowlist");+ let denial = policy+ .authorize_public_email("[email protected]")+ .expect_err("email should be denied");++ let policy_debug = format!("{policy:?}");+ let denial_debug = format!("{denial:?}");+ let denial_display = denial.to_string();++ for diagnostic in [policy_debug, denial_debug, denial_display] {+ assert!(!diagnostic.contains("[email protected]"));+ assert!(!diagnostic.contains("[email protected]"));+ }+}++#[test]+fn config_errors_do_not_reveal_entries() {+ let error = SignupPolicy::from_allowlist_json(r#"["not-an-email"]"#)+ .expect_err("invalid entry should fail");++ let debug = format!("{error:?}");+ let display = error.to_string();++ assert!(!debug.contains("not-an-email"));+ assert!(!display.contains("not-an-email"));+}