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
image proxy service (#1717)
Will Hutchinsonfa97d3e72567
diff --git a/.github/services-config.json b/.github/services-config.jsonindex 7ebe3daf2f..775a9524c6 100644--- a/.github/services-config.json+++ b/.github/services-config.json@@ -141,6 +141,12 @@"rust/cloud-storage/dlp_handler/**"],"stack_path": "infra/stacks/dlp-handler/**"+ },+ "image-proxy-service": {+ "source_paths": [+ "rust/cloud-storage/image_proxy_service/**"+ ],+ "stack_path": "infra/stacks/image-proxy-service/**"}}}diff --git a/.github/workflows/deploy-service-generic.yml b/.github/workflows/deploy-service-generic.ymlindex c0897ac6bd..46a2f24cfa 100644--- a/.github/workflows/deploy-service-generic.yml+++ b/.github/workflows/deploy-service-generic.yml@@ -22,6 +22,7 @@ on:- document-text-extractor- email-service- email-suppression+ - image-proxy-service- lambda-aggregate-frecency- link-sharing- notification-servicediff --git a/docker-compose.yml b/docker-compose.ymlindex 3b398983fd..67466e9d02 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -273,6 +273,27 @@ services:retries: 3start_period: 10s+ # ============================================================================+ # image_proxy_service (Port 8097)+ # Proxies external images to avoid CORS issues and IP leakage+ # ============================================================================+ image_proxy_service:+ <<: *common-env+ build:+ context: ./rust/cloud-storage+ dockerfile: Dockerfile.dev+ target: image_proxy_service+ ports:+ - "8097:8080"+ networks:+ - services+ healthcheck:+ test: ["CMD", "curl", "-f", "http://localhost:8080/health"]+ interval: 30s+ timeout: 10s+ retries: 3+ start_period: 10s+# ============================================================================# websocket_service (Port 6969)# Simple WebSocket service - responds with "ping" to all messagesdiff --git a/infra/bun.lock b/infra/bun.lockindex 9512c2faba..7bb9ba923e 100644--- a/infra/bun.lock+++ b/infra/bun.lock@@ -122,6 +122,10 @@"pulumi-fusionauth": "6.0.2",},},+ "stacks/image-proxy-service": {+ "name": "image-proxy-service-stack",+ "version": "0.0.0",+ },"stacks/link-sharing": {"name": "link-sharing-stack","version": "0.0.0",@@ -680,6 +684,8 @@"ignore-walk": ["[email protected]", "", { "dependencies": { "minimatch": "^9.0.0" } }, "sha512-VuuG0wCnjhnylG1ABXT3dAuIpTNDs/G8jlpmwXY03fXoXy/8ZK8/T+hMzt8L4WnrLCJgdybqgPagnF/f97cg3A=="],+ "image-proxy-service-stack": ["image-proxy-service-stack@workspace:stacks/image-proxy-service"],+"import-in-the-middle": ["[email protected]", "", { "dependencies": { "acorn": "^8.8.2", "acorn-import-attributes": "^1.9.5", "cjs-module-lexer": "^1.2.2", "module-details-from-path": "^1.0.3" } }, "sha512-yAgSE7GmtRcu4ZUSFX/4v69UGXwugFFSdIQJ14LHPOPPQrWv8Y7O9PHsw8Ovk7bKCLe4sjXMbZFqGFcLHpZ89w=="],"imurmurhash": ["[email protected]", "", {}, "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA=="],diff --git a/infra/stacks/image-proxy-service/Pulumi.dev.yaml b/infra/stacks/image-proxy-service/Pulumi.dev.yamlnew file mode 100644index 0000000000..d2433ab189--- /dev/null+++ b/infra/stacks/image-proxy-service/Pulumi.dev.yaml@@ -0,0 +1,6 @@+config:+ aws-native:region: us-east-1+ aws:region: us-east-1+ image-proxy-service:jwt_secret_key: fusionauth-jwt-secret-dev+ image-proxy-service:fusionauth_client_id: fusionauth-client-id-key-dev+ image-proxy-service:fusionauth_issuer: fusionauth-dev.macro.comdiff --git a/infra/stacks/image-proxy-service/Pulumi.prod.yaml b/infra/stacks/image-proxy-service/Pulumi.prod.yamlnew file mode 100644index 0000000000..4c99a987eb--- /dev/null+++ b/infra/stacks/image-proxy-service/Pulumi.prod.yaml@@ -0,0 +1,6 @@+config:+ aws-native:region: us-east-1+ aws:region: us-east-1+ image-proxy-service:jwt_secret_key: fusionauth-jwt-secret-prod+ image-proxy-service:fusionauth_client_id: fusionauth-client-id-key-prod+ image-proxy-service:fusionauth_issuer: auth.macro.comdiff --git a/infra/stacks/image-proxy-service/Pulumi.yaml b/infra/stacks/image-proxy-service/Pulumi.yamlnew file mode 100644index 0000000000..35473f7dc6--- /dev/null+++ b/infra/stacks/image-proxy-service/Pulumi.yaml@@ -0,0 +1,3 @@+name: image-proxy-service+runtime: nodejs+description: Image Proxy Servicediff --git a/infra/stacks/image-proxy-service/image-proxy-service.ts b/infra/stacks/image-proxy-service/image-proxy-service.tsnew file mode 100644index 0000000000..06992dce3c--- /dev/null+++ b/infra/stacks/image-proxy-service/image-proxy-service.ts@@ -0,0 +1,517 @@+import * as aws from '@pulumi/aws';+import * as awsx from '@pulumi/awsx';+import * as pulumi from '@pulumi/pulumi';+import {+ DATADOG_API_KEY,+ datadogAgentContainer,+ fargateLogRouterSidecarContainer,+ serviceLoadBalancer,+} from '../../packages/resources';+import { EcrImage } from '../../packages/service';+import {+ BASE_DOMAIN,+ CLOUD_TRAIL_SNS_TOPIC_ARN,+ stack,+} from '../../packages/shared';++const BASE_NAME = 'image-proxy-service';+const BASE_PATH = '../../../rust/cloud-storage';++export const SERVICE_DOMAIN_NAME = `image-proxy${+ stack === 'prod' ? '' : `-${stack}`+}.${BASE_DOMAIN}`;++type CreateImageProxyServiceArgs = {+ cloudStorageClusterName: pulumi.Output<string> | string;+ ecsClusterArn: pulumi.Output<string> | string;+ vpc: {+ vpcId: pulumi.Output<string> | string;+ publicSubnetIds: pulumi.Output<string[]> | string[];+ privateSubnetIds: pulumi.Output<string[]> | string[];+ };+ platform: { family: string; architecture: 'amd64' | 'arm64' };+ serviceContainerPort: number;+ isPrivate?: boolean;+ containerEnvVars?: { name: string; value: pulumi.Output<string> | string }[];+ healthCheckPath: string;+ secretKeyArns: (pulumi.Output<string> | string)[];+ tags: { [key: string]: string };+};++export class ImageProxyService extends pulumi.ComponentResource {+ public ecr: awsx.ecr.Repository;+ public serviceAlbSg: aws.ec2.SecurityGroup;+ public serviceSg: aws.ec2.SecurityGroup;+ public targetGroup: aws.lb.TargetGroup;+ public lb: aws.lb.LoadBalancer;+ public listener: aws.lb.Listener;+ public service: awsx.ecs.FargateService;+ public domain: string;+ public cloudStorageClusterName: pulumi.Output<string> | string;+ public tags: { [key: string]: string };+ public role: aws.iam.Role;++ constructor(+ name: string,+ {+ ecsClusterArn,+ vpc,+ platform,+ serviceContainerPort,+ healthCheckPath,+ isPrivate,+ containerEnvVars,+ cloudStorageClusterName,+ secretKeyArns,+ tags,+ }: CreateImageProxyServiceArgs,+ opts?: pulumi.ComponentResourceOptions+ ) {+ super('my:components:ImageProxyService', name, {}, opts);+ this.tags = tags;++ this.cloudStorageClusterName = cloudStorageClusterName;++ // ecr image+ const image = new EcrImage(+ `${BASE_NAME}-ecr-image-${stack}`,+ {+ repositoryId: `${BASE_NAME}-ecr-${stack}`,+ repositoryName: `${BASE_NAME}-${stack}`,+ imageId: `${BASE_NAME}-image-${stack}`,+ imagePath: BASE_PATH,+ dockerfile: 'Dockerfile',+ platform,+ buildArgs: {+ SERVICE_NAME: 'image_proxy_service',+ },+ tags: this.tags,+ },+ { parent: this }+ );+ this.ecr = image.ecr;++ // sg+ const sg = this.initializeSecurityGroups({+ vpcId: vpc.vpcId,+ serviceContainerPort,+ });+ this.serviceAlbSg = sg.serviceAlbSg;+ this.serviceSg = sg.serviceSg;++ // lb+ const { targetGroup, lb, listener } = serviceLoadBalancer(this, {+ serviceName: BASE_NAME,+ serviceContainerPort,+ healthCheckPath,+ vpc,+ albSecurityGroupId: this.serviceAlbSg.id,+ isPrivate,+ tags,+ idleTimeout: 3600,+ });+ this.targetGroup = targetGroup;+ this.lb = lb;+ this.listener = listener;++ this.role = new aws.iam.Role(+ `${BASE_NAME}-role`,+ {+ name: `${BASE_NAME}-role-${stack}`,+ assumeRolePolicy: {+ Version: '2012-10-17',+ Statement: [+ {+ Action: 'sts:AssumeRole',+ Principal: {+ Service: 'ecs-tasks.amazonaws.com',+ },+ Effect: 'Allow',+ Sid: '',+ },+ ],+ },+ managedPolicyArns: [],+ tags: this.tags,+ },+ { parent: this }+ );++ // Secrets Manager access for JWT validation+ const secretsPolicy = new aws.iam.Policy(+ `${BASE_NAME}-secrets-policy`,+ {+ policy: {+ Version: '2012-10-17',+ Statement: [+ {+ Action: ['secretsmanager:GetSecretValue'],+ Resource: [...secretKeyArns],+ Effect: 'Allow',+ },+ ],+ },+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.iam.RolePolicyAttachment(+ `${BASE_NAME}-secrets-policy-attachment`,+ {+ role: this.role.name,+ policyArn: secretsPolicy.arn,+ },+ { parent: this }+ );++ // service+ const service = new awsx.ecs.FargateService(+ `${BASE_NAME}`,+ {+ tags,+ cluster: ecsClusterArn,+ networkConfiguration: {+ subnets: vpc.privateSubnetIds,+ securityGroups: [this.serviceSg.id],+ },+ taskDefinitionArgs: {+ taskRole: {+ roleArn: this.role.arn,+ },+ containers: {+ log_router: fargateLogRouterSidecarContainer,+ datadog_agent: datadogAgentContainer,+ service: {+ name: BASE_NAME,+ image: image.image.imageUri,+ stopTimeout: 10,+ cpu: 512,+ memory: 1024,+ environment: containerEnvVars,+ logConfiguration: {+ logDriver: 'awsfirelens',+ options: {+ Name: 'datadog',+ Host: 'http-intake.logs.us5.datadoghq.com',+ apikey: DATADOG_API_KEY,+ dd_service: 'image-proxy-service',+ dd_source: 'fargate',+ dd_tags: `project:image-proxy-service, env:${stack}`,+ provider: 'ecs',+ },+ },+ portMappings: [+ {+ appProtocol: 'http',+ name: `${BASE_NAME}-tcp-${stack}`,+ hostPort: serviceContainerPort,+ containerPort: serviceContainerPort,+ targetGroup,+ },+ ],+ },+ },+ runtimePlatform: {+ operatingSystemFamily: `${platform.family.toUpperCase()}`,+ cpuArchitecture: `${+ platform.architecture === 'amd64'+ ? 'X86_64'+ : platform.architecture.toUpperCase()+ }`,+ },+ },+ desiredCount: 1,+ },+ { parent: this }+ );++ this.service = service;++ this.setupAutoScaling();++ this.setupServiceAlarms();++ // domain record+ const zone = aws.route53.getZoneOutput({ name: BASE_DOMAIN });++ new aws.route53.Record(+ `${BASE_NAME}-domain-record`,+ {+ name: `${SERVICE_DOMAIN_NAME}`,+ type: 'A',+ zoneId: zone.zoneId,+ aliases: [+ {+ evaluateTargetHealth: false,+ name: this.lb.dnsName,+ zoneId: this.lb.zoneId,+ },+ ],+ },+ { parent: this }+ );++ this.domain = `https://${SERVICE_DOMAIN_NAME}`;+ }++ initializeSecurityGroups({+ vpcId,+ serviceContainerPort,+ }: {+ vpcId: pulumi.Output<string> | string;+ serviceContainerPort: number;+ }) {+ const serviceAlbSg = new aws.ec2.SecurityGroup(+ `${BASE_NAME}-alb-sg-${stack}`,+ {+ name: `${BASE_NAME}-alb-sg-${stack}`,+ description: `${BASE_NAME} application load balancer security group`,+ vpcId,+ tags: this.tags,+ },+ { parent: this }+ );++ const serviceSg = new aws.ec2.SecurityGroup(+ `${BASE_NAME}-sg-${stack}`,+ {+ name: `${BASE_NAME}-sg-${stack}`,+ vpcId,+ description: `${BASE_NAME} security group that is attached directly to the service`,+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.vpc.SecurityGroupIngressRule(+ `${BASE_NAME}-alb-in`,+ {+ securityGroupId: serviceSg.id,+ description: 'Allow inbound traffic from the services ALB',+ referencedSecurityGroupId: serviceAlbSg.id,+ fromPort: serviceContainerPort,+ toPort: serviceContainerPort,+ ipProtocol: 'tcp',+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.vpc.SecurityGroupEgressRule(+ `${BASE_NAME}-all-out`,+ {+ securityGroupId: serviceSg.id,+ description: 'Allow all outbound',+ cidrIpv4: '0.0.0.0/0',+ ipProtocol: '-1',+ tags: this.tags,+ },+ { parent: this }+ );++ // ALB SG rules+ new aws.vpc.SecurityGroupIngressRule(+ `${BASE_NAME}-http`,+ {+ securityGroupId: serviceAlbSg.id,+ description: 'Allow inbound HTTP traffic',+ cidrIpv4: '0.0.0.0/0',+ fromPort: 80,+ ipProtocol: 'tcp',+ toPort: 80,+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.vpc.SecurityGroupIngressRule(+ `${BASE_NAME}-https`,+ {+ securityGroupId: serviceAlbSg.id,+ description: 'Allow inbound HTTPS traffic',+ cidrIpv4: '0.0.0.0/0',+ fromPort: 443,+ ipProtocol: 'tcp',+ toPort: 443,+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.vpc.SecurityGroupEgressRule(+ `${BASE_NAME}-out-service`,+ {+ description: 'Allow traffic to the service security group',+ securityGroupId: serviceAlbSg.id,+ referencedSecurityGroupId: serviceSg.id,+ fromPort: serviceContainerPort,+ ipProtocol: 'tcp',+ toPort: serviceContainerPort,+ tags: this.tags,+ },+ { parent: this }+ );++ return { serviceAlbSg, serviceSg };+ }++ setupAutoScaling() {+ if (!this.service) return;++ const serviceScalableTarget = new aws.appautoscaling.Target(+ `${BASE_NAME}-service-scalable-target-${stack}`,+ {+ maxCapacity: stack === 'prod' ? 15 : 3,+ minCapacity: 1,+ resourceId: pulumi.interpolate`service/${this.cloudStorageClusterName}/${this.service.service.name}`,+ scalableDimension: 'ecs:service:DesiredCount',+ serviceNamespace: 'ecs',+ tags: this.tags,+ },+ { 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}`;++ new aws.appautoscaling.Policy(+ `${BASE_NAME}-scaling-policy-request-count-${stack}`,+ {+ policyType: 'TargetTrackingScaling',+ resourceId: serviceScalableTarget.resourceId,+ scalableDimension: serviceScalableTarget.scalableDimension,+ serviceNamespace: serviceScalableTarget.serviceNamespace,+ targetTrackingScalingPolicyConfiguration: {+ targetValue: 1000,+ predefinedMetricSpecification: {+ predefinedMetricType: 'ALBRequestCountPerTarget',+ resourceLabel,+ },+ scaleInCooldown: 60,+ scaleOutCooldown: 120,+ },+ },+ { parent: this }+ );++ new aws.appautoscaling.Policy(+ `${BASE_NAME}-scaling-policy-cpu-${stack}`,+ {+ policyType: 'TargetTrackingScaling',+ resourceId: serviceScalableTarget.resourceId,+ scalableDimension: serviceScalableTarget.scalableDimension,+ serviceNamespace: serviceScalableTarget.serviceNamespace,+ targetTrackingScalingPolicyConfiguration: {+ targetValue: 70.0,+ predefinedMetricSpecification: {+ predefinedMetricType: 'ECSServiceAverageCPUUtilization',+ },+ scaleInCooldown: 100,+ scaleOutCooldown: 300,+ },+ },+ { parent: this }+ );++ new aws.appautoscaling.Policy(+ `${BASE_NAME}-scaling-policy-memory-${stack}`,+ {+ policyType: 'TargetTrackingScaling',+ resourceId: serviceScalableTarget.resourceId,+ scalableDimension: serviceScalableTarget.scalableDimension,+ serviceNamespace: serviceScalableTarget.serviceNamespace,+ targetTrackingScalingPolicyConfiguration: {+ targetValue: 70.0,+ predefinedMetricSpecification: {+ predefinedMetricType: 'ECSServiceAverageMemoryUtilization',+ },+ scaleInCooldown: 100,+ scaleOutCooldown: 300,+ },+ },+ { parent: this }+ );+ }++ setupServiceAlarms() {+ new aws.cloudwatch.MetricAlarm(+ `${BASE_NAME}-high-cpu-alarm`,+ {+ name: `${BASE_NAME}-high-cpu-alarm-${stack}`,+ metricName: 'CPUUtilization',+ namespace: 'AWS/ECS',+ statistic: 'Average',+ period: 180,+ evaluationPeriods: 1,+ threshold: 80,+ comparisonOperator: 'GreaterThanThreshold',+ dimensions: {+ ClusterName: this.cloudStorageClusterName,+ ServiceName: this.service.service.name,+ },+ alarmDescription: `High CPU usage alarm for ${BASE_NAME} service.`,+ actionsEnabled: true,+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.cloudwatch.MetricAlarm(+ `${BASE_NAME}-high-mem-alarm`,+ {+ name: `${BASE_NAME}-high-mem-alarm-${stack}`,+ metricName: 'MemoryUtilization',+ namespace: 'AWS/ECS',+ statistic: 'Average',+ period: 180,+ evaluationPeriods: 1,+ threshold: 80,+ comparisonOperator: 'GreaterThanThreshold',+ dimensions: {+ ClusterName: this.cloudStorageClusterName,+ ServiceName: this.service.service.name,+ },+ alarmDescription: `High Memory usage alarm for ${BASE_NAME} service.`,+ actionsEnabled: true,+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],+ tags: this.tags,+ },+ { parent: this }+ );++ new aws.cloudwatch.MetricAlarm(+ `${BASE_NAME}-http-5xx-alarm`,+ {+ name: `${BASE_NAME}-http-5xx-${stack}`,+ metricName: 'HTTPCode_ELB_5XX_Count',+ namespace: 'AWS/ApplicationELB',+ statistic: 'Sum',+ period: 180,+ evaluationPeriods: 1,+ threshold: 25,+ comparisonOperator: 'GreaterThanOrEqualToThreshold',+ dimensions: {+ LoadBalancer: this.lb.arn,+ },+ alarmDescription: `High HTTP 5XX count alarm for ${BASE_NAME} Load Balancer.`,+ actionsEnabled: true,+ alarmActions: [CLOUD_TRAIL_SNS_TOPIC_ARN],+ tags: this.tags,+ },+ { parent: this }+ );+ }+}diff --git a/infra/stacks/image-proxy-service/index.ts b/infra/stacks/image-proxy-service/index.tsnew file mode 100644index 0000000000..173306dfd0--- /dev/null+++ b/infra/stacks/image-proxy-service/index.ts@@ -0,0 +1,109 @@+import * as aws from '@pulumi/aws';+import * as pulumi from '@pulumi/pulumi';+import { config, getMacroApiToken, stack } from '../../packages/shared';+import { get_coparse_api_vpc } from '../../packages/vpc';+import { ImageProxyService } from './image-proxy-service';++const tags = {+ environment: stack,+ tech_lead: 'hutch',+ project: 'image-proxy-service',+};++export const coparse_api_vpc = get_coparse_api_vpc();++const cloudStorageStack = new pulumi.StackReference('cloud-storage-stack', {+ name: `macro-inc/document-storage/${stack}`,+});++const cloudStorageClusterArn: pulumi.Output<string> = cloudStorageStack+ .getOutput('cloudStorageClusterArn')+ .apply((arn) => arn as string);++const cloudStorageClusterName: pulumi.Output<string> = cloudStorageStack+ .getOutput('cloudStorageClusterName')+ .apply((arn) => arn as string);++// JWT secrets+const JWT_SECRET_KEY = config.require(`jwt_secret_key`);+const jwtSecretKeyArn: pulumi.Output<string> = aws.secretsmanager+ .getSecretVersionOutput({ secretId: JWT_SECRET_KEY })+ .apply((secret) => secret.arn);++const fusionauthClientIdSecretKey = config.require(`fusionauth_client_id`);+const FUSIONAUTH_CLIENT_ID = aws.secretsmanager+ .getSecretVersionOutput({+ secretId: fusionauthClientIdSecretKey,+ })+ .apply((secret) => secret.secretString);+const FUSIONAUTH_ISSUER = config.require(`fusionauth_issuer`);++const MACRO_API_TOKENS = getMacroApiToken();++const secretKeyArns = [+ pulumi.interpolate`${jwtSecretKeyArn}`,+ pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenPublicKeyArn}`,+];++const imageProxyService = new ImageProxyService(+ `image-proxy-service-${stack}`,+ {+ ecsClusterArn: cloudStorageClusterArn,+ cloudStorageClusterName: cloudStorageClusterName,+ vpc: coparse_api_vpc,+ platform: {+ family: 'linux',+ architecture: 'amd64',+ },+ serviceContainerPort: 8080,+ healthCheckPath: '/health',+ secretKeyArns,+ containerEnvVars: [+ {+ name: 'ENVIRONMENT',+ value: stack,+ },+ {+ name: 'RUST_LOG',+ value: `image_proxy_service=${+ stack === 'prod' ? 'debug' : 'trace'+ },tower_http=debug`,+ },+ {+ name: 'JWT_SECRET_KEY',+ value: pulumi.interpolate`${JWT_SECRET_KEY}`,+ },+ {+ name: 'AUDIENCE',+ value: pulumi.interpolate`${FUSIONAUTH_CLIENT_ID}`,+ },+ {+ name: 'ISSUER',+ value: pulumi.interpolate`${FUSIONAUTH_ISSUER}`,+ },+ {+ name: 'MACRO_API_TOKEN_ISSUER',+ value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenIssuer}`,+ },+ {+ name: 'MACRO_API_TOKEN_PUBLIC_KEY',+ value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenPublicKey}`,+ },+ // OpenTelemetry / Datadog tracing configuration+ {+ name: 'DD_SERVICE',+ value: 'image-proxy-service',+ },+ {+ name: 'DD_ENV',+ value: stack,+ },+ ],+ isPrivate: false,+ tags,+ }+);++export const imageProxyServiceSgId = imageProxyService.serviceSg.id;+export const imageProxyServiceAlbSgId = imageProxyService.serviceAlbSg.id;+export const imageProxyServiceUrl = pulumi.interpolate`${imageProxyService.domain}`;diff --git a/infra/stacks/image-proxy-service/package.json b/infra/stacks/image-proxy-service/package.jsonnew file mode 100644index 0000000000..7627a663d1--- /dev/null+++ b/infra/stacks/image-proxy-service/package.json@@ -0,0 +1,6 @@+{+ "name": "image-proxy-service-stack",+ "version": "0.0.0",+ "private": true,+ "license": "MIT"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex eb02009f04..cd3d723cca 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -4860,6 +4860,33 @@ dependencies = ["quick-error",]+[[package]]+name = "image_proxy_service"+version = "0.1.0"+dependencies = [+ "anyhow",+ "aws-sdk-secretsmanager",+ "axum",+ "http-body-util",+ "macro_auth",+ "macro_aws_config",+ "macro_cors",+ "macro_entrypoint",+ "macro_env",+ "macro_middleware",+ "model",+ "reqwest",+ "secretsmanager_client",+ "serde",+ "serde_json",+ "tokio",+ "tower 0.5.2",+ "tower-http",+ "tracing",+ "utoipa",+ "utoipa-swagger-ui",+]+[[package]]name = "imgref"version = "1.11.0"diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex c1cc29c330..c2bebd0f36 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -46,6 +46,7 @@ members = ["fusionauth","github","gmail_client",+ "image_proxy_service","integration_tests/*","lambda_client","lexical_client",diff --git a/rust/cloud-storage/Dockerfile.dev b/rust/cloud-storage/Dockerfile.devindex c50e3540e8..f33afffbc8 100644--- a/rust/cloud-storage/Dockerfile.dev+++ b/rust/cloud-storage/Dockerfile.dev@@ -20,6 +20,7 @@ RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=shared \--bin notification_service \--bin static_file_service \--bin unfurl_service \+ --bin image_proxy_service \&& mkdir -p /app/out \&& cp /app/target/debug/authentication_service /app/out/ \&& cp /app/target/debug/connection_gateway_service /app/out/ \@@ -29,7 +30,8 @@ RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=shared \&& cp /app/target/debug/email_service /app/out/ \&& cp /app/target/debug/notification_service /app/out/ \&& cp /app/target/debug/static_file_service /app/out/ \- && cp /app/target/debug/unfurl_service /app/out/+ && cp /app/target/debug/unfurl_service /app/out/ \+ && cp /app/target/debug/image_proxy_service /app/out/# Base runtime imageFROM debian:trixie-slim AS base@@ -85,3 +87,8 @@ FROM base AS unfurl_serviceCOPY --from=builder /app/out/unfurl_service /app/svcRUN chmod +x /app/svcENTRYPOINT ["dumb-init", "./svc"]++FROM base AS image_proxy_service+COPY --from=builder /app/out/image_proxy_service /app/svc+RUN chmod +x /app/svc+ENTRYPOINT ["dumb-init", "./svc"]diff --git a/rust/cloud-storage/image_proxy_service/Cargo.toml b/rust/cloud-storage/image_proxy_service/Cargo.tomlnew file mode 100644index 0000000000..5dd74e5af1--- /dev/null+++ b/rust/cloud-storage/image_proxy_service/Cargo.toml@@ -0,0 +1,42 @@+[package]+edition = "2024"+name = "image_proxy_service"+publish = false+version = "0.1.0"+default-run = "image_proxy_service"++[[bin]]+name = "image_proxy_service"+path = "src/main.rs"++[[bin]]+name = "image_proxy_service_openapi"+path = "src/openapi.rs"++[dependencies]+anyhow = { workspace = true }+aws-sdk-secretsmanager = { workspace = true }+axum = { workspace = true, features = ["macros"] }+macro_auth = { path = "../macro_auth" }+macro_aws_config = { path = "../macro_aws_config" }+macro_cors = { path = "../macro_cors" }+macro_entrypoint = { path = "../macro_entrypoint" }+macro_env = { path = "../macro_env" }+macro_middleware = { path = "../macro_middleware", default-features = false, features = [+ "auth",+ "tracking",+] }+model = { path = "../model" }+reqwest = { workspace = true, features = ["stream"] }+secretsmanager_client = { path = "../secretsmanager_client" }+serde = { workspace = true }+serde_json = { workspace = true }+tokio = { workspace = true }+tower = { workspace = true }+tower-http = { workspace = true }+tracing = { workspace = true }+utoipa = { workspace = true, features = ["axum_extras", "chrono", "uuid"] }+utoipa-swagger-ui = { workspace = true, features = ["axum"] }++[dev-dependencies]+http-body-util = { workspace = true }diff --git a/rust/cloud-storage/image_proxy_service/src/api/context.rs b/rust/cloud-storage/image_proxy_service/src/api/context.rsnew file mode 100644index 0000000000..a93d913171--- /dev/null+++ b/rust/cloud-storage/image_proxy_service/src/api/context.rs@@ -0,0 +1,10 @@+use axum::extract::FromRef;+use macro_auth::middleware::decode_jwt::JwtValidationArgs;+use macro_env::Environment;++#[derive(Clone, FromRef)]+pub struct ApiContext {+ pub jwt_args: JwtValidationArgs,+ pub environment: Environment,+ pub http_client: reqwest::Client,+}diff --git a/rust/cloud-storage/image_proxy_service/src/api/health/mod.rs b/rust/cloud-storage/image_proxy_service/src/api/health/mod.rsnew file mode 100644index 0000000000..89c9fb2e43--- /dev/null+++ b/rust/cloud-storage/image_proxy_service/src/api/health/mod.rs@@ -0,0 +1,21 @@+use axum::{Json, Router, http::StatusCode, response::IntoResponse, routing::get};+use model::response::EmptyResponse;++/// Health check+#[utoipa::path(+ get,+ path = "/health",+ responses(+ (status = 200, description = "health", body = EmptyResponse),+ )+)]+pub async fn health_handler() -> impl IntoResponse {+ (StatusCode::OK, Json(EmptyResponse::default()))+}++pub fn router() -> Router {+ Router::new().route("/health", get(health_handler))+}++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/image_proxy_service/src/api/health/test.rs b/rust/cloud-storage/image_proxy_service/src/api/health/test.rsnew file mode 100644index 0000000000..5e362ff40d--- /dev/null+++ b/rust/cloud-storage/image_proxy_service/src/api/health/test.rs@@ -0,0 +1,26 @@+use super::*;+use axum::{+ body::Body,+ http::{Request, StatusCode},+};+#[allow(unused_imports)]+use http_body_util::BodyExt;+use tower::ServiceExt;++#[tokio::test]+async fn test_health_check() {+ let api = router();++ let response = api+ .oneshot(+ Request::builder()+ .uri("/health")+ .method("GET")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+}diff --git a/rust/cloud-storage/image_proxy_service/src/api/mod.rs b/rust/cloud-storage/image_proxy_service/src/api/mod.rsnew file mode 100644index 0000000000..50f723eddc--- /dev/null+++ b/rust/cloud-storage/image_proxy_service/src/api/mod.rs@@ -0,0 +1,54 @@+use crate::api::context::ApiContext;+use anyhow::Context;+use axum::Router;+use tower::ServiceBuilder;+use tower_http::trace::TraceLayer;+use utoipa::OpenApi;+use utoipa_swagger_ui::SwaggerUi;++pub mod context;+mod health;+mod proxy;+pub(crate) mod swagger;++pub async fn setup_and_serve(state: ApiContext, port: usize) -> anyhow::Result<()> {+ let cors = macro_cors::cors_layer();++ let env = state.environment;+ let app = api_router(state.clone())+ .with_state(state)+ .layer(ServiceBuilder::new().layer(TraceLayer::new_for_http()))+ .merge(health::router())+ .layer(cors)+ .merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", swagger::ApiDoc::openapi()));++ let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port))+ .await+ .unwrap();++ tracing::info!(+ "\n🖼️ image_proxy_service 🖼️\nenvironment {:?}\nport: {}",+ &env,+ &port+ );++ axum::serve(listener, app.into_make_service())+ .await+ .context("error starting service")+}++fn api_router(state: ApiContext) -> Router<ApiContext> {+ Router::new().nest(+ "/proxy",+ proxy::router().layer(+ ServiceBuilder::new()+ .layer(axum::middleware::from_fn(+ macro_middleware::tracking::attach_ip_context_handler,+ ))+ .layer(axum::middleware::from_fn_with_state(+ state.jwt_args.clone(),+ macro_middleware::auth::decode_jwt::handler,+ )),+ ),+ )+}diff --git a/rust/cloud-storage/image_proxy_service/src/api/proxy/mod.rs b/rust/cloud-storage/image_proxy_service/src/api/proxy/mod.rsnew file mode 100644index 0000000000..1cfd5e7124--- /dev/null+++ b/rust/cloud-storage/image_proxy_service/src/api/proxy/mod.rs@@ -0,0 +1,61 @@+use axum::Router;+use axum::body::Body;+use axum::extract::{Query, State};+use axum::response::{IntoResponse, Response};+use axum::routing::get;+use reqwest::StatusCode;+use serde::Deserialize;+use utoipa::ToSchema;++#[derive(Debug, ToSchema, Deserialize)]+pub struct ProxyParams {+ pub url: String,+}++#[utoipa::path(+ get,+ path = "/proxy",+ params(("url" = String, Query, description = "The image url to proxy")),+)]+#[tracing::instrument(err(Debug), skip(http_client))]+pub async fn proxy_request_handler(+ Query(params): Query<ProxyParams>,+ State(http_client): State<reqwest::Client>,+) -> Result<impl IntoResponse, impl IntoResponse> {+ let response = http_client+ .get(¶ms.url)+ .send()+ .await+ .map_err(|err| (StatusCode::BAD_REQUEST, err.to_string()))?;++ if !response.status().is_success() {+ return Err((+ StatusCode::BAD_GATEWAY,+ format!("upstream returned status {}", response.status()),+ ));+ }++ let content_type = response+ .headers()+ .get(reqwest::header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .unwrap_or("application/octet-stream")+ .to_string();++ Response::builder()+ .header("Content-Type", content_type)+ .header("Cache-Control", "public, max-age=31536000, immutable")+ .header("Cross-Origin-Resource-Policy", "cross-origin")+ .body(Body::from_stream(response.bytes_stream()))+ .map_err(|e| {+ tracing::error!(error=?e, "could not stream chunks");+ (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())+ })+}++pub fn router() -> Router<crate::api::context::ApiContext> {+ Router::new().route("/", get(proxy_request_handler))+}++#[cfg(test)]+mod test;diff --git a/rust/cloud-storage/image_proxy_service/src/api/proxy/test.rs b/rust/cloud-storage/image_proxy_service/src/api/proxy/test.rsnew file mode 100644index 0000000000..c1d80956b7--- /dev/null+++ b/rust/cloud-storage/image_proxy_service/src/api/proxy/test.rs@@ -0,0 +1,8 @@+use super::*;++#[test]+fn test_proxy_params_deserialization() {+ let params: ProxyParams =+ serde_json::from_str(r#"{"url":"https://example.com/image.png"}"#).unwrap();+ assert_eq!(params.url, "https://example.com/image.png");+}diff --git a/rust/cloud-storage/image_proxy_service/src/api/swagger.rs b/rust/cloud-storage/image_proxy_service/src/api/swagger.rsnew file mode 100644index 0000000000..629be0437e--- /dev/null+++ b/rust/cloud-storage/image_proxy_service/src/api/swagger.rs@@ -0,0 +1,27 @@+use model::response::{EmptyResponse, ErrorResponse};+use utoipa::OpenApi;++use super::health;+use super::proxy::{self, ProxyParams};++#[derive(OpenApi)]+#[openapi(+ info(+ terms_of_service = "https://macro.com/terms",+ ),+ paths(+ health::health_handler,+ proxy::proxy_request_handler,+ ),+ components(+ schemas(+ EmptyResponse,+ ErrorResponse,+ ProxyParams,+ ),+ ),+ tags(+ (name = "macro image proxy service", description = "Image Proxy Service")+ )+)]+pub struct ApiDoc;diff --git a/rust/cloud-storage/image_proxy_service/src/config.rs b/rust/cloud-storage/image_proxy_service/src/config.rsnew file mode 100644index 0000000000..8a63fcc0f0--- /dev/null+++ b/rust/cloud-storage/image_proxy_service/src/config.rs@@ -0,0 +1,22 @@+pub use macro_env::Environment;++/// The configuration parameters for the application.+#[derive(Debug)]+pub struct Config {+ /// The port to listen on+ pub port: usize,+ /// The environment we are in+ pub environment: Environment,+}++impl Config {+ pub fn from_env() -> anyhow::Result<Self> {+ let port: usize = std::env::var("PORT")+ .unwrap_or("8080".to_string())+ .parse::<usize>()+ .unwrap();+ let environment = Environment::new_or_prod();++ Ok(Config { port, environment })+ }+}diff --git a/rust/cloud-storage/image_proxy_service/src/main.rs b/rust/cloud-storage/image_proxy_service/src/main.rsnew file mode 100644index 0000000000..ac367b5291--- /dev/null+++ b/rust/cloud-storage/image_proxy_service/src/main.rs@@ -0,0 +1,35 @@+mod api;+mod config;++use anyhow::Context;+use config::Config;+use macro_auth::middleware::decode_jwt::JwtValidationArgs;+use macro_entrypoint::MacroEntrypoint;++#[tokio::main]+async fn main() -> anyhow::Result<()> {+ MacroEntrypoint::default().init();++ let config = Config::from_env().context("expected to be able to generate config")?;++ tracing::trace!("initialized config");++ let secretsmanager_client = secretsmanager_client::SecretsManager::new(+ aws_sdk_secretsmanager::Client::new(¯o_aws_config::get_macro_aws_config().await),+ );++ let jwt_args =+ JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client)+ .await?;++ let http_client = reqwest::Client::new();++ let state = api::context::ApiContext {+ jwt_args,+ environment: config.environment,+ http_client,+ };++ api::setup_and_serve(state, config.port).await?;+ Ok(())+}diff --git a/rust/cloud-storage/image_proxy_service/src/openapi.rs b/rust/cloud-storage/image_proxy_service/src/openapi.rsnew file mode 100644index 0000000000..faf5b1c433--- /dev/null+++ b/rust/cloud-storage/image_proxy_service/src/openapi.rs@@ -0,0 +1,13 @@+#![allow(unused)]++mod api;+mod config;++use utoipa::OpenApi;++fn main() {+ println!(+ "{}",+ api::swagger::ApiDoc::openapi().to_pretty_json().unwrap()+ );+}