AWSTemplateFormatVersion: "2010-09-09"
# LanguageExtensions lets VaultCluster's DeletionPolicy come from a parameter.
# Deploy with --capabilities CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND.
Transform: AWS::LanguageExtensions
Description: >-
  Tenet PII Engine - enterprise in-VPC reference deployment (ECS on EC2, Graviton).
  Zero data egress by default: no NAT, no internet route; AWS APIs via VPC endpoints only.
  EnableUsageTelemetryEgress=true is an explicit opt-in that adds a NAT gateway so the detect
  service can send hourly usage counts (no text, no values) to Tenet.
  Detect and (optional) rehydrate run as separate services with separate IAM roles.
  Callers authenticate with their own IAM role through Amazon VPC Lattice.
  Reference template - review before use. See
  https://docs.tenetlabs.com/pii-engine/deploy/ecs-cloudformation.

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label: { default: Naming }
        Parameters: [NamePrefix, DeploymentId]
      - Label: { default: "Authentication: IAM through VPC Lattice" }
        Parameters:
          [LatticePrefixListId, ExistingServiceNetworkArn, AllowedSourceVpcIds,
           DetectInvokerRoleArns, ErasureInvokerRoleArns]
      - Label: { default: "Network: existing VPC, private subnets, no NAT" }
        Parameters:
          [VpcId, VpcCidr, PrivateSubnetIds, PrivateRouteTableIds, S3PrefixListId,
           CreateVpcEndpoints, EnableSsmEndpoints]
      - Label: { default: Customer-managed KMS key }
        Parameters: [KmsKeyArn, KeyAdminRoleArn, KeyPolicyIncludeAccountRoot]
      - Label: { default: Vault (Aurora PostgreSQL) }
        Parameters:
          [CreateVaultDatabase, AuroraEngineVersion, AuroraDeletionProtection, VaultDeletionPolicy,
           AuroraMinCapacity, AuroraMaxCapacity,
           VaultDatabaseName, ExistingVaultEndpoint, ExistingVaultPort, ExistingVaultSecretArn,
           ExistingVaultSecurityGroupId]
      - Label: { default: Rehydration (privileged) }
        Parameters:
          [EnableRehydration, RehydrateDesiredCount, ExistingAuditBucketName, AuditPrefix,
           ErasureAuditPrefix, AuditObjectLockMode, AuditRetentionDays, AuditReaderRoleArn,
           RehydrateInvokerRoleArns, RequireRehydrateApprovalTag, BreakGlassTrustedPrincipalArn]
      - Label: { default: Compute }
        Parameters:
          [ImageUri, InstanceType, EcsAmiId, AsgMinSize, AsgMaxSize, DetectDesiredCount,
           EnableDetectAutoScaling, DetectMaxCount, DetectCpuTargetPercent,
           DeploymentMinimumHealthyPercent, DeploymentMaximumPercent]
      - Label: { default: Logs }
        Parameters: [TelemetryPath, LogRetentionDays, AlarmTopicArn]
      - Label: { default: "Usage telemetry egress (opt-in; adds a NAT gateway)" }
        Parameters:
          [EnableUsageTelemetryEgress, UsageTelemetrySinkUrl, UsageTelemetryApiKeySecretArn,
           UsageTelemetryNatSubnetId, UsageTelemetryCreateDefaultRoute]

Parameters:
  NamePrefix:
    Type: String
    Default: tenet-pii
    AllowedPattern: "^[a-z][a-z0-9-]{1,20}$"
    Description: Prefix for resource names (lowercase, <= 21 chars).

  DeploymentId:
    Type: String
    AllowedPattern: "^[a-z0-9][a-z0-9-]{2,62}$"
    Description: >-
      TENET_DEPLOYMENT_ID - stable id for this install (e.g. acme-prod-use1). Bound into the KMS
      encryption context as tenet:deployment and pinned in every key-policy/IAM condition. The
      runtime refuses to start if it changes; never change it on an existing vault.
  TelemetryPath:
    Type: String
    Default: ""
    AllowedPattern: "^(/tmp/.+)?$"
    Description: >-
      TENET_TELEMETRY_PATH (optional local JSONL of counts-only usage records; never sent
      anywhere). Empty = stdout (CloudWatch).

  EnableUsageTelemetryEgress:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "false"
    Description: >-
      Opt in to sending hourly usage counts (documents by length, findings per entity label;
      never text or values) to Tenet. "false" creates nothing and keeps the zero-egress shape.
      "true" creates a NAT gateway and lets only the detect task reach tcp/443 outbound
      (about $37/month fixed in us-east-1).
  UsageTelemetrySinkUrl:
    Type: String
    Default: https://judge.tenetlabs.com
    AllowedPattern: "^https://[A-Za-z0-9.-]+(:[0-9]{1,5})?(/[A-Za-z0-9._~/-]*)?$"
    Description: TENET_TELEMETRY_SINK_URL. Used only when EnableUsageTelemetryEgress=true.
  UsageTelemetryApiKeySecretArn:
    Type: String
    Default: ""
    AllowedPattern: "^(arn:aws[a-z-]*:secretsmanager:.+)?$"
    Description: >-
      Secrets Manager secret (plain-string value) holding the Tenet telemetry API key, created by
      you. Injected as TENET_TELEMETRY_API_KEY. Required when EnableUsageTelemetryEgress=true.
      If it uses a customer-managed key, allow DetectExecutionRole to kms:Decrypt with it.
  UsageTelemetryCreateDefaultRoute:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "true"
    Description: >-
      Add 0.0.0.0/0 -> the telemetry NAT gateway on every PrivateRouteTableIds entry. Set "false"
      if those route tables already have a default route (creating one fails with
      RouteAlreadyExists); you then own the routing to a NAT.
  UsageTelemetryNatSubnetId:
    Type: String
    Default: ""
    AllowedPattern: "^(subnet-[0-9a-f]+)?$"
    Description: >-
      An existing PUBLIC subnet (route to an internet gateway) that hosts the NAT gateway.
      Required when EnableUsageTelemetryEgress=true. One NAT in one AZ.

  # ---------------------------------------------------------------- authentication
  LatticePrefixListId:
    Type: String
    AllowedPattern: "^pl-[0-9a-f]+$"
    Description: >-
      AWS-managed prefix list for com.amazonaws.<region>.vpc-lattice
      (aws ec2 describe-managed-prefix-lists --filters
      Name=prefix-list-name,Values=com.amazonaws.<region>.vpc-lattice). Tasks admit 19991 only from it.
  ExistingServiceNetworkArn:
    Type: String
    Default: ""
    AllowedPattern: "^(arn:aws[a-z-]*:vpc-lattice:[a-z0-9-]+:[0-9]{12}:servicenetwork/sn-[0-9a-z]{17})?$"
    Description: >-
      Empty = create a service network and associate VpcId with it. A VPC can join
      only one service network: if VpcId already has one, give its ARN here and manage its VPC
      association and auth policy yourself.
  AllowedSourceVpcIds:
    Type: CommaDelimitedList
    Default: ""
    Description: >-
      VPCs whose callers may reach the services (vpc-lattice-svcs:SourceVpc).
      Empty = VpcId only. Other VPCs must also be associated with the service network.
  ErasureInvokerRoleArns:
    Type: CommaDelimitedList
    Default: ""
    Description: >-
      IAM roles allowed to erase a session (DELETE /sessions/{id}). Every erasure is
      audited before it happens. Empty = nobody can erase; sessions expire on their TTL.

  # ---------------------------------------------------------------- network
  VpcId:
    Type: AWS::EC2::VPC::Id
  VpcCidr:
    Type: String
    AllowedPattern: "^([0-9]{1,3}\\.){3}[0-9]{1,3}/[0-9]{1,2}$"
    Description: VPC CIDR. Interface-endpoint security group admits 443 from here.
  PrivateSubnetIds:
    Type: List<AWS::EC2::Subnet::Id>
    Description: >-
      Private subnets in >= 2 AZs (3 recommended). They must have NO route to an internet or
      NAT gateway; this template never creates one.
  PrivateRouteTableIds:
    Type: CommaDelimitedList
    Description: Route tables of the private subnets (for the S3 gateway endpoint).
  S3PrefixListId:
    Type: String
    AllowedPattern: "^pl-[0-9a-f]+$"
    Description: >-
      AWS-managed prefix list for com.amazonaws.<region>.s3 (aws ec2 describe-managed-prefix-lists
      --filters Name=prefix-list-name,Values=com.amazonaws.<region>.s3). Used only in egress rules.
  CreateVpcEndpoints:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "true"
    Description: >-
      Create the interface/gateway endpoints. Set false if the VPC already has them with private
      DNS (creating a second private-DNS endpoint for the same service fails).
  EnableSsmEndpoints:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "false"
    Description: Add ssm/ssmmessages/ec2messages endpoints + SSM instance policy (Session Manager).
  # ---------------------------------------------------------------- KMS
  KmsKeyArn:
    Type: String
    Default: ""
    Description: >-
      Existing customer-managed KMS key ARN. Empty = create one whose key policy names only this
      account's roles. With an existing key, add the key policy statements from the deploy guide,
      "Bringing your own KMS key".
  KeyAdminRoleArn:
    Type: String
    Default: ""
    Description: >-
      Required when creating the key: the customer role that administers it AND runs this stack
      (it needs CreateGrant via RDS and data-key access via Secrets Manager during creation). It
      gets no direct Decrypt.
  KeyPolicyIncludeAccountRoot:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "false"
    Description: >-
      Add the standard "account root" statement (delegates key access to IAM in THIS account).
      false = only the named roles can use the key; if KeyAdminRoleArn is ever deleted the key
      becomes unmanageable. Neither setting grants Tenet anything.

  # ---------------------------------------------------------------- vault
  CreateVaultDatabase:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "true"
    Description: true = new Aurora PostgreSQL Serverless v2 cluster encrypted with the CMK.
  AuroraEngineVersion:
    Type: String
    Default: "16.15"
    Description: >-
      Aurora PostgreSQL engine version. Check that it is offered in your Region:
      aws rds describe-db-engine-versions --engine aurora-postgresql.
  AuroraMinCapacity:
    Type: Number
    Default: 0.5
    MinValue: 0
  AuroraDeletionProtection:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "true"
    Description: >-
      Aurora deletion protection. Keep true in production. With true, a failed CREATE ends in
      ROLLBACK_FAILED (CloudFormation cannot delete the cluster); use false for trial stacks.
  VaultDeletionPolicy:
    Type: String
    AllowedValues: [Snapshot, Delete]
    Default: Snapshot
    Description: >-
      What a stack delete does to the vault cluster. Snapshot (production) leaves a final
      cluster snapshot you must delete yourself; Delete removes it. Vault rows are TTL-bound
      (~1 h), so Delete is reasonable for trial stacks.
  AuroraMaxCapacity:
    Type: Number
    Default: 8
    MinValue: 1
  VaultDatabaseName:
    Type: String
    Default: tenet
    AllowedPattern: "^[a-z][a-z0-9_]{0,62}$"
  ExistingVaultEndpoint:
    Type: String
    Default: ""
    Description: Existing Aurora PostgreSQL writer endpoint (when CreateVaultDatabase=false).
  ExistingVaultPort:
    Type: Number
    Default: 5432
  ExistingVaultSecretArn:
    Type: String
    Default: ""
    AllowedPattern: "^(arn:aws[a-z-]*:secretsmanager:[a-z0-9-]+:[0-9]{12}:secret:.+)?$"
    Description: Secrets Manager secret (JSON with "username" and "password") for the existing cluster.
  ExistingVaultSecurityGroupId:
    Type: String
    Default: ""
    AllowedPattern: "^(sg-[0-9a-f]+)?$"
    Description: Security group of the existing cluster. This stack adds 5432 ingress from the task SGs.

  # ---------------------------------------------------------------- rehydration
  EnableRehydration:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "true"
    Description: >-
      false = no rehydrate service, task role or Lattice service. Detection and de-identification
      work without it. The audit bucket is still created, for the detect role's erasure records.
  RehydrateDesiredCount:
    Type: Number
    Default: 2
    MinValue: 1
    Description: >-
      2 (the default) rolls out without a gap. With 1, each rollout stops the task before starting
      its replacement.
  ExistingAuditBucketName:
    Type: String
    Default: ""
    Description: >-
      Existing audit bucket (MUST have S3 Object Lock enabled and SSE-KMS with the CMK). Empty =
      create one.
  AuditPrefix:
    Type: String
    Default: rehydrate/
    AllowedPattern: "^([a-zA-Z0-9!_.*'()-]+/)+$"
  ErasureAuditPrefix:
    Type: String
    Default: erasure/
    AllowedPattern: "^([a-zA-Z0-9!_.*'()-]+/)+$"
    Description: Audit-bucket prefix for the detect role's erasure records.
  AuditObjectLockMode:
    Type: String
    AllowedValues: [GOVERNANCE, COMPLIANCE]
    Default: GOVERNANCE
    Description: >-
      COMPLIANCE: nobody (including the root user) can delete or shorten retention until it
      expires. Use it in production; GOVERNANCE is the default only so trial stacks can be torn down.
  AuditRetentionDays:
    Type: Number
    Default: 2190
    MinValue: 1
    Description: Default Object Lock retention (2190 days = 6 years, the HIPAA documentation period).
  AuditReaderRoleArn:
    Type: String
    Default: ""
    Description: Optional role allowed to read audit events (auditors / SIEM).
  DetectInvokerRoleArns:
    Type: CommaDelimitedList
    Default: ""
    Description: >-
      IAM roles of your applications that call detect, redact and de-identify, named in the detect
      service's auth policy. Required.
  RehydrateInvokerRoleArns:
    Type: CommaDelimitedList
    Default: ""
    Description: >-
      IAM roles allowed to rehydrate, named in the rehydrate service's auth policy and in the
      runtime's own allow-list. Required when EnableRehydration=true.
  RequireRehydrateApprovalTag:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "false"
    Description: >-
      true = invokers must carry the session tag tenet-approval-id (set by your approval workflow
      when it assumes the invoker role). The auth policy checks it on every rehydration.
  BreakGlassTrustedPrincipalArn:
    Type: String
    Default: ""
    Description: >-
      Principal (e.g. your incident-response role) allowed to assume the break-glass role, with
      MFA. The role may rehydrate without the approval tag. Empty = no break-glass role is created.

  # ---------------------------------------------------------------- compute
  ImageUri:
    Type: String
    Description: >-
      The AWS Marketplace image,
      709825985650.dkr.ecr.us-east-1.amazonaws.com/tenet-labs/tenet-pii-engine:<version>, in any
      Region. Marketplace serves it only from us-east-1; outside us-east-1 the stack's ECR and S3
      endpoints reach it across Regions. Admin roles can create them; a deploy role scoped to specific
      actions also needs vpce:AllowMultiRegion.
  InstanceType:
    Type: String
    Default: c9g.xlarge
    Description: >-
      Graviton (arm64) instance type. c9g.xlarge is the measured default. Check that it is
      offered in your Region; where it is not, use c8g.xlarge, the measured fallback.
  EcsAmiId:
    Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
    Default: /aws/service/ecs/optimized-ami/amazon-linux-2023/arm64/recommended/image_id
    Description: ECS-optimized Amazon Linux 2023 arm64 AMI (public SSM parameter).
  AsgMinSize:
    Type: Number
    Default: 2
    MinValue: 0
  AsgMaxSize:
    Type: Number
    Default: 12
    MinValue: 2
  DetectDesiredCount:
    Type: Number
    Default: 2
    MinValue: 2
    Description: Detect tasks (>= 2, spread across AZs).
  EnableDetectAutoScaling:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "true"
  DetectMaxCount:
    Type: Number
    Default: 10
    MinValue: 2
  DeploymentMinimumHealthyPercent:
    Type: Number
    Default: 50
    MinValue: 0
    MaxValue: 100
    Description: >-
      ECS rolling-deploy floor for both services. Each detect task fills a whole c9g.xlarge, so
      the old 100/200 setting made every rollout scale out an extra instance. 50/100 replaces
      tasks in place: half the tasks stop, their instances take the new revision, then the other
      half. Trade-off: capacity halves during a rollout (1 of 2 detect tasks serving), so deploy
      off-peak or raise DetectDesiredCount first. Set 100/200 to keep full capacity and pay
      for surge instances (raise AsgMaxSize accordingly).
  DeploymentMaximumPercent:
    Type: Number
    Default: 100
    MinValue: 100
    MaxValue: 200
  DetectCpuTargetPercent:
    Type: Number
    Default: 60
    MinValue: 10
    MaxValue: 90
    Description: Target-tracking CPU for detect.

  # ---------------------------------------------------------------- logs
  LogRetentionDays:
    Type: Number
    Default: 365
    AllowedValues: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1096, 1827, 2192, 2557, 2922, 3288, 3653]
  AlarmTopicArn:
    Type: String
    Default: ""
    AllowedPattern: "^$|^arn:aws[a-z-]*:sns:[a-z0-9-]+:[0-9]{12}:.+$"
    Description: SNS topic notified when usage can't be reported to AWS Marketplace. Empty = the alarm shows in CloudWatch only.

