AWSTemplateFormatVersion: "2010-09-09"

# Redactor on AWS Fargate for Hybrid SaaS buyers. Publish this template to
# versioned S3 for Marketplace Quick Launch. See docs/marketplace/README.md.

Metadata:
  cfn-lint:
    config:
      # Mode-dependent parameters default to ""; Rules enforce them.
      ignore_checks: [W1030]
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label: {default: "Required: container images"}
        Parameters: [AppImage, PresidioImage]
      - Label: {default: "Required: AWS Marketplace license & Quick Launch enrollment"}
        Parameters: [LicenseControlPlaneUrl, LicenseAllowedHosts, LicensePublicKeysJson, LicenseEnvironment, LicenseRenewInterval, EnrollmentSecretArn]
      - Label: {default: "Required: network"}
        Parameters: [VpcId, SubnetIds, LoadBalancerScheme, ControlAllowedCidr, DataAllowedCidr, AssignPublicIp]
      - Label: {default: "Sign-in (Cognito by default; AdminEmail is required for it)"}
        Parameters: [AuthMode, AdminEmail, SessionTimeout, IdpEgressCidr]
      - Label: {default: "Optional: your own OIDC provider (AuthMode=Oidc only)"}
        Parameters: [OidcIssuer, OidcAuthorizationEndpoint, OidcTokenEndpoint, OidcUserInfoEndpoint, OidcClientId, OidcClientSecretArn, OidcScope, OidcRoleClaim, OidcAdminValues, OidcViewerValues]
      - Label: {default: "Optional: your own certificate and host name (empty = self-signed for the load balancer name)"}
        Parameters: [CertificateArn, EndpointHostname]
      - Label: {default: "Optional: your own database and retained keys (empty = create)"}
        Parameters: [DatabaseMode, DbInstanceClass, DbEngineVersion, DbAllocatedStorage, OwnerDsnSecretArn, RuntimeDsnSecretArn, TokenKeySecretArn, ContentHmacKeySecretArn, AdmissionKeySecretArn]
      - Label: {default: "Optional: where redacted output goes (default = a new S3 bucket)"}
        Parameters: [Destination, DestinationTarget, WebhookAuthSecretArn]
      - Label: {default: "Optional: read input files from an S3 bucket"}
        Parameters: [InputSource, InputPipeline]
      - Label: {default: "Optional: tuning, optional AWS detectors/OCR and private networking"}
        Parameters: [TaskSubnetIds, DurableAdmission, DurableDelivery, RequireIngestKey, EnableComprehendMedical, ComprehendRegion, SageMakerEndpointName, PdfOcrMode, TaskCpu, TaskMemory, LogRetentionDays]

