AWSTemplateFormatVersion: '2010-09-09'
Description: VectorProof by Hill Consulting LLC. Runs the console, API and worker on Amazon ECS on AWS Fargate with Amazon RDS for PostgreSQL in your AWS account.

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label: { default: Product }
        Parameters: [ImageUri, ProductSku, AppUrl, TargetAllowedHosts, EnableDemoTargets]
      - Label: { default: Network }
        Parameters: [VpcId, PrivateSubnets, PublicSubnets, CertificateArn, AllowedIngressCidr]
      - Label: { default: Sizing and data }
        Parameters: [DbInstanceClass, DbAllocatedStorage, EvidenceRetentionDays]
      - Label: { default: Optional AWS access for Bedrock targets }
        Parameters: [TargetBedrockArns, FixtureBucketArn]

Parameters:
  ImageUri:
    Type: String
    Description: The VectorProof image URI shown after you subscribe in AWS Marketplace.
  ProductSku:
    Type: String
    Description: The product SKU shown in the usage instructions.
  AppUrl:
    Type: String
    AllowedPattern: '^https://[^/]+$'
    Description: HTTPS origin users will open, with no path. Example https://vectorproof.example.com
  TargetAllowedHosts:
    Type: String
    Description: Comma-separated hostnames this installation may test. Example rag.example.com,*.corp.example.com
  EnableDemoTargets:
    Type: String
    AllowedValues: ['true', 'false']
    Default: 'false'
    Description: Adds two simulated RAG apps on localhost in the worker task, for evaluation only.
  VpcId:
    Type: AWS::EC2::VPC::Id
  PrivateSubnets:
    Type: List<AWS::EC2::Subnet::Id>
    Description: At least two private subnets with outbound access to AWS service endpoints.
  PublicSubnets:
    Type: List<AWS::EC2::Subnet::Id>
    Description: At least two subnets for the load balancer.
  CertificateArn:
    Type: String
    Description: AWS Certificate Manager certificate for the AppUrl hostname.
  AllowedIngressCidr:
    Type: String
    Description: CIDR allowed to reach the console and API. Restrict this to your network.
    AllowedPattern: '^\d{1,3}(\.\d{1,3}){3}/\d{1,2}$'
  DbInstanceClass:
    Type: String
    Default: db.t4g.small
  DbAllocatedStorage:
    Type: Number
    Default: 50
    MinValue: 20
  EvidenceRetentionDays:
    Type: Number
    Default: 90
    MinValue: 1
  TargetBedrockArns:
    Type: CommaDelimitedList
    Default: ''
    Description: Optional ARNs of Bedrock models and Knowledge Bases the worker may call.
  FixtureBucketArn:
    Type: String
    Default: ''
    Description: Optional S3 bucket ARN for active fixtures on Knowledge Base targets. Use a dedicated prefix.

Conditions:
  Demo: !Equals [!Ref EnableDemoTargets, 'true']
  HasBedrock: !Not [!Equals [!Join ['', !Ref TargetBedrockArns], '']]
  HasFixtureBucket: !Not [!Equals [!Ref FixtureBucketArn, '']]