Rules:
  KeyAdminRequiredWhenCreatingKey:
    RuleCondition: !Equals [!Ref KmsKeyArn, ""]
    Assertions:
      - Assert: !Not [!Equals [!Ref KeyAdminRoleArn, ""]]
        AssertDescription: KeyAdminRoleArn is required when the stack creates the KMS key.
  ExistingVaultInputs:
    RuleCondition: !Equals [!Ref CreateVaultDatabase, "false"]
    Assertions:
      - Assert: !Not [!Equals [!Ref ExistingVaultEndpoint, ""]]
        AssertDescription: ExistingVaultEndpoint is required when CreateVaultDatabase=false.
      - Assert: !Not [!Equals [!Ref ExistingVaultSecretArn, ""]]
        AssertDescription: ExistingVaultSecretArn is required when CreateVaultDatabase=false.
      - Assert: !Not [!Equals [!Ref ExistingVaultSecurityGroupId, ""]]
        AssertDescription: ExistingVaultSecurityGroupId is required when CreateVaultDatabase=false.
  UsageTelemetryEgressInputs:
    RuleCondition: !Equals [!Ref EnableUsageTelemetryEgress, "true"]
    Assertions:
      - Assert: !Not [!Equals [!Ref UsageTelemetryApiKeySecretArn, ""]]
        AssertDescription: UsageTelemetryApiKeySecretArn is required when EnableUsageTelemetryEgress=true.
      - Assert: !Not [!Equals [!Ref UsageTelemetryNatSubnetId, ""]]
        AssertDescription: UsageTelemetryNatSubnetId is required when EnableUsageTelemetryEgress=true.
  DetectInvokerInputs:
    Assertions:
      # Rules allow only the rule functions (no Fn::Join): every member empty == none given.
      - Assert: !Not [!EachMemberEquals [!Ref DetectInvokerRoleArns, ""]]
        AssertDescription: DetectInvokerRoleArns is required; nobody else can call detect.
  RehydrationInputs:
    RuleCondition: !Equals [!Ref EnableRehydration, "true"]
    Assertions:
      - Assert: !Not [!EachMemberEquals [!Ref RehydrateInvokerRoleArns, ""]]
        AssertDescription: RehydrateInvokerRoleArns is required when EnableRehydration=true.

Conditions:
  CreateKey: !Equals [!Ref KmsKeyArn, ""]
  IncludeRoot: !And [!Condition CreateKey, !Equals [!Ref KeyPolicyIncludeAccountRoot, "true"]]
  CreateDb: !Equals [!Ref CreateVaultDatabase, "true"]
  Rehydration: !Equals [!Ref EnableRehydration, "true"]
  UseExistingServiceNetwork: !Not [!Equals [!Ref ExistingServiceNetworkArn, ""]]
  CreateServiceNetwork: !Not [!Condition UseExistingServiceNetwork]
  HasErasers: !Not [!Equals [!Join ["", !Ref ErasureInvokerRoleArns], ""]]
  DefaultSourceVpcs: !Equals [!Join ["", !Ref AllowedSourceVpcIds], ""]
  # The bucket exists even without rehydration: detect writes erasure records.
  CreateAuditBucket: !Equals [!Ref ExistingAuditBucketName, ""]
  HasAuditReader: !Not [!Equals [!Ref AuditReaderRoleArn, ""]]
  HasAlarmTopic: !Not [!Equals [!Ref AlarmTopicArn, ""]]
  RequireApproval: !Equals [!Ref RequireRehydrateApprovalTag, "true"]
  CreateBreakGlass: !And [!Condition Rehydration, !Not [!Equals [!Ref BreakGlassTrustedPrincipalArn, ""]]]
  CreateEndpoints: !Equals [!Ref CreateVpcEndpoints, "true"]
  # AWS Marketplace serves container images only from us-east-1. Elsewhere the ECR and S3 endpoints
  # reach it across Regions (PrivateLink), so no one copies the image.
  ImageRegionIsRemote: !Not [!Equals [!Ref AWS::Region, us-east-1]]
  CreateRemoteImageEndpoints: !And [!Condition CreateEndpoints, !Condition ImageRegionIsRemote]
  CreateSsmEndpoints: !And [!Condition CreateEndpoints, !Equals [!Ref EnableSsmEndpoints, "true"]]
  EnableSsm: !Equals [!Ref EnableSsmEndpoints, "true"]
  DetectAutoScaling: !Equals [!Ref EnableDetectAutoScaling, "true"]
  TelemetryEgress: !Equals [!Ref EnableUsageTelemetryEgress, "true"]
  TelemetryDefaultRoute: !And [!Condition TelemetryEgress, !Equals [!Ref UsageTelemetryCreateDefaultRoute, "true"]]
  HasTelemetryPath: !Not [!Equals [!Ref TelemetryPath, ""]]
  VaultDeletionProtection: !Equals [!Ref AuroraDeletionProtection, "true"]
  SingleRehydrate: !Equals [!Ref RehydrateDesiredCount, 1]