Parameters:
  AppImage:
    Type: String
    Default: '709825985650.dkr.ecr.us-east-1.amazonaws.com/software-sushi/softwaresushi/redactor@sha256:27a305ecaec8373efc16181c1116631b458b35b12a33f2c493c32b315d92c33b'
    Description: Redactor service image, pinned by digest (…/redactor@sha256:…).
    AllowedPattern: ".+@sha256:[0-9a-f]{64}"
  PresidioImage:
    Type: String
    Default: '709825985650.dkr.ecr.us-east-1.amazonaws.com/software-sushi/softwaresushi/redactor-presidio-analyzer@sha256:f68c00fd349f8d693b84cd483be53ab895779fb809bdf11a90f20689545c4dff'
    Description: Analyzer image, pinned by digest (…/redactor-presidio-analyzer@sha256:…).
    AllowedPattern: ".+@sha256:[0-9a-f]{64}"

  LicenseControlPlaneUrl:
    Type: String
    Default: 'https://licensing.softwaresushi.com'
    Description: HTTPS base URL of the Software Sushi license control plane.
    AllowedPattern: "^https://\\S+$"
  LicenseAllowedHosts:
    Type: String
    Default: 'licensing.softwaresushi.com'
    Description: Comma-separated allowlisted DNS hostnames. Include the hostname of LicenseControlPlaneUrl.
    AllowedPattern: '^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)*[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\s*,\s*(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)*[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$'
  LicensePublicKeysJson:
    Type: String
    Default: '{"d36cd79a-36b7-4ad8-accb-06bb2cf1a060":"-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEcbXncSku2QqzVHYxPpoZ+w6Yh3Da\nR4d2SY52BvZ0Dqehejmfh6xau8kb/eLXBdzKurI4JQ0tF8J7+lYz1v8Gmw==\n-----END PUBLIC KEY-----\n"}'
    Description: Non-empty JSON map of key IDs to pinned KMS ECDSA P-256 verification public keys in SPKI PEM format.
    AllowedPattern: '^\s*\{\s*"[^"]+"\s*:\s*"[\s\S]+"\s*\}\s*$'
    ConstraintDescription: Supply a JSON object with at least one key ID and PEM public key.
  LicenseEnvironment:
    Type: String
    AllowedValues: [prod, nonprod]
    Default: prod
    Description: License slot environment for this deployment.
  LicenseRenewInterval:
    Type: String
    Default: '1h'
    AllowedPattern: "^[0-9]+(m|h)$"
    Description: Signed license renewal cadence, in minutes or hours. Default is hourly.
  EnrollmentSecretArn:
    Type: String
    # AWS Marketplace uses "marketplace-deployment!" in its managed secret names.
    AllowedPattern: '^arn:[a-z0-9-]+:secretsmanager:[a-z0-9-]+:[0-9]{12}:secret:[A-Za-z0-9/!_+=.@-]+$'
    Description: Full Secrets Manager ARN auto-populated by AWS Marketplace Quick Launch parameter EnrollmentSecretArn.

  VpcId:
    Type: AWS::EC2::VPC::Id
  SubnetIds:
    Type: List<AWS::EC2::Subnet::Id>
    Description: At least two subnets in different AZs (ALB, RDS, and tasks unless TaskSubnetIds is set).
  LoadBalancerScheme:
    Type: String
    AllowedValues: [internet-facing, internal]
    Description: internet-facing or internal (VPN/peered only).
  ControlAllowedCidr:
    Type: String
    Description: Operators CIDR for UI/config (port 8080). No default.
    AllowedPattern: "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}/\\d{1,2}$"
  DataAllowedCidr:
    Type: String
    Description: Submitters CIDR for ingest/health (port 8081). No default.
    AllowedPattern: "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}/\\d{1,2}$"
  AssignPublicIp:
    Type: String
    AllowedValues: [ENABLED, DISABLED]
    Default: ENABLED
    Description: ENABLED for public subnets without NAT; DISABLED for private subnets with NAT/endpoints.
  AuthMode:
    Type: String
    AllowedValues: [Cognito, Oidc]
    Default: Cognito
    Description: Cognito creates a user pool and invites AdminEmail; Oidc uses your provider.
  AdminEmail:
    Type: String
    Default: ""
    Description: AuthMode=Cognito. First admin email.
    AllowedPattern: "^$|^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$"
  SessionTimeout:
    Type: Number
    Default: 28800
    MinValue: 300
    MaxValue: 604800
    Description: ALB sign-in session lifetime in seconds (300–604800; default 8h).
  IdpEgressCidr:
    Type: String
    AllowedPattern: "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}/\\d{1,2}$"
    Description: ALB HTTPS (443) egress CIDR to IdP token/user-info endpoints. Specify 0.0.0.0/0 for Amazon Cognito or a public OIDC provider, or a narrower CIDR for a private IdP.
  OidcIssuer:
    Type: String
    Default: ""
    AllowedPattern: "^$|^https://\\S+$"
    Description: AuthMode=Oidc. Exact HTTPS issuer URL.
  OidcAuthorizationEndpoint:
    Type: String
    Default: ""
    AllowedPattern: "^$|^https://\\S+$"
  OidcTokenEndpoint:
    Type: String
    Default: ""
    AllowedPattern: "^$|^https://\\S+$"
  OidcUserInfoEndpoint:
    Type: String
    Default: ""
    AllowedPattern: "^$|^https://\\S+$"
  OidcClientId:
    Type: String
    Default: ""
    MaxLength: 255
  OidcClientSecretArn:
    Type: String
    Default: ""
    AllowedPattern: "^$|^arn:[^:]+:secretsmanager:.+"
    Description: Secrets Manager ARN for the OIDC client secret (resolved by CloudFormation into the listener only).
  OidcScope:
    Type: String
    Default: openid
    AllowedPattern: "^(?=.*(?:^| )openid(?: |$))[A-Za-z0-9._:/ -]{1,256}$"
    Description: Scopes requested by ALB (must include openid).
  OidcRoleClaim:
    Type: String
    Default: groups
    AllowedPattern: "^[A-Za-z0-9_.:/-]{1,128}$"
    Description: User-info claim carrying Redactor role (string or list).
  OidcAdminValues:
    Type: String
    Default: redactor-admins
    Description: Comma-separated admin claim values.
  OidcViewerValues:
    Type: String
    Default: redactor-viewers
    Description: Comma-separated viewer claim values.
  CertificateArn:
    Type: String
    Default: ""
    Description: Optional ACM certificate ARN (empty generates a self-signed cert).
    AllowedPattern: "^$|^arn:[^:]+:acm:.+"
  EndpointHostname:
    Type: String
    Default: ""
    AllowedPattern: "^$|^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$"
    ConstraintDescription: a lowercase DNS host name
    Description: Optional DNS host name aliased to the ALB (covered by CertificateArn).
  DatabaseMode:
    Type: String
    AllowedValues: [Create, Existing]
    Default: Create
    Description: Create an encrypted RDS PostgreSQL DB, or use an existing DB prepared with deploy/sql/01-roles.sql.
  DbInstanceClass:
    Type: String
    Default: db.t4g.micro
  DbEngineVersion:
    Type: String
    Default: "17.11"
    AllowedPattern: "^1[5-9](\\.[0-9]+)?$"
    Description: PostgreSQL engine version for DatabaseMode=Create (tested on PostgreSQL 15-18).
  DbAllocatedStorage:
    Type: Number
    Default: 20
    MinValue: 20
  OwnerDsnSecretArn:
    Type: String
    Default: ""
    Description: DatabaseMode=Existing. Schema-owner DSN secret ARN.
    AllowedPattern: "^$|^arn:[^:]+:secretsmanager:.+"
  RuntimeDsnSecretArn:
    Type: String
    Default: ""
    Description: DatabaseMode=Existing. Runtime-role DSN secret ARN.
    AllowedPattern: "^$|^arn:[^:]+:secretsmanager:.+"
  TokenKeySecretArn:
    Type: String
    Default: ""
    Description: Optional retained token-key secret ARN (for snapshot restore). Empty creates one.
    AllowedPattern: "^$|^arn:[^:]+:secretsmanager:.+"
  ContentHmacKeySecretArn:
    Type: String
    Default: ""
    Description: Optional retained content-HMAC secret ARN (for snapshot restore). Empty creates one.
    AllowedPattern: "^$|^arn:[^:]+:secretsmanager:.+"
  AdmissionKeySecretArn:
    Type: String
    Default: ""
    Description: Optional retained admission-key secret ARN (needed to restore durable-admission DBs). Empty creates one.
    AllowedPattern: "^$|^arn:[^:]+:secretsmanager:.+"
  Destination:
    Type: String
    AllowedValues: [CreatedBucket, ExistingBucket, SqsQueue, SnsTopic, Webhook]
    Default: CreatedBucket
    Description: Default output destination (CreatedBucket, ExistingBucket, SqsQueue, SnsTopic, or Webhook).
  DestinationTarget:
    Type: String
    Default: ""
    Description: Bucket name, SQS queue URL, SNS topic ARN, or HTTPS webhook URL (unused for CreatedBucket).
  WebhookAuthSecretArn:
    Type: String
    Default: ""
    AllowedPattern: "^$|^arn:[^:]+:secretsmanager:.+"
    Description: Webhook only, optional Authorization header secret ARN.
  InputSource:
    Type: String
    AllowedValues: [None, CreatedBucket]
    Default: None
    Description: CreatedBucket creates an S3 input bucket and failure queue.
  InputPipeline:
    Type: String
    Default: default
    AllowedPattern: "^[a-z0-9][a-z0-9-]{0,62}$"
    Description: Pipeline processing S3 input files.
  TaskSubnetIds:
    Type: CommaDelimitedList
    Default: ""
    Description: Optional separate task subnets (empty uses SubnetIds).
  DurableAdmission:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "true"
  DurableDelivery:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "false"
    Description: Opt-in encrypted delivery outbox (requires DurableAdmission=true; buffers post-decision envelopes in PostgreSQL up to 15m).
  RequireIngestKey:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "true"
  EnableComprehendMedical:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "false"
    Description: Enables AWS Comprehend Medical (billed per character; sends text to AWS API).
  ComprehendRegion:
    Type: String
    Default: us-east-1
  SageMakerEndpointName:
    Type: String
    Default: ""
    AllowedPattern: "^$|^[A-Za-z0-9](-*[A-Za-z0-9]){0,62}$"
    Description: Optional Amazon SageMaker NER endpoint name in this AWS region (empty disables; billed by AWS).
  PdfOcrMode:
    Type: String
    AllowedValues: [none, textract]
    Default: none
    Description: Optional OCR for scanned/image-only PDFs (none disables; textract invokes Amazon Textract in this AWS region).
  TaskCpu:
    Type: String
    AllowedValues: ["1024", "2048", "4096"]
    Default: "1024"
  TaskMemory:
    Type: String
    AllowedValues: ["4096", "8192"]
    Default: "4096"
  LogRetentionDays:
    Type: Number
    Default: 90
    AllowedValues: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1096, 1827, 2192, 2557, 2922, 3288, 3653]

Rules:
  ValidFargateCpuMemory:
    RuleCondition: !Equals [!Ref TaskCpu, "4096"]
    Assertions:
      - Assert: !Equals [!Ref TaskMemory, "8192"]
        AssertDescription: 4 vCPU requires 8 GiB of memory on Fargate.
  ExistingDatabaseNeedsDsns:
    RuleCondition: !Equals [!Ref DatabaseMode, Existing]
    Assertions:
      - Assert: !And [!Not [!Equals [!Ref OwnerDsnSecretArn, ""]], !Not [!Equals [!Ref RuntimeDsnSecretArn, ""]]]
        AssertDescription: DatabaseMode=Existing needs OwnerDsnSecretArn and RuntimeDsnSecretArn.
  CognitoNeedsAdminEmail:
    RuleCondition: !Equals [!Ref AuthMode, Cognito]
    Assertions:
      - Assert: !Not [!Equals [!Ref AdminEmail, ""]]
        AssertDescription: AuthMode=Cognito needs AdminEmail, the first administrator.
  OidcNeedsProvider:
    RuleCondition: !Equals [!Ref AuthMode, Oidc]
    Assertions:
      - Assert: !And
          - !Not [!Equals [!Ref OidcIssuer, ""]]
          - !Not [!Equals [!Ref OidcAuthorizationEndpoint, ""]]
          - !Not [!Equals [!Ref OidcTokenEndpoint, ""]]
          - !Not [!Equals [!Ref OidcUserInfoEndpoint, ""]]
          - !Not [!Equals [!Ref OidcClientId, ""]]
          - !Not [!Equals [!Ref OidcClientSecretArn, ""]]
        AssertDescription: AuthMode=Oidc needs the issuer, the three endpoints, the client ID and the client secret ARN.
  DestinationNeedsTarget:
    RuleCondition: !Not [!Equals [!Ref Destination, CreatedBucket]]
    Assertions:
      - Assert: !Not [!Equals [!Ref DestinationTarget, ""]]
        AssertDescription: ExistingBucket, SqsQueue, SnsTopic and Webhook need DestinationTarget.
  DurableDeliveryNeedsAdmissionKey:
    RuleCondition: !Equals [!Ref DurableDelivery, "true"]
    Assertions:
      - Assert: !Equals [!Ref DurableAdmission, "true"]
        AssertDescription: DurableDelivery=true requires DurableAdmission=true so the stack supplies the encryption key.

Conditions:
  CreateDb: !Equals [!Ref DatabaseMode, Create]
  CreateTokenKey: !Equals [!Ref TokenKeySecretArn, ""]
  CreateContentKey: !Equals [!Ref ContentHmacKeySecretArn, ""]
  CreateAdmissionKey: !Equals [!Ref AdmissionKeySecretArn, ""]
  SelfSigned: !Equals [!Ref CertificateArn, ""]
  NeedsSetupSecrets: !Or [!Condition CreateTokenKey, !Condition CreateContentKey, !Condition CreateAdmissionKey, !Condition SelfSigned, !Condition CreateDb]
  HasHostname: !Not [!Equals [!Ref EndpointHostname, ""]]
  Durable: !Equals [!Ref DurableAdmission, "true"]
  UseCognito: !Equals [!Ref AuthMode, Cognito]
  CognitoWithHostname: !And [!Condition UseCognito, !Condition HasHostname]
  DestCreatedBucket: !Equals [!Ref Destination, CreatedBucket]
  DestExistingBucket: !Equals [!Ref Destination, ExistingBucket]
  DestSqs: !Equals [!Ref Destination, SqsQueue]
  DestSns: !Equals [!Ref Destination, SnsTopic]
  DestWebhook: !Equals [!Ref Destination, Webhook]
  HasWebhookAuth: !And [!Condition DestWebhook, !Not [!Equals [!Ref WebhookAuthSecretArn, ""]]]
  HasTaskSubnets: !Not [!Equals [!Join ["", !Ref TaskSubnetIds], ""]]
  ComprehendOn: !Equals [!Ref EnableComprehendMedical, "true"]
  SageMakerOn: !Not [!Equals [!Ref SageMakerEndpointName, ""]]
  TextractOcrOn: !Equals [!Ref PdfOcrMode, textract]
  HasInput: !Equals [!Ref InputSource, CreatedBucket]

Resources:
  LogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Sub /ecs/${AWS::StackName}
      RetentionInDays: !Ref LogRetentionDays

  # Stack-owned so the task runner's logs are deleted with the stack.
  TaskRunnerLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Sub /aws/lambda/${AWS::StackName}-task-runner
      RetentionInDays: !Ref LogRetentionDays

  # Secrets: created without static SecretString values; SetupRun seeds
  # uninitialized secrets once and redactor setup populates random keys/DSNs
  # without ever replacing existing provisioned values.
  TokenKeySecret:
    Type: AWS::SecretsManager::Secret
    Condition: CreateTokenKey
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      Description: Redactor deterministic tokenization key (provisioned once by setup).
  ContentHmacKeySecret:
    Type: AWS::SecretsManager::Secret
    Condition: CreateContentKey
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      Description: Redactor content HMAC key (provisioned once by setup).
  AdmissionKeySecret:
    Type: AWS::SecretsManager::Secret
    Condition: CreateAdmissionKey
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      Description: Encrypts pending inputs. Losing or changing it makes pending inputs unrecoverable.
  CertificateSecret:
    Type: AWS::SecretsManager::Secret
    Condition: SelfSigned
    Properties:
      Description: Self-signed ALB TLS certificate material (provisioned once by setup).
  OwnerDsnSecret:
    Type: AWS::SecretsManager::Secret
    Condition: CreateDb
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      Description: Schema owner. Read only by the migrate task; can rewrite the audit trail.
  RuntimeDsnSecret:
    Type: AWS::SecretsManager::Secret
    Condition: CreateDb
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      Description: Redactor runtime database DSN (provisioned once by setup).

  # Network: two planes, two CIDRs, tasks reachable only from the balancer.
  LoadBalancerSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: !Sub "${AWS::StackName} per-plane ingress: 8080 operators only, 8081 submitters only"
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - {IpProtocol: tcp, FromPort: 8080, ToPort: 8080, CidrIp: !Ref ControlAllowedCidr, Description: control plane (UI and configuration)}
        - {IpProtocol: tcp, FromPort: 8081, ToPort: 8081, CidrIp: !Ref DataAllowedCidr, Description: data plane (item submission and health)}
      SecurityGroupEgress:
        - {IpProtocol: tcp, FromPort: 8080, ToPort: 8081, DestinationSecurityGroupId: !Ref TaskSecurityGroup, Description: to the service tasks only}
        # The sign-in action calls the provider's token and user-info endpoints.
        - {IpProtocol: tcp, FromPort: 443, ToPort: 443, CidrIp: !Ref IdpEgressCidr, Description: sign-in provider token and user-info endpoints}

  TaskSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: !Sub "${AWS::StackName} tasks admit the load balancer only"
      VpcId: !Ref VpcId
      SecurityGroupEgress:
        # Preserve database and destination access. This includes HTTPS (443)
        # for the license control plane, Secrets Manager, ECR, and ALB keys.
        - {IpProtocol: "-1", CidrIp: 0.0.0.0/0, Description: AWS APIs and the database}

  TaskFromLoadBalancerIngress:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref TaskSecurityGroup
      IpProtocol: tcp
      FromPort: 8080
      ToPort: 8081
      SourceSecurityGroupId: !Ref LoadBalancerSecurityGroup
      Description: from the load balancer only

  DatabaseSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Condition: CreateDb
    Properties:
      GroupDescription: !Sub "${AWS::StackName} database admits Redactor tasks only"
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - {IpProtocol: tcp, FromPort: 5432, ToPort: 5432, SourceSecurityGroupId: !Ref TaskSecurityGroup, Description: Redactor tasks}

  DatabaseSubnetGroup:
    Type: AWS::RDS::DBSubnetGroup
    Condition: CreateDb
    Properties:
      DBSubnetGroupDescription: !Sub "${AWS::StackName} database subnets"
      SubnetIds: !Ref SubnetIds

  Database:
    Type: AWS::RDS::DBInstance
    Condition: CreateDb
    DeletionPolicy: Snapshot
    UpdateReplacePolicy: Snapshot
    Properties:
      Engine: postgres
      EngineVersion: !Ref DbEngineVersion
      DBInstanceClass: !Ref DbInstanceClass
      AllocatedStorage: !Ref DbAllocatedStorage
      StorageType: gp3
      StorageEncrypted: true
      MasterUsername: redactoradmin
      ManageMasterUserPassword: true
      DBSubnetGroupName: !Ref DatabaseSubnetGroup
      VPCSecurityGroups: [!Ref DatabaseSecurityGroup]
      PubliclyAccessible: false
      BackupRetentionPeriod: 7
      AutoMinorVersionUpgrade: true
      CopyTagsToSnapshot: true

  OutputBucket:
    Type: AWS::S3::Bucket
    Condition: DestCreatedBucket
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault: {SSEAlgorithm: AES256}
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      OwnershipControls:
        Rules: [{ObjectOwnership: BucketOwnerEnforced}]

  # Input: uploads notify a queue the service reads; failures go to the
  # failure queue (explicitly, or after 5 receives).
  InputFailureQueue:
    Type: AWS::SQS::Queue
    Condition: HasInput
    Properties: {SqsManagedSseEnabled: true, MessageRetentionPeriod: 1209600}
  InputQueue:
    Type: AWS::SQS::Queue
    Condition: HasInput
    Properties:
      SqsManagedSseEnabled: true
      VisibilityTimeout: 120
      MessageRetentionPeriod: 1209600
      RedrivePolicy: {deadLetterTargetArn: !GetAtt InputFailureQueue.Arn, maxReceiveCount: 5}
  InputQueuePolicy:
    Type: AWS::SQS::QueuePolicy
    Condition: HasInput
    Properties:
      Queues: [!Ref InputQueue]
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: {Service: s3.amazonaws.com}
            Action: sqs:SendMessage
            Resource: !GetAtt InputQueue.Arn
            Condition:
              ArnLike: {aws:SourceArn: !Sub ["arn:${AWS::Partition}:s3:::redactor-input-${Id}", {Id: !Select [2, !Split ["/", !Ref AWS::StackId]]}]}
              StringEquals: {aws:SourceAccount: !Ref AWS::AccountId}
  InputBucket:
    Type: AWS::S3::Bucket
    Condition: HasInput
    DependsOn: InputQueuePolicy
    # Holds original documents: kept on deletion.
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      BucketName: !Sub ["redactor-input-${Id}", {Id: !Select [2, !Split ["/", !Ref AWS::StackId]]}]
      BucketEncryption:
        ServerSideEncryptionConfiguration: [{ServerSideEncryptionByDefault: {SSEAlgorithm: AES256}}]
      PublicAccessBlockConfiguration: {BlockPublicAcls: true, BlockPublicPolicy: true, IgnorePublicAcls: true, RestrictPublicBuckets: true}
      OwnershipControls: {Rules: [{ObjectOwnership: BucketOwnerEnforced}]}
      NotificationConfiguration:
        QueueConfigurations: [{Event: "s3:ObjectCreated:*", Queue: !GetAtt InputQueue.Arn}]

  # Cognito: the role is custom:redactor_role (user-info omits groups); the app
  # client cannot write it.
  UserPool:
    Type: AWS::Cognito::UserPool
    Condition: UseCognito
    Properties:
      UserPoolName: !Sub ${AWS::StackName}-users
      UsernameAttributes: [email]
      AutoVerifiedAttributes: [email]
      AccountRecoverySetting:
        RecoveryMechanisms: [{Name: verified_email, Priority: 1}]
      AdminCreateUserConfig:
        AllowAdminCreateUserOnly: true
        InviteMessageTemplate:
          EmailSubject: Your Redactor sign-in
          EmailMessage: !Sub
            - "You have been invited to Redactor.<br><br>Address: ${Url}<br>Username: {username}<br>Temporary password: {####}<br><br>Sign in and choose a new password. With a self-signed certificate your browser shows a warning before the sign-in page."
            - Url: !If [HasHostname, !Sub "https://${EndpointHostname}:8080", !Sub "https://${LoadBalancer.DNSName}:8080"]
      Policies:
        PasswordPolicy:
          MinimumLength: 12
          RequireLowercase: true
          RequireUppercase: true
          RequireNumbers: true
          RequireSymbols: true
          TemporaryPasswordValidityDays: 7
      Schema:
        - Name: redactor_role
          AttributeDataType: String
          Mutable: true
          StringAttributeConstraints: {MinLength: "0", MaxLength: "16"}

  UserPoolDomain:
    Type: AWS::Cognito::UserPoolDomain
    Condition: UseCognito
    Properties:
      UserPoolId: !Ref UserPool
      Domain: !Sub
        - redactor-${Id}
        - Id: !Select [2, !Split ["/", !Ref AWS::StackId]]

  # Cognito requires lowercase callback URLs; ALB names are mixed case.
  CallbackHost:
    Type: Custom::Lowercase
    Condition: UseCognito
    Properties:
      ServiceToken: !GetAtt TaskRunnerFunction.Arn
      Lowercase: !GetAtt LoadBalancer.DNSName

  UserPoolClient:
    Type: AWS::Cognito::UserPoolClient
    Condition: UseCognito
    Properties:
      ClientName: !Sub ${AWS::StackName}-load-balancer
      UserPoolId: !Ref UserPool
      GenerateSecret: true
      AllowedOAuthFlowsUserPoolClient: true
      AllowedOAuthFlows: [code]
      AllowedOAuthScopes: [openid, email]
      SupportedIdentityProviders: [COGNITO]
      CallbackURLs: !If
        - CognitoWithHostname
        - [!Sub "https://${CallbackHost.Value}:8080/oauth2/idpresponse", !Sub "https://${EndpointHostname}:8080/oauth2/idpresponse"]
        - [!Sub "https://${CallbackHost.Value}:8080/oauth2/idpresponse"]
      # Hosted page only; users cannot change their email or role.
      ExplicitAuthFlows: [ALLOW_REFRESH_TOKEN_AUTH]
      # The ALB re-reads claims when the access token expires: 5 minutes bounds
      # how long a demoted or disabled user keeps a role.
      AccessTokenValidity: 5
      IdTokenValidity: 5
      RefreshTokenValidity: 1
      TokenValidityUnits: {AccessToken: minutes, IdToken: minutes, RefreshToken: days}
      ReadAttributes: [email, email_verified, custom:redactor_role]
      WriteAttributes: [name]
      PreventUserExistenceErrors: ENABLED

  AdminUser:
    Type: AWS::Cognito::UserPoolUser
    Condition: UseCognito
    Properties:
      UserPoolId: !Ref UserPool
      Username: !Ref AdminEmail
      DesiredDeliveryMediums: [EMAIL]
      UserAttributes:
        - {Name: email, Value: !Ref AdminEmail}
        - {Name: email_verified, Value: "true"}
        - {Name: custom:redactor_role, Value: admin}

  # Control authenticates before forwarding in both modes; data uses ingest keys.
  LoadBalancer:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Type: application
      Scheme: !Ref LoadBalancerScheme
      Subnets: !Ref SubnetIds
      SecurityGroups: [!Ref LoadBalancerSecurityGroup]
      LoadBalancerAttributes:
        - {Key: routing.http.drop_invalid_header_fields.enabled, Value: "true"}

  ControlTargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      VpcId: !Ref VpcId
      TargetType: ip
      Protocol: HTTP
      Port: 8080
      # Control routes require sign-in; health lives on the data port.
      HealthCheckPort: "8081"
      HealthCheckPath: /healthz
      HealthCheckIntervalSeconds: 15
      HealthyThresholdCount: 2
      UnhealthyThresholdCount: 3
      Matcher: {HttpCode: "200"}
      TargetGroupAttributes:
        - {Key: deregistration_delay.timeout_seconds, Value: "30"}

  DataTargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      VpcId: !Ref VpcId
      TargetType: ip
      Protocol: HTTP
      Port: 8081
      HealthCheckPath: /healthz
      HealthCheckIntervalSeconds: 15
      HealthyThresholdCount: 2
      UnhealthyThresholdCount: 3
      Matcher: {HttpCode: "200"}
      TargetGroupAttributes:
        - {Key: deregistration_delay.timeout_seconds, Value: "30"}

  ControlListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      LoadBalancerArn: !Ref LoadBalancer
      Port: 8080
      Protocol: HTTPS
      Certificates: [{CertificateArn: !If [SelfSigned, !GetAtt SetupRun.CertificateArn, !Ref CertificateArn]}]
      SslPolicy: ELBSecurityPolicy-TLS13-1-2-2021-06
      DefaultActions: !If
        - UseCognito
        - - Type: authenticate-cognito
            Order: 1
            AuthenticateCognitoConfig:
              UserPoolArn: !GetAtt UserPool.Arn
              UserPoolClientId: !Ref UserPoolClient
              UserPoolDomain: !Ref UserPoolDomain
              # Exactly openid: "openid email" drops custom:redactor_role.
              Scope: openid
              SessionTimeout: !Ref SessionTimeout
              SessionCookieName: !Sub AWSELBAuthSessionCookie-${AWS::StackName}
              OnUnauthenticatedRequest: authenticate
          - Type: forward
            Order: 2
            TargetGroupArn: !Ref ControlTargetGroup
        - - Type: authenticate-oidc
            Order: 1
            AuthenticateOidcConfig:
              Issuer: !Ref OidcIssuer
              AuthorizationEndpoint: !Ref OidcAuthorizationEndpoint
              TokenEndpoint: !Ref OidcTokenEndpoint
              UserInfoEndpoint: !Ref OidcUserInfoEndpoint
              ClientId: !Ref OidcClientId
              # Resolved by CloudFormation; never reaches ECS or the outputs.
              ClientSecret: !Sub "{{resolve:secretsmanager:${OidcClientSecretArn}:SecretString}}"
              Scope: !Ref OidcScope
              SessionTimeout: !Ref SessionTimeout
              SessionCookieName: !Sub AWSELBAuthSessionCookie-${AWS::StackName}
              OnUnauthenticatedRequest: authenticate
          - Type: forward
            Order: 2
            TargetGroupArn: !Ref ControlTargetGroup

  DataListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      LoadBalancerArn: !Ref LoadBalancer
      Port: 8081
      Protocol: HTTPS
      Certificates: [{CertificateArn: !If [SelfSigned, !GetAtt SetupRun.CertificateArn, !Ref CertificateArn]}]
      SslPolicy: ELBSecurityPolicy-TLS13-1-2-2021-06
      DefaultActions: [{Type: forward, TargetGroupArn: !Ref DataTargetGroup}]

  # IAM: separate roles so each part reads only the secrets it needs.
  SetupExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement: [{Effect: Allow, Principal: {Service: ecs-tasks.amazonaws.com}, Action: sts:AssumeRole}]
      ManagedPolicyArns: [arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy]

  SetupTaskRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement: [{Effect: Allow, Principal: {Service: ecs-tasks.amazonaws.com}, Action: sts:AssumeRole}]
      Policies: !If
        - NeedsSetupSecrets
        - - PolicyName: provision-this-stacks-secrets
            PolicyDocument:
              Version: "2012-10-17"
              Statement:
                - Effect: Allow
                  Action: [secretsmanager:GetSecretValue, secretsmanager:PutSecretValue]
                  Resource:
                    - !If [CreateTokenKey, !Ref TokenKeySecret, !Ref AWS::NoValue]
                    - !If [CreateContentKey, !Ref ContentHmacKeySecret, !Ref AWS::NoValue]
                    - !If [CreateAdmissionKey, !Ref AdmissionKeySecret, !Ref AWS::NoValue]
                    - !If [SelfSigned, !Ref CertificateSecret, !Ref AWS::NoValue]
                    - !If [CreateDb, !Ref OwnerDsnSecret, !Ref AWS::NoValue]
                    - !If [CreateDb, !Ref RuntimeDsnSecret, !Ref AWS::NoValue]
                - !If
                  - CreateDb
                  - Effect: Allow
                    Action: secretsmanager:GetSecretValue
                    Resource: !GetAtt Database.MasterUserSecret.SecretArn
                  - !Ref AWS::NoValue
        - !Ref AWS::NoValue

  MigrateExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement: [{Effect: Allow, Principal: {Service: ecs-tasks.amazonaws.com}, Action: sts:AssumeRole}]
      ManagedPolicyArns: [arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy]
      Policies:
        - PolicyName: read-owner-dsn-only
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action: secretsmanager:GetSecretValue
                Resource: !If [CreateDb, !Ref OwnerDsnSecret, !Ref OwnerDsnSecretArn]

  ServiceExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement: [{Effect: Allow, Principal: {Service: ecs-tasks.amazonaws.com}, Action: sts:AssumeRole}]
      ManagedPolicyArns: [arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy]
      Policies:
        - PolicyName: read-marketplace-enrollment-secret
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action: secretsmanager:GetSecretValue
                Resource: !Ref EnrollmentSecretArn
        - PolicyName: read-runtime-secrets
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              # Deliberately NOT the owner DSN or the RDS master secret.
              - Effect: Allow
                Action: secretsmanager:GetSecretValue
                Resource:
                  - !If [CreateDb, !Ref RuntimeDsnSecret, !Ref RuntimeDsnSecretArn]
                  - !If [CreateTokenKey, !Ref TokenKeySecret, !Ref TokenKeySecretArn]
                  - !If [CreateContentKey, !Ref ContentHmacKeySecret, !Ref ContentHmacKeySecretArn]
                  - !If [CreateAdmissionKey, !Ref AdmissionKeySecret, !Ref AdmissionKeySecretArn]
                  - !If [HasWebhookAuth, !Ref WebhookAuthSecretArn, !Ref AWS::NoValue]

  MigrateTaskRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement: [{Effect: Allow, Principal: {Service: ecs-tasks.amazonaws.com}, Action: sts:AssumeRole}]

  # Only what the chosen destination and detectors need.
  ServiceTaskRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement: [{Effect: Allow, Principal: {Service: ecs-tasks.amazonaws.com}, Action: sts:AssumeRole}]
      Policies:
        - !If
          - DestCreatedBucket
          - PolicyName: write-output-objects-only
            PolicyDocument:
              Version: "2012-10-17"
              Statement: [{Effect: Allow, Action: s3:PutObject, Resource: !Sub "${OutputBucket.Arn}/*"}]
          - !Ref AWS::NoValue
        - !If
          - DestExistingBucket
          - PolicyName: write-output-objects-only
            PolicyDocument:
              Version: "2012-10-17"
              Statement: [{Effect: Allow, Action: s3:PutObject, Resource: !Sub "arn:${AWS::Partition}:s3:::${DestinationTarget}/*"}]
          - !Ref AWS::NoValue
        - !If
          - DestSqs
          - PolicyName: send-to-output-queue-only
            PolicyDocument:
              Version: "2012-10-17"
              Statement:
                # https://sqs.<region>.amazonaws.com/<account>/<name> -> its ARN.
                - Effect: Allow
                  Action: sqs:SendMessage
                  Resource: !Sub
                    - "arn:${AWS::Partition}:sqs:${Region}:${Account}:${Name}"
                    - Region: !Select [1, !Split [".", !Select [2, !Split ["/", !Ref DestinationTarget]]]]
                      Account: !Select [3, !Split ["/", !Ref DestinationTarget]]
                      Name: !Select [4, !Split ["/", !Ref DestinationTarget]]
          - !Ref AWS::NoValue
        - !If
          - DestSns
          - PolicyName: publish-to-output-topic-only
            PolicyDocument:
              Version: "2012-10-17"
              Statement: [{Effect: Allow, Action: sns:Publish, Resource: !Ref DestinationTarget}]
          - !Ref AWS::NoValue
        - !If
          - HasInput
          - PolicyName: read-input-only
            PolicyDocument:
              Version: "2012-10-17"
              Statement:
                - {Effect: Allow, Action: s3:GetObject, Resource: !Sub "${InputBucket.Arn}/*"}
                - {Effect: Allow, Action: [sqs:ReceiveMessage, sqs:DeleteMessage, sqs:ChangeMessageVisibility], Resource: !GetAtt InputQueue.Arn}
                - {Effect: Allow, Action: sqs:SendMessage, Resource: !GetAtt InputFailureQueue.Arn}
          - !Ref AWS::NoValue
        - !If
          - ComprehendOn
          - PolicyName: comprehend-medical-detect-only
            PolicyDocument:
              Version: "2012-10-17"
              Statement: [{Effect: Allow, Action: comprehendmedical:DetectPHI, Resource: "*"}]
          - !Ref AWS::NoValue
        - !If
          - SageMakerOn
          - PolicyName: sagemaker-ner-invoke-only
            PolicyDocument:
              Version: "2012-10-17"
              Statement: [{Effect: Allow, Action: sagemaker:InvokeEndpoint, Resource: !Sub "arn:${AWS::Partition}:sagemaker:${AWS::Region}:${AWS::AccountId}:endpoint/${SageMakerEndpointName}"}]
          - !Ref AWS::NoValue
        - !If
          - TextractOcrOn
          - PolicyName: textract-ocr-detect-only
            PolicyDocument:
              Version: "2012-10-17"
              Statement: [{Effect: Allow, Action: textract:DetectDocumentText, Resource: "*"}]
          - !Ref AWS::NoValue

  Cluster:
    Type: AWS::ECS::Cluster
    Properties:
      ClusterName: !Ref AWS::StackName

  SetupTaskDefinition:
    Type: AWS::ECS::TaskDefinition
    Properties:
      Family: !Sub ${AWS::StackName}-setup
      RequiresCompatibilities: [FARGATE]
      NetworkMode: awsvpc
      Cpu: "256"
      Memory: "512"
      ExecutionRoleArn: !GetAtt SetupExecutionRole.Arn
      TaskRoleArn: !GetAtt SetupTaskRole.Arn
      RuntimePlatform: {CpuArchitecture: X86_64, OperatingSystemFamily: LINUX}
      ContainerDefinitions:
        - Name: setup
          Image: !Ref AppImage
          Command: [setup]
          Essential: true
          ReadonlyRootFilesystem: true
          User: "65532:65532"
          Environment:
            - Name: REDACTOR_SETUP_KEY_SECRET_ARNS
              Value: !Join
                - ","
                - - !If [CreateTokenKey, !Ref TokenKeySecret, ""]
                  - !If [CreateContentKey, !Ref ContentHmacKeySecret, ""]
                  - !If [CreateAdmissionKey, !Ref AdmissionKeySecret, ""]
            - !If [SelfSigned, {Name: REDACTOR_SETUP_CERT_SECRET_ARN, Value: !Ref CertificateSecret}, !Ref AWS::NoValue]
            - !If
              - SelfSigned
              - Name: REDACTOR_SETUP_CERT_DNS_NAMES
                Value: !If [HasHostname, !Sub "${LoadBalancer.DNSName},${EndpointHostname}", !GetAtt LoadBalancer.DNSName]
              - !Ref AWS::NoValue
            - !If [CreateDb, {Name: REDACTOR_SETUP_MASTER_SECRET_ARN, Value: !GetAtt Database.MasterUserSecret.SecretArn}, !Ref AWS::NoValue]
            - !If [CreateDb, {Name: REDACTOR_SETUP_DB_ENDPOINT, Value: !Sub "${Database.Endpoint.Address}:${Database.Endpoint.Port}"}, !Ref AWS::NoValue]
            - !If [CreateDb, {Name: REDACTOR_SETUP_OWNER_DSN_SECRET_ARN, Value: !Ref OwnerDsnSecret}, !Ref AWS::NoValue]
            - !If [CreateDb, {Name: REDACTOR_SETUP_RUNTIME_DSN_SECRET_ARN, Value: !Ref RuntimeDsnSecret}, !Ref AWS::NoValue]
          LogConfiguration:
            LogDriver: awslogs
            Options: {awslogs-group: !Ref LogGroup, awslogs-region: !Ref AWS::Region, awslogs-stream-prefix: setup}

  MigrateTaskDefinition:
    Type: AWS::ECS::TaskDefinition
    Properties:
      Family: !Sub ${AWS::StackName}-migrate
      RequiresCompatibilities: [FARGATE]
      NetworkMode: awsvpc
      Cpu: "256"
      Memory: "512"
      ExecutionRoleArn: !GetAtt MigrateExecutionRole.Arn
      TaskRoleArn: !GetAtt MigrateTaskRole.Arn
      RuntimePlatform: {CpuArchitecture: X86_64, OperatingSystemFamily: LINUX}
      ContainerDefinitions:
        - Name: migrate
          Image: !Ref AppImage
          Command: [migrate]
          Essential: true
          ReadonlyRootFilesystem: true
          User: "65532:65532"
          Secrets:
            - {Name: REDACTOR_POSTGRES_DSN, ValueFrom: !If [CreateDb, !Ref OwnerDsnSecret, !Ref OwnerDsnSecretArn]}
          LogConfiguration:
            LogDriver: awslogs
            Options: {awslogs-group: !Ref LogGroup, awslogs-region: !Ref AWS::Region, awslogs-stream-prefix: migrate}

  # Runs setup/migrate tasks, imports (and on delete removes) the certificate,
  # and lowercases the ALB name.
  TaskRunnerRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement: [{Effect: Allow, Principal: {Service: lambda.amazonaws.com}, Action: sts:AssumeRole}]
      Policies:
        - PolicyName: run-this-stacks-one-off-tasks
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              # No CreateLogGroup: late logs would re-create it after deletion.
              - {Effect: Allow, Action: [logs:CreateLogStream, logs:PutLogEvents], Resource: !GetAtt TaskRunnerLogGroup.Arn}
              - Effect: Allow
                Action: ecs:RunTask
                Resource:
                  - !Sub arn:${AWS::Partition}:ecs:${AWS::Region}:${AWS::AccountId}:task-definition/${AWS::StackName}-setup:*
                  - !Sub arn:${AWS::Partition}:ecs:${AWS::Region}:${AWS::AccountId}:task-definition/${AWS::StackName}-migrate:*
              - Effect: Allow
                Action: ecs:DescribeTasks
                Resource: "*"
                Condition: {ArnEquals: {ecs:cluster: !GetAtt Cluster.Arn}}
              - Effect: Allow
                Action: iam:PassRole
                Resource:
                  - !GetAtt SetupExecutionRole.Arn
                  - !GetAtt SetupTaskRole.Arn
                  - !GetAtt MigrateExecutionRole.Arn
                  - !GetAtt MigrateTaskRole.Arn
                Condition:
                  StringEquals:
                    iam:PassedToService: ecs-tasks.amazonaws.com
              - !If
                - NeedsSetupSecrets
                - Effect: Allow
                  Action: [secretsmanager:ListSecretVersionIds, secretsmanager:PutSecretValue]
                  Resource:
                    - !If [CreateTokenKey, !Ref TokenKeySecret, !Ref AWS::NoValue]
                    - !If [CreateContentKey, !Ref ContentHmacKeySecret, !Ref AWS::NoValue]
                    - !If [CreateAdmissionKey, !Ref AdmissionKeySecret, !Ref AWS::NoValue]
                    - !If [SelfSigned, !Ref CertificateSecret, !Ref AWS::NoValue]
                    - !If [CreateDb, !Ref OwnerDsnSecret, !Ref AWS::NoValue]
                    - !If [CreateDb, !Ref RuntimeDsnSecret, !Ref AWS::NoValue]
                - !Ref AWS::NoValue
              - !If
                - SelfSigned
                - Effect: Allow
                  Action: secretsmanager:GetSecretValue
                  Resource: !Ref CertificateSecret
                - !Ref AWS::NoValue
              - !If
                - SelfSigned
                - Effect: Allow
                  Action: [acm:ImportCertificate, acm:DeleteCertificate, acm:AddTagsToCertificate]
                  Resource: "*"
                - !Ref AWS::NoValue

  TaskRunnerFunction:
    Type: AWS::Lambda::Function
    Properties:
      Description: !Sub "${AWS::StackName}: runs one-off setup/migrate tasks; imports the self-signed certificate"
      Runtime: python3.12
      Handler: index.handler
      Timeout: 890
      Role: !GetAtt TaskRunnerRole.Arn
      LoggingConfig:
        LogGroup: !Ref TaskRunnerLogGroup
      Code:
        ZipFile: |
          import json, time, urllib.request, boto3
          def respond(e, status, reason, pid=None, data=None):
              b = json.dumps({"Status": status, "Reason": reason[:900],
                  "PhysicalResourceId": pid or e.get("PhysicalResourceId") or e["LogicalResourceId"],
                  "StackId": e["StackId"], "RequestId": e["RequestId"],
                  "LogicalResourceId": e["LogicalResourceId"], "Data": data or {}}).encode()
              urllib.request.urlopen(urllib.request.Request(e["ResponseURL"], data=b,
                  method="PUT", headers={"Content-Type": ""}))
          def run_task(p):
              ecs = boto3.client("ecs")
              o = ecs.run_task(cluster=p["Cluster"], taskDefinition=p["TaskDefinition"],
                  launchType="FARGATE", networkConfiguration={"awsvpcConfiguration": {
                      "subnets": p["Subnets"], "securityGroups": [p["SecurityGroup"]],
                      "assignPublicIp": p["AssignPublicIp"]}})
              if o.get("failures"):
                  return "RunTask: %s" % o["failures"]
              arn = o["tasks"][0]["taskArn"]
              deadline = time.time() + 840
              while time.time() < deadline:
                  time.sleep(10)
                  t = ecs.describe_tasks(cluster=p["Cluster"], tasks=[arn])["tasks"][0]
                  if t["lastStatus"] != "STOPPED":
                      continue
                  c = t["containers"][0]
                  if c.get("exitCode") == 0:
                      return None
                  return "%s exited %s: %s | %s (see the CloudWatch log group)" % (
                      p["TaskDefinition"].split("/")[-1], c.get("exitCode"),
                      t.get("stoppedReason", ""), c.get("reason", ""))
              return "%s timed out waiting for task completion" % p["TaskDefinition"].split("/")[-1]
          def handler(e, ctx):
              p = e.get("ResourceProperties", {})
              pid = e.get("PhysicalResourceId")
              try:
                  if "Lowercase" in p:
                      v = p["Lowercase"].lower()
                      return respond(e, "SUCCESS", "lowercased", v, {"Value": v})
                  if e["RequestType"] == "Delete":
                      if pid and ":acm:" in pid:
                          try:
                              boto3.client("acm").delete_certificate(CertificateArn=pid)
                          except Exception as x:
                              return respond(e, "SUCCESS", "certificate not deleted: %s" % x, pid)
                      return respond(e, "SUCCESS", "nothing else to undo", pid)
                  if p.get("InitSecrets"):
                      sm = boto3.client("secretsmanager")
                      for arn in p["InitSecrets"]:
                          vers = sm.list_secret_version_ids(SecretId=arn, IncludeDeprecated=False).get("Versions", [])
                          if not vers:
                              sm.put_secret_value(SecretId=arn, SecretString="pending-setup")
                  err = run_task(p)
                  if err:
                      return respond(e, "FAILED", err, pid)
                  if not p.get("CertSecretArn"):
                      return respond(e, "SUCCESS", "task succeeded", pid or "task-run")
                  d = json.loads(boto3.client("secretsmanager").get_secret_value(
                      SecretId=p["CertSecretArn"])["SecretString"])
                  kw = {"Certificate": d["certificate"].encode(), "PrivateKey": d["private_key"].encode()}
                  if pid and ":acm:" in pid:
                      kw["CertificateArn"] = pid
                  else:
                      kw["Tags"] = [{"Key": "redactor:stack", "Value": p["StackName"]}]
                  pid = boto3.client("acm").import_certificate(**kw)["CertificateArn"]
                  return respond(e, "SUCCESS", "certificate imported", pid, {"CertificateArn": pid})
              except Exception as x:
                  respond(e, "FAILED", "runner error: %s" % x, pid)

  SetupRun:
    Type: Custom::RedactorSetup
    Properties:
      ServiceToken: !GetAtt TaskRunnerFunction.Arn
      Cluster: !Ref Cluster
      TaskDefinition: !Ref SetupTaskDefinition
      Subnets: !If [HasTaskSubnets, !Ref TaskSubnetIds, !Ref SubnetIds]
      SecurityGroup: !Ref TaskSecurityGroup
      AssignPublicIp: !Ref AssignPublicIp
      StackName: !Ref AWS::StackName
      CertSecretArn: !If [SelfSigned, !Ref CertificateSecret, ""]
      InitSecrets:
        - !If [CreateTokenKey, !Ref TokenKeySecret, !Ref AWS::NoValue]
        - !If [CreateContentKey, !Ref ContentHmacKeySecret, !Ref AWS::NoValue]
        - !If [CreateAdmissionKey, !Ref AdmissionKeySecret, !Ref AWS::NoValue]
        - !If [SelfSigned, !Ref CertificateSecret, !Ref AWS::NoValue]
        - !If [CreateDb, !Ref OwnerDsnSecret, !Ref AWS::NoValue]
        - !If [CreateDb, !Ref RuntimeDsnSecret, !Ref AWS::NoValue]

  MigrateRun:
    Type: Custom::RunMigrations
    DependsOn: SetupRun
    Properties:
      ServiceToken: !GetAtt TaskRunnerFunction.Arn
      Cluster: !Ref Cluster
      # A new image changes this ARN, so migrations re-run before the service.
      TaskDefinition: !Ref MigrateTaskDefinition
      Subnets: !If [HasTaskSubnets, !Ref TaskSubnetIds, !Ref SubnetIds]
      SecurityGroup: !Ref TaskSecurityGroup
      AssignPublicIp: !Ref AssignPublicIp

  # The service: app + analyzer sidecar, one task, stop-then-start.
  ServiceTaskDefinition:
    Type: AWS::ECS::TaskDefinition
    Properties:
      Family: !Sub ${AWS::StackName}-service
      RequiresCompatibilities: [FARGATE]
      NetworkMode: awsvpc
      Cpu: !Ref TaskCpu
      Memory: !Ref TaskMemory
      ExecutionRoleArn: !GetAtt ServiceExecutionRole.Arn
      TaskRoleArn: !GetAtt ServiceTaskRole.Arn
      RuntimePlatform: {CpuArchitecture: X86_64, OperatingSystemFamily: LINUX}
      Volumes:
        - {Name: tmp}
      ContainerDefinitions:
        - Name: redactor
          Image: !Ref AppImage
          Essential: true
          ReadonlyRootFilesystem: true
          User: "65532:65532"
          PortMappings:
            - {ContainerPort: 8080, Protocol: tcp}
            - {ContainerPort: 8081, Protocol: tcp}
          StopTimeout: 120
          DependsOn:
            - {ContainerName: presidio, Condition: HEALTHY}
          Environment:
            - {Name: REDACTOR_ADDR, Value: ":8080"}
            - {Name: REDACTOR_DATA_ADDR, Value: ":8081"}
            - {Name: REDACTOR_LICENSE_ENFORCED, Value: "true"}
            - {Name: REDACTOR_LICENSE_CONTROL_PLANE_URL, Value: !Ref LicenseControlPlaneUrl}
            - {Name: REDACTOR_LICENSE_ALLOWED_HOSTS, Value: !Ref LicenseAllowedHosts}
            - {Name: REDACTOR_LICENSE_PUBLIC_KEYS_JSON, Value: !Ref LicensePublicKeysJson}
            - {Name: REDACTOR_LICENSE_AWS_ACCOUNT_ID, Value: !Ref AWS::AccountId}
            - {Name: REDACTOR_LICENSE_STACK_ID, Value: !Ref AWS::StackId}
            - {Name: REDACTOR_LICENSE_REGION, Value: !Ref AWS::Region}
            - {Name: REDACTOR_LICENSE_ENVIRONMENT, Value: !Ref LicenseEnvironment}
            - {Name: REDACTOR_LICENSE_RENEW_INTERVAL, Value: !Ref LicenseRenewInterval}
            - {Name: REDACTOR_PRESIDIO_URL, Value: "http://localhost:3000"}
            - {Name: REDACTOR_REQUIRE_INGEST_KEY, Value: !Ref RequireIngestKey}
            - {Name: REDACTOR_DURABLE_ADMISSION, Value: !Ref DurableAdmission}
            - {Name: REDACTOR_DURABLE_DELIVERY, Value: !Ref DurableDelivery}
            - {Name: REDACTOR_COMPREHEND_ENABLED, Value: !Ref EnableComprehendMedical}
            - !If
              - HasInput
              - Name: REDACTOR_SOURCE_SPEC
                Value: !Sub '{"kind":"s3","queue_url":"${InputQueue}","failure_queue_url":"${InputFailureQueue}","pipeline":"${InputPipeline}","region":"${AWS::Region}"}'
              - !Ref AWS::NoValue
            - !If [ComprehendOn, {Name: REDACTOR_COMPREHEND_REGION, Value: !Ref ComprehendRegion}, !Ref AWS::NoValue]
            - !If [SageMakerOn, {Name: REDACTOR_SAGEMAKER_ENDPOINT, Value: !Ref SageMakerEndpointName}, !Ref AWS::NoValue]
            - !If [SageMakerOn, {Name: REDACTOR_SAGEMAKER_REGION, Value: !Ref AWS::Region}, !Ref AWS::NoValue]
            - !If [TextractOcrOn, {Name: REDACTOR_PDF_OCR_MODE, Value: textract}, !Ref AWS::NoValue]
            - !If [TextractOcrOn, {Name: REDACTOR_PDF_OCR_REGION, Value: !Ref AWS::Region}, !Ref AWS::NoValue]
            # No local passwords; roles come from tokens signed by THIS ALB.
            - {Name: REDACTOR_DISABLE_LOCAL_AUTH, Value: "true"}
            - {Name: REDACTOR_PROXY_AUTH_ROLE, Value: claim}
            - {Name: REDACTOR_PROXY_JWT_SIGNER, Value: !Ref LoadBalancer}
            - {Name: REDACTOR_IDENTITY_HEADER, Value: none}
            - {Name: REDACTOR_PROXY_ROLE_CLAIM, Value: !If [UseCognito, "custom:redactor_role", !Ref OidcRoleClaim]}
            - {Name: REDACTOR_PROXY_ADMIN_VALUES, Value: !If [UseCognito, admin, !Ref OidcAdminValues]}
            - {Name: REDACTOR_PROXY_VIEWER_VALUES, Value: !If [UseCognito, viewer, !Ref OidcViewerValues]}
            # Every pipeline without its own destination profile delivers here.
            - Name: REDACTOR_EGRESS_SPEC
              Value: !If
                - DestCreatedBucket
                - !Sub '{"sink":"s3","bucket":"${OutputBucket}","key_prefix":"{pipeline}/{outcome}/","region":"${AWS::Region}"}'
                - !If
                  - DestExistingBucket
                  - !Sub '{"sink":"s3","bucket":"${DestinationTarget}","key_prefix":"{pipeline}/{outcome}/","region":"${AWS::Region}"}'
                  - !If
                    - DestSqs
                    - !Sub
                      - '{"sink":"sqs","queue_url":"${DestinationTarget}","region":"${Region}"}'
                      - Region: !Select [1, !Split [".", !Select [2, !Split ["/", !Ref DestinationTarget]]]]
                    - !If
                      - DestSns
                      - !Sub
                        - '{"sink":"sns","topic_arn":"${DestinationTarget}","region":"${Region}"}'
                        - Region: !Select [3, !Split [":", !Ref DestinationTarget]]
                      - !If
                        - HasWebhookAuth
                        - !Sub '{"sink":"webhook","url":"${DestinationTarget}","header_envs":{"Authorization":"REDACTOR_EGRESS_AUTHORIZATION"}}'
                        - !Sub '{"sink":"webhook","url":"${DestinationTarget}"}'
          Secrets:
            - {Name: REDACTOR_LICENSE_ENROLLMENT_TOKEN, ValueFrom: !Ref EnrollmentSecretArn}
            - {Name: REDACTOR_POSTGRES_DSN, ValueFrom: !If [CreateDb, !Ref RuntimeDsnSecret, !Ref RuntimeDsnSecretArn]}
            - {Name: REDACTOR_TOKEN_KEY, ValueFrom: !If [CreateTokenKey, !Ref TokenKeySecret, !Ref TokenKeySecretArn]}
            - {Name: REDACTOR_CONTENT_HMAC_KEY, ValueFrom: !If [CreateContentKey, !Ref ContentHmacKeySecret, !Ref ContentHmacKeySecretArn]}
            - !If [Durable, {Name: REDACTOR_ADMISSION_KEY, ValueFrom: !If [CreateAdmissionKey, !Ref AdmissionKeySecret, !Ref AdmissionKeySecretArn]}, !Ref AWS::NoValue]
            - !If [HasWebhookAuth, {Name: REDACTOR_EGRESS_AUTHORIZATION, ValueFrom: !Ref WebhookAuthSecretArn}, !Ref AWS::NoValue]
          LogConfiguration:
            LogDriver: awslogs
            Options: {awslogs-group: !Ref LogGroup, awslogs-region: !Ref AWS::Region, awslogs-stream-prefix: redactor}
        - Name: presidio
          Image: !Ref PresidioImage
          Essential: true
          ReadonlyRootFilesystem: true
          MountPoints:
            - {SourceVolume: tmp, ContainerPath: /tmp}
          HealthCheck:
            Command: ["CMD", "python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:3000/health').status==200 else 1)"]
            Interval: 15
            Timeout: 5
            Retries: 5
            StartPeriod: 120
          LogConfiguration:
            LogDriver: awslogs
            Options: {awslogs-group: !Ref LogGroup, awslogs-region: !Ref AWS::Region, awslogs-stream-prefix: presidio}

  Service:
    Type: AWS::ECS::Service
    DependsOn: [ControlListener, DataListener, MigrateRun]
    Properties:
      ServiceName: !Sub ${AWS::StackName}-service
      Cluster: !Ref Cluster
      LaunchType: FARGATE
      TaskDefinition: !Ref ServiceTaskDefinition
      # One replica, by design: see docs/operations/supported-topology.md.
      DesiredCount: 1
      DeploymentConfiguration:
        MinimumHealthyPercent: 0
        MaximumPercent: 100
        DeploymentCircuitBreaker: {Enable: true, Rollback: true}
      HealthCheckGracePeriodSeconds: 240
      NetworkConfiguration:
        AwsvpcConfiguration:
          AssignPublicIp: !Ref AssignPublicIp
          Subnets: !If [HasTaskSubnets, !Ref TaskSubnetIds, !Ref SubnetIds]
          SecurityGroups: [!Ref TaskSecurityGroup]
      LoadBalancers:
        - {ContainerName: redactor, ContainerPort: 8080, TargetGroupArn: !Ref ControlTargetGroup}
        - {ContainerName: redactor, ContainerPort: 8081, TargetGroupArn: !Ref DataTargetGroup}

