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): serve authentication-service on the gateway /auth prefix (#6166)
Will Hutchinsonf82f7110b4b8
diff --git a/apps/web/src/lib/core/constant/servers.ts b/apps/web/src/lib/core/constant/servers.tsindex 5a0d7eee82..eed009dec2 100644--- a/apps/web/src/lib/core/constant/servers.ts+++ b/apps/web/src/lib/core/constant/servers.ts@@ -29,7 +29,7 @@ const authLogoutUrl =: 'https://auth.macro.com/oauth2/logout?client_id=75409999-7dc4-4241-b73b-a51818c3a71c&tenantId=a3e53c3d-8d6a-3e92-d64c-fa3bf30a60be';const serverHostRemote = {- 'auth-service': `https://auth-service${devServerSuffix}.macro.com`,+ 'auth-service': `${gatewayHost}/auth`,'auth-logout': authLogoutUrl,'pdf-service': `https://pdf-service${devServerSuffix}.macro.com`,'document-storage-service': `${gatewayHost}/dss`,diff --git a/crates/macro_service_urls/src/lib.rs b/crates/macro_service_urls/src/lib.rsindex ac055a90cd..80da09a0f0 100644--- a/crates/macro_service_urls/src/lib.rs+++ b/crates/macro_service_urls/src/lib.rs@@ -503,8 +503,8 @@ service_url! {/// Authentication service API URL.pub AuthServiceUrl {local: "http://localhost:8080",- dev: "https://auth-service-dev.macro.com",- prod: "https://auth-service.macro.com",+ dev: "https://dev-gateway.macro.com/auth",+ prod: "https://gateway.macro.com/auth",},/// Document storage service API URL.pub DocumentStorageServiceUrl {diff --git a/crates/macro_service_urls/src/test.rs b/crates/macro_service_urls/src/test.rsindex 68aa7adf43..aaec3af8f3 100644--- a/crates/macro_service_urls/src/test.rs+++ b/crates/macro_service_urls/src/test.rs@@ -425,7 +425,7 @@ fn exported_service_urls_match_dev_values() {);assert_eq!(service_urls.auth_service_url.as_ref(),- "https://auth-service-dev.macro.com",+ "https://dev-gateway.macro.com/auth",);assert_eq!(service_urls.document_storage_service_url.as_ref(),@@ -496,7 +496,7 @@ fn exported_service_urls_match_prod_values() {assert_eq!(service_urls.app_service_url.as_ref(), "https://macro.com");assert_eq!(service_urls.auth_service_url.as_ref(),- "https://auth-service.macro.com",+ "https://gateway.macro.com/auth",);assert_eq!(service_urls.document_storage_service_url.as_ref(),diff --git a/docs/AGENT_GUIDE/observability.md b/docs/AGENT_GUIDE/observability.mdindex d16f5473ff..6fd7a033f0 100644--- a/docs/AGENT_GUIDE/observability.md+++ b/docs/AGENT_GUIDE/observability.md@@ -37,9 +37,10 @@ URL prefix → service mapping: `/dss/*` → document_storage_service,exports to `/i/otlp/v1/{traces,logs}`.The local Caddy proxy strips these prefixes before forwarding, so `span.url.path` is-unprefixed locally. The deployed gateway ALB does **not** strip `/dss` or `/unfurl` —-those services serve the same routes at both `/` and the prefix — so in dev and prod-`span.url.path` includes the prefix. Query both forms when a search comes back empty.+unprefixed locally. The deployed gateway ALB does **not** strip `/dss`, `/unfurl`, or+`/auth` — those services serve the same routes at both `/` and the prefix — so in+dev and prod `span.url.path` includes the prefix. Query both forms when a search+comes back empty.## Logs (Loki)diff --git a/infra/packages/shared/src/gateway_priorities.ts b/infra/packages/shared/src/gateway_priorities.tsindex d4fef92c7e..633f176601 100644--- a/infra/packages/shared/src/gateway_priorities.ts+++ b/infra/packages/shared/src/gateway_priorities.ts@@ -13,6 +13,7 @@ export enum GatewayService {AGENT_HARNESS_SERVICE = 'AGENT_HARNESS_SERVICE',AGENT_SCHEDULE_SERVICE = 'AGENT_SCHEDULE_SERVICE',CONNECTION_GATEWAY = 'CONNECTION_GATEWAY',+ AUTHENTICATION_SERVICE = 'AUTHENTICATION_SERVICE',}/**@@ -34,6 +35,7 @@ export const GATEWAY_PRIORITIES: GatewayPriorityMap = {[GatewayService.AGENT_HARNESS_SERVICE]: 70,[GatewayService.AGENT_SCHEDULE_SERVICE]: 80,[GatewayService.CONNECTION_GATEWAY]: 90,+ [GatewayService.AUTHENTICATION_SERVICE]: 100,[GatewayService.CONVERT_SERVICE]: 3000,};diff --git a/infra/packages/shared/src/service_urls.ts b/infra/packages/shared/src/service_urls.tsindex 6df92c1d7f..b0b0e15ba1 100644--- a/infra/packages/shared/src/service_urls.ts+++ b/infra/packages/shared/src/service_urls.ts@@ -35,7 +35,7 @@ const DEV_SERVICE_URLS: ServiceUrlMap = {'https://static-file-service-dev.macro.com',[ServiceUrl.NOTIFICATION_SERVICE_URL]:'https://dev-gateway.macro.com/notification',- [ServiceUrl.AUTHENTICATION_SERVICE_URL]: 'https://auth-service-dev.macro.com',+ [ServiceUrl.AUTHENTICATION_SERVICE_URL]: 'https://dev-gateway.macro.com/auth',[ServiceUrl.DOCUMENT_STORAGE_SERVICE_URL]:'https://dev-gateway.macro.com/dss',[ServiceUrl.CONNECTION_GATEWAY_URL]:@@ -59,7 +59,7 @@ const PROD_SERVICE_URLS: ServiceUrlMap = {[ServiceUrl.STATIC_FILE_SERVICE_URL]: 'https://static-file-service.macro.com',[ServiceUrl.NOTIFICATION_SERVICE_URL]:'https://gateway.macro.com/notification',- [ServiceUrl.AUTHENTICATION_SERVICE_URL]: 'https://auth-service.macro.com',+ [ServiceUrl.AUTHENTICATION_SERVICE_URL]: 'https://gateway.macro.com/auth',[ServiceUrl.DOCUMENT_STORAGE_SERVICE_URL]: 'https://gateway.macro.com/dss',[ServiceUrl.CONNECTION_GATEWAY_URL]:'https://gateway.macro.com/connection-gateway',diff --git a/infra/stacks/authentication-service/service.ts b/infra/stacks/authentication-service/service.tsindex eb411e0c9b..b04d617de1 100644--- a/infra/stacks/authentication-service/service.ts+++ b/infra/stacks/authentication-service/service.ts@@ -8,16 +8,21 @@ import {datadogAgentContainer,fargateLogRouterSidecarContainer,serviceLoadBalancer,+ ServiceTargetGroup,} from '../../packages/resources';import { EcrImage } from '../../packages/service';import {BASE_DOMAIN,CLOUD_TRAIL_SNS_TOPIC_ARN,DopplerEcsEnvironment,+ getGatewayAlb,+ GatewayService,getKafkaClusterPolicy,stack,} from '../../packages/shared';+const gatewayLoadBalancer = getGatewayAlb();+const BASE_NAME = pulumi.getProject();const REPO_ROOT = '../../..';@@ -378,6 +383,22 @@ export class AuthenticationService extends pulumi.ComponentResource {this.serviceAlbSg = sg.serviceAlbSg;this.serviceSg = sg.serviceSg;+ const gatewayTargetGroup = new ServiceTargetGroup(+ `${stack}-${BASE_NAME}`,+ {+ tags: this.tags,+ listenerArn: gatewayLoadBalancer.httpsListenerArn,+ vpcId: vpc.vpcId,+ containerPort: serviceContainerPort,+ service: GatewayService.AUTHENTICATION_SERVICE,+ healthCheckPath,+ pathPatterns: ['/auth', '/auth/*'],+ serviceSecurityGroupId: this.serviceSg.id,+ albSecurityGroupId: gatewayLoadBalancer.albSecurityGroupId,+ },+ { parent: this }+ );+// lbconst { targetGroup, lb, listener } = serviceLoadBalancer(this, {serviceName: BASE_NAME, // service name@@ -413,6 +434,23 @@ export class AuthenticationService extends pulumi.ComponentResource {enable: true,rollback: true,},+ // Register tasks in both the legacy ALB's target group and the gateway+ // target group while we migrate to the gateway. An explicit+ // `loadBalancers` replaces the list awsx derives from+ // `portMappings.targetGroup`, so the legacy entry must be listed here+ // too.+ loadBalancers: [+ {+ targetGroupArn: targetGroup.arn,+ containerName: 'service',+ containerPort: serviceContainerPort,+ },+ {+ targetGroupArn: gatewayTargetGroup.target_group.arn,+ containerName: 'service',+ containerPort: serviceContainerPort,+ },+ ],taskDefinitionArgs: {taskRole: {roleArn: this.role.arn,@@ -479,12 +517,19 @@ export class AuthenticationService extends pulumi.ComponentResource {},{parent: this,+ // ECS refuses a service whose target group is not yet associated with+ // a load balancer; it is the listener rule that creates that+ // association+ dependsOn: [gatewayTargetGroup.listener_rule],});this.service = service;- this.setupAutoScaling();+ this.setupAutoScaling({+ gatewayAlbArnSuffix: gatewayLoadBalancer.albArnSuffix,+ gatewayTargetGroup: gatewayTargetGroup.target_group,+ });this.setupServiceAlarms();@@ -610,7 +655,13 @@ export class AuthenticationService extends pulumi.ComponentResource {return { serviceAlbSg, serviceSg };}- setupAutoScaling() {+ setupAutoScaling({+ gatewayAlbArnSuffix,+ gatewayTargetGroup,+ }: {+ gatewayAlbArnSuffix: pulumi.Output<string>;+ gatewayTargetGroup: aws.lb.TargetGroup;+ }) {if (!this.service) return;const serviceScalableTarget = new aws.appautoscaling.Target(@@ -626,19 +677,7 @@ export class AuthenticationService extends pulumi.ComponentResource {{ parent: this });- const lbPortion: pulumi.Output<string> = this.lb.arn.apply((arn) => {- const parts = arn.split(':loadbalancer/');- return parts[1];- });-- const tgPortion: pulumi.Output<string> = this.targetGroup.arn.apply(- (arn) => {- const parts = arn.split(':');- return parts[parts.length - 1];- }- );-- const resourceLabel = pulumi.interpolate`${lbPortion}/${tgPortion}`;+ const resourceLabel = pulumi.interpolate`${gatewayAlbArnSuffix}/${gatewayTargetGroup.arnSuffix}`;// Create an Auto Scaling policy for request count.new aws.appautoscaling.Policy(diff --git a/infra/stacks/fusionauth-instance/index.ts b/infra/stacks/fusionauth-instance/index.tsindex f8bc02ba2f..7cfe0b9c30 100644--- a/infra/stacks/fusionauth-instance/index.ts+++ b/infra/stacks/fusionauth-instance/index.ts@@ -12,7 +12,12 @@ import {} from 'pulumi-fusionauth';import * as pulumi from '@pulumi/pulumi';import * as fs from 'fs';-import { config, stack } from '../../packages/shared';+import {+ config,+ getServiceUrl,+ ServiceUrl,+ stack,+} from '../../packages/shared';import 'dotenv/config';import {@@ -292,6 +297,11 @@ const macroApplication = new FusionAuthApplication(stack === 'local' || stack === 'dev' ? 'AllowWildcards' : 'ExactMatch',authorizedRedirectUrls: [`${AUTHENTICATION_SERVICE_DOMAIN}/oauth/redirect`,+ ...(stack === 'dev' || stack === 'prod'+ ? [+ `${getServiceUrl(ServiceUrl.AUTHENTICATION_SERVICE_URL)}/oauth/redirect`,+ ]+ : []),`https://mcp-server${stack === 'prod' ? '' : `-${stack}`}.macro.com/oauth/callback`,...(stack === 'local' || stack === 'dev'? ['http://localhost:8085/*', 'http://localhost:8085/oauth/*']diff --git a/infra/stacks/fusionauth-instance/origins.ts b/infra/stacks/fusionauth-instance/origins.tsindex 497b722fcb..80dedc2f57 100644--- a/infra/stacks/fusionauth-instance/origins.ts+++ b/infra/stacks/fusionauth-instance/origins.ts@@ -6,6 +6,7 @@ import { AUTHENTICATION_SERVICE_DOMAIN } from './constants';*/export const ALLOWED_ORIGINS = () => {const allowedOrigins = [AUTHENTICATION_SERVICE_DOMAIN];+switch (stack) {case 'local':return [@@ -30,6 +31,7 @@ export const ALLOWED_ORIGINS = () => {case 'dev':return [...allowedOrigins,+ 'https://dev-gateway.macro.com','http://localhost:3000','http://localhost:3001','http://localhost:3002',@@ -53,6 +55,7 @@ export const ALLOWED_ORIGINS = () => {case 'prod':return [...allowedOrigins,+ 'https://gateway.macro.com','https://macro.com','https://dashboard.macro.com','https://staging.macro.com',diff --git a/packages/sdk/src/config.ts b/packages/sdk/src/config.tsindex c45a13242f..21fa86bd99 100644--- a/packages/sdk/src/config.ts+++ b/packages/sdk/src/config.ts@@ -27,7 +27,7 @@ export const HOSTS: Record<Env, Record<ServiceName, string>> = {dev: {'agent-harness': 'https://dev-gateway.macro.com/agent-harness',storage: 'https://dev-gateway.macro.com/dss',- auth: 'https://auth-service-dev.macro.com',+ auth: 'https://dev-gateway.macro.com/auth',email: 'https://email-service-dev.macro.com',cognition: 'https://document-cognition-dev.macro.com',notification: 'https://dev-gateway.macro.com/notification',@@ -42,7 +42,7 @@ export const HOSTS: Record<Env, Record<ServiceName, string>> = {prod: {'agent-harness': 'https://gateway.macro.com/agent-harness',storage: 'https://gateway.macro.com/dss',- auth: 'https://auth-service.macro.com',+ auth: 'https://gateway.macro.com/auth',email: 'https://email-service.macro.com',cognition: 'https://document-cognition.macro.com',notification: 'https://gateway.macro.com/notification',diff --git a/services/authentication_service/src/api.rs b/services/authentication_service/src/api.rsindex 84ef94898e..2f312b3ef5 100644--- a/services/authentication_service/src/api.rs+++ b/services/authentication_service/src/api.rs@@ -44,6 +44,13 @@ mod middleware;pub(crate) mod swagger;mod utils;+#[cfg(test)]+mod test;++/// Path prefix the shared gateway ALB forwards unmodified. Dual-mounted+/// alongside `/` so the dedicated ALB keeps working during cutover.+const GATEWAY_PATH_PREFIX: &str = "/auth";+pub async fn setup_and_serve(state: ApiContext, port: usize) -> anyhow::Result<()> {let cors = macro_cors::cors_layer_with_headers(vec![HeaderName::from_static(MACRO_REFRESH_TOKEN_HEADER,@@ -57,8 +64,10 @@ pub async fn setup_and_serve(state: ApiContext, port: usize) -> anyhow::Result<(// The health router is attached here so we don't attach the logging middleware to it.merge(health::router()).layer(cors)- .merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", swagger::ApiDoc::openapi())).layer(CompressionLayer::new());+ // Swagger sits outside the dual-mount. Nested under `/auth`, the absolute+ // `/api-doc/openapi.json` URL in the UI would 404 on the gateway.+ let app = mount_at_root_and_prefix(app).merge(swagger_ui());let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port)).await@@ -77,6 +86,21 @@ pub async fn setup_and_serve(state: ApiContext, port: usize) -> anyhow::Result<(.context("error starting service")}+fn mount_at_root_and_prefix(inner: Router) -> Router {+ Router::new()+ .merge(inner.clone())+ .nest(GATEWAY_PATH_PREFIX, inner)+}++fn swagger_ui() -> Router {+ Router::new()+ .merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", swagger::ApiDoc::openapi()))+ .merge(+ SwaggerUi::new("/auth/docs")+ .url("/auth/api-doc/openapi.json", swagger::ApiDoc::openapi()),+ )+}+fn api_router(state: ApiContext) -> Router<ApiContext> {Router::new().merge(native_app_service::inbound::native_app_router(diff --git a/services/authentication_service/src/api/test.rs b/services/authentication_service/src/api/test.rsnew file mode 100644index 0000000000..a80bfb7963--- /dev/null+++ b/services/authentication_service/src/api/test.rs@@ -0,0 +1,61 @@+use super::{health, mount_at_root_and_prefix, swagger_ui};+use axum::{+ body::Body,+ http::{Request, StatusCode},+};+use tower::ServiceExt;++#[tokio::test]+async fn health_is_reachable_at_root_and_gateway_prefix() {+ for path in ["/health", "/auth/health"] {+ let response = mount_at_root_and_prefix(health::router())+ .oneshot(+ Request::builder()+ .uri(path)+ .method("GET")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK, "{path}");+ }+}++#[tokio::test]+async fn unprefixed_unknown_path_is_not_rewritten_onto_the_prefix() {+ let response = mount_at_root_and_prefix(health::router())+ .oneshot(+ Request::builder()+ .uri("/missing")+ .method("GET")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::NOT_FOUND);+}++#[tokio::test]+async fn openapi_is_served_at_root_and_gateway_prefix() {+ let api = swagger_ui();++ for uri in ["/api-doc/openapi.json", "/auth/api-doc/openapi.json"] {+ let response = api+ .clone()+ .oneshot(+ Request::builder()+ .uri(uri)+ .method("GET")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK, "{uri}");+ }+}