AWSTemplateFormatVersion: '2010-09-09'
Description: |
  Outseen: cost approval for new AWS resources. Customer onboarding stack.
  Forwards resource-launch CloudTrail events to Outseen (minimized: no source IP, user
  agent or session details) and creates a read-only IAM role that only Outseen's
  OutseenCustomerAccessRole can assume, with your External ID. No data-plane access and
  no tag writes. Stopping resources is OFF unless you opt in, and even then applies only
  to resources carrying the tag you choose.

  Works as a single stack (one region) or as a StackSet (many regions): the IAM role is
  created only in PrimaryRegion; event forwarding is created in every region you deploy to.
  Every permission and the data Outseen receives are listed at https://outseen.com/security

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label: { default: "Outseen configuration (from your Outseen dashboard)" }
        Parameters: [ExternalId, IngestKey]
      - Label: { default: "Regions" }
        Parameters: [PrimaryRegion]
      - Label: { default: "Missed-event check" }
        Parameters: [AllowMissedEventCheck]
      - Label: { default: "CloudTrail" }
        Parameters: [CreateTrail, TrailRetentionDays]
      - Label: { default: "Optional: security alerts" }
        Parameters: [SecurityAlertEmail]
      - Label: { default: "Optional: Auto-Quarantine (off by default)" }
        Parameters: [EnableAutoQuarantine, QuarantineTagKey, QuarantineTagValue]
    ParameterLabels:
      ExternalId: { default: "External ID" }
      IngestKey: { default: "Ingest key (shown once in the Outseen dashboard)" }
      PrimaryRegion: { default: "Region that holds the IAM role" }
      AllowMissedEventCheck: { default: "Let Outseen look up missed launches in CloudTrail?" }
      CreateTrail: { default: "Create a CloudTrail trail? (only if this account has no trail)" }
      TrailRetentionDays: { default: "Days to keep the trail's logs" }
      SecurityAlertEmail: { default: "Email for security alerts (optional)" }
      EnableAutoQuarantine: { default: "Allow Outseen to stop rejected resources?" }
      QuarantineTagKey: { default: "Only stop resources with this tag key" }
      QuarantineTagValue: { default: "…and this tag value" }

Parameters:
  ExternalId:
    Type: String
    Description: The External ID Outseen generated for this AWS account (prevents confused-deputy attacks). Not a secret.
    AllowedPattern: '^outseen-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
    ConstraintDescription: Paste the External ID exactly as shown in the Outseen dashboard (outseen-<uuid>)

  IngestKey:
    Type: String
    NoEcho: true
    AllowedPattern: '^osk_[A-Za-z0-9_-]{20,}$'
    ConstraintDescription: Paste the key exactly as shown in the Outseen dashboard (starts with osk_)
    Description: Authenticates this account's events. Stored by AWS in your Secrets Manager via the EventBridge Connection.

  PrimaryRegion:
    Type: String
    Default: 'us-east-1'
    Description: The IAM role (and the optional trail) are created only in this region. For a single stack, set this to the region you deploy in.

  AllowMissedEventCheck:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: >-
      EventBridge drops an event it couldn't deliver for 24 hours. When true, the role may call
      cloudtrail:LookupEvents so Outseen can recover such launches once a day. AWS can't limit
      LookupEvents to certain events; Outseen only queries its 16 launch event names. When false,
      undelivered events stay in this stack's dead-letter queue instead.

  CreateTrail:
    Type: String
    Default: 'false'
    AllowedValues: ['true', 'false']
    Description: >-
      Leave false if this account already has a trail, including an organization trail from
      your management account. Outseen works with any active trail. EventBridge only receives
      "AWS API Call via CloudTrail" events while a trail is logging. Choose true only if the
      account has no trail at all. It then creates a multi-region trail of write management
      events and an S3 bucket for its logs. That trail is free as the account's first copy of
      management events. If another trail exists, AWS bills it as a second copy, at $2.00 per
      100,000 events.

  TrailRetentionDays:
    Type: Number
    Default: 30
    MinValue: 1
    Description: Only used when CreateTrail is true. Log files are deleted after this many days.

  SecurityAlertEmail:
    Type: String
    Default: ''
    AllowedPattern: '^$|^[^@\s]+@[^@\s]+\.[^@\s]+$'
    ConstraintDescription: Leave empty, or enter one email address
    Description: >-
      Optional. When set, creates an SNS topic (confirm the subscription email) that alerts on
      resources stopped by Outseen's role, on changes to this stack's role, policies or
      EventBridge resources, and on events that failed to reach Outseen.

  EnableAutoQuarantine:
    Type: String
    Default: 'false'
    AllowedValues: ['true', 'false']
    Description: When true, Outseen may stop EC2 instances and RDS databases in this account that were rejected or timed out, and only if they carry the tag below.

  QuarantineTagKey:
    Type: String
    Default: 'outseen-quarantine-eligible'
    AllowedPattern: '^(?!outseen:).+$'
    ConstraintDescription: Must not start with "outseen:"
    Description: Tag key a resource must have before Outseen may stop it. Use a dedicated tag, not a broad one such as env. Outseen cannot write any tags.

  QuarantineTagValue:
    Type: String
    Default: 'true'
    Description: Tag value a resource must have before Outseen may stop it