Outputs:
  ControlEndpoint:
    Description: UI URL (sign in via ALB; self-signed cert warns in browsers).
    Value: !If [HasHostname, !Sub "https://${EndpointHostname}:8080", !Sub "https://${LoadBalancer.DNSName}:8080"]
  DataEndpoint:
    Description: Ingest URL (POST /v1/items with an ingest key).
    Value: !If [HasHostname, !Sub "https://${EndpointHostname}:8081", !Sub "https://${LoadBalancer.DNSName}:8081"]
  LoadBalancerDnsName:
    Description: Target for EndpointHostname DNS alias/CNAME.
    Value: !GetAtt LoadBalancer.DNSName
  UserPoolId:
    Condition: UseCognito
    Description: Cognito User Pool ID (set custom:redactor_role to admin or viewer).
    Value: !Ref UserPool
  OutputBucket:
    Condition: DestCreatedBucket
    Description: Redacted envelopes bucket (<pipeline>/<outcome>/<yyyy>/<mm>/<dd>/<item_id>.json).
    Value: !Ref OutputBucket
  MigrateTaskDefinitionArn:
    Description: One-off migration task definition ARN (owner role).
    Value: !Ref MigrateTaskDefinition
  InputBucket:
    Condition: HasInput
    Description: S3 input bucket for UTF-8 text files.
    Value: !Ref InputBucket
  InputFailureQueue:
    Condition: HasInput
    Description: SQS queue for rejected input files.
    Value: !Ref InputFailureQueue
  LogGroupName:
    Value: !Ref LogGroup
