AWSTemplateFormatVersion: "2010-09-09"
Description: >-
  Epok read-only role: lets Epok read resource inventory, tags and CloudTrail
  management (write) events for EC2, Lambda, ECS, RDS and Elastic Load Balancing.
  No data-plane reads (no S3 objects, no DynamoDB items, no queue messages, no
  secrets). Design: docs/planning/aws-readonly-role-inventory-design-2026-11-09.md §3, §R.
  To remove Epok's access, delete this stack.

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label: {default: Epok}
        Parameters: [EpokPrincipalAccountId, EpokPrincipalArn, ExternalId, ExternalIdNext]
      - Label: {default: Options}
        Parameters: [RoleNameSuffix, EnableChangeEvents]

Parameters:
  EpokPrincipalAccountId:
    Type: String
    AllowedPattern: "^[0-9]{12}$"
    Description: Epok's AWS account (shown on the Epok AWS integration page).
  EpokPrincipalArn:
    Type: String
    AllowedPattern: "^arn:aws:iam::[0-9]{12}:(user|role)/[A-Za-z0-9+=,.@_/-]{1,128}$"
    Description: >-
      The ONE Epok identity allowed to assume this role (shown on the Epok AWS integration
      page; e.g. arn:aws:iam::<EpokPrincipalAccountId>:user/epok-assumer). Must be in
      EpokPrincipalAccountId. No other identity in Epok's account can assume the role.
  ExternalId:
    Type: String
    NoEcho: true
    AllowedPattern: "^epk1-[0-9a-f]{48}$"
    Description: >-
      The external ID Epok generated for this integration (shown on the Epok AWS
      integration page). Epok must send it on every AssumeRole call.
  ExternalIdNext:
    Type: String
    NoEcho: true
    Default: ""
    AllowedPattern: "^(epk1-[0-9a-f]{48})?$"
    Description: Optional second external ID, accepted only during a rotation. Leave empty.
  RoleNameSuffix:
    Type: String
    Default: default
    AllowedPattern: "^[A-Za-z0-9+=,.@_-]{1,40}$"
  EnableChangeEvents:
    Type: String
    AllowedValues: ["true", "false"]
    Default: "true"
    Description: Allow Epok to read CloudTrail management events (cloudtrail:LookupEvents).

Conditions:
  HasNextId: !Not [!Equals [!Ref ExternalIdNext, ""]]
  ChangeEvents: !Equals [!Ref EnableChangeEvents, "true"]

Resources:
  EpokReadOnlyRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "EpokReadOnly-${RoleNameSuffix}"
      Path: /epok/
      MaxSessionDuration: 3600
      Description: Epok read-only access (inventory, tags, CloudTrail write events). Delete the stack to revoke.
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: EpokAssumeWithExternalId
            Effect: Allow
            Principal:
              AWS: !Sub "arn:${AWS::Partition}:iam::${EpokPrincipalAccountId}:root"
            Action: sts:AssumeRole
            Condition:
              # Only Epok's single assuming identity, not every principal in its account.
              # aws:PrincipalArn is the user/role ARN (not the session ARN) and survives a
              # recreate of that identity, unlike a Principal element naming it directly.
              ArnEquals:
                aws:PrincipalArn: !Ref EpokPrincipalArn
              StringEquals:
                sts:ExternalId: !If
                  - HasNextId
                  - [!Ref ExternalId, !Ref ExternalIdNext]
                  - [!Ref ExternalId]
      Tags:
        - {Key: "epok:integration", Value: readonly-role}

  EpokReadOnlyPolicy:
    Type: AWS::IAM::RolePolicy
    Properties:
      RoleName: !Ref EpokReadOnlyRole
      PolicyName: EpokReadOnly
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: InventoryReadOnly
            Effect: Allow
            Action:
              - tag:GetResources
              - ec2:DescribeInstances
              - ec2:DescribeSecurityGroups
              - ec2:DescribeRegions
              - rds:DescribeDBInstances
              - rds:DescribeDBClusters
              - lambda:ListFunctions
              - elasticloadbalancing:DescribeLoadBalancers
              - elasticloadbalancing:DescribeTargetGroups
              - elasticloadbalancing:DescribeListeners
              - ecs:ListClusters
              - ecs:ListServices
              - ecs:DescribeServices
            Resource: "*"
          - !If
            - ChangeEvents
            - Sid: ChangeEventsReadOnly
              Effect: Allow
              Action:
                - cloudtrail:LookupEvents
                - cloudtrail:DescribeTrails
              Resource: "*"
            - !Ref AWS::NoValue
          # Belt and braces: wins even if a broader policy is attached to this role later.
          - Sid: DenyDataPlaneAndSecrets
            Effect: Deny
            Action:
              - s3:GetObject*
              - s3:ListBucket*
              - dynamodb:GetItem
              - dynamodb:BatchGetItem
              - dynamodb:Query
              - dynamodb:Scan
              - dynamodb:ExportTableToPointInTime
              - sqs:ReceiveMessage
              - lambda:GetFunction
              - lambda:GetFunctionConfiguration
              - lambda:InvokeFunction
              - ec2:DescribeInstanceAttribute
              - ec2:DescribeLaunchTemplateVersions
              - ec2:GetPasswordData
              - ec2:GetConsoleOutput
              - ec2:GetConsoleScreenshot
              - ecs:DescribeTaskDefinition
              - ecs:DescribeTasks
              - rds:DescribeDBSnapshotAttributes
              - secretsmanager:*
              - ssm:GetParameter*
              - kms:Decrypt
              - rds:DownloadDBLogFilePortion
              - rds:DownloadCompleteDBLogFile
              - logs:GetLogEvents
              - logs:FilterLogEvents
              - logs:StartQuery
              - lambda:GetFunctionUrlConfig
            Resource: "*"
          - Sid: DenyApiGatewaySecrets
            Effect: Deny
            Action: apigateway:GET
            Resource:
              - !Sub "arn:${AWS::Partition}:apigateway:*::/apikeys*"
              - !Sub "arn:${AWS::Partition}:apigateway:*::/usageplans/*/keys*"
              - !Sub "arn:${AWS::Partition}:apigateway:*::/restapis/*/exports/*"
              - !Sub "arn:${AWS::Partition}:apigateway:*::/domainnames*"
              - !Sub "arn:${AWS::Partition}:apigateway:*::/clientcertificates*"

Outputs:
  RoleArn:
    Description: Paste this into Epok (Settings > Integrations > AWS > Verify).
    Value: !GetAtt EpokReadOnlyRole.Arn
