AWSTemplateFormatVersion: '2010-09-09'
Description: Cloud Stratus role-based AWS account connection using temporary credentials.

Parameters:
  PlatformPrincipalArn:
    Type: String
    Description: Stable Cloud Stratus platform principal allowed to assume the customer role.
    AllowedPattern: '^arn:aws(-[a-z]+)?:iam::[0-9]{12}:(role|user)/[A-Za-z0-9+=,.@_/-]+$'
  ExternalId:
    Type: String
    Description: Unique Cloud Stratus connection identifier used to prevent confused-deputy access.
    MinLength: 24
    MaxLength: 128
    AllowedPattern: '^[A-Za-z0-9+=,.@:/_-]+$'
  RoleName:
    Type: String
    Default: CloudStratusAccess
    AllowedPattern: '^[A-Za-z0-9+=,.@_-]{1,64}$'
  PolicyVersion:
    Type: String
    Default: '2026-11-24.1'
    AllowedPattern: '^[A-Za-z0-9._-]{1,64}$'
  EnableCur:
    Type: String
    Default: 'false'
    AllowedValues: ['true', 'false']
  KeepCurBucket:
    Type: String
    Default: 'false'
    Description: Keep a previously-created retained CUR bucket managed by this stack while CUR access is disabled.
    AllowedValues: ['true', 'false']
  CurPrefix:
    Type: String
    Default: cloud-stratus-cur
    AllowedPattern: '^[A-Za-z0-9!_.*()/-]{1,256}$'
  DiscoveryNonce:
    Type: String
    Default: ''
    Description: Changes on every Cloud Stratus stack update so CUR export discovery re-runs and the role's S3 read follows the export AWS delivers to now.
    AllowedPattern: '^[A-Za-z0-9-]{0,64}$'
  CallbackUrl:
    Type: String
    Default: ''
    Description: Cloud Stratus endpoint that receives this account's ID and role ARN when the stack finishes, so nobody types the account ID. Empty skips the report.
    AllowedPattern: '^(https?://[A-Za-z0-9.:/_-]{1,500})?$'
  CurBucketName:
    Type: String
    Description: Deterministic globally unique CUR delivery bucket name.
    AllowedPattern: '^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$'

Conditions:
  CurEnabled: !Equals [!Ref EnableCur, 'true']
  CurBucketManaged: !Or
    - !Condition CurEnabled
    - !Equals [!Ref KeepCurBucket, 'true']

Resources:
  CurDiscoveryRole:
    Type: AWS::IAM::Role
    Condition: CurEnabled
    Properties:
      Description: Discovers an existing compatible billing export during stack setup.
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: CloudStratusCurDiscovery
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: ReadBillingExportDefinitions
                Effect: Allow
                Action:
                  - bcm-data-exports:ListExports
                  - bcm-data-exports:GetExport
                Resource: '*'
              - Sid: WriteDiscoveryLogs
                Effect: Allow
                Action:
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource: '*'

  CurDiscoveryFunction:
    Type: AWS::Lambda::Function
    Condition: CurEnabled
    Properties:
      Description: Selects the newest healthy compatible CUR export, or the managed fallback bucket.
      Runtime: python3.12
      Handler: index.handler
      Role: !GetAtt CurDiscoveryRole.Arn
      Timeout: 60
      MemorySize: 128
      Code:
        ZipFile: |
          import boto3
          import cfnresponse

          REQUIRED_COLUMNS = {
              "line_item_resource_id", "line_item_line_item_type", "line_item_unblended_cost",
              "line_item_product_code", "line_item_usage_account_id", "reservation_effective_cost",
              "savings_plan_savings_plan_effective_cost", "resource_tags"
          }

          def compatible(query):
              # Same rule as shared/curExport.js isCompatibleCurQuery. A stricter
              # check here grants the role a different bucket than the backend adopts.
              normalized = str(query or "").lower()
              return "cost_and_usage_report" in normalized and all(column in normalized for column in REQUIRED_COLUMNS)

          def recency(reference):
              status = reference.get("ExportStatus") or {}
              value = status.get("LastRefreshedAt") or status.get("LastUpdatedAt") or status.get("CreatedAt")
              return value.timestamp() if hasattr(value, "timestamp") else 0

          def bucket_missing(bucket, region):
              try:
                  boto3.client("s3", region_name=region).head_bucket(Bucket=bucket)
              except Exception as error:
                  return str(getattr(error, "response", {}).get("Error", {}).get("Code", "")) in {"404", "NoSuchBucket"}
              return False

          def choose_export():
              client = boto3.client("bcm-data-exports", region_name="us-east-1")
              references = []
              token = None
              while True:
                  request = {"MaxResults": 100}
                  if token:
                      request["NextToken"] = token
                  response = client.list_exports(**request)
                  references.extend(response.get("Exports") or [])
                  token = response.get("NextToken")
                  if not token:
                      break
              references.sort(
                  key=lambda ref: (
                      str((ref.get("ExportStatus") or {}).get("StatusCode") or "").upper() == "HEALTHY",
                      recency(ref),
                  ),
                  reverse=True,
              )
              for reference in references:
                  arn = reference.get("ExportArn")
                  if not arn:
                      continue
                  try:
                      response = client.get_export(ExportArn=arn)
                  except Exception:
                      # Skip this export, as the backend does; one unreadable
                      # definition must not send the grant to the fallback bucket.
                      continue
                  export = response.get("Export") or {}
                  destination = (export.get("DestinationConfigurations") or {}).get("S3Destination") or {}
                  output = destination.get("S3OutputConfigurations") or {}
                  format_name = str(output.get("Format") or "").upper()
                  if not destination.get("S3Bucket") or format_name not in {"PARQUET", "TEXT_OR_CSV", "CSV"}:
                      continue
                  if not compatible((export.get("DataQuery") or {}).get("QueryStatement")):
                      continue
                  # An export can outlive its bucket. S3 answers 404 for a
                  # missing bucket without any permission, so a dead feed is
                  # skipped here, as the backend skips it, instead of the role
                  # being granted a bucket that no longer exists.
                  if bucket_missing(destination["S3Bucket"], destination.get("S3Region") or "us-east-1"):
                      continue
                  return {
                      "bucket": destination["S3Bucket"],
                      "prefix": destination.get("S3Prefix") or export.get("Name") or reference.get("ExportName") or "",
                      "region": destination.get("S3Region") or "us-east-1",
                      "format": "parquet" if format_name == "PARQUET" else "csv-gz",
                      "source": "existing",
                  }
              return None

          def handler(event, context):
              physical_id = "cloud-stratus-cur-discovery"
              try:
                  properties = event.get("ResourceProperties") or {}
                  if event.get("RequestType") == "Delete":
                      selected = None
                  else:
                      try:
                          selected = choose_export()
                      except Exception:
                          # Member accounts cannot manage payer-level Data Exports.
                          # Keep role onboarding available; the backend derives
                          # the account topology after the role is created.
                          selected = None
                  selected = selected or {
                      "bucket": properties.get("FallbackBucket"),
                      "prefix": properties.get("FallbackPrefix") or "cloud-stratus-cur",
                      "region": "us-east-1",
                      "format": "parquet",
                      "source": "managed",
                  }
                  bucket = selected["bucket"]
                  prefix = str(selected["prefix"] or "").strip("/")
                  object_path = f"/{prefix}/*" if prefix else "/*"
                  data = {
                      "BucketName": bucket,
                      "BucketArn": f"arn:{event.get('ResourceProperties', {}).get('Partition', 'aws')}:s3:::{bucket}",
                      "ObjectArn": f"arn:{event.get('ResourceProperties', {}).get('Partition', 'aws')}:s3:::{bucket}{object_path}",
                      "Prefix": prefix,
                      "Region": selected["region"],
                      "Format": selected["format"],
                      "Source": selected["source"],
                  }
                  cfnresponse.send(event, context, cfnresponse.SUCCESS, data, physical_id)
              except Exception as error:
                  cfnresponse.send(event, context, cfnresponse.FAILED, {"Error": str(error)[:512]}, physical_id)

  CurDiscovery:
    Type: AWS::CloudFormation::CustomResource
    Condition: CurEnabled
    Properties:
      ServiceToken: !GetAtt CurDiscoveryFunction.Arn
      FallbackBucket: !Ref CurBucket
      FallbackPrefix: !Ref CurPrefix
      Partition: !Ref AWS::Partition
      # A changed property is the only thing that re-runs a custom resource.
      DiscoveryNonce: !Ref DiscoveryNonce

  CloudStratusRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Ref RoleName
      Description: !Sub 'Cloud Stratus account inventory and cost access (${PolicyVersion})'
      MaxSessionDuration: 3600
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              AWS: !Ref PlatformPrincipalArn
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId: !Ref ExternalId
      Policies:
        - PolicyName: !Sub 'CloudStratus-${PolicyVersion}'
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: CloudStratusInventoryAndCostRead
                Effect: Allow
                Action:
                  - ec2:DescribeRegions
                  - iam:ListAccountAliases
                  - organizations:DescribeOrganization
                  - ce:GetAnomalies
                  - ce:GetAnomalyMonitors
                  - ce:GetCostAndUsage
                  - ce:GetReservationCoverage
                  - ce:GetReservationUtilization
                  - ce:GetSavingsPlansCoverage
                  - ce:GetSavingsPlansPurchaseRecommendation
                  - ce:GetSavingsPlansUtilization
                  - ce:GetSavingsPlansUtilizationDetails
                  - pricing:GetProducts
                  - ec2:DescribeAddresses
                  - ec2:DescribeImages
                  - ec2:DescribeInstanceAttribute
                  - ec2:DescribeInstances
                  - ec2:DescribeLaunchTemplateVersions
                  - ec2:DescribeNatGateways
                  - ec2:DescribeNetworkInterfaces
                  - ec2:DescribeReservedInstances
                  - ec2:DescribeRouteTables
                  - ec2:DescribeSecurityGroups
                  - ec2:DescribeSnapshots
                  - ec2:DescribeSubnets
                  - ec2:DescribeVolumes
                  - ec2:DescribeVpcs
                  - rds:DescribeDBInstances
                  - dms:DescribeReplicationInstances
                  - dms:DescribeReplicationTasks
                  - dms:DescribeEndpoints
                  # Scheduled backups of servers (Data Lifecycle Manager): which
                  # policies image which servers. Read-only.
                  - dlm:GetLifecyclePolicies
                  - dlm:GetLifecyclePolicy
                  # What the account needs before anything else: the Billing
                  # home's recommended actions. Read-only.
                  - bcm-recommended-actions:ListRecommendedActions
                  - cost-optimization-hub:ListEnrollmentStatuses
                  # Savings Plan hourly rates, to size commitment advice. Read-only:
                  # it lists rates and buys nothing.
                  - savingsplans:DescribeSavingsPlansOfferingRates
                  # Live checks by the bill investigator: describes by name or
                  # ID, never a write. QuickSight is only asked whether a
                  # subscription exists; its user list is not granted.
                  - rds:DescribeDBClusters
                  - redshift:DescribeClusters
                  - redshift-serverless:GetWorkgroup
                  - redshift-serverless:GetNamespace
                  - quicksight:DescribeAccountSubscription
                  - lambda:ListFunctions
                  - cloudfront:ListDistributions
                  - elasticloadbalancing:DescribeLoadBalancers
                  - elasticloadbalancing:DescribeTargetGroups
                  - elasticloadbalancing:DescribeTargetHealth
                  - cloudwatch:GetMetricData
                  - cloudtrail:LookupEvents
                  - compute-optimizer:GetEnrollmentStatus
                  - compute-optimizer:GetEC2InstanceRecommendations
                  - iam:ListAccessKeys
                  - iam:ListEntitiesForPolicy
                  - iam:ListMFADevices
                  - iam:ListPolicies
                  - iam:ListUsers
                  - s3:ListAllMyBuckets
                  - s3:GetBucketLocation
                  - s3:GetBucketVersioning
                  - s3:GetEncryptionConfiguration
                  - s3:GetLifecycleConfiguration
                  - kms:ListKeys
                  - kms:ListAliases
                  - kms:DescribeKey
                Resource: '*'
              # Unfinished multipart uploads: S3 bills their parts but never
              # lists them as objects. These list each upload's key and start
              # date and its parts' sizes, never contents (there is no
              # s3:GetObject here), to price cleaning them up.
              # ListBucketMultipartUploads is a bucket-level action (bucket
              # ARNs); ListMultipartUploadParts is object-level (object ARNs).
              - Sid: CloudStratusS3MultipartUploadList
                Effect: Allow
                Action: s3:ListBucketMultipartUploads
                Resource: 'arn:aws:s3:::*'
              - Sid: CloudStratusS3MultipartPartList
                Effect: Allow
                Action: s3:ListMultipartUploadParts
                Resource: 'arn:aws:s3:::*/*'
              # Lists object names, sizes and dates, never contents (there is
              # no s3:GetObject here), to price moving old data in large S3
              # Standard buckets with no lifecycle rule to a cheaper class.
              # ListBucket is a bucket-level action, so the resource is every
              # bucket's ARN, not its objects.
              - Sid: CloudStratusS3ObjectList
                Effect: Allow
                Action: s3:ListBucket
                Resource: 'arn:aws:s3:::*'
              - !If
                - CurEnabled
                # Creates Cloud Stratus's own export and reads exports. It
                # cannot delete or change an export or report: AWS requires
                # cur:PutReportDefinition alongside CreateExport for CUR 2.0,
                # and it only adds a new report definition.
                - Sid: CloudStratusCurProvisioning
                  Effect: Allow
                  Action:
                    - bcm-data-exports:CreateExport
                    - bcm-data-exports:ListExports
                    - bcm-data-exports:GetExport
                    - cur:PutReportDefinition
                  Resource: '*'
                - !Ref AWS::NoValue
              - !If
                - CurEnabled
                - Sid: CloudStratusCurServiceLinkedRole
                  Effect: Allow
                  Action: iam:CreateServiceLinkedRole
                  Resource: '*'
                  Condition:
                    StringEquals:
                      iam:AWSServiceName: bcm-data-exports.amazonaws.com
                - !Ref AWS::NoValue
              - !If
                - CurEnabled
                - Sid: CloudStratusCurBucketList
                  Effect: Allow
                  Action: s3:ListBucket
                  Resource: !GetAtt CurDiscovery.BucketArn
                  Condition:
                    StringLike:
                      s3:prefix:
                        - !GetAtt CurDiscovery.Prefix
                        - !Sub
                          - '${SelectedPrefix}/*'
                          - SelectedPrefix: !GetAtt CurDiscovery.Prefix
                - !Ref AWS::NoValue
              - !If
                - CurEnabled
                - Sid: CloudStratusCurObjectRead
                  Effect: Allow
                  Action: s3:GetObject
                  Resource: !GetAtt CurDiscovery.ObjectArn
                - !Ref AWS::NoValue

  # Tells Cloud Stratus which account and role this stack created. The report
  # grants nothing: Cloud Stratus still has to assume the role with the
  # ExternalId before the connection counts. Failure never fails the stack;
  # the app falls back to asking for the account ID.
  ConnectionReportRole:
    Type: AWS::IAM::Role
    Properties:
      Description: Reports the new Cloud Stratus role to Cloud Stratus. Writes its own logs only.
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: CloudStratusConnectionReportLogs
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: WriteReportLogs
                Effect: Allow
                Action:
                  - logs:CreateLogGroup
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource: '*'

  ConnectionReportFunction:
    Type: AWS::Lambda::Function
    Properties:
      Description: Sends this account's ID and the Cloud Stratus role ARN to Cloud Stratus.
      Runtime: python3.12
      Handler: index.handler
      Role: !GetAtt ConnectionReportRole.Arn
      Timeout: 30
      MemorySize: 128
      Code:
        ZipFile: |
          import json
          import urllib.request
          import cfnresponse

          def handler(event, context):
              try:
                  properties = event.get("ResourceProperties") or {}
                  url = properties.get("CallbackUrl") or ""
                  if event.get("RequestType") != "Delete" and url:
                      body = json.dumps({
                          "externalId": properties.get("ExternalId"),
                          "accountId": properties.get("AccountId"),
                          "roleArn": properties.get("RoleArn"),
                      }).encode("utf-8")
                      # Explicit User-Agent: Cloudflare rejects urllib's default
                      # "Python-urllib/x.y" with error 1010 before it reaches the app.
                      request = urllib.request.Request(url, data=body, method="POST", headers={
                          "Content-Type": "application/json",
                          "User-Agent": "CloudStratus-ConnectionReport/1.0 (+https://cloud-stratus.com)",
                      })
                      with urllib.request.urlopen(request, timeout=10) as response:
                          print(f"Cloud Stratus report delivered: HTTP {response.status}")
              except Exception as error:
                  print(f"Cloud Stratus report not delivered: {error}")
              cfnresponse.send(event, context, cfnresponse.SUCCESS, {}, "cloud-stratus-connection-report")

  ConnectionReport:
    Type: AWS::CloudFormation::CustomResource
    Properties:
      ServiceToken: !GetAtt ConnectionReportFunction.Arn
      CallbackUrl: !Ref CallbackUrl
      ExternalId: !Ref ExternalId
      AccountId: !Ref AWS::AccountId
      RoleArn: !GetAtt CloudStratusRole.Arn

  CurBucket:
    Type: AWS::S3::Bucket
    Condition: CurBucketManaged
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      BucketName: !Ref CurBucketName
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      VersioningConfiguration:
        Status: Enabled

  CurBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Condition: CurEnabled
    # Other connections can adopt this bucket's export. Retaining only the
    # bucket would remove delivery permissions on stack deletion/CUR disable.
    # This retains the AWS delivery grant, not the Cloud Stratus IAM role.
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
    Properties:
      Bucket: !Ref CurBucket
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          # Matches AWS's canonical Data Exports destination policy: the service
          # validates delivery by reading the bucket policy (s3:GetBucketPolicy)
          # before it will accept CreateExport. Do NOT add an s3:x-amz-acl
          # condition — bcm-data-exports sends no ACL header on ACL-disabled
          # buckets, so a conditioned PutObject grant fails CreateExport with
          # "S3 bucket permission validation failed" (regression 8d28e00).
          - Sid: EnableAWSDataExportsToWriteToS3
            Effect: Allow
            Principal:
              Service:
                - billingreports.amazonaws.com
                - bcm-data-exports.amazonaws.com
            Action:
              - s3:PutObject
              - s3:GetBucketPolicy
            Resource:
              - !GetAtt CurBucket.Arn
              - !Sub '${CurBucket.Arn}/*'
            Condition:
              ArnLike:
                aws:SourceArn:
                  - !Sub 'arn:aws:cur:us-east-1:${AWS::AccountId}:definition/*'
                  - !Sub 'arn:aws:bcm-data-exports:us-east-1:${AWS::AccountId}:export/*'
              StringEquals:
                aws:SourceAccount: !Ref AWS::AccountId

Outputs:
  RoleArn:
    Description: Role assumed by Cloud Stratus using the connection ExternalId.
    Value: !GetAtt CloudStratusRole.Arn
  PolicyVersion:
    Description: Cloud Stratus access policy version.
    Value: !Ref PolicyVersion
  CurBucket:
    Condition: CurBucketManaged
    Description: Selected CUR delivery bucket; an existing compatible export is preferred.
    Value: !If [CurEnabled, !GetAtt CurDiscovery.BucketName, !Ref CurBucket]
  CurPrefix:
    Condition: CurEnabled
    Description: CUR delivery prefix.
    Value: !GetAtt CurDiscovery.Prefix
  CurSource:
    Condition: CurEnabled
    Description: Whether the stack selected an existing export or the managed fallback.
    Value: !GetAtt CurDiscovery.Source