Resources:
  # ======================================================================================
  # IAM roles. Created first (without KMS statements) so the key policy can name them;
  # the KMS/S3 statements are attached afterwards as AWS::IAM::RolePolicy (no cycle).
  # ======================================================================================
  DetectTaskRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "${NamePrefix}-detect-task"
      Description: Tenet detect/de-identify task role. No audit-bucket access.
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: { Service: ecs-tasks.amazonaws.com }
            Action: sts:AssumeRole
            Condition:
              StringEquals: { "aws:SourceAccount": !Ref AWS::AccountId }
              ArnLike: { "aws:SourceArn": !Sub "arn:${AWS::Partition}:ecs:${AWS::Region}:${AWS::AccountId}:*" }
      Policies:
        - PolicyName: marketplace-metering
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              # MeterUsage has no resource-level permissions. AWS requires the task role for this
              # call and rejects the instance role, so this lives here and nowhere else.
              - Effect: Allow
                Action: aws-marketplace:MeterUsage
                Resource: "*"

  RehydrateTaskRole:
    Type: AWS::IAM::Role
    Condition: Rehydration
    Properties:
      RoleName: !Sub "${NamePrefix}-rehydrate-task"
      Description: Tenet rehydrate task role. The only role that writes the audit bucket.
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: { Service: ecs-tasks.amazonaws.com }
            Action: sts:AssumeRole
            Condition:
              StringEquals: { "aws:SourceAccount": !Ref AWS::AccountId }
              ArnLike: { "aws:SourceArn": !Sub "arn:${AWS::Partition}:ecs:${AWS::Region}:${AWS::AccountId}:*" }
      # No MeterUsage: only detect checks the subscription and bills.

  # Separate execution roles, one per service.
  DetectExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "${NamePrefix}-detect-exec"
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: { Service: ecs-tasks.amazonaws.com }
            Action: sts:AssumeRole
            Condition:
              StringEquals: { "aws:SourceAccount": !Ref AWS::AccountId }
      ManagedPolicyArns:
        - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"

  RehydrateExecutionRole:
    Type: AWS::IAM::Role
    Condition: Rehydration
    Properties:
      RoleName: !Sub "${NamePrefix}-rehydrate-exec"
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: { Service: ecs-tasks.amazonaws.com }
            Action: sts:AssumeRole
            Condition:
              StringEquals: { "aws:SourceAccount": !Ref AWS::AccountId }
      ManagedPolicyArns:
        - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"

  BreakGlassRole:
    Type: AWS::IAM::Role
    Condition: CreateBreakGlass
    Properties:
      RoleName: !Sub "${NamePrefix}-rehydrate-breakglass"
      Description: >-
        Break-glass rehydration: may invoke the rehydrate service without the approval tag. MFA
        required, 1 h sessions. Every AssumeRole is in CloudTrail; alert on it.
      MaxSessionDuration: 3600
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: { AWS: !Ref BreakGlassTrustedPrincipalArn }
            Action: [sts:AssumeRole, sts:TagSession]
            Condition:
              Bool: { "aws:MultiFactorAuthPresent": "true" }
              NumericLessThan: { "aws:MultiFactorAuthAge": "3600" }

  InstanceRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "${NamePrefix}-ecs-instance"
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: { Service: ec2.amazonaws.com }
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role"
        - !If
          - EnableSsm
          - !Sub "arn:${AWS::Partition}:iam::aws:policy/AmazonSSMManagedInstanceCore"
          - !Ref AWS::NoValue

  InstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Roles: [!Ref InstanceRole]

  # ======================================================================================
  # Customer-managed KMS key (optional create). Key policy names only this account's roles.
  # ======================================================================================
  VaultKey:
    Type: AWS::KMS::Key
    Condition: CreateKey
    # A failed CREATE deletes it (no orphaned keys/buckets from rollbacks); once the stack has
    # been created, a stack delete or replacement retains it.
    DeletionPolicy: RetainExceptOnCreate
    UpdateReplacePolicy: Retain
    Properties:
      Description: !Sub "${NamePrefix} vault/audit/log CMK (customer-managed; Tenet has no access)"
      EnableKeyRotation: true
      PendingWindowInDays: 30
      KeyPolicy:
        Version: "2012-10-17"
        Statement:
          - !If
            - IncludeRoot
            - Sid: AccountRootDelegatesToIam
              Effect: Allow
              Principal: { AWS: !Sub "arn:${AWS::Partition}:iam::${AWS::AccountId}:root" }
              Action: kms:*
              Resource: "*"
            - !Ref AWS::NoValue
          - Sid: KeyAdministration
            Effect: Allow
            Principal: { AWS: !Ref KeyAdminRoleArn }
            Action:
              - kms:Create*
              - kms:Describe*
              - kms:Enable*
              - kms:List*
              - kms:Put*
              - kms:Update*
              - kms:Revoke*
              - kms:Disable*
              - kms:Get*
              - kms:Delete*
              - kms:TagResource
              - kms:UntagResource
              - kms:ScheduleKeyDeletion
              - kms:CancelKeyDeletion
              - kms:RotateKeyOnDemand
            Resource: "*"
          - Sid: StackDeployerViaRdsAndSecretsManager
            Effect: Allow
            Principal: { AWS: !Ref KeyAdminRoleArn }
            Action: [kms:CreateGrant, kms:DescribeKey, kms:GenerateDataKey*, kms:Decrypt]
            Resource: "*"
            Condition:
              StringEquals:
                kms:ViaService:
                  - !Sub "rds.${AWS::Region}.amazonaws.com"
                  - !Sub "secretsmanager.${AWS::Region}.amazonaws.com"
          # Detect creates each vault key pair: it wraps the lookup key and the private key, and
          # unwraps only the lookup key.
          - Sid: DetectWrapsVaultKeyPairs
            Effect: Allow
            Principal: { AWS: !GetAtt DetectTaskRole.Arn }
            Action: kms:Encrypt
            Resource: "*"
            Condition:
              StringEquals:
                "kms:EncryptionContext:tenet:purpose": [pii-vault-lookup-key, pii-vault-private-key]
                "kms:EncryptionContext:tenet:deployment": !Ref DeploymentId
          - Sid: DetectUnwrapsLookupKeys
            Effect: Allow
            Principal: { AWS: !GetAtt DetectTaskRole.Arn }
            Action: kms:Decrypt
            Resource: "*"
            Condition:
              StringEquals:
                "kms:EncryptionContext:tenet:purpose": pii-vault-lookup-key
                "kms:EncryptionContext:tenet:deployment": !Ref DeploymentId
          # Explicit Denies win over every Allow, including an IAM policy someone attaches to the
          # detect role later. Detect must never unwrap a private key, and ReEncrypt or a grant could
          # do it for it.
          - Sid: DenyDetectPrivateKeys
            Effect: Deny
            Principal: { AWS: !GetAtt DetectTaskRole.Arn }
            Action: kms:Decrypt
            Resource: "*"
            Condition:
              StringEquals:
                "kms:EncryptionContext:tenet:purpose": pii-vault-private-key
          - Sid: DenyDetectReEncryptAndGrants
            Effect: Deny
            Principal: { AWS: !GetAtt DetectTaskRole.Arn }
            Action: [kms:ReEncrypt*, kms:CreateGrant]
            Resource: "*"
          - !If
            - Rehydration
            - Sid: RehydrateVaultKeysDecryptOnly
              Effect: Allow
              Principal: { AWS: !GetAtt RehydrateTaskRole.Arn }
              Action: kms:Decrypt
              Resource: "*"
              Condition:
                StringEquals:
                  "kms:EncryptionContext:tenet:purpose": [pii-vault-lookup-key, pii-vault-private-key]
                  "kms:EncryptionContext:tenet:deployment": !Ref DeploymentId
            - !Ref AWS::NoValue
          - !If
            - Rehydration
            - Sid: RehydrateAuditWritesViaS3
              Effect: Allow
              Principal: { AWS: !GetAtt RehydrateTaskRole.Arn }
              Action: kms:GenerateDataKey
              Resource: "*"
              Condition:
                StringEquals: { kms:ViaService: !Sub "s3.${AWS::Region}.amazonaws.com" }
            - !Ref AWS::NoValue
          - Sid: DetectErasureAuditWritesViaS3
            Effect: Allow
            Principal: { AWS: !GetAtt DetectTaskRole.Arn }
            Action: kms:GenerateDataKey
            Resource: "*"
            Condition:
              StringEquals: { kms:ViaService: !Sub "s3.${AWS::Region}.amazonaws.com" }
          - Sid: ExecutionRolesReadSecretsViaSecretsManager
            Effect: Allow
            Principal:
              AWS:
                - !GetAtt DetectExecutionRole.Arn
                - !If [Rehydration, !GetAtt RehydrateExecutionRole.Arn, !Ref AWS::NoValue]
            Action: kms:Decrypt
            Resource: "*"
            Condition:
              StringEquals: { kms:ViaService: !Sub "secretsmanager.${AWS::Region}.amazonaws.com" }
          - !If
            - HasAuditReader
            - Sid: AuditReaderViaS3
              Effect: Allow
              Principal: { AWS: !Ref AuditReaderRoleArn }
              Action: kms:Decrypt
              Resource: "*"
              Condition:
                StringEquals: { kms:ViaService: !Sub "s3.${AWS::Region}.amazonaws.com" }
            - !Ref AWS::NoValue
          - Sid: CloudWatchLogsForThisStacksLogGroups
            Effect: Allow
            Principal: { Service: !Sub "logs.${AWS::Region}.amazonaws.com" }
            Action: [kms:Encrypt*, kms:Decrypt*, kms:ReEncrypt*, kms:GenerateDataKey*, kms:Describe*]
            Resource: "*"
            Condition:
              ArnLike:
                kms:EncryptionContext:aws:logs:arn: !Sub "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/${NamePrefix}/*"

  VaultKeyAlias:
    Type: AWS::KMS::Alias
    Condition: CreateKey
    Properties:
      AliasName: !Sub "alias/${NamePrefix}-vault"
      TargetKeyId: !Ref VaultKey

  # IAM-side KMS grants (needed when an existing CMK's policy delegates to IAM; harmless otherwise).
  DetectTaskKmsPolicy:
    Type: AWS::IAM::RolePolicy
    Properties:
      RoleName: !Ref DetectTaskRole
      PolicyName: vault-data-keys
      PolicyDocument:
        Version: "2012-10-17"
        # The Denies repeat the key policy's, so they also hold for an existing CMK whose policy
        # this stack doesn't write.
        Statement:
          - Sid: WrapVaultKeyPairs
            Effect: Allow
            Action: kms:Encrypt
            Resource: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn]
            Condition:
              StringEquals:
                "kms:EncryptionContext:tenet:purpose": [pii-vault-lookup-key, pii-vault-private-key]
                "kms:EncryptionContext:tenet:deployment": !Ref DeploymentId
          - Sid: UnwrapLookupKeys
            Effect: Allow
            Action: kms:Decrypt
            Resource: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn]
            Condition:
              StringEquals:
                "kms:EncryptionContext:tenet:purpose": pii-vault-lookup-key
                "kms:EncryptionContext:tenet:deployment": !Ref DeploymentId
          - Sid: NeverUnwrapPrivateKeys
            Effect: Deny
            Action: kms:Decrypt
            Resource: "*"
            Condition:
              StringEquals:
                "kms:EncryptionContext:tenet:purpose": pii-vault-private-key
          - Sid: NeverReEncryptOrGrant
            Effect: Deny
            Action: [kms:ReEncrypt*, kms:CreateGrant]
            Resource: "*"

  RehydrateTaskPolicy:
    Type: AWS::IAM::RolePolicy
    Condition: Rehydration
    Metadata:
      cfn-lint:
        config:
          # ExistingAuditBucketName is only reached when the stack does not create the bucket;
          # cfn-lint resolves its "" default into an ARN.
          ignore_checks: [W1031]
    Properties:
      RoleName: !Ref RehydrateTaskRole
      PolicyName: vault-decrypt-and-audit-write
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: UnwrapVaultKeys
            Effect: Allow
            Action: kms:Decrypt
            Resource: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn]
            Condition:
              StringEquals:
                "kms:EncryptionContext:tenet:purpose": [pii-vault-lookup-key, pii-vault-private-key]
                "kms:EncryptionContext:tenet:deployment": !Ref DeploymentId
          - Sid: AuditSseKms
            Effect: Allow
            Action: kms:GenerateDataKey
            Resource: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn]
            Condition:
              StringEquals: { kms:ViaService: !Sub "s3.${AWS::Region}.amazonaws.com" }
          # Write-only, one prefix. No GetObject/DeleteObject/PutObjectRetention/BypassGovernance.
          - Sid: AuditAppendOnly
            Effect: Allow
            Action: s3:PutObject
            Resource: !Sub
              - "arn:${AWS::Partition}:s3:::${Bucket}/${AuditPrefix}*"
              - Bucket: !If [CreateAuditBucket, !Ref AuditBucket, !Ref ExistingAuditBucketName]
          # The runtime refuses to start rehydrate unless Object Lock is verifiably on.
          - Sid: VerifyObjectLockAtStartup
            Effect: Allow
            Action: s3:GetBucketObjectLockConfiguration
            Resource: !Sub
              - "arn:${AWS::Partition}:s3:::${Bucket}"
              - Bucket: !If [CreateAuditBucket, !Ref AuditBucket, !Ref ExistingAuditBucketName]

  # Detect audits every erasure before it happens (tenet.erasure-audit.v1).
  DetectErasureAuditPolicy:
    Type: AWS::IAM::RolePolicy
    Metadata:
      cfn-lint:
        config:
          # ExistingAuditBucketName is only reached when the stack does not create the bucket;
          # cfn-lint resolves its "" default into an ARN.
          ignore_checks: [W1031]
    Properties:
      RoleName: !Ref DetectTaskRole
      PolicyName: erasure-audit-write
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: AuditSseKms
            Effect: Allow
            Action: kms:GenerateDataKey
            Resource: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn]
            Condition:
              StringEquals: { kms:ViaService: !Sub "s3.${AWS::Region}.amazonaws.com" }
          # Write-only, one prefix, as for the rehydrate role.
          - Sid: ErasureAuditAppendOnly
            Effect: Allow
            Action: s3:PutObject
            Resource: !Sub
              - "arn:${AWS::Partition}:s3:::${Bucket}/${ErasureAuditPrefix}*"
              - Bucket: !If [CreateAuditBucket, !Ref AuditBucket, !Ref ExistingAuditBucketName]
          - Sid: VerifyObjectLockAtStartup
            Effect: Allow
            Action: s3:GetBucketObjectLockConfiguration
            Resource: !Sub
              - "arn:${AWS::Partition}:s3:::${Bucket}"
              - Bucket: !If [CreateAuditBucket, !Ref AuditBucket, !Ref ExistingAuditBucketName]

  DetectExecutionSecretsPolicy:
    Type: AWS::IAM::RolePolicy
    Metadata:
      cfn-lint:
        config:
          # Refs to Existing* params are only reached when CreateVaultDatabase=false, where the
          # Rules section has already asserted they are non-empty; cfn-lint resolves the "" default.
          ignore_checks: [W1030, W1031]
    Properties:
      RoleName: !Ref DetectExecutionRole
      PolicyName: inject-secrets
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Action: secretsmanager:GetSecretValue
            Resource:
              - !If [CreateDb, !GetAtt VaultCluster.MasterUserSecret.SecretArn, !Sub "${ExistingVaultSecretArn}"]
              - !If [TelemetryEgress, !Sub "${UsageTelemetryApiKeySecretArn}", !Ref AWS::NoValue]

  RehydrateExecutionSecretsPolicy:
    Type: AWS::IAM::RolePolicy
    Condition: Rehydration
    Metadata:
      cfn-lint:
        config:
          # Refs to Existing* params are only reached when CreateVaultDatabase=false, where the
          # Rules section has already asserted they are non-empty; cfn-lint resolves the "" default.
          ignore_checks: [W1030, W1031]
    Properties:
      RoleName: !Ref RehydrateExecutionRole
      PolicyName: inject-secrets
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Action: secretsmanager:GetSecretValue
            Resource:
              - !If [CreateDb, !GetAtt VaultCluster.MasterUserSecret.SecretArn, !Sub "${ExistingVaultSecretArn}"]

  # Same-account callers need an identity policy as well as the service's auth policy.
  BreakGlassInvokePolicy:
    Type: AWS::IAM::RolePolicy
    Condition: CreateBreakGlass
    Properties:
      RoleName: !Ref BreakGlassRole
      PolicyName: invoke-rehydrate
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Action: vpc-lattice-svcs:Invoke
            Resource: !Sub "${RehydrateLatticeService.Arn}/*"

  # ======================================================================================
  # Audit bucket: Object Lock, SSE-KMS (CMK), no public access. Writers: the rehydrate role, and
  # the detect role (erasure records, its own prefix).
  # ======================================================================================
  AuditBucket:
    Type: AWS::S3::Bucket
    Condition: CreateAuditBucket
    # A failed CREATE deletes it (no orphaned keys/buckets from rollbacks); once the stack has
    # been created, a stack delete or replacement retains it.
    DeletionPolicy: RetainExceptOnCreate
    UpdateReplacePolicy: Retain
    Properties:
      BucketName: !Sub "${NamePrefix}-audit-${AWS::AccountId}-${AWS::Region}"
      ObjectLockEnabled: true
      ObjectLockConfiguration:
        ObjectLockEnabled: Enabled
        Rule:
          DefaultRetention:
            Mode: !Ref AuditObjectLockMode
            Days: !Ref AuditRetentionDays
      VersioningConfiguration:
        Status: Enabled
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: aws:kms
              KMSMasterKeyID: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn]
            BucketKeyEnabled: true
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      OwnershipControls:
        Rules:
          - ObjectOwnership: BucketOwnerEnforced

  AuditBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Condition: CreateAuditBucket
    Properties:
      Bucket: !Ref AuditBucket
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: DenyInsecureTransport
            Effect: Deny
            Principal: "*"
            Action: s3:*
            Resource: [!GetAtt AuditBucket.Arn, !Sub "${AuditBucket.Arn}/*"]
            Condition:
              Bool: { "aws:SecureTransport": "false" }
          - Sid: OnlyAuditWritersWrite
            Effect: Deny
            Principal: "*"
            Action: s3:PutObject
            Resource: !Sub "${AuditBucket.Arn}/*"
            Condition:
              ArnNotEquals:
                aws:PrincipalArn:
                  - !If [Rehydration, !GetAtt RehydrateTaskRole.Arn, !Ref AWS::NoValue]
                  - !GetAtt DetectTaskRole.Arn
          - Sid: NobodyBypassesGovernanceRetention
            Effect: Deny
            Principal: "*"
            Action: s3:BypassGovernanceRetention
            Resource: !Sub "${AuditBucket.Arn}/*"
          - Sid: DenyWrongKmsKey
            Effect: Deny
            Principal: "*"
            Action: s3:PutObject
            Resource: !Sub "${AuditBucket.Arn}/*"
            Condition:
              StringNotEqualsIfExists:
                s3:x-amz-server-side-encryption-aws-kms-key-id: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn]
          - !If
            - HasAuditReader
            - Sid: AuditReaderRead
              Effect: Allow
              Principal: { AWS: !Ref AuditReaderRoleArn }
              Action: [s3:GetObject, s3:GetObjectVersion, s3:GetObjectRetention, s3:ListBucket]
              Resource: [!GetAtt AuditBucket.Arn, !Sub "${AuditBucket.Arn}/*"]
            - !Ref AWS::NoValue

  # ======================================================================================
  # Logs: CMK-encrypted, finite retention. The runtime logs counts/identifiers only.
  # ======================================================================================
  DetectLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Sub "/${NamePrefix}/detect"
      RetentionInDays: !Ref LogRetentionDays
      KmsKeyId: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn]

  # The runtime logs this when AWS refuses an hour of usage or never receives it.
  UnbilledUsageMetricFilter:
    Type: AWS::Logs::MetricFilter
    Properties:
      LogGroupName: !Ref DetectLogGroup
      FilterPattern: '"unbilled usage lost"'
      MetricTransformations:
        - MetricName: UnbilledUsageLost
          MetricNamespace: !Sub "TenetPII/${NamePrefix}"
          MetricValue: "1"

  UnbilledUsageAlarm:
    Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmName: !Sub "${NamePrefix}-unbilled-usage"
      AlarmDescription: Metered usage could not be reported to AWS Marketplace. See the detect logs.
      Namespace: !Sub "TenetPII/${NamePrefix}"
      MetricName: UnbilledUsageLost
      Statistic: Sum
      Period: 3600
      EvaluationPeriods: 1
      Threshold: 0
      ComparisonOperator: GreaterThanThreshold
      TreatMissingData: notBreaching
      AlarmActions: !If [HasAlarmTopic, [!Ref AlarmTopicArn], !Ref AWS::NoValue]

  RehydrateLogGroup:
    Type: AWS::Logs::LogGroup
    Condition: Rehydration
    Properties:
      LogGroupName: !Sub "/${NamePrefix}/rehydrate"
      RetentionInDays: !Ref LogRetentionDays
      KmsKeyId: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn]

  # ======================================================================================
  # Security groups. Every egress rule is explicit; nothing reaches 0.0.0.0/0.
  # ======================================================================================
  EndpointSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Condition: CreateEndpoints
    Properties:
      GroupDescription: Interface VPC endpoints - 443 from the VPC only
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: !Ref VpcCidr
          Description: HTTPS to AWS APIs from inside the VPC
      SecurityGroupEgress:
        # Replaces the implicit allow-all egress rule. Endpoints never initiate connections.
        - IpProtocol: "-1"
          CidrIp: 127.0.0.1/32
          Description: no egress

  InstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: ECS container instances (host network) - no ingress
      VpcId: !Ref VpcId
      SecurityGroupEgress:
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          DestinationSecurityGroupId: !If [CreateEndpoints, !Ref EndpointSecurityGroup, !Ref AWS::NoValue]
          CidrIp: !If [CreateEndpoints, !Ref AWS::NoValue, !Ref VpcCidr]
          Description: ECS agent / ECR / Logs / SSM via interface endpoints
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          DestinationPrefixListId: !Ref S3PrefixListId
          Description: ECR image layers via the S3 gateway endpoint

  DetectTaskSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Detect tasks - ingress from VPC Lattice only
      VpcId: !Ref VpcId
      SecurityGroupEgress:
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          DestinationSecurityGroupId: !If [CreateEndpoints, !Ref EndpointSecurityGroup, !Ref AWS::NoValue]
          CidrIp: !If [CreateEndpoints, !Ref AWS::NoValue, !Ref VpcCidr]
          Description: KMS / STS / Marketplace metering via interface endpoints

  # Opt-in usage telemetry. The telemetry endpoint has no stable address range, so the rule is
  # limited by protocol and port: tcp/443 to 0.0.0.0/0. A compromised detect task
  # could use it to reach any HTTPS host. Only the detect task
  # group gets it.
  DetectUsageTelemetryEgress:
    Type: AWS::EC2::SecurityGroupEgress
    Condition: TelemetryEgress
    Properties:
      GroupId: !Ref DetectTaskSecurityGroup
      IpProtocol: tcp
      FromPort: 443
      ToPort: 443
      CidrIp: 0.0.0.0/0
      Description: Opt-in usage telemetry to judge.tenetlabs.com (counts only)

  RehydrateTaskSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Condition: Rehydration
    Properties:
      GroupDescription: Rehydrate tasks - ingress from VPC Lattice only
      VpcId: !Ref VpcId
      SecurityGroupEgress:
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          DestinationSecurityGroupId: !If [CreateEndpoints, !Ref EndpointSecurityGroup, !Ref AWS::NoValue]
          CidrIp: !If [CreateEndpoints, !Ref AWS::NoValue, !Ref VpcCidr]
          Description: KMS / STS / Marketplace metering via interface endpoints
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          DestinationPrefixListId: !Ref S3PrefixListId
          Description: Audit bucket via the S3 gateway endpoint

  # Attach to workloads that call the Tenet services. IAM decides who may call what;
  # this only opens the path.
  LatticeClientSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Members may call the Tenet VPC Lattice services on 443
      VpcId: !Ref VpcId
      SecurityGroupEgress:
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          DestinationPrefixListId: !Ref LatticePrefixListId
          Description: VPC Lattice services

  LatticeAssociationSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Condition: CreateServiceNetwork
    Properties:
      GroupDescription: VPC Lattice service network association - 443 from the VPC only
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: !Ref VpcCidr
          Description: Callers inside the VPC
      SecurityGroupEgress:
        - IpProtocol: "-1"
          CidrIp: 127.0.0.1/32
          Description: no egress

  DatabaseSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Condition: CreateDb
    Properties:
      GroupDescription: Vault Aurora PostgreSQL - 5432 from Tenet tasks only
      VpcId: !Ref VpcId
      SecurityGroupEgress:
        - IpProtocol: "-1"
          CidrIp: 127.0.0.1/32
          Description: no egress

  DetectFromLatticeIngress:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: !Ref DetectTaskSecurityGroup
      IpProtocol: tcp
      FromPort: 19991
      ToPort: 19991
      SourcePrefixListId: !Ref LatticePrefixListId
      Description: VPC Lattice (traffic and /readyz health checks)
  RehydrateFromLatticeIngress:
    Type: AWS::EC2::SecurityGroupIngress
    Condition: Rehydration
    Properties:
      GroupId: !Ref RehydrateTaskSecurityGroup
      IpProtocol: tcp
      FromPort: 19991
      ToPort: 19991
      SourcePrefixListId: !Ref LatticePrefixListId
      Description: VPC Lattice (traffic and /readyz health checks)
  DetectToS3Egress:
    Type: AWS::EC2::SecurityGroupEgress
    Properties:
      GroupId: !Ref DetectTaskSecurityGroup
      IpProtocol: tcp
      FromPort: 443
      ToPort: 443
      DestinationPrefixListId: !Ref S3PrefixListId
      Description: Erasure audit via the S3 gateway endpoint

  DetectToDbEgress:
    Type: AWS::EC2::SecurityGroupEgress
    Metadata:
      cfn-lint:
        config:
          # Refs to Existing* params are only reached when CreateVaultDatabase=false, where the
          # Rules section has already asserted they are non-empty; cfn-lint resolves the "" default.
          ignore_checks: [W1030, W1031]
    Properties:
      GroupId: !Ref DetectTaskSecurityGroup
      IpProtocol: tcp
      FromPort: !If [CreateDb, 5432, !Ref ExistingVaultPort]
      ToPort: !If [CreateDb, 5432, !Ref ExistingVaultPort]
      DestinationSecurityGroupId: !If [CreateDb, !Ref DatabaseSecurityGroup, !Ref ExistingVaultSecurityGroupId]
      Description: Vault
  RehydrateToDbEgress:
    Type: AWS::EC2::SecurityGroupEgress
    Condition: Rehydration
    Metadata:
      cfn-lint:
        config:
          # Refs to Existing* params are only reached when CreateVaultDatabase=false, where the
          # Rules section has already asserted they are non-empty; cfn-lint resolves the "" default.
          ignore_checks: [W1030, W1031]
    Properties:
      GroupId: !Ref RehydrateTaskSecurityGroup
      IpProtocol: tcp
      FromPort: !If [CreateDb, 5432, !Ref ExistingVaultPort]
      ToPort: !If [CreateDb, 5432, !Ref ExistingVaultPort]
      DestinationSecurityGroupId: !If [CreateDb, !Ref DatabaseSecurityGroup, !Ref ExistingVaultSecurityGroupId]
      Description: Vault
  DbFromDetectIngress:
    Type: AWS::EC2::SecurityGroupIngress
    Metadata:
      cfn-lint:
        config:
          # Refs to Existing* params are only reached when CreateVaultDatabase=false, where the
          # Rules section has already asserted they are non-empty; cfn-lint resolves the "" default.
          ignore_checks: [W1030, W1031]
    Properties:
      GroupId: !If [CreateDb, !Ref DatabaseSecurityGroup, !Ref ExistingVaultSecurityGroupId]
      IpProtocol: tcp
      FromPort: !If [CreateDb, 5432, !Ref ExistingVaultPort]
      ToPort: !If [CreateDb, 5432, !Ref ExistingVaultPort]
      SourceSecurityGroupId: !Ref DetectTaskSecurityGroup
      Description: Tenet detect tasks
  DbFromRehydrateIngress:
    Type: AWS::EC2::SecurityGroupIngress
    Condition: Rehydration
    Metadata:
      cfn-lint:
        config:
          # Refs to Existing* params are only reached when CreateVaultDatabase=false, where the
          # Rules section has already asserted they are non-empty; cfn-lint resolves the "" default.
          ignore_checks: [W1030, W1031]
    Properties:
      GroupId: !If [CreateDb, !Ref DatabaseSecurityGroup, !Ref ExistingVaultSecurityGroupId]
      IpProtocol: tcp
      FromPort: !If [CreateDb, 5432, !Ref ExistingVaultPort]
      ToPort: !If [CreateDb, 5432, !Ref ExistingVaultPort]
      SourceSecurityGroupId: !Ref RehydrateTaskSecurityGroup
      Description: Tenet rehydrate tasks

  # ======================================================================================
  # Opt-in usage-telemetry egress (EnableUsageTelemetryEgress). Nothing below exists by default.
  # Default route to a NAT gateway in a customer-supplied public subnet. It is added to every
  # PrivateRouteTableId; only DetectTaskSecurityGroup has an egress rule that can use it.
  # ======================================================================================
  UsageTelemetryNatEip:
    Type: AWS::EC2::EIP
    Condition: TelemetryEgress
    Properties:
      Domain: vpc
      Tags: [{ Key: Name, Value: !Sub "${NamePrefix}-telemetry-nat" }]

  UsageTelemetryNatGateway:
    Type: AWS::EC2::NatGateway
    Condition: TelemetryEgress
    Metadata:
      cfn-lint:
        config:
          # Only reached when EnableUsageTelemetryEgress=true, where the Rules section has already
          # asserted the subnet id is non-empty; cfn-lint resolves the "" default.
          ignore_checks: [W1030]
    Properties:
      AllocationId: !GetAtt UsageTelemetryNatEip.AllocationId
      SubnetId: !Ref UsageTelemetryNatSubnetId
      Tags: [{ Key: Name, Value: !Sub "${NamePrefix}-telemetry" }]

  Fn::ForEach::UsageTelemetryRoutes:
    - RouteTableId
    - !Ref PrivateRouteTableIds
    - UsageTelemetryRoute&{RouteTableId}:
        Type: AWS::EC2::Route
        Condition: TelemetryDefaultRoute
        Properties:
          RouteTableId: !Ref RouteTableId
          DestinationCidrBlock: 0.0.0.0/0
          NatGatewayId: !Ref UsageTelemetryNatGateway

  # ======================================================================================
  # VPC endpoints (optional). Service names verified against the AWS PrivateLink service list.
  # Endpoint policies pin data-bearing services to resources in THIS account, so an endpoint
  # cannot be used to write to someone else's bucket / log group / key / secret.
  # ======================================================================================
  S3GatewayEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: !Sub "com.amazonaws.${AWS::Region}.s3"
      VpcEndpointType: Gateway
      RouteTableIds: !Ref PrivateRouteTableIds
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: InAccountBucketsOnly
            Effect: Allow
            Principal: "*"
            Action: s3:*
            Resource: "*"
            Condition:
              StringEquals: { "aws:ResourceAccount": !Ref AWS::AccountId }
          - Sid: EcrImageLayers
            Effect: Allow
            Principal: "*"
            Action: s3:GetObject
            Resource: !Sub "arn:${AWS::Partition}:s3:::prod-${AWS::Region}-starport-layer-bucket/*"

  # Image layers outside us-east-1: ECR hands out us-east-1 S3 URLs, which a gateway endpoint can't
  # reach across Regions. Only the Marketplace layer bucket is allowed.
  MarketplaceLayersEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateRemoteImageEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: com.amazonaws.us-east-1.s3
      ServiceRegion: us-east-1
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: EcrImageLayers
            Effect: Allow
            Principal: "*"
            Action: s3:GetObject
            Resource: !Sub "arn:${AWS::Partition}:s3:::prod-us-east-1-starport-layer-bucket/*"

  KmsEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: !Sub "com.amazonaws.${AWS::Region}.kms"
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: "*"
            Action: kms:*
            Resource: "*"
            Condition:
              StringEquals: { "aws:ResourceAccount": !Ref AWS::AccountId }
  LogsEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: !Sub "com.amazonaws.${AWS::Region}.logs"
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: "*"
            Action: logs:*
            Resource: "*"
            Condition:
              StringEquals: { "aws:ResourceAccount": !Ref AWS::AccountId }
  SecretsManagerEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: !Sub "com.amazonaws.${AWS::Region}.secretsmanager"
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: "*"
            Action: secretsmanager:*
            Resource: "*"
            Condition:
              StringEquals: { "aws:ResourceAccount": !Ref AWS::AccountId }
  StsEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: !Sub "com.amazonaws.${AWS::Region}.sts"
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]
  MeteringEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: !Sub "com.amazonaws.${AWS::Region}.metering-marketplace"
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]
  # The image's registry is in us-east-1 (Marketplace), so these two point there from any Region.
  EcrApiEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: com.amazonaws.us-east-1.ecr.api
      ServiceRegion: !If [ImageRegionIsRemote, us-east-1, !Ref AWS::NoValue]
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]
  EcrDkrEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: com.amazonaws.us-east-1.ecr.dkr
      ServiceRegion: !If [ImageRegionIsRemote, us-east-1, !Ref AWS::NoValue]
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]
  EcsEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: !Sub "com.amazonaws.${AWS::Region}.ecs"
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]
  EcsAgentEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: !Sub "com.amazonaws.${AWS::Region}.ecs-agent"
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]
  EcsTelemetryEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: !Sub "com.amazonaws.${AWS::Region}.ecs-telemetry"
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]
  SsmEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateSsmEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: !Sub "com.amazonaws.${AWS::Region}.ssm"
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]
  SsmMessagesEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateSsmEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: !Sub "com.amazonaws.${AWS::Region}.ssmmessages"
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]
  Ec2MessagesEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Condition: CreateSsmEndpoints
    Properties:
      VpcId: !Ref VpcId
      ServiceName: !Sub "com.amazonaws.${AWS::Region}.ec2messages"
      VpcEndpointType: Interface
      PrivateDnsEnabled: true
      SubnetIds: !Ref PrivateSubnetIds
      SecurityGroupIds: [!Ref EndpointSecurityGroup]

  # ======================================================================================
  # Vault: Aurora PostgreSQL Serverless v2 (optional), encrypted with the CMK.
  # ======================================================================================
  VaultSubnetGroup:
    Type: AWS::RDS::DBSubnetGroup
    Condition: CreateDb
    Properties:
      DBSubnetGroupDescription: !Sub "${NamePrefix} vault"
      SubnetIds: !Ref PrivateSubnetIds

  VaultCluster:
    Type: AWS::RDS::DBCluster
    Condition: CreateDb
    DeletionPolicy: !Ref VaultDeletionPolicy
    UpdateReplacePolicy: Snapshot
    Properties:
      DBClusterIdentifier: !Sub "${NamePrefix}-vault"
      Engine: aurora-postgresql
      EngineVersion: !Ref AuroraEngineVersion
      DatabaseName: !Ref VaultDatabaseName
      MasterUsername: tenet_admin
      ManageMasterUserPassword: true
      MasterUserSecret:
        KmsKeyId: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn]
      StorageEncrypted: true
      KmsKeyId: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn]
      ServerlessV2ScalingConfiguration:
        MinCapacity: !Ref AuroraMinCapacity
        MaxCapacity: !Ref AuroraMaxCapacity
      DBSubnetGroupName: !Ref VaultSubnetGroup
      VpcSecurityGroupIds: [!Ref DatabaseSecurityGroup]
      BackupRetentionPeriod: 7
      CopyTagsToSnapshot: true
      DeletionProtection: !If [VaultDeletionProtection, true, false]
      EnableIAMDatabaseAuthentication: false

  VaultWriter:
    Type: AWS::RDS::DBInstance
    Condition: CreateDb
    Properties:
      DBClusterIdentifier: !Ref VaultCluster
      DBInstanceClass: db.serverless
      Engine: aurora-postgresql
      PubliclyAccessible: false
      AutoMinorVersionUpgrade: true

  # Same pattern as EndpointsReady: DependsOn can't name a conditional resource directly. The
  # writer takes minutes to create, longer than a task's wait for the vault at startup.
  VaultReady:
    Type: AWS::CloudFormation::WaitConditionHandle
    Metadata:
      Writer: !If [CreateDb, !Ref VaultWriter, ""]

  VaultReader:
    Type: AWS::RDS::DBInstance
    Condition: CreateDb
    DependsOn: VaultWriter
    Properties:
      DBClusterIdentifier: !Ref VaultCluster
      DBInstanceClass: db.serverless
      Engine: aurora-postgresql
      PubliclyAccessible: false
      AutoMinorVersionUpgrade: true

  # ======================================================================================
  # ECS on EC2 (Graviton). Not Fargate.
  # ======================================================================================
  Cluster:
    Type: AWS::ECS::Cluster
    Properties:
      ClusterName: !Sub "${NamePrefix}"
      ClusterSettings:
        - Name: containerInsights
          Value: disabled

  LaunchTemplate:
    Type: AWS::EC2::LaunchTemplate
    Properties:
      LaunchTemplateData:
        ImageId: !Ref EcsAmiId
        InstanceType: !Ref InstanceType
        IamInstanceProfile: { Arn: !GetAtt InstanceProfile.Arn }
        SecurityGroupIds: [!Ref InstanceSecurityGroup]
        MetadataOptions:
          HttpTokens: required
          HttpPutResponseHopLimit: 1
          HttpEndpoint: enabled
        BlockDeviceMappings:
          - DeviceName: /dev/xvda
            Ebs:
              VolumeSize: 30
              VolumeType: gp3
              Encrypted: true
        TagSpecifications:
          - ResourceType: instance
            Tags: [{ Key: Name, Value: !Sub "${NamePrefix}-ecs" }]
        UserData:
          Fn::Base64: !Sub |
            #!/bin/bash
            cat >> /etc/ecs/ecs.config <<'EOF'
            ECS_CLUSTER=${Cluster}
            ECS_AWSVPC_BLOCK_IMDS=true
            ECS_ENABLE_TASK_IAM_ROLE=true
            EOF

  # Conditional DependsOn: CloudFormation can't DependsOn a resource whose Condition is false,
  # so this handle references the endpoints through Fn::If and the ASG depends on the handle.
  # Effect: on CREATE, instances boot only after the endpoints (and their private DNS) exist;
  # on DELETE, the services -> capacity provider association -> capacity provider -> ASG are
  # all gone BEFORE any endpoint is removed.
  EndpointsReady:
    Type: AWS::CloudFormation::WaitConditionHandle
    Metadata:
      Endpoints:
        - !If [CreateEndpoints, !Ref EcsEndpoint, ""]
        - !If [CreateEndpoints, !Ref EcsAgentEndpoint, ""]
        - !If [CreateEndpoints, !Ref EcsTelemetryEndpoint, ""]
        - !If [CreateEndpoints, !Ref EcrApiEndpoint, ""]
        - !If [CreateEndpoints, !Ref EcrDkrEndpoint, ""]
        - !If [CreateEndpoints, !Ref S3GatewayEndpoint, ""]
        - !If [CreateRemoteImageEndpoints, !Ref MarketplaceLayersEndpoint, ""]
        - !If [CreateEndpoints, !Ref LogsEndpoint, ""]
        - !If [CreateEndpoints, !Ref SecretsManagerEndpoint, ""]
        - !If [CreateEndpoints, !Ref KmsEndpoint, ""]
        - !If [CreateEndpoints, !Ref StsEndpoint, ""]
        - !If [CreateEndpoints, !Ref MeteringEndpoint, ""]

  AutoScalingGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    DependsOn: EndpointsReady
    Properties:
      VPCZoneIdentifier: !Ref PrivateSubnetIds
      MinSize: !Ref AsgMinSize
      MaxSize: !Ref AsgMaxSize
      NewInstancesProtectedFromScaleIn: false
      LaunchTemplate:
        LaunchTemplateId: !Ref LaunchTemplate
        Version: !GetAtt LaunchTemplate.LatestVersionNumber
      Tags:
        - Key: Name
          Value: !Sub "${NamePrefix}-ecs"
          PropagateAtLaunch: true

  CapacityProvider:
    Type: AWS::ECS::CapacityProvider
    Properties:
      AutoScalingGroupProvider:
        AutoScalingGroupArn: !Ref AutoScalingGroup
        # Off, because protected instances outlive this capacity provider and block the ASG's
        # delete. Draining still moves tasks off an instance before scale-in or instance refresh
        # terminates it, which needs the agent's endpoints to outlive the services
        # (EndpointsReady above).
        ManagedTerminationProtection: DISABLED
        ManagedDraining: ENABLED
        ManagedScaling:
          Status: ENABLED
          TargetCapacity: 100

  ClusterCapacityProviders:
    Type: AWS::ECS::ClusterCapacityProviderAssociations
    Properties:
      Cluster: !Ref Cluster
      CapacityProviders: [!Ref CapacityProvider]
      DefaultCapacityProviderStrategy:
        - CapacityProvider: !Ref CapacityProvider
          Weight: 1

  # ---- VPC Lattice -------------------------------------------------------------------------------
  # Callers sign requests with their own IAM role (SigV4, service vpc-lattice-svcs). Lattice checks
  # each service's auth policy per path and method, terminates TLS, and forwards identity headers
  # that the runtime checks again. A same-account caller needs an identity policy too
  # (DetectCallerPolicy, RehydrateCallerPolicy outputs), so the Allows below are the whole gate:
  # no Deny is needed.
  LatticeServiceNetwork:
    Type: AWS::VpcLattice::ServiceNetwork
    Condition: CreateServiceNetwork
    Properties:
      Name: !Ref NamePrefix
      AuthType: AWS_IAM

  # Coarse gate: signed requests only. The service policies decide who may call what.
  LatticeServiceNetworkPolicy:
    Type: AWS::VpcLattice::AuthPolicy
    Condition: CreateServiceNetwork
    Properties:
      ResourceIdentifier: !Ref LatticeServiceNetwork
      Policy:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: "*"
            Action: vpc-lattice-svcs:Invoke
            Resource: "*"
            Condition:
              StringNotEqualsIgnoreCase: { "aws:PrincipalType": anonymous }

  LatticeVpcAssociation:
    Type: AWS::VpcLattice::ServiceNetworkVpcAssociation
    Condition: CreateServiceNetwork
    Properties:
      ServiceNetworkIdentifier: !Ref LatticeServiceNetwork
      VpcIdentifier: !Ref VpcId
      SecurityGroupIds: [!Ref LatticeAssociationSecurityGroup]

  # Access logs record the caller principal, its tags, the source VPC and any deny reason; join
  # them to audit records on requestId = upstream_request_id.
  LatticeLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Sub "/${NamePrefix}/lattice"
      RetentionInDays: !Ref LogRetentionDays
      KmsKeyId: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn]

  # ECS registers and deregisters task IPs in the Lattice target groups with this role. No RoleName:
  # ECS keeps credentials for a role ARN, so a role deleted (say by a rolled-back stack update)
  # and recreated under the same name is refused for a while ("missing permissions on ECS
  # Infrastructure Role"). A generated name is new every time.
  EcsLatticeRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: { Service: ecs.amazonaws.com }
            Action: sts:AssumeRole
            Condition:
              StringEquals: { "aws:SourceAccount": !Ref AWS::AccountId }
      ManagedPolicyArns:
        - !Sub "arn:${AWS::Partition}:iam::aws:policy/AmazonECSInfrastructureRolePolicyForVpcLattice"

  DetectLatticeTargetGroup:
    Type: AWS::VpcLattice::TargetGroup
    Properties:
      Name: !Sub "${NamePrefix}-detect"
      Type: IP
      Config:
        Port: 19991
        Protocol: HTTPS
        ProtocolVersion: HTTP1
        IpAddressType: IPV4
        VpcIdentifier: !Ref VpcId
        HealthCheck:
          Enabled: true
          Protocol: HTTPS
          Port: 19991
          Path: /readyz
          HealthCheckIntervalSeconds: 10
          HealthyThresholdCount: 2
          UnhealthyThresholdCount: 2
          Matcher: { HttpCode: "200" }

  DetectLatticeService:
    Type: AWS::VpcLattice::Service
    Properties:
      Name: !Sub "${NamePrefix}-detect"
      AuthType: AWS_IAM

  # Only the API's own routes are forwarded; anything else gets a fixed 404 from Lattice.
  DetectLatticeListener:
    Type: AWS::VpcLattice::Listener
    Properties:
      ServiceIdentifier: !Ref DetectLatticeService
      Protocol: HTTPS
      Port: 443
      DefaultAction: { FixedResponse: { StatusCode: 404 } }

  DetectRuleDetect:
    Type: AWS::VpcLattice::Rule
    Properties:
      ServiceIdentifier: !Ref DetectLatticeService
      ListenerIdentifier: !Ref DetectLatticeListener
      Priority: 10
      Match: { HttpMatch: { Method: POST, PathMatch: { Match: { Exact: /detect }, CaseSensitive: true } } }
      Action: { Forward: { TargetGroups: [{ TargetGroupIdentifier: !Ref DetectLatticeTargetGroup, Weight: 100 }] } }

  DetectRuleRedact:
    Type: AWS::VpcLattice::Rule
    Properties:
      ServiceIdentifier: !Ref DetectLatticeService
      ListenerIdentifier: !Ref DetectLatticeListener
      Priority: 20
      Match: { HttpMatch: { Method: POST, PathMatch: { Match: { Exact: /redact }, CaseSensitive: true } } }
      Action: { Forward: { TargetGroups: [{ TargetGroupIdentifier: !Ref DetectLatticeTargetGroup, Weight: 100 }] } }

  DetectRuleDeidentify:
    Type: AWS::VpcLattice::Rule
    Properties:
      ServiceIdentifier: !Ref DetectLatticeService
      ListenerIdentifier: !Ref DetectLatticeListener
      Priority: 30
      Match: { HttpMatch: { Method: POST, PathMatch: { Match: { Exact: /deidentify }, CaseSensitive: true } } }
      Action: { Forward: { TargetGroups: [{ TargetGroupIdentifier: !Ref DetectLatticeTargetGroup, Weight: 100 }] } }

  DetectRuleErase:
    Type: AWS::VpcLattice::Rule
    Properties:
      ServiceIdentifier: !Ref DetectLatticeService
      ListenerIdentifier: !Ref DetectLatticeListener
      Priority: 40
      Match: { HttpMatch: { Method: DELETE, PathMatch: { Match: { Prefix: /sessions/ }, CaseSensitive: true } } }
      Action: { Forward: { TargetGroups: [{ TargetGroupIdentifier: !Ref DetectLatticeTargetGroup, Weight: 100 }] } }

  DetectLatticeServiceAssociation:
    Type: AWS::VpcLattice::ServiceNetworkServiceAssociation
    Properties:
      ServiceNetworkIdentifier: !If [UseExistingServiceNetwork, !Ref ExistingServiceNetworkArn, !Ref LatticeServiceNetwork]
      ServiceIdentifier: !Ref DetectLatticeService

  DetectLatticeAccessLogs:
    Type: AWS::VpcLattice::AccessLogSubscription
    Properties:
      ResourceIdentifier: !Ref DetectLatticeService
      DestinationArn: !GetAtt LatticeLogGroup.Arn

  DetectLatticeAuthPolicy:
    Type: AWS::VpcLattice::AuthPolicy
    Properties:
      ResourceIdentifier: !Ref DetectLatticeService
      Policy:
        Version: "2012-10-17"
        Statement:
          - Sid: Detect
            Effect: Allow
            Principal: { AWS: !Ref DetectInvokerRoleArns }
            Action: vpc-lattice-svcs:Invoke
            Resource: !Sub "${DetectLatticeService.Arn}/*"
            Condition:
              StringEquals:
                vpc-lattice-svcs:RequestMethod: POST
                vpc-lattice-svcs:RequestPath: [/detect, /redact, /deidentify]
                vpc-lattice-svcs:SourceVpc: !If [DefaultSourceVpcs, [!Ref VpcId], !Ref AllowedSourceVpcIds]
          - !If
            - HasErasers
            - Sid: Erase
              Effect: Allow
              Principal: { AWS: !Ref ErasureInvokerRoleArns }
              Action: vpc-lattice-svcs:Invoke
              Resource: !Sub "${DetectLatticeService.Arn}/*"
              Condition:
                StringEquals:
                  vpc-lattice-svcs:RequestMethod: DELETE
                  vpc-lattice-svcs:SourceVpc: !If [DefaultSourceVpcs, [!Ref VpcId], !Ref AllowedSourceVpcIds]
                StringLike:
                  vpc-lattice-svcs:RequestPath: /sessions/*
            - !Ref AWS::NoValue

  RehydrateLatticeTargetGroup:
    Type: AWS::VpcLattice::TargetGroup
    Condition: Rehydration
    Properties:
      Name: !Sub "${NamePrefix}-rehydrate"
      Type: IP
      Config:
        Port: 19991
        Protocol: HTTPS
        ProtocolVersion: HTTP1
        IpAddressType: IPV4
        VpcIdentifier: !Ref VpcId
        HealthCheck:
          Enabled: true
          Protocol: HTTPS
          Port: 19991
          Path: /readyz
          HealthCheckIntervalSeconds: 10
          HealthyThresholdCount: 2
          UnhealthyThresholdCount: 2
          Matcher: { HttpCode: "200" }

  RehydrateLatticeService:
    Type: AWS::VpcLattice::Service
    Condition: Rehydration
    Properties:
      Name: !Sub "${NamePrefix}-rehydrate"
      AuthType: AWS_IAM

  # Only the API's own routes are forwarded; anything else gets a fixed 404 from Lattice.
  RehydrateLatticeListener:
    Type: AWS::VpcLattice::Listener
    Condition: Rehydration
    Properties:
      ServiceIdentifier: !Ref RehydrateLatticeService
      Protocol: HTTPS
      Port: 443
      DefaultAction: { FixedResponse: { StatusCode: 404 } }

  RehydrateRuleReidentify:
    Type: AWS::VpcLattice::Rule
    Condition: Rehydration
    Properties:
      ServiceIdentifier: !Ref RehydrateLatticeService
      ListenerIdentifier: !Ref RehydrateLatticeListener
      Priority: 10
      Match: { HttpMatch: { Method: POST, PathMatch: { Match: { Exact: /reidentify }, CaseSensitive: true } } }
      Action: { Forward: { TargetGroups: [{ TargetGroupIdentifier: !Ref RehydrateLatticeTargetGroup, Weight: 100 }] } }

  RehydrateLatticeServiceAssociation:
    Type: AWS::VpcLattice::ServiceNetworkServiceAssociation
    Condition: Rehydration
    Properties:
      ServiceNetworkIdentifier: !If [UseExistingServiceNetwork, !Ref ExistingServiceNetworkArn, !Ref LatticeServiceNetwork]
      ServiceIdentifier: !Ref RehydrateLatticeService

  # After detect's: each subscription makes CloudWatch Logs rewrite the log group's resource policy,
  # and two at once fail with OperationAbortedException.
  RehydrateLatticeAccessLogs:
    Type: AWS::VpcLattice::AccessLogSubscription
    Condition: Rehydration
    DependsOn: DetectLatticeAccessLogs
    Properties:
      ResourceIdentifier: !Ref RehydrateLatticeService
      DestinationArn: !GetAtt LatticeLogGroup.Arn

  RehydrateLatticeAuthPolicy:
    Type: AWS::VpcLattice::AuthPolicy
    Condition: Rehydration
    Properties:
      ResourceIdentifier: !Ref RehydrateLatticeService
      Policy:
        Version: "2012-10-17"
        Statement:
          # The approval tag is checked on every rehydration. Lattice doesn't forward session tags,
          # so this policy is the only place it can be checked.
          - Sid: Reidentify
            Effect: Allow
            Principal: { AWS: !Ref RehydrateInvokerRoleArns }
            Action: vpc-lattice-svcs:Invoke
            Resource: !Sub "${RehydrateLatticeService.Arn}/*"
            Condition: !If
              - RequireApproval
              - StringEquals:
                  vpc-lattice-svcs:RequestMethod: POST
                  vpc-lattice-svcs:RequestPath: /reidentify
                  vpc-lattice-svcs:SourceVpc: !If [DefaultSourceVpcs, [!Ref VpcId], !Ref AllowedSourceVpcIds]
                "Null": { "aws:PrincipalTag/tenet-approval-id": "false" }
              - StringEquals:
                  vpc-lattice-svcs:RequestMethod: POST
                  vpc-lattice-svcs:RequestPath: /reidentify
                  vpc-lattice-svcs:SourceVpc: !If [DefaultSourceVpcs, [!Ref VpcId], !Ref AllowedSourceVpcIds]
          - !If
            - CreateBreakGlass
            - Sid: BreakGlass
              Effect: Allow
              Principal: { AWS: !GetAtt BreakGlassRole.Arn }
              Action: vpc-lattice-svcs:Invoke
              Resource: !Sub "${RehydrateLatticeService.Arn}/*"
              Condition:
                StringEquals:
                  vpc-lattice-svcs:RequestMethod: POST
                  vpc-lattice-svcs:RequestPath: /reidentify
                  vpc-lattice-svcs:SourceVpc: !If [DefaultSourceVpcs, [!Ref VpcId], !Ref AllowedSourceVpcIds]
            - !Ref AWS::NoValue

  # ---- detect -----------------------------------------------------------------------------
  DetectTaskDefinition:
    Type: AWS::ECS::TaskDefinition
    Properties:
      Family: !Sub "${NamePrefix}-detect"
      RequiresCompatibilities: [EC2]
      NetworkMode: awsvpc
      RuntimePlatform: { CpuArchitecture: ARM64, OperatingSystemFamily: LINUX }
      TaskRoleArn: !GetAtt DetectTaskRole.Arn
      ExecutionRoleArn: !GetAtt DetectExecutionRole.Arn
      ContainerDefinitions:
        - Name: detect
          Image: !Ref ImageUri
          Essential: true
          # One 4-thread worker; 4 vCPU, 3 GiB soft / 4 GiB hard memory.
          Cpu: 4096
          MemoryReservation: 3072
          Memory: 4096
          User: "10001"
          ReadonlyRootFilesystem: true
          LinuxParameters:
            InitProcessEnabled: true
            Capabilities: { Drop: [ALL] }
            Tmpfs: [{ ContainerPath: /tmp, Size: 512 }]
          PortMappings: [{ Name: tenet, ContainerPort: 19991, Protocol: tcp }]
          Environment:
            - { Name: TENET_ROLE, Value: detect }
            - Name: TENET_VAULT_URL
              Value: !Sub
                - "postgresql://${Host}:${Port}/${VaultDatabaseName}?sslmode=require"
                - Host: !If [CreateDb, !GetAtt VaultCluster.Endpoint.Address, !Ref ExistingVaultEndpoint]
                  Port: !If [CreateDb, "5432", !Ref ExistingVaultPort]
            - { Name: TENET_KMS_KEY_ARN, Value: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn] }
            - { Name: TENET_DEPLOYMENT_ID, Value: !Ref DeploymentId }
            - !If
              - HasTelemetryPath
              - { Name: TENET_TELEMETRY_PATH, Value: !Ref TelemetryPath }
              - !Ref AWS::NoValue
            - { Name: TENET_LATTICE_SERVICE_ARN, Value: !GetAtt DetectLatticeService.Arn }
            - { Name: TENET_LATTICE_ERASE_PRINCIPALS, Value: !Join [",", !Ref ErasureInvokerRoleArns] }
            - Name: TENET_AUDIT_S3_URI
              Value: !Sub
                - "s3://${Bucket}/${ErasureAuditPrefix}"
                - Bucket: !If [CreateAuditBucket, !Ref AuditBucket, !Ref ExistingAuditBucketName]
            - !If
              - TelemetryEgress
              - { Name: TENET_TELEMETRY_SINK_URL, Value: !Ref UsageTelemetrySinkUrl }
              - !Ref AWS::NoValue
            - { Name: AWS_REGION, Value: !Ref AWS::Region }
            - { Name: AWS_STS_REGIONAL_ENDPOINTS, Value: regional }
            - { Name: HOME, Value: /tmp }
            - { Name: TMPDIR, Value: /tmp }
          Secrets:
            - !If
              - TelemetryEgress
              - { Name: TENET_TELEMETRY_API_KEY, ValueFrom: !Ref UsageTelemetryApiKeySecretArn }
              - !Ref AWS::NoValue
            # libpq reads PGUSER/PGPASSWORD, so the password never appears in TENET_VAULT_URL.
            - Name: PGUSER
              ValueFrom: !Sub
                - "${S}:username::"
                - S: !If [CreateDb, !GetAtt VaultCluster.MasterUserSecret.SecretArn, !Ref ExistingVaultSecretArn]
            - Name: PGPASSWORD
              ValueFrom: !Sub
                - "${S}:password::"
                - S: !If [CreateDb, !GetAtt VaultCluster.MasterUserSecret.SecretArn, !Ref ExistingVaultSecretArn]
          # Liveness = /healthz (container health); readiness = /readyz (Lattice target health).
          # The subcommand probes HTTPS.
          HealthCheck:
            Command: [CMD, tenet-pii-enterprise, healthcheck]
            Interval: 15
            Timeout: 5
            Retries: 3
            StartPeriod: 300
          LogConfiguration:
            LogDriver: awslogs
            Options:
              awslogs-group: !Ref DetectLogGroup
              awslogs-region: !Ref AWS::Region
              awslogs-stream-prefix: detect
              mode: non-blocking

  DetectService:
    Type: AWS::ECS::Service
    # Starts once its Lattice routes and auth policy exist, so no caller sees it half configured.
    DependsOn:
      - DetectRuleDetect
      - DetectRuleRedact
      - DetectRuleDeidentify
      - DetectRuleErase
      - DetectLatticeServiceAssociation
      - DetectLatticeAuthPolicy
      - ClusterCapacityProviders
      - VaultReady
    Properties:
      ServiceName: detect
      Cluster: !Ref Cluster
      TaskDefinition: !Ref DetectTaskDefinition
      DesiredCount: !Ref DetectDesiredCount
      CapacityProviderStrategy:
        - CapacityProvider: !Ref CapacityProvider
          Weight: 1
      NetworkConfiguration:
        AwsvpcConfiguration:
          Subnets: !Ref PrivateSubnetIds
          SecurityGroups: [!Ref DetectTaskSecurityGroup]
          AssignPublicIp: DISABLED
      VpcLatticeConfigurations:
        - RoleArn: !GetAtt EcsLatticeRole.Arn
          TargetGroupArn: !GetAtt DetectLatticeTargetGroup.Arn
          PortName: tenet
      PlacementStrategies:
        - { Type: spread, Field: "attribute:ecs.availability-zone" }
        - { Type: spread, Field: instanceId }
      DeploymentConfiguration:
        MinimumHealthyPercent: !Ref DeploymentMinimumHealthyPercent
        MaximumPercent: !Ref DeploymentMaximumPercent
        DeploymentCircuitBreaker: { Enable: true, Rollback: true }
      EnableExecuteCommand: false
      PropagateTags: SERVICE

  DetectScalableTarget:
    Type: AWS::ApplicationAutoScaling::ScalableTarget
    Condition: DetectAutoScaling
    Properties:
      ServiceNamespace: ecs
      ScalableDimension: ecs:service:DesiredCount
      ResourceId: !Sub "service/${Cluster}/${DetectService.Name}"
      MinCapacity: !Ref DetectDesiredCount
      MaxCapacity: !Ref DetectMaxCount

  DetectCpuScaling:
    Type: AWS::ApplicationAutoScaling::ScalingPolicy
    Condition: DetectAutoScaling
    Properties:
      PolicyName: !Sub "${NamePrefix}-detect-cpu"
      PolicyType: TargetTrackingScaling
      ScalingTargetId: !Ref DetectScalableTarget
      TargetTrackingScalingPolicyConfiguration:
        TargetValue: !Ref DetectCpuTargetPercent
        PredefinedMetricSpecification:
          PredefinedMetricType: ECSServiceAverageCPUUtilization
        ScaleInCooldown: 600
        ScaleOutCooldown: 120

  # ---- rehydrate (its own Lattice service) -------------------------------------------------------
  RehydrateTaskDefinition:
    Type: AWS::ECS::TaskDefinition
    Condition: Rehydration
    Properties:
      Family: !Sub "${NamePrefix}-rehydrate"
      RequiresCompatibilities: [EC2]
      NetworkMode: awsvpc
      RuntimePlatform: { CpuArchitecture: ARM64, OperatingSystemFamily: LINUX }
      TaskRoleArn: !GetAtt RehydrateTaskRole.Arn
      ExecutionRoleArn: !GetAtt RehydrateExecutionRole.Arn
      ContainerDefinitions:
        - Name: rehydrate
          Image: !Ref ImageUri
          Essential: true
          # Small and rarely called; memory matches detect because /readyz
          # requires the model to be loaded in both roles.
          Cpu: 1024
          MemoryReservation: 3072
          Memory: 4096
          User: "10001"
          ReadonlyRootFilesystem: true
          LinuxParameters:
            InitProcessEnabled: true
            Capabilities: { Drop: [ALL] }
            Tmpfs: [{ ContainerPath: /tmp, Size: 512 }]
          PortMappings: [{ Name: tenet, ContainerPort: 19991, Protocol: tcp }]
          Environment:
            - { Name: TENET_ROLE, Value: rehydrate }
            - Name: TENET_VAULT_URL
              Value: !Sub
                - "postgresql://${Host}:${Port}/${VaultDatabaseName}?sslmode=require"
                - Host: !If [CreateDb, !GetAtt VaultCluster.Endpoint.Address, !Ref ExistingVaultEndpoint]
                  Port: !If [CreateDb, "5432", !Ref ExistingVaultPort]
            - { Name: TENET_KMS_KEY_ARN, Value: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn] }
            - Name: TENET_AUDIT_S3_URI
              Value: !Sub
                - "s3://${Bucket}/${AuditPrefix}"
                - Bucket: !If [CreateAuditBucket, !Ref AuditBucket, !Ref ExistingAuditBucketName]
            - { Name: TENET_LATTICE_SERVICE_ARN, Value: !GetAtt RehydrateLatticeService.Arn }
            # The runtime's own allow-list, checked after Lattice's. Break-glass must be on it.
            - Name: TENET_LATTICE_REIDENTIFY_PRINCIPALS
              Value: !Join
                - ","
                - - !Join [",", !Ref RehydrateInvokerRoleArns]
                  - !If [CreateBreakGlass, !GetAtt BreakGlassRole.Arn, !Ref AWS::NoValue]
            - { Name: TENET_DEPLOYMENT_ID, Value: !Ref DeploymentId }
            - !If
              - HasTelemetryPath
              - { Name: TENET_TELEMETRY_PATH, Value: !Ref TelemetryPath }
              - !Ref AWS::NoValue
            - { Name: AWS_REGION, Value: !Ref AWS::Region }
            - { Name: AWS_STS_REGIONAL_ENDPOINTS, Value: regional }
            - { Name: HOME, Value: /tmp }
            - { Name: TMPDIR, Value: /tmp }
          Secrets:
            - Name: PGUSER
              ValueFrom: !Sub
                - "${S}:username::"
                - S: !If [CreateDb, !GetAtt VaultCluster.MasterUserSecret.SecretArn, !Ref ExistingVaultSecretArn]
            - Name: PGPASSWORD
              ValueFrom: !Sub
                - "${S}:password::"
                - S: !If [CreateDb, !GetAtt VaultCluster.MasterUserSecret.SecretArn, !Ref ExistingVaultSecretArn]
          # Readiness-gated: a task that can't reach the vault is unhealthy, and ECS replaces it.
          HealthCheck:
            Command: [CMD, tenet-pii-enterprise, healthcheck, --ready]
            Interval: 15
            Timeout: 5
            Retries: 3
            StartPeriod: 300
          LogConfiguration:
            LogDriver: awslogs
            Options:
              awslogs-group: !Ref RehydrateLogGroup
              awslogs-region: !Ref AWS::Region
              awslogs-stream-prefix: rehydrate
              mode: non-blocking

  RehydrateService:
    Type: AWS::ECS::Service
    Condition: Rehydration
    DependsOn:
      - RehydrateRuleReidentify
      - RehydrateLatticeServiceAssociation
      - RehydrateLatticeAuthPolicy
      - ClusterCapacityProviders
      - VaultReady
    Properties:
      ServiceName: rehydrate
      Cluster: !Ref Cluster
      TaskDefinition: !Ref RehydrateTaskDefinition
      DesiredCount: !Ref RehydrateDesiredCount
      CapacityProviderStrategy:
        - CapacityProvider: !Ref CapacityProvider
          Weight: 1
      NetworkConfiguration:
        AwsvpcConfiguration:
          Subnets: !Ref PrivateSubnetIds
          SecurityGroups: [!Ref RehydrateTaskSecurityGroup]
          AssignPublicIp: DISABLED
      VpcLatticeConfigurations:
        - RoleArn: !GetAtt EcsLatticeRole.Arn
          TargetGroupArn: !GetAtt RehydrateLatticeTargetGroup.Arn
          PortName: tenet
      PlacementStrategies:
        - { Type: spread, Field: "attribute:ecs.availability-zone" }
        - { Type: spread, Field: instanceId }
      DeploymentConfiguration:
        # With one task, any floor above 0 rounds up to that task: ECS can neither stop it nor start
        # a second (maximum 100%), and the rollout never finishes.
        MinimumHealthyPercent: !If [SingleRehydrate, 0, !Ref DeploymentMinimumHealthyPercent]
        MaximumPercent: !Ref DeploymentMaximumPercent
        DeploymentCircuitBreaker: { Enable: true, Rollback: true }
      EnableExecuteCommand: false
      PropagateTags: SERVICE

Outputs:
  DetectEndpoint:
    Description: >-
      Detect / de-identify / erase API (in-VPC). Callers sign requests (SigV4, service
      vpc-lattice-svcs) and attach LatticeClientSecurityGroupId.
    Value: !Sub "https://${DetectLatticeService.DnsEntry.DomainName}"
  RehydrateEndpoint:
    Condition: Rehydration
    Description: >-
      Rehydrate API. Callers sign requests and must be in RehydrateInvokerRoleArns.
    Value: !Sub "https://${RehydrateLatticeService.DnsEntry.DomainName}"
  KmsKeyArn:
    Value: !If [CreateKey, !GetAtt VaultKey.Arn, !Ref KmsKeyArn]
  AuditBucket:
    Value: !If [CreateAuditBucket, !Ref AuditBucket, !Ref ExistingAuditBucketName]
  VaultEndpoint:
    Value: !If [CreateDb, !GetAtt VaultCluster.Endpoint.Address, !Ref ExistingVaultEndpoint]
  DetectTaskRoleArn:
    Value: !GetAtt DetectTaskRole.Arn
  RehydrateTaskRoleArn:
    Condition: Rehydration
    Value: !GetAtt RehydrateTaskRole.Arn
  BreakGlassRoleArn:
    Condition: CreateBreakGlass
    Value: !GetAtt BreakGlassRole.Arn
  ClusterName:
    Value: !Ref Cluster
  DeploymentId:
    Description: TENET_DEPLOYMENT_ID (pinned as kms:EncryptionContext:tenet:deployment)
    Value: !Ref DeploymentId
  ServiceNetworkArn:
    Description: Associate other caller VPCs with this service network, or share it with AWS RAM.
    Value: !If [UseExistingServiceNetwork, !Ref ExistingServiceNetworkArn, !Ref LatticeServiceNetwork]
  DetectServiceArn:
    Value: !GetAtt DetectLatticeService.Arn
  RehydrateServiceArn:
    Condition: Rehydration
    Value: !GetAtt RehydrateLatticeService.Arn
  LatticeClientSecurityGroupId:
    Description: Attach to workloads that call the services (egress 443 to VPC Lattice only).
    Value: !Ref LatticeClientSecurityGroup
  DetectCallerPolicy:
    Description: >-
      Identity policy for each role in DetectInvokerRoleArns and ErasureInvokerRoleArns. A
      same-account caller needs it as well as the service's auth policy.
    Value: !Sub '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"vpc-lattice-svcs:Invoke","Resource":"${DetectLatticeService.Arn}/*"}]}'
  RehydrateCallerPolicy:
    Condition: Rehydration
    Description: Identity policy for each role in RehydrateInvokerRoleArns.
    Value: !Sub '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"vpc-lattice-svcs:Invoke","Resource":"${RehydrateLatticeService.Arn}/*"}]}'
