AWSTemplateFormatVersion: "2010-09-09"
Description: >-
  V19 change watch. Sends AWS API calls that change something (from CloudTrail, through EventBridge)
  to V19, so V19 can flag production changes that did not go through it. No forwarder or Lambda.
  Deploy once in every Region you use. IAM and other global services report in us-east-1, so include
  us-east-1. Needs a CloudTrail trail that is logging management events (AWS sends
  these events to EventBridge only then); set CreateTrail to Yes if the account has none. The API key is kept by EventBridge in AWS Secrets Manager (a small monthly AWS charge).

Parameters:
  V19ApiKey:
    Type: String
    NoEcho: true
    MinLength: 20
    Description: A V19 API key with only the change:observe scope (create it under API keys in V19).
  V19Endpoint:
    Type: String
    Default: https://visionxixlabs.com/api/v1/changes/observed
    AllowedPattern: "^https://.+"
    Description: Leave as is unless you run V19 yourself.
  MaxCallsPerSecond:
    Type: Number
    Default: 10
    MinValue: 1
    MaxValue: 300
    Description: Upper limit on calls to V19 per second. Extra events wait and are retried for up to 24 hours.
  CreateTrail:
    Type: String
    Default: "No"
    AllowedValues: ["Yes", "No"]
    Description: >-
      Yes creates a multi-Region CloudTrail trail and a private S3 bucket for it (logs expire after
      90 days). Use it only if this account has no trail logging management events yet. Create it in
      one Region only. The first trail's management events are free; S3 storage is billed by AWS.

Conditions:
  MakeTrail: !Equals [!Ref CreateTrail, "Yes"]

Resources:
  V19Connection:
    Type: AWS::Events::Connection
    Properties:
      Description: V19 change watch API key
      AuthorizationType: API_KEY
      AuthParameters:
        ApiKeyAuthParameters:
          ApiKeyName: Authorization
          ApiKeyValue: !Sub "Bearer ${V19ApiKey}"

  V19Destination:
    Type: AWS::Events::ApiDestination
    Properties:
      Description: V19 observed changes endpoint
      ConnectionArn: !GetAtt V19Connection.Arn
      HttpMethod: POST
      InvocationEndpoint: !Ref V19Endpoint
      InvocationRateLimitPerSecond: !Ref MaxCallsPerSecond

  V19InvokeRole:
    Type: AWS::IAM::Role
    Properties:
      Description: Lets EventBridge call the V19 change watch destination and nothing else.
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal: { Service: events.amazonaws.com }
            Action: sts:AssumeRole
            Condition:
              StringEquals: { "aws:SourceAccount": !Ref "AWS::AccountId" }
      Policies:
        - PolicyName: invoke-v19-destination
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action: events:InvokeApiDestination
                Resource: !GetAtt V19Destination.Arn

  V19ChangeRule:
    Type: AWS::Events::Rule
    Properties:
      Description: Successful AWS API calls that change something, sent to V19.
      State: ENABLED
      EventPattern:
        detail-type:
          - AWS API Call via CloudTrail
        detail:
          errorCode:
            - exists: false
          $or:
            - readOnly: [false]
            - readOnly:
                - exists: false
      Targets:
        - Id: v19-change-watch
          Arn: !GetAtt V19Destination.Arn
          RoleArn: !GetAtt V19InvokeRole.Arn
          InputTransformer:
            InputPathsMap:
              detail: $.detail
            InputTemplate: '{"provider":"aws_cloudtrail","records":[<detail>]}'
          RetryPolicy:
            MaximumEventAgeInSeconds: 86400
            MaximumRetryAttempts: 185

  V19TrailBucket:
    Type: AWS::S3::Bucket
    Condition: MakeTrail
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault: { SSEAlgorithm: AES256 }
      OwnershipControls:
        Rules:
          - ObjectOwnership: BucketOwnerEnforced
      LifecycleConfiguration:
        Rules:
          - Id: expire-trail-logs
            Status: Enabled
            ExpirationInDays: 90

  V19TrailBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Condition: MakeTrail
    Properties:
      Bucket: !Ref V19TrailBucket
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: CloudTrailAclCheck
            Effect: Allow
            Principal: { Service: cloudtrail.amazonaws.com }
            Action: s3:GetBucketAcl
            Resource: !GetAtt V19TrailBucket.Arn
            Condition:
              StringEquals: { "aws:SourceArn": !Sub "arn:${AWS::Partition}:cloudtrail:${AWS::Region}:${AWS::AccountId}:trail/v19-change-watch" }
          - Sid: CloudTrailWrite
            Effect: Allow
            Principal: { Service: cloudtrail.amazonaws.com }
            Action: s3:PutObject
            Resource: !Sub "${V19TrailBucket.Arn}/AWSLogs/${AWS::AccountId}/*"
            Condition:
              StringEquals: { "aws:SourceArn": !Sub "arn:${AWS::Partition}:cloudtrail:${AWS::Region}:${AWS::AccountId}:trail/v19-change-watch" }
          - Sid: DenyInsecureTransport
            Effect: Deny
            Principal: "*"
            Action: s3:*
            Resource: [!GetAtt V19TrailBucket.Arn, !Sub "${V19TrailBucket.Arn}/*"]
            Condition:
              Bool: { "aws:SecureTransport": "false" }

  V19Trail:
    Type: AWS::CloudTrail::Trail
    Condition: MakeTrail
    DependsOn: V19TrailBucketPolicy
    Properties:
      TrailName: v19-change-watch
      S3BucketName: !Ref V19TrailBucket
      IsLogging: true
      IsMultiRegionTrail: true
      IncludeGlobalServiceEvents: true
      EnableLogFileValidation: true

Outputs:
  RuleName:
    Description: Disable this rule to pause sending changes to V19.
    Value: !Ref V19ChangeRule
  TrailBucket:
    Condition: MakeTrail
    Description: Bucket holding the trail's logs. It is kept if you delete the stack; empty and delete it yourself.
    Value: !Ref V19TrailBucket