Conditions:
  IsPrimaryRegion: !Equals [!Ref 'AWS::Region', !Ref PrimaryRegion]
  MissedEventCheckOn: !Equals [!Ref AllowMissedEventCheck, 'true']
  AutoQuarantineEnabled: !And
    - !Condition IsPrimaryRegion
    - !Equals [!Ref EnableAutoQuarantine, 'true']
  CreateTrailInPrimary: !And
    - !Condition IsPrimaryRegion
    - !Equals [!Ref CreateTrail, 'true']
  AlertsEnabled: !Not [!Equals [!Ref SecurityAlertEmail, '']]
  # IAM is global: its CloudTrail events are delivered to EventBridge in us-east-1 only.
  IamAlertsHere: !And
    - !Condition AlertsEnabled
    - !Equals [!Ref 'AWS::Region', 'us-east-1']

Resources:
  # ─── IAM role assumed by Outseen (global, primary region only) ─────────────
  OutseenMonitorRole:
    Type: AWS::IAM::Role
    Condition: IsPrimaryRegion
    Properties:
      RoleName: OutseenMonitorRole
      Description: Read-only role Outseen assumes to price launches (optional stop, only if enabled)
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          # Only Outseen's dedicated access role, not every identity in Outseen's account.
          # Outseen's account ID and this role ARN are published at https://outseen.com/security
          - Effect: Allow
            Principal:
              AWS: 'arn:aws:iam::711162121527:role/OutseenCustomerAccessRole'
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId: !Ref ExternalId
      MaxSessionDuration: 3600
      Tags:
        - Key: ManagedBy
          Value: Outseen
        - Key: Purpose
          Value: CostMonitoring

  OutseenMonitorPolicy:
    Type: AWS::IAM::ManagedPolicy
    Condition: IsPrimaryRegion
    Properties:
      # Changing a managed policy's Description replaces it, and CloudFormation can't replace a
      # resource with a fixed name. Renamed from OutseenMonitorPolicy so stacks deployed before
      # Nov 2026 can update; change the name again whenever the description changes.
      ManagedPolicyName: OutseenReadOnlyPolicy
      Description: Read-only metadata Outseen needs to price launches. Each action names its feature.
      Roles: [!Ref OutseenMonitorRole]
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: PriceAndConfirmLaunches
            Effect: Allow
            Action:
              - ec2:DescribeImages              # price the AMI's operating system and licenses
              - ec2:DescribeSpotPriceHistory    # price Spot launches at the current Spot price
              - ec2:DescribeInstances           # confirm an EC2 resize after "Request Downsize"; price started instances
              - rds:DescribeDBInstances         # confirm an RDS resize after "Request Downsize"; price started databases
              - rds:DescribeDBClusters          # price Aurora instances by their cluster's storage mode and Serverless v2 range
              - elasticache:DescribeCacheClusters  # confirm an ElastiCache resize after "Request Downsize"
              - sagemaker:DescribeEndpointConfig   # price a SageMaker endpoint by its config's instance types and counts
            # Describe calls don't support resource-level permissions.
            Resource: '*'
          - !If
            - MissedEventCheckOn
            - Sid: RecoverMissedLaunches
              Effect: Allow
              Action: cloudtrail:LookupEvents   # daily check for launches EventBridge failed to deliver
              Resource: '*'
            - !Ref AWS::NoValue

  # Separate policy so it only exists when the customer opts in.
  OutseenQuarantinePolicy:
    Type: AWS::IAM::ManagedPolicy
    Condition: AutoQuarantineEnabled
    Properties:
      # Renamed from OutseenQuarantinePolicy for the same reason as OutseenReadOnlyPolicy.
      ManagedPolicyName: OutseenStopTaggedPolicy
      Description: !Sub 'Lets Outseen stop EC2/RDS resources in this account tagged ${QuarantineTagKey}=${QuarantineTagValue}'
      Roles: [!Ref OutseenMonitorRole]
      # Written as a JSON string because the condition key contains a parameter,
      # and CloudFormation doesn't allow intrinsic functions as YAML map keys.
      PolicyDocument: !Sub |
        {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Sid": "StopTaggedResourcesOnly",
              "Effect": "Allow",
              "Action": ["ec2:StopInstances", "rds:StopDBInstance", "rds:StopDBCluster"],
              "Resource": [
                "arn:${AWS::Partition}:ec2:*:${AWS::AccountId}:instance/*",
                "arn:${AWS::Partition}:rds:*:${AWS::AccountId}:db:*",
                "arn:${AWS::Partition}:rds:*:${AWS::AccountId}:cluster:*"
              ],
              "Condition": {
                "StringEquals": { "aws:ResourceTag/${QuarantineTagKey}": "${QuarantineTagValue}" }
              }
            }
          ]
        }

  # ─── Event forwarding (every region) ─────────────────────────────────────────
  OutseenConnection:
    Type: AWS::Events::Connection
    Properties:
      Description: Authenticates CloudTrail events sent to Outseen
      AuthorizationType: API_KEY
      AuthParameters:
        ApiKeyAuthParameters:
          ApiKeyName: x-outseen-key
          ApiKeyValue: !Ref IngestKey

  OutseenApiDestination:
    Type: AWS::Events::ApiDestination
    Properties:
      Description: Outseen ingest endpoint
      ConnectionArn: !GetAtt OutseenConnection.Arn
      # Fixed: events and the ingest key can only go to Outseen.
      InvocationEndpoint: 'https://app.outseen.com/api/ingest'
      HttpMethod: POST
      InvocationRateLimitPerSecond: 20

  OutseenEventBridgeRole:
    Type: AWS::IAM::Role
    Properties:
      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: InvokeOutseenApiDestination
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: events:InvokeApiDestination
                Resource: !GetAtt OutseenApiDestination.Arn

  # Holds events EventBridge couldn't deliver to Outseen for 24 hours, in your account.
  OutseenDeadLetterQueue:
    Type: AWS::SQS::Queue
    Properties:
      MessageRetentionPeriod: 1209600 # 14 days, the SQS maximum
      SqsManagedSseEnabled: true

  OutseenDeadLetterQueuePolicy:
    Type: AWS::SQS::QueuePolicy
    Properties:
      Queues: [!Ref OutseenDeadLetterQueue]
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: OnlyOutseenRule
            Effect: Allow
            Principal: { Service: events.amazonaws.com }
            Action: sqs:SendMessage
            Resource: !GetAtt OutseenDeadLetterQueue.Arn
            Condition:
              ArnEquals:
                aws:SourceArn: !GetAtt OutseenEventBridgeRule.Arn

  OutseenEventBridgeRule:
    Type: AWS::Events::Rule
    Properties:
      Description: Forwards resource-launch CloudTrail events to Outseen, minimized, for cost approval
      State: ENABLED
      EventPattern:
        source:
          - 'aws.ec2'
          - 'aws.rds'
          - 'aws.elasticache'
          - 'aws.redshift'
          - 'aws.eks'
          - 'aws.sagemaker'
          - 'aws.elasticloadbalancing'
          - 'aws.s3'
        detail-type:
          - 'AWS API Call via CloudTrail'
        detail:
          # Failed calls created nothing, so they never leave the account.
          errorCode:
            - exists: false
          eventName:
            - RunInstances
            - StartInstances
            - CreateDBInstance
            - StartDBInstance
            - CreateDBCluster
            - CreateVolume
            - CreateBucket
            - CreateNatGateway
            - CreateCacheCluster
            - CreateCluster
            - CreateNodegroup
            - CreateNotebookInstance
            - CreateEndpoint
            - CreateLoadBalancer
            # Resizes: re-estimate cost, close "Request Downsize" requests, catch upsizes
            - ModifyInstanceAttribute
            - ModifyDBInstance
            - ModifyCacheCluster
      Targets:
        - Id: OutseenIngest
          Arn: !GetAtt OutseenApiDestination.Arn
          RoleArn: !GetAtt OutseenEventBridgeRole.Arn
          RetryPolicy:
            MaximumEventAgeInSeconds: 86400
            MaximumRetryAttempts: 185
          DeadLetterConfig:
            Arn: !GetAtt OutseenDeadLetterQueue.Arn
          # Send only what pricing needs. Not sent: source IP, user agent, access key ID,
          # session attributes, TLS details, request ID and the rest of the envelope.
          # Optional values are wrapped in arrays so a missing value can't break the JSON.
          InputTransformer:
            InputPathsMap:
              account: '$.account'
              region: '$.region'
              detailType: '$.detail-type'
              eventVersion: '$.detail.eventVersion'
              eventID: '$.detail.eventID'
              eventName: '$.detail.eventName'
              eventSource: '$.detail.eventSource'
              eventTime: '$.detail.eventTime'
              awsRegion: '$.detail.awsRegion'
              identityType: '$.detail.userIdentity.type'
              identityArn: '$.detail.userIdentity.arn'
              principalId: '$.detail.userIdentity.principalId'
              invokedBy: '$.detail.userIdentity.invokedBy'
              issuerArn: '$.detail.userIdentity.sessionContext.sessionIssuer.arn'
              requestParameters: '$.detail.requestParameters'
              responseElements: '$.detail.responseElements'
            InputTemplate: |
              {
                "account": <account>,
                "region": <region>,
                "detail-type": <detailType>,
                "format": "outseen-minimized-v1",
                "eventSet": 2,
                "detail": {
                  "eventVersion": [<eventVersion>],
                  "eventID": <eventID>,
                  "eventName": <eventName>,
                  "eventSource": <eventSource>,
                  "eventTime": <eventTime>,
                  "awsRegion": <awsRegion>,
                  "userIdentity": {
                    "type": [<identityType>],
                    "arn": [<identityArn>],
                    "principalId": [<principalId>],
                    "invokedBy": [<invokedBy>],
                    "sessionIssuerArn": [<issuerArn>]
                  },
                  "requestParameters": [<requestParameters>],
                  "responseElements": [<responseElements>]
                }
              }

  # ─── Optional security alerts ────────────────────────────────────────────────
  OutseenAlertTopic:
    Type: AWS::SNS::Topic
    Condition: AlertsEnabled
    Properties:
      DisplayName: Outseen security alerts
      Subscription:
        - Protocol: email
          Endpoint: !Ref SecurityAlertEmail

  OutseenAlertTopicPolicy:
    Type: AWS::SNS::TopicPolicy
    Condition: AlertsEnabled
    Properties:
      Topics: [!Ref OutseenAlertTopic]
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: EventBridgeAndCloudWatchFromThisAccount
            Effect: Allow
            Principal: { Service: [events.amazonaws.com, cloudwatch.amazonaws.com] }
            Action: sns:Publish
            Resource: !Ref OutseenAlertTopic
            Condition:
              StringEquals:
                aws:SourceAccount: !Ref AWS::AccountId

  OutseenStopAlertRule:
    Type: AWS::Events::Rule
    Condition: AlertsEnabled
    Properties:
      Description: Alerts when Outseen's role stops an EC2 instance or RDS database
      State: ENABLED
      EventPattern:
        detail-type: ['AWS API Call via CloudTrail']
        detail:
          eventName: [StopInstances, StopDBInstance, StopDBCluster]
          userIdentity:
            sessionContext:
              sessionIssuer:
                userName: [OutseenMonitorRole]
      Targets:
        - Id: Alert
          Arn: !Ref OutseenAlertTopic

  OutseenEventBridgeChangeAlertRule:
    Type: AWS::Events::Rule
    Condition: AlertsEnabled
    Properties:
      Description: Alerts on changes to the EventBridge resources that forward events to Outseen
      State: ENABLED
      EventPattern:
        source: ['aws.events']
        detail-type: ['AWS API Call via CloudTrail']
        detail:
          eventName:
            - PutRule
            - DeleteRule
            - DisableRule
            - PutTargets
            - RemoveTargets
            - UpdateConnection
            - DeleteConnection
            - DeauthorizeConnection
            - UpdateApiDestination
            - DeleteApiDestination
          $or:
            - requestParameters:
                name: [!Ref OutseenEventBridgeRule, !Ref OutseenConnection, !Ref OutseenApiDestination]
            - requestParameters:
                rule: [!Ref OutseenEventBridgeRule]
      Targets:
        - Id: Alert
          Arn: !Ref OutseenAlertTopic

  OutseenIamChangeAlertRule:
    Type: AWS::Events::Rule
    Condition: IamAlertsHere
    Properties:
      Description: Alerts on changes to Outseen's IAM role or its policies (IAM events arrive in us-east-1)
      State: ENABLED
      EventPattern:
        source: ['aws.iam']
        detail-type: ['AWS API Call via CloudTrail']
        detail:
          eventName:
            - UpdateAssumeRolePolicy
            - AttachRolePolicy
            - DetachRolePolicy
            - PutRolePolicy
            - DeleteRolePolicy
            - DeleteRole
            - CreatePolicyVersion
            - SetDefaultPolicyVersion
          $or:
            - requestParameters:
                roleName: [OutseenMonitorRole]
            - requestParameters:
                policyArn:
                  - prefix: !Sub 'arn:${AWS::Partition}:iam::${AWS::AccountId}:policy/Outseen'
      Targets:
        - Id: Alert
          Arn: !Ref OutseenAlertTopic

  OutseenFailedDeliveryAlarm:
    Type: AWS::CloudWatch::Alarm
    Condition: AlertsEnabled
    Properties:
      AlarmDescription: Events in this region are failing to reach Outseen (they are retried for 24 hours, then kept in the dead-letter queue)
      Namespace: AWS/Events
      MetricName: FailedInvocations
      Dimensions:
        - Name: RuleName
          Value: !Ref OutseenEventBridgeRule
      Statistic: Sum
      Period: 300
      EvaluationPeriods: 1
      Threshold: 1
      ComparisonOperator: GreaterThanOrEqualToThreshold
      TreatMissingData: notBreaching
      AlarmActions: [!Ref OutseenAlertTopic]

  OutseenDeadLetterAlarm:
    Type: AWS::CloudWatch::Alarm
    Condition: AlertsEnabled
    Properties:
      AlarmDescription: Events Outseen never received are waiting in the dead-letter queue
      Namespace: AWS/SQS
      MetricName: ApproximateNumberOfMessagesVisible
      Dimensions:
        - Name: QueueName
          Value: !GetAtt OutseenDeadLetterQueue.QueueName
      Statistic: Maximum
      Period: 300
      EvaluationPeriods: 1
      Threshold: 1
      ComparisonOperator: GreaterThanOrEqualToThreshold
      TreatMissingData: notBreaching
      AlarmActions: [!Ref OutseenAlertTopic]

  # ─── Optional trail (primary region, multi-region trail) ────────────────────
  # Kept when the stack is deleted, so audit logs don't disappear with it. Its
  # lifecycle rule keeps deleting old logs; delete the bucket yourself when done.
  OutseenTrailBucket:
    Type: AWS::S3::Bucket
    Condition: CreateTrailInPrimary
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      VersioningConfiguration:
        Status: Enabled
      LifecycleConfiguration:
        Rules:
          - Id: ExpireTrailLogs
            Status: Enabled
            ExpirationInDays: !Ref TrailRetentionDays
            NoncurrentVersionExpiration:
              NoncurrentDays: 1

  OutseenTrailBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Condition: CreateTrailInPrimary
    Properties:
      Bucket: !Ref OutseenTrailBucket
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: CloudTrailAclCheck
            Effect: Allow
            Principal: { Service: cloudtrail.amazonaws.com }
            Action: s3:GetBucketAcl
            Resource: !GetAtt OutseenTrailBucket.Arn
            Condition:
              StringEquals:
                aws:SourceArn: !Sub 'arn:${AWS::Partition}:cloudtrail:${AWS::Region}:${AWS::AccountId}:trail/outseen-management-events'
          - Sid: CloudTrailWrite
            Effect: Allow
            Principal: { Service: cloudtrail.amazonaws.com }
            Action: s3:PutObject
            Resource: !Sub '${OutseenTrailBucket.Arn}/AWSLogs/${AWS::AccountId}/*'
            Condition:
              StringEquals:
                s3:x-amz-acl: bucket-owner-full-control
                aws:SourceArn: !Sub 'arn:${AWS::Partition}:cloudtrail:${AWS::Region}:${AWS::AccountId}:trail/outseen-management-events'
          - Sid: DenyInsecureTransport
            Effect: Deny
            Principal: '*'
            Action: 's3:*'
            Resource:
              - !GetAtt OutseenTrailBucket.Arn
              - !Sub '${OutseenTrailBucket.Arn}/*'
            Condition:
              Bool:
                aws:SecureTransport: 'false'

  OutseenTrail:
    Type: AWS::CloudTrail::Trail
    Condition: CreateTrailInPrimary
    DependsOn: OutseenTrailBucketPolicy
    Properties:
      TrailName: outseen-management-events
      S3BucketName: !Ref OutseenTrailBucket
      IsLogging: true
      IsMultiRegionTrail: true
      IncludeGlobalServiceEvents: true
      EnableLogFileValidation: true
      # Write events only. Outseen's rule (state ENABLED) never matches read events, and
      # reads are most of an account's volume, so logging them would only add cost if
      # this trail turns out to be a billed second copy.
      EventSelectors:
        - ReadWriteType: WriteOnly
          IncludeManagementEvents: true

Outputs:
  OutseenRoleArn:
    Condition: IsPrimaryRegion
    Description: The IAM Role ARN to enter in the Outseen dashboard
    Value: !GetAtt OutseenMonitorRole.Arn
  OutseenRuleArn:
    Description: EventBridge rule forwarding events in this region (disable it to stop sending events at once)
    Value: !GetAtt OutseenEventBridgeRule.Arn
  OutseenDeadLetterQueueUrl:
    Description: Events that couldn't be delivered to Outseen for 24 hours land here
    Value: !Ref OutseenDeadLetterQueue