Resources:
  DbAdminSecret:
    Type: AWS::SecretsManager::Secret
    Properties:
      Description: VectorProof database administrator, used only by the migration container.
      GenerateSecretString:
        SecretStringTemplate: '{"username":"vectorproof_admin"}'
        GenerateStringKey: password
        PasswordLength: 40
        ExcludePunctuation: true
  DbAppSecret:
    Type: AWS::SecretsManager::Secret
    Properties:
      Description: VectorProof runtime database login. This role cannot bypass row-level security.
      GenerateSecretString:
        SecretStringTemplate: '{"username":"vectorproof_app"}'
        GenerateStringKey: password
        PasswordLength: 40
        ExcludePunctuation: true
  EncryptionKeySecret:
    Type: AWS::SecretsManager::Secret
    Properties:
      Description: VectorProof key for target credentials. Back this up with the database.
      GenerateSecretString: { PasswordLength: 64, ExcludePunctuation: true }
  SessionKeySecret:
    Type: AWS::SecretsManager::Secret
    Properties:
      Description: VectorProof console session signing key.
      GenerateSecretString: { PasswordLength: 64, ExcludePunctuation: true }
  BootstrapSecret:
    Type: AWS::SecretsManager::Secret
    Properties:
      Description: One-time VectorProof setup secret. It stops working after first-run setup.
      GenerateSecretString: { PasswordLength: 48, ExcludePunctuation: true }

  AlbSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: VectorProof load balancer
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - { IpProtocol: tcp, FromPort: 443, ToPort: 443, CidrIp: !Ref AllowedIngressCidr, Description: HTTPS from the allowed network }
  TaskSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: VectorProof tasks
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - { IpProtocol: tcp, FromPort: 8080, ToPort: 8080, SourceSecurityGroupId: !Ref AlbSecurityGroup, Description: From the load balancer }
  DbSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: VectorProof database
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - { IpProtocol: tcp, FromPort: 5432, ToPort: 5432, SourceSecurityGroupId: !Ref TaskSecurityGroup, Description: From VectorProof tasks }

  DbSubnetGroup:
    Type: AWS::RDS::DBSubnetGroup
    Properties:
      DBSubnetGroupDescription: VectorProof database subnets
      SubnetIds: !Ref PrivateSubnets
  Database:
    Type: AWS::RDS::DBInstance
    DeletionPolicy: Snapshot
    UpdateReplacePolicy: Snapshot
    Properties:
      Engine: postgres
      EngineVersion: '17.7'
      DBName: vectorproof
      DBInstanceClass: !Ref DbInstanceClass
      AllocatedStorage: !Ref DbAllocatedStorage
      StorageType: gp3
      StorageEncrypted: true
      PubliclyAccessible: false
      MultiAZ: true
      BackupRetentionPeriod: 14
      DeletionProtection: true
      CopyTagsToSnapshot: true
      MasterUsername: !Sub '{{resolve:secretsmanager:${DbAdminSecret}:SecretString:username}}'
      MasterUserPassword: !Sub '{{resolve:secretsmanager:${DbAdminSecret}:SecretString:password}}'
      DBSubnetGroupName: !Ref DbSubnetGroup
      VPCSecurityGroups: [!Ref DbSecurityGroup]

  LogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Sub '/vectorproof/${AWS::StackName}'
      RetentionInDays: 90

  ExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement: [{ Effect: Allow, Principal: { Service: ecs-tasks.amazonaws.com }, Action: sts:AssumeRole }]
      ManagedPolicyArns: [arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy]
      Policies:
        - PolicyName: read-secrets
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: secretsmanager:GetSecretValue
                Resource: [!Ref DbAdminSecret, !Ref DbAppSecret, !Ref EncryptionKeySecret, !Ref SessionKeySecret, !Ref BootstrapSecret]
  TaskRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement: [{ Effect: Allow, Principal: { Service: ecs-tasks.amazonaws.com }, Action: sts:AssumeRole }]
      Policies:
        - PolicyName: marketplace-license
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - license-manager:CheckoutLicense
                  - license-manager:GetLicense
                  - license-manager:CheckInLicense
                  - license-manager:ExtendLicenseConsumption
                  - license-manager:ListReceivedLicenses
                Resource: '*'
        - !If
          - HasBedrock
          - PolicyName: bedrock-targets
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: Allow
                  Action: [bedrock:InvokeModel, bedrock:Retrieve, bedrock:RetrieveAndGenerate, bedrock:StartIngestionJob]
                  Resource: !Ref TargetBedrockArns
          - !Ref AWS::NoValue
        - !If
          - HasFixtureBucket
          - PolicyName: fixture-objects
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: Allow
                  Action: [s3:PutObject, s3:PutObjectTagging, s3:DeleteObject]
                  Resource: !Sub '${FixtureBucketArn}/*'
          - !Ref AWS::NoValue

  Cluster:
    Type: AWS::ECS::Cluster
    Properties:
      ClusterSettings: [{ Name: containerInsights, Value: enabled }]

  ApiTask:
    Type: AWS::ECS::TaskDefinition
    Properties:
      Family: !Sub '${AWS::StackName}-api'
      Cpu: '512'
      Memory: '1024'
      NetworkMode: awsvpc
      RequiresCompatibilities: [FARGATE]
      ExecutionRoleArn: !GetAtt ExecutionRole.Arn
      TaskRoleArn: !GetAtt TaskRole.Arn
      ContainerDefinitions:
        - Name: migrate
          Image: !Ref ImageUri
          Essential: false
          Command: [migrate]
          ReadonlyRootFilesystem: true
          Environment:
            - { Name: DB_HOST, Value: !GetAtt Database.Endpoint.Address }
            - { Name: DB_NAME, Value: vectorproof }
            - { Name: DB_USER, Value: vectorproof_app }
          Secrets:
            - { Name: DB_ADMIN_USER, ValueFrom: !Sub '${DbAdminSecret}:username::' }
            - { Name: DB_ADMIN_PASSWORD, ValueFrom: !Sub '${DbAdminSecret}:password::' }
            - { Name: DB_PASSWORD, ValueFrom: !Sub '${DbAppSecret}:password::' }
          LogConfiguration: &logs
            LogDriver: awslogs
            Options:
              awslogs-group: !Ref LogGroup
              awslogs-region: !Ref AWS::Region
              awslogs-stream-prefix: vectorproof
        - Name: api
          Image: !Ref ImageUri
          Essential: true
          Command: [serve]
          ReadonlyRootFilesystem: true
          DependsOn: [{ ContainerName: migrate, Condition: SUCCESS }]
          PortMappings: [{ ContainerPort: 8080 }]
          HealthCheck:
            Command: ['CMD', '/usr/local/bin/vectorproof', 'healthcheck']
            Interval: 30
            Timeout: 5
            Retries: 3
            StartPeriod: 30
          Environment: &env
            - { Name: DB_HOST, Value: !GetAtt Database.Endpoint.Address }
            - { Name: DB_NAME, Value: vectorproof }
            - { Name: DB_USER, Value: vectorproof_app }
            - { Name: LICENSE_MODE, Value: marketplace }
            - { Name: MARKETPLACE_PRODUCT_SKU, Value: !Ref ProductSku }
            - { Name: AWS_REGION, Value: !Ref AWS::Region }
            - { Name: APP_URL, Value: !Ref AppUrl }
            - { Name: EVIDENCE_RETENTION_DAYS, Value: !Ref EvidenceRetentionDays }
            - Name: TARGET_ALLOWED_HOSTS
              Value: !If [Demo, !Sub '${TargetAllowedHosts},127.0.0.1', !Ref TargetAllowedHosts]
            - { Name: ALLOW_INSECURE_TARGETS, Value: !Ref EnableDemoTargets }
          Secrets: &secrets
            - { Name: DB_PASSWORD, ValueFrom: !Sub '${DbAppSecret}:password::' }
            - { Name: ENCRYPTION_KEY, ValueFrom: !Ref EncryptionKeySecret }
            - { Name: SESSION_KEY, ValueFrom: !Ref SessionKeySecret }
            - { Name: BOOTSTRAP_SECRET, ValueFrom: !Ref BootstrapSecret }
          LogConfiguration: *logs

  WorkerTask:
    Type: AWS::ECS::TaskDefinition
    Properties:
      Family: !Sub '${AWS::StackName}-worker'
      Cpu: '512'
      Memory: '1024'
      NetworkMode: awsvpc
      RequiresCompatibilities: [FARGATE]
      ExecutionRoleArn: !GetAtt ExecutionRole.Arn
      TaskRoleArn: !GetAtt TaskRole.Arn
      ContainerDefinitions:
        - Name: worker
          Image: !Ref ImageUri
          Essential: true
          Command: [worker]
          ReadonlyRootFilesystem: true
          Environment: *env
          Secrets: *secrets
          LogConfiguration: *logs
        - !If
          - Demo
          - Name: demo-vulnerable
            Image: !Ref ImageUri
            Essential: false
            Command: [demo-target, -addr, '127.0.0.1:9191', -vulnerable]
            ReadonlyRootFilesystem: true
            LogConfiguration: *logs
          - !Ref AWS::NoValue
        - !If
          - Demo
          - Name: demo-hardened
            Image: !Ref ImageUri
            Essential: false
            Command: [demo-target, -addr, '127.0.0.1:9192']
            ReadonlyRootFilesystem: true
            LogConfiguration: *logs
          - !Ref AWS::NoValue

  LoadBalancer:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Scheme: internet-facing
      Subnets: !Ref PublicSubnets
      SecurityGroups: [!Ref AlbSecurityGroup]
      LoadBalancerAttributes:
        - { Key: routing.http.drop_invalid_header_fields.enabled, Value: 'true' }
  TargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      VpcId: !Ref VpcId
      TargetType: ip
      Protocol: HTTP
      Port: 8080
      HealthCheckPath: /readyz
      HealthCheckIntervalSeconds: 30
      HealthyThresholdCount: 2
      UnhealthyThresholdCount: 3
  Listener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      LoadBalancerArn: !Ref LoadBalancer
      Port: 443
      Protocol: HTTPS
      SslPolicy: ELBSecurityPolicy-TLS13-1-2-2021-06
      Certificates: [{ CertificateArn: !Ref CertificateArn }]
      DefaultActions: [{ Type: forward, TargetGroupArn: !Ref TargetGroup }]

  ApiService:
    Type: AWS::ECS::Service
    DependsOn: Listener
    Properties:
      Cluster: !Ref Cluster
      LaunchType: FARGATE
      DesiredCount: 1
      TaskDefinition: !Ref ApiTask
      HealthCheckGracePeriodSeconds: 180
      DeploymentConfiguration: { DeploymentCircuitBreaker: { Enable: true, Rollback: true } }
      NetworkConfiguration:
        AwsvpcConfiguration: { AssignPublicIp: DISABLED, Subnets: !Ref PrivateSubnets, SecurityGroups: [!Ref TaskSecurityGroup] }
      LoadBalancers: [{ ContainerName: api, ContainerPort: 8080, TargetGroupArn: !Ref TargetGroup }]
  WorkerService:
    Type: AWS::ECS::Service
    DependsOn: ApiService
    Properties:
      Cluster: !Ref Cluster
      LaunchType: FARGATE
      DesiredCount: 1
      TaskDefinition: !Ref WorkerTask
      DeploymentConfiguration: { DeploymentCircuitBreaker: { Enable: true, Rollback: true } }
      NetworkConfiguration:
        AwsvpcConfiguration: { AssignPublicIp: DISABLED, Subnets: !Ref PrivateSubnets, SecurityGroups: [!Ref TaskSecurityGroup] }

Outputs:
  LoadBalancerDns:
    Description: Point your AppUrl hostname at this name.
    Value: !GetAtt LoadBalancer.DNSName
  BootstrapSecretArn:
    Description: Read this once during first-run setup.
    Value: !Ref BootstrapSecret
  EncryptionKeySecretArn:
    Description: Back this up with your database. Encrypted target settings cannot be recovered without it.
    Value: !Ref EncryptionKeySecret
