AWSTemplateFormatVersion: '2010-09-09'
Description: '>> DEPLOY IN US-EAST-1 ONLY << CloudWise Cost Monitoring Setup (CUR 1.0 + CUR 2.0) - This template MUST be deployed in us-east-1 (N. Virginia) because AWS Cost Report APIs are only available there.'

Metadata:
  # CloudWise Template Version - Used for update notifications
  # Increment this when adding new permissions or features that require user stack updates
  CloudWise:
    TemplateVersion: "1.38.0"
    LastUpdated: "2026-11-10"
    ChangeLog:
      - Version: "1.38.0"
        Date: "2026-11-10"
        Changes:
          - "Added elasticloadbalancing:DescribeInstanceHealth (read-only, CLO-833). CloudWise calls it for each Classic Load Balancer to count the instances that are in service. Without it, a Classic Load Balancer's instance health reads as missing, so the checks that need it (an idle or unused load balancer, such as one behind an Elastic Beanstalk environment) are withheld for that load balancer: noted, never reported. The call returns the health state of the instances registered to a load balancer; it reads no instance or application data."
          - "IAM permission changes only; no resources change. Stacks on 1.37.0 are not required to update; accounts whose scan was denied this action are told to."
      - Version: "1.37.0"
        Date: "2026-11-10"
        Changes:
          - "Added ec2:DescribeAccountAttributes and ec2:DescribeAvailabilityZones (read-only, CLO-833). Elastic Beanstalk's own DescribeConfigurationSettings and related describe calls make these two EC2 reads with the caller's permissions; a CloudTrail trace of the scan role showed both denied. Today the Beanstalk reads still succeed without them, so this keeps those reads from depending on an EC2 permission the role lacks. DescribeAccountAttributes returns account-level EC2 settings (such as the default VPC); DescribeAvailabilityZones returns the Availability Zones of a Region. Neither reads instance or application data."
          - "IAM permission changes only; no resources change. Stacks on 1.36.0 are not required to update; accounts whose scan was denied either action are told to."
      - Version: "1.36.0"
        Date: "2026-11-05"
        Changes:
          - "Added ec2:DescribeSubnets (read-only, CLO-830). For an Elastic Beanstalk environment in a VPC with a load balancer, Beanstalk's own DescribeConfigurationSettings reads the environment's subnets with the caller's permissions, so CloudWise needs it to read that environment's configuration (instance type, environment type, scaling limits). Without it CloudWise cannot check those environments for previous-generation instances, an unnecessary load balancer or over-provisioning: it withholds those verdicts (noted, never reported). The call returns subnet IDs, CIDR ranges and Availability Zones; it reads no instance or application data."
          - "IAM permission changes only; no resources change. Stacks on 1.35.0 are not required to update; accounts whose scan was denied this action are told to."
      - Version: "1.35.0"
        Date: "2026-11-03"
        Changes:
          - "Added redshift:DescribeScheduledActions, transfer:ListWebApps and transfer:DescribeWebApp (read-only, CLO-815). Redshift: CloudWise reads a cluster's scheduled pause and resume actions so it does not suggest a pause schedule for a cluster that already has one; without it the pause-schedule check withholds its verdict (noted, never reported). Transfer Family: CloudWise lists your Transfer Family web apps and reads each one's details so the idle web app check can see them; without them that check finds no web apps."
          - "IAM permission changes only; no resources change. Stacks on 1.34.0 are not required to update; accounts whose scan was denied one of these actions are told to."
      - Version: "1.34.0"
        Date: "2026-11-02"
        Changes:
          - "Added ec2:DescribeReservedInstances and ec2:DescribeRegions (read-only, CLO-771): CloudWise lists the Regions enabled on your account and reads the EC2 Reserved Instance inventory (instance type, count, term, price and end date) in each one, so you get alerts for expiring Reserved Instances and convertible-exchange opportunities. Without ec2:DescribeReservedInstances the inventory reads as empty and these alerts can't appear; without ec2:DescribeRegions, Reserved Instances are read in us-east-1 only. CloudWise also uses the Region list to skip opt-in Regions your account has not enabled."
          - "IAM permission changes only; no resources change. Every stack below 1.34.0 is asked to update."
      - Version: "1.33.0"
        Date: "2026-11-01"
        Changes:
          - "Added s3:ListBucketVersions (read-only, CLO-734): before calling an S3 bucket empty, CloudWise now asks for one entry from its version listing, because a versioned bucket whose objects were all deleted still holds noncurrent versions and delete markers that the normal object listing does not show. A bucket with any version is never reported as empty. Without this permission the check cannot run: CloudWise treats the bucket's contents as unknown and does not report it as empty, and this account gets a targeted notice. The call returns at most one entry and reads no object content."
          - "IAM permission changes only; no resources change. Only accounts with an empty-looking S3 bucket need to update; CloudWise shows those accounts a targeted notice."
      - Version: "1.32.0"
        Date: "2026-10-24"
        Changes:
          - "Narrowed apigateway:GET (CLO-648). It used to apply to every API Gateway path ('*'), which includes API keys and usage plan keys. It now applies only to the two paths CloudWise reads: the list of REST APIs (/restapis) and each REST API's stages (/restapis/*/stages, to see whether a stage cache is enabled). A new explicit Deny blocks apigateway:GET on API keys (/apikeys) and usage plan keys (/usageplans/*/keys), even if a broader policy is attached to this role later. Note that a REST API's stages still include its stage variables: the cache check reads stages, and IAM cannot exclude one field of a response."
          - "IAM permission changes only; no resources change, and no detector loses access. Existing stacks keep working without an update; update to drop the broader grant."
      - Version: "1.31.0"
        Date: "2026-10-19"
        Changes:
          - "Added es:DescribeOutboundConnections and es:DescribeInboundConnections (read-only, CLO-626): before calling an OpenSearch domain idle, CloudWise checks whether it is on either end of a cross-cluster search or replication connection, since such a domain can serve traffic its own request metrics do not show. Without these permissions CloudWise falls back to the domain's cross-cluster CloudWatch metrics and still never calls a domain idle unless it holds almost no data, and this account gets a targeted notice."
          - "IAM permission changes only; no resources change. Only accounts with an OpenSearch domain that would otherwise be reported idle need to update; CloudWise shows those accounts a targeted notice."
      - Version: "1.30.0"
        Date: "2026-10-14"
        Changes:
          - "Added rds:DescribeDBSnapshotAttributes (read-only, CLO-612): before recommending deletion of an old manual RDS snapshot, CloudWise now checks whether it is shared with other AWS accounts or made public. A shared or public snapshot is withheld, never recommended for deletion, since deleting it would silently remove that other account's access. Without this permission the check cannot run: the snapshot is still reported, at lower confidence, with a warning to confirm it is not shared before deleting it, and this account gets a targeted notice."
          - "IAM permission changes only; no resources change. Only accounts with an old manual RDS snapshot that would otherwise be recommended for deletion need to update; CloudWise shows those accounts a targeted notice."
      - Version: "1.29.0"
        Date: "2026-10-06"
        Changes:
          - "Added cloudwatch:ListMetrics (read-only): it lists which CloudWatch metric series exist, never their values. Kinesis enhanced fan-out detection uses it to tell a consumer that was never subscribed in the last two weeks from one in use, and the idle VPC endpoint check uses it to confirm an endpoint's empty traffic series is real silence. Without it both checks withhold their verdict (noted, never reported as idle)."
          - "IAM permission changes only; no resources change. Only accounts with Kinesis enhanced fan-out consumers or VPC endpoints need to update; CloudWise shows those accounts a targeted notice."
      - Version: "1.28.0"
        Date: "2026-10-03"
        Changes:
          - "Added lightsail:GetRelationalDatabaseMetricData (CLO-540, read-only): idle Lightsail database detection reads each available database's CPU and connection metrics, and without this permission the read was denied, so an idle running database was never reported (only a stopped one was)."
          - "IAM permission changes only; no resources change. Only accounts with Lightsail databases need to update; CloudWise shows those accounts a targeted notice."
      - Version: "1.27.0"
        Date: "2026-10-02"
        Changes:
          - "Added lightsail:GetInstanceMetricData (CLO-527, read-only): idle Lightsail instance detection reads each running instance's CPU metrics, and without this permission the read was denied, so a running idle instance was never reported."
          - "pricing:GetProducts is deliberately NOT granted (CLO-527): orphaned RDS and Elastic Beanstalk savings use CloudWise's region-scaled static price tables, which need no extra permission and make no API calls."
          - "IAM permission changes only; no resources change. Existing stacks should update."
      - Version: "1.26.0"
        Date: "2026-09-21"
        Changes:
          - "The role now carries a CloudWiseTemplateVersion tag, and grants iam:ListRoleTags on ITSELF so CloudWise can read it (CLO-472). Until now CloudWise only knew the template version you pasted when you first connected, so updating your stack never cleared the 'template update available' banner - the one action the banner asked for could not clear it. Scoped to this role alone; it grants no visibility into any other identity in your account."
          - "IAM permission changes only; no resources change. Existing stacks should update."
      - Version: "1.25.0"
        Date: "2026-09-15"
        Changes:
          - "Added compute-optimizer:GetRDSDatabaseRecommendations (CLO-375): RDS rightsizing from Compute Optimizer previously hit AccessDenied on every scan and never produced a finding."
          - "Added a read-only AWS Cost Optimization Hub statement (CLO-367): cost-optimization-hub:ListEnrollmentStatuses, ListRecommendations, GetPreferences and GetRecommendation. Hub corroborates CloudWise findings and supplies AWS's after-discount savings figures. CloudWise never enables Hub or changes its preferences on your behalf."
          - "Added dynamodb:DescribeContinuousBackups (CLO-384): point-in-time recovery now counts as backup coverage for DynamoDB tables."
          - "Removed compute-optimizer:GetAutoScalingGroupRecommendations: granted since 1.x but never read."
          - "IAM permission changes only; no resources change. Existing stacks should update."
      - Version: "1.24.1"
        Date: "2026-09-13"
        Changes:
          - "One-click connect on an account that already has a CloudWise stack no longer fails with 'bucket already exists' (CLO-396): new optional ResourceSuffix parameter (default empty) appended to the cost-report bucket, CUR report and Data Export names. One-click connect passes a per-session suffix; with the default the names are exactly as before, so updating an existing stack changes no resource. NO IAM permission changes; existing stacks do not need to update."
      - Version: "1.24.0"
        Date: "2026-07-24"
        Changes:
          - "One-click connect support (CLO-208): ExternalId now accepts per-workspace values (previously locked to a shared constant), new RoleName parameter (default unchanged), and an optional CloudFormation custom resource that reports the created role back to CloudWise automatically (ConnectSessionId + CallbackServiceToken parameters). NO IAM permission changes."
      - Version: "1.23.0"
        Date: "2026-07-14"
        Changes:
          - "Added route53:ListResourceRecordSets for orphaned DNS record detection (subdomain-takeover hygiene; the detector previously hit AccessDenied on every zone and silently returned no findings)"
      - Version: "1.22.0"
        Date: "2026-07-13"
        Changes:
          - "Added elasticfilesystem:DescribeLifecycleConfiguration for EFS lifecycle-policy waste detection (no_lifecycle_efs previously logged AccessDenied and the finding was skipped)"
      - Version: "1.21.0"
        Date: "2026-06-12"
        Changes:
          - "Added ec2:DescribeVpcEndpoints for idle VPC endpoint waste detection (scan previously logged UnauthorizedOperation and silently skipped the detector)"
          - "Added glue:GetDatabases and glue:GetTables for Glue Data Catalog waste detection (catalog paging previously unauthorized)"
      - Version: "1.20.0"
        Date: "2026-04-16"
        Changes:
          - "Added elasticache:ListTagsForResource for ElastiCache environment tag detection (replication waste, non-production replica identification)"
      - Version: "1.19.0"
        Date: "2026-04-15"
        Changes:
          - "Added elasticbeanstalk:DescribeConfigurationSettings for Beanstalk environment configuration analysis (unnecessary ALB, previous-gen instances, over-provisioned detection)"
          - "Added elasticbeanstalk:DescribeInstancesHealth for Beanstalk instance-level health metrics"
      - Version: "1.18.0"
        Date: "2026-04-12"
        Changes:
          - "Added workspaces:DescribeWorkspaceBundles for WorkSpaces bundle rightsizing detection"
          - "Added workspaces:DescribeWorkspacesPools for WorkSpaces pool overprovisioning detection"
      - Version: "1.17.0"
        Date: "2026-04-14"
        Changes:
          - "Added elasticmapreduce:ListSteps for EMR step history analysis (long-running cluster detection)"
          - "Added elasticmapreduce:GetAutoTerminationPolicy for EMR auto-termination waste detection"
          - "Added elasticmapreduce:DescribeStep for EMR step detail inspection"
      - Version: "1.16.0"
        Date: "2026-04-13"
        Changes:
          - "Added kinesis:ListStreamConsumers, kinesis:DescribeStreamConsumer for Kinesis enhanced fan-out waste detection"
          - "Added firehose:ListDeliveryStreams, firehose:DescribeDeliveryStream for Firehose idle delivery stream detection"
      - Version: "1.15.0"
        Date: "2026-04-08"
        Changes:
          - "Added savingsplans:DescribeSavingsPlans for commitment risk intelligence (RI/Savings Plan analysis)"
      - Version: "1.14.0"
        Date: "2026-04-05"
        Changes:
          - "Added iam:SimulatePrincipalPolicy for comprehensive dry-run permission verification (Troubleshoot Connection)"
      - Version: "1.13.0"
        Date: "2026-04-04"
        Changes:
          - "Added lightsail:GetStaticIps, GetDisks, GetInstanceSnapshots, GetLoadBalancers, GetRelationalDatabases for Lightsail waste detection expansion"
      - Version: "1.12.0"
        Date: "2026-04-01"
        Changes:
          - "Added eks:ListClusters and eks:DescribeCluster for EKS extended-support waste detection"
      - Version: "1.11.0"
        Date: "2026-03-27"
        Changes:
          - "Added mq:DescribeBroker for MQ broker waste detection (idle and oversized)"
      - Version: "1.10.0"
        Date: "2026-03-24"
        Changes:
          - "Added appsync:GetApiCache for AppSync idle cache waste detection"
      - Version: "1.9.0"
        Date: "2026-03-19"
        Changes:
          - "Added es:DescribeDomains for OpenSearch expanded waste detection (oversized domain, EBS overprovisioned, RI opportunity)"
      - Version: "1.8.0"
        Date: "2026-03-18"
        Changes:
          - "Added fsx:DescribeBackups for FSx old backup waste detection"
      - Version: "1.7.0"
        Date: "2026-03-18"
        Changes:
          - "Added rds:DescribeDBClusterSnapshots for DocumentDB old snapshot detection"
          - "Added rds:ListTagsForResource for DocumentDB snapshot retention tag checking"
      - Version: "1.6.0"
        Date: "2026-03-17"
        Changes:
          - "Added AWS Backup read permissions for backup waste detection (5 new detectors)"
          - "backup:ListBackupVaults, ListRecoveryPointsByBackupVault, ListBackupPlans, GetBackupPlan, ListBackupSelections, GetBackupSelection, ListCopyJobs"
      - Version: "1.5.0"
        Date: "2026-03-12"
        Changes:
          - "Added ecs:ListTaskDefinitions, ecs:ListTagsForResource permissions for ECS/Fargate waste detection"
      - Version: "1.4.0"
        Date: "2026-02-28"
        Changes:
          - "Added CUR 2.0 (Data Exports) support - users can choose between CUR 1.0 and CUR 2.0 format"
          - "Added bcm-data-exports:GetExport, bcm-data-exports:ListExports IAM permissions"
          - "Added AWS::BCMDataExports::Export resource for CUR 2.0 deployments"
          - "S3 bucket policy now includes both billingreports and bcm-data-exports service principals"
      - Version: "1.3.0"
        Date: "2026-02-23"
        Changes:
          - "Added sagemaker:DescribeNotebookInstance, sagemaker:DescribeEndpoint, sagemaker:DescribeEndpointConfig permissions for SageMaker waste detection"
      - Version: "1.2.0"
        Date: "2026-01-25"
        Changes:
          - "Added lambda:ListProvisionedConcurrencyConfigs permission for Lambda waste detection"
          - "Fixed permission gap that caused AccessDenied errors during Lambda analysis"
      - Version: "1.1.0"
        Date: "2026-01-19"
        Changes:
          - "Added region validation rule - template now fails gracefully with clear error if not deployed in us-east-1"
          - "Updated description to prominently warn about us-east-1 requirement"
      - Version: "1.0.0"
        Date: "2026-01-02"
        Changes:
          - "Initial versioned template"
          - "90+ Waste Detectors including EC2, EBS, RDS, Lambda, S3, DynamoDB"
          - "Compute Optimizer integration for ML-backed recommendations"
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: "Cost Report Format"
        Parameters:
          - CURVersion
      - Label:
          default: "Security Settings (Pre-configured - Do Not Change)"
        Parameters:
          - CloudWiseAccountId
          - ExternalId
      - Label:
          default: "One-Click Connect (Auto-filled by CloudWise - Do Not Change)"
        Parameters:
          - RoleName
          - ConnectSessionId
          - ConnectSecret
          - CallbackServiceToken
          - ResourceSuffix
    ParameterLabels:
      CURVersion:
        default: "AWS Cost Report Version (CUR 1.0 or CUR 2.0)"
      CloudWiseAccountId:
        default: "CloudWise Service Account (Read-Only)"
      ExternalId:
        default: "Security Key (from the CloudWise app)"
      RoleName:
        default: "IAM Role Name (Auto-filled)"
      ConnectSessionId:
        default: "CloudWise Connect Session (Auto-filled)"
      ConnectSecret:
        default: "CloudWise Connect Secret (Auto-filled)"
      CallbackServiceToken:
        default: "CloudWise Callback (Auto-filled)"
      ResourceSuffix:
        default: "Resource Name Suffix (Auto-filled)"

Parameters:
  CloudWiseAccountId:
    Type: String
    Description: "CloudWise service account ID (DO NOT CHANGE - required for CloudWise to access your cost data)"
    Default: "513158236564"
    AllowedValues:
      - "513158236564"
    ConstraintDescription: This value cannot be changed

  ExternalId:
    Type: String
    Description: "Security key for CloudWise access. One-click connect fills this in. For a manual setup, replace the default with the External ID the CloudWise app shows for this AWS account; CloudWise will not accept the account otherwise."
    # CLO-641: this default is the pre-CLO-197 shared value. It stays only so
    # existing stacks that were created with it keep their parameter on
    # update; new manual setups must replace it (POST /aws-accounts rejects it).
    Default: "cloudwise-cost-access-2025"
    MinLength: 6
    AllowedPattern: '[\w+=,.@:/-]+'
    ConstraintDescription: Must be a valid sts:ExternalId (letters, digits, and +=,.@:/-_)
    NoEcho: true

  RoleName:
    Type: String
    Description: "Name of the IAM role created for CloudWise access (auto-filled by one-click connect; keep the default for manual setup)"
    Default: "CloudWise-Cost-Monitoring-Role"
    MinLength: 1
    MaxLength: 64
    AllowedPattern: '[\w+=,.@-]+'

  ConnectSessionId:
    Type: String
    Description: "CloudWise connect-session id (auto-filled by one-click connect; leave empty for manual setup)"
    Default: ""

  ConnectSecret:
    Type: String
    Description: "Single-use secret CloudWise uses to authenticate this stack's callback (auto-filled by one-click connect; leave empty for manual setup)"
    Default: ""
    NoEcho: true

  CallbackServiceToken:
    Type: String
    Description: "CloudWise callback Lambda ARN used to auto-verify this stack (auto-filled by one-click connect; leave empty for manual setup)"
    Default: ""

  # CLO-396: the cost-report bucket, CUR report and Data Export names are
  # unique per ACCOUNT, so a second stack in an account that already has a
  # CloudWise stack failed pre-deployment validation ("already exists").
  # One-click connect passes a per-session suffix so each new stack gets its
  # own names. KEEP THE DEFAULT EMPTY: with "" every name renders exactly as
  # it did in v1.24.0, so updating an existing stack never renames — and so
  # never REPLACES — the bucket that holds the customer's CUR data. Never pass
  # this on a stack UPDATE.
  ResourceSuffix:
    Type: String
    Description: "Suffix for the cost-report bucket and report names (auto-filled by one-click connect; leave empty for manual setup and for stack updates)"
    Default: ""
    MaxLength: 12
    AllowedPattern: '^$|^[a-z0-9]{1,12}$'
    ConstraintDescription: Must be empty or 1-12 lowercase letters and digits

  CURVersion:
    Type: String
    Description: "Choose your AWS Cost Report format. CUR 1.0 (Legacy) is the standard Cost and Usage Report. CUR 2.0 (Data Exports) uses the newer AWS Billing and Cost Management Data Exports service with improved column naming. CloudWise supports both formats."
    Default: "1.0"
    AllowedValues:
      - "1.0"
      - "2.0"

Conditions:
  IsCUR1: !Equals [!Ref CURVersion, "1.0"]
  IsCUR2: !Equals [!Ref CURVersion, "2.0"]
  # One-click connect: only create the callback custom resource when CloudWise
  # prefilled a ServiceToken (manual/download deployments leave it empty).
  HasConnectCallback: !Not [!Equals [!Ref CallbackServiceToken, ""]]
  # CLO-396: suffix the account-scoped names only when one-click passed one.
  # The else-branch of every !If below is the v1.24.0 expression, unchanged.
  HasResourceSuffix: !Not [!Equals [!Ref ResourceSuffix, ""]]

# NOTE: CloudFormation Rules cannot prevent the "Unrecognized resource types" error
# because AWS rejects AWS::CUR::ReportDefinition during template parsing (before rules run).
# The us-east-1 requirement is enforced by:
# 1. The CloudWise UI which opens AWS Console directly in us-east-1
# 2. Clear documentation and warnings in the UI
# See: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cur-reportdefinition.html

Resources:
  # S3 Bucket for Cost Reports
  # Note: Bucket can be in any region, but CUR service is only in us-east-1
  CostReportsBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !If
        - HasResourceSuffix
        - !Sub 'cloudwise-cur-${AWS::AccountId}-${AWS::Region}-${ResourceSuffix}'
        - !Sub 'cloudwise-cur-${AWS::AccountId}-${AWS::Region}'
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      VersioningConfiguration:
        Status: Enabled
      LifecycleConfiguration:
        Rules:
          - Id: DeleteOldReports
            Status: Enabled
            ExpirationInDays: 90  # Keep reports for 90 days
            AbortIncompleteMultipartUpload:
              DaysAfterInitiation: 1
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true

  # Bucket Policy to Allow AWS Billing Service
  CostReportsBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref CostReportsBucket
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: AllowAWSBillingReports
            Effect: Allow
            Principal:
              Service: billingreports.amazonaws.com
            Action:
              - s3:GetBucketAcl
              - s3:GetBucketPolicy
            Resource: !GetAtt CostReportsBucket.Arn
            Condition:
              StringEquals:
                'aws:SourceArn': !Sub 'arn:aws:cur:us-east-1:${AWS::AccountId}:definition/*'
                'aws:SourceAccount': !Ref AWS::AccountId
          - Sid: AllowAWSBillingDelivery
            Effect: Allow
            Principal:
              Service: billingreports.amazonaws.com
            Action:
              - s3:PutObject
            Resource: !Sub '${CostReportsBucket.Arn}/*'
            Condition:
              StringEquals:
                'aws:SourceArn': !Sub 'arn:aws:cur:us-east-1:${AWS::AccountId}:definition/*'
                'aws:SourceAccount': !Ref AWS::AccountId
          # CUR 2.0 (Data Exports) service access - included regardless of CUR
          # version to allow seamless upgrades from CUR 1.0 to 2.0
          # NOTE: Unlike CUR 1.0, the Data Exports service validates bucket permissions
          # during export creation (before the export ARN exists). Using SourceArn here
          # causes a chicken-and-egg failure. SourceAccount is sufficient security.
          - Sid: AllowDataExportsReports
            Effect: Allow
            Principal:
              Service: bcm-data-exports.amazonaws.com
            Action:
              - s3:GetBucketAcl
              - s3:GetBucketPolicy
            Resource: !GetAtt CostReportsBucket.Arn
            Condition:
              StringEquals:
                'aws:SourceAccount': !Ref AWS::AccountId
          - Sid: AllowDataExportsDelivery
            Effect: Allow
            Principal:
              Service: bcm-data-exports.amazonaws.com
            Action:
              - s3:PutObject
            Resource: !Sub '${CostReportsBucket.Arn}/*'
            Condition:
              StringEquals:
                'aws:SourceAccount': !Ref AWS::AccountId

  # Cost and Usage Report Definition (CUR 1.0 - Legacy format)
  # CUR reports are always generated in us-east-1 regardless of stack deployment region
  CostUsageReport:
    Type: AWS::CUR::ReportDefinition
    Condition: IsCUR1
    DependsOn: 
      - CostReportsBucketPolicy
    Properties:
      ReportName: !If
        - HasResourceSuffix
        - !Sub 'CloudWiseReports-${AWS::AccountId}-${ResourceSuffix}'
        - !Sub 'CloudWiseReports-${AWS::AccountId}'
      TimeUnit: DAILY
      Format: textORcsv
      Compression: GZIP
      AdditionalSchemaElements:
        - RESOURCES
      S3Bucket: !Ref CostReportsBucket
      S3Prefix: 'daily-v1'
      S3Region: 'us-east-1'
      RefreshClosedReports: true
      ReportVersioning: OVERWRITE_REPORT

  # Cost and Usage Report via Data Exports (CUR 2.0 - Modern format)
  # Uses AWS Billing and Cost Management Data Exports service
  CostUsageDataExport:
    Type: AWS::BCMDataExports::Export
    Condition: IsCUR2
    DependsOn:
      - CostReportsBucketPolicy
    Properties:
      Export:
        Name: !If
          - HasResourceSuffix
          - !Sub 'CloudWiseReports-${AWS::AccountId}-${ResourceSuffix}'
          - !Sub 'CloudWiseReports-${AWS::AccountId}'
        Description: 'CloudWise Cost and Usage Report (CUR 2.0 via Data Exports)'
        DataQuery:
          QueryStatement: "SELECT * FROM COST_AND_USAGE_REPORT"
          TableConfigurations:
            COST_AND_USAGE_REPORT:
              TIME_GRANULARITY: DAILY
              INCLUDE_RESOURCES: "TRUE"
              INCLUDE_MANUAL_DISCOUNT_COMPATIBILITY: "TRUE"
              INCLUDE_SPLIT_COST_ALLOCATION_DATA: "TRUE"
        DestinationConfigurations:
          S3Destination:
            S3Bucket: !Ref CostReportsBucket
            S3Prefix: 'daily-v2'
            S3Region: 'us-east-1'
            S3OutputConfigurations:
              OutputType: CUSTOM
              Format: TEXT_OR_CSV
              Compression: GZIP
              Overwrite: OVERWRITE_REPORT
        RefreshCadence:
          Frequency: SYNCHRONOUS

  # IAM Role for CloudWise Access
  CloudWiseAccessRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Ref RoleName
      # CLO-472: the role carries the version of the template that last wrote
      # it, so CloudWise can tell what is actually deployed instead of
      # remembering what was pasted at connect time. Before this, the stored
      # version never changed when a stack was UPDATED, so the "your template
      # is outdated" banner could not be cleared by doing what it asked.
      Tags:
        - Key: CloudWiseTemplateVersion
          Value: '1.38.0'
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          # Allow only CloudWise service role (three-tier security architecture)
          - Effect: Allow
            Principal:
              AWS: !Sub 'arn:aws:iam::${CloudWiseAccountId}:role/cloudwise-customer-access-service-role'
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                'sts:ExternalId': !Ref ExternalId

  # IAM Policy for S3 and Cost Access
  CloudWiseCostPolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: 'CloudWise-Cost-Monitoring-Policy'
      Roles:
        - !Ref CloudWiseAccessRole
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          # CLO-472: read THIS role's own tags, so CloudWise can see which
          # template version is deployed. Scoped to the role itself — it grants
          # no visibility into any other identity in the account.
          - Sid: AllowReadOwnRoleTags
            Effect: Allow
            Action:
              - iam:ListRoleTags
            Resource: !GetAtt CloudWiseAccessRole.Arn

          # S3 Access for Cost Data
          - Sid: AllowCostDataAccess
            Effect: Allow
            Action:
              - s3:GetObject
              - s3:ListBucket
              - s3:GetBucketLocation
            Resource:
              - !GetAtt CostReportsBucket.Arn
              - !Sub '${CostReportsBucket.Arn}/*'
          
          # Cost Report Access (CUR 1.0 + CUR 2.0 Data Exports)
          - Sid: AllowCostReportAccess
            Effect: Allow
            Action:
              - cur:DescribeReportDefinitions
              - bcm-data-exports:GetExport
              - bcm-data-exports:ListExports
            Resource: '*'
            
          # Cost Explorer Access (for transition period and validation)
          - Sid: AllowCostExplorerAccess
            Effect: Allow
            Action:
              - ce:GetCostAndUsage
              - ce:GetDimensionValues
              - ce:GetReservationCoverage
              - ce:GetReservationPurchaseRecommendation
              - ce:GetReservationUtilization
              - ce:GetSavingsPlansUtilization
              - ce:GetSavingsPlansCoverage
              - ce:GetSavingsPlansPurchaseRecommendation
              - ce:GetCostCategories
              - ce:GetRightsizingRecommendation
              - ce:GetSavingsPlansUtilizationDetails
            Resource: '*'

          # Savings Plans read-only access (commitment risk analysis)
          - Sid: AllowSavingsPlansAccess
            Effect: Allow
            Action:
              - savingsplans:DescribeSavingsPlans
            Resource: '*'

          # Compute Optimizer Access (ML-backed rightsizing recommendations)
          - Sid: AllowComputeOptimizerAccess
            Effect: Allow
            Action:
              - compute-optimizer:GetEnrollmentStatus
              - compute-optimizer:GetEC2InstanceRecommendations
              - compute-optimizer:GetEBSVolumeRecommendations
              - compute-optimizer:GetLambdaFunctionRecommendations
              - compute-optimizer:GetRDSDatabaseRecommendations
            Resource: '*'

          # Cost Optimization Hub read access (CLO-367). Read/List actions only:
          # CloudWise never calls UpdateEnrollmentStatus or UpdatePreferences.
          # Hub supports no resource ARNs or condition keys, so '*' is required.
          - Sid: AllowCostOptimizationHubRead
            Effect: Allow
            Action:
              - cost-optimization-hub:ListEnrollmentStatuses
              - cost-optimization-hub:ListRecommendations
              - cost-optimization-hub:GetPreferences
              - cost-optimization-hub:GetRecommendation
            Resource: '*'

          # Organizations Access (if using consolidated billing)
          - Sid: AllowOrganizationsReadAccess
            Effect: Allow
            Action:
              - organizations:ListAccounts
              - organizations:DescribeAccount
              - organizations:DescribeOrganization
            Resource: '*'

          # Support for Account Information
          - Sid: AllowAccountInfo
            Effect: Allow
            Action:
              - iam:GetAccountSummary
              - iam:SimulatePrincipalPolicy
              - sts:GetCallerIdentity
            Resource: '*'

          # Waste Detection - Read-only access to detect unused/underutilized resources
          # Covers 46+ detectors including: EC2, EBS, RDS, Network, Lambda, S3, DynamoDB, ElastiCache,
          # Redshift, OpenSearch, ECS, CloudWatch, SecretsManager, KMS, EMR, SageMaker, Kinesis,
          # Glue, EFS, FSx, ECR, APIGateway, CloudFront, Route53, GlobalAccelerator, MSK, MQ,
          # Neptune, DocumentDB, Timestream, QLDB, WorkSpaces, Lightsail, ElasticBeanstalk,
          # TransferFamily, StepFunctions, AppSync, CloudTrail, AWS Backup
          # Plus: AWS Compute Optimizer (ML-backed rightsizing), RI/Savings Plans recommendations
          
          - Sid: AllowWasteDetectionCompute
            Effect: Allow
            Action:
              # EC2
              - ec2:DescribeInstances
              - ec2:DescribeInstanceTypes
              - ec2:DescribeVolumes
              - ec2:DescribeSnapshots
              - ec2:DescribeImages
              - ec2:DescribeAddresses
              - ec2:DescribeNatGateways
              - ec2:DescribeVpcEndpoints
              - ec2:DescribeReservedInstances
              - ec2:DescribeRegions
              # Lambda
              - lambda:ListFunctions
              - lambda:GetFunction
              - lambda:ListProvisionedConcurrencyConfigs
              # ECS
              - ecs:ListClusters
              - ecs:DescribeClusters
              - ecs:ListServices
              - ecs:DescribeServices
              - ecs:DescribeTaskDefinition
              - ecs:ListTaskDefinitions
              - ecs:ListTagsForResource
              # EKS
              - eks:ListClusters
              - eks:DescribeCluster
              # Lightsail
              - lightsail:GetInstances
              # CLO-527: CPU metrics for idle_lightsail's running-instance branch (read-only)
              - lightsail:GetInstanceMetricData
              - lightsail:GetStaticIps
              - lightsail:GetDisks
              - lightsail:GetInstanceSnapshots
              - lightsail:GetLoadBalancers
              - lightsail:GetRelationalDatabases
              # CLO-540: CPU and connection metrics for lightsail_idle_database's
              # available (idle) branch (read-only)
              - lightsail:GetRelationalDatabaseMetricData
              # Elastic Beanstalk
              - elasticbeanstalk:DescribeEnvironments
              - elasticbeanstalk:DescribeConfigurationSettings
              - elasticbeanstalk:DescribeInstancesHealth
              # CLO-830: DescribeConfigurationSettings reads a VPC, load-balanced
              # environment's subnets with the CALLER's permissions (CloudTrail:
              # invokedBy elasticbeanstalk.amazonaws.com). Without it the read fails
              # with InvalidParameterValue and the environment's config is unknown.
              - ec2:DescribeSubnets
              # CLO-833: a CloudTrail trace of the scan role showed Beanstalk making
              # these two reads on the CALLER's behalf (invokedBy
              # elasticbeanstalk.amazonaws.com) and being denied. Read-only, no data.
              - ec2:DescribeAccountAttributes
              - ec2:DescribeAvailabilityZones
              # CLO-527: pricing:GetProducts is deliberately not granted. Orphaned RDS
              # and Beanstalk prices come from region-scaled static tables (no API call,
              # no extra permission); a test pins its absence.
            Resource: '*'

          - Sid: AllowWasteDetectionStorage
            Effect: Allow
            Action:
              # S3
              - s3:ListAllMyBuckets
              - s3:GetBucketLocation
              - s3:GetBucketTagging
              - s3:ListBucket
              - s3:ListBucketMultipartUploads
              - s3:ListBucketVersions
              - s3:GetLifecycleConfiguration
              # EFS
              - elasticfilesystem:DescribeFileSystems
              - elasticfilesystem:DescribeMountTargets
              - elasticfilesystem:DescribeLifecycleConfiguration
              # FSx
              - fsx:DescribeFileSystems
              - fsx:DescribeBackups
              # ECR
              - ecr:DescribeRepositories
              - ecr:DescribeImages
              # AWS Backup
              - backup:ListBackupVaults
              - backup:ListRecoveryPointsByBackupVault
              - backup:ListBackupPlans
              - backup:GetBackupPlan
              - backup:ListBackupSelections
              - backup:GetBackupSelection
              - backup:ListCopyJobs
            Resource: '*'

          - Sid: AllowWasteDetectionDatabases
            Effect: Allow
            Action:
              # RDS (also covers Neptune and DocumentDB)
              - rds:DescribeDBInstances
              - rds:DescribeDBClusters
              - rds:DescribeDBSnapshots
              - rds:DescribeDBSnapshotAttributes
              - rds:DescribeDBClusterSnapshots
              - rds:ListTagsForResource
              # DynamoDB
              - dynamodb:ListTables
              - dynamodb:DescribeTable
              - dynamodb:DescribeContinuousBackups
              # ElastiCache
              - elasticache:DescribeReplicationGroups
              - elasticache:DescribeCacheClusters
              - elasticache:ListTagsForResource
              # Redshift
              - redshift:DescribeClusters
              - redshift:DescribeScheduledActions
              # OpenSearch
              - es:ListDomainNames
              - es:DescribeDomain
              - es:DescribeDomains
              - es:DescribeOutboundConnections
              - es:DescribeInboundConnections
              # Timestream
              - timestream:ListDatabases
              - timestream:ListTables
              # QLDB
              - qldb:ListLedgers
            Resource: '*'

          - Sid: AllowWasteDetectionNetworking
            Effect: Allow
            Action:
              # ELB
              - elasticloadbalancing:DescribeInstanceHealth
              - elasticloadbalancing:DescribeLoadBalancers
              - elasticloadbalancing:DescribeTargetGroups
              - elasticloadbalancing:DescribeTargetHealth
              # API Gateway: its own statement below (CLO-648), scoped to
              # the two paths the scan reads.
              # CloudFront
              - cloudfront:ListDistributions
              # Route 53
              - route53:ListHostedZones
              - route53:ListResourceRecordSets
              # Global Accelerator
              - globalaccelerator:ListAccelerators
              - globalaccelerator:ListListeners
              - globalaccelerator:ListEndpointGroups
            Resource: '*'

          # API Gateway (CLO-648). apigateway:GET is one IAM action for every
          # API Gateway read, including API keys, so it is never granted on
          # '*'. The scan makes two calls: GetRestApis (GET /restapis) and
          # GetStages (GET /restapis/{id}/stages, for cacheClusterEnabled).
          # Region is '*' because the scan covers every enabled region; the
          # account field of an API Gateway ARN is always empty.
          - Sid: AllowWasteDetectionApiGatewayRead
            Effect: Allow
            Action:
              - apigateway:GET
            Resource:
              - 'arn:aws:apigateway:*::/restapis'
              - 'arn:aws:apigateway:*::/restapis/*/stages'

          # Defense in depth (CLO-648): never read API keys or usage plan
          # keys, even if a broader policy is attached to this role later.
          - Sid: DenyApiGatewayKeyReads
            Effect: Deny
            Action:
              - apigateway:GET
            Resource:
              - 'arn:aws:apigateway:*::/apikeys'
              - 'arn:aws:apigateway:*::/apikeys/*'
              - 'arn:aws:apigateway:*::/usageplans/*/keys'
              - 'arn:aws:apigateway:*::/usageplans/*/keys/*'

          - Sid: AllowWasteDetectionAnalyticsML
            Effect: Allow
            Action:
              # EMR
              - elasticmapreduce:ListClusters
              - elasticmapreduce:DescribeCluster
              - elasticmapreduce:ListInstanceGroups
              - elasticmapreduce:ListSteps
              - elasticmapreduce:GetAutoTerminationPolicy
              - elasticmapreduce:DescribeStep
              # SageMaker
              - sagemaker:ListNotebookInstances
              - sagemaker:DescribeNotebookInstance
              - sagemaker:ListEndpoints
              - sagemaker:DescribeEndpoint
              - sagemaker:DescribeEndpointConfig
              # Kinesis
              - kinesis:ListStreams
              - kinesis:DescribeStreamSummary
              - kinesis:ListStreamConsumers
              - kinesis:DescribeStreamConsumer
              # Firehose
              - firehose:ListDeliveryStreams
              - firehose:DescribeDeliveryStream
              # Glue
              - glue:GetDevEndpoints
            Resource: '*'

          - Sid: AllowWasteDetectionMessaging
            Effect: Allow
            Action:
              # MSK (Kafka)
              - kafka:ListClusters
              # MQ (RabbitMQ/ActiveMQ)
              - mq:ListBrokers
              - mq:DescribeBroker
            Resource: '*'

          - Sid: AllowWasteDetectionIntegration
            Effect: Allow
            Action:
              # Step Functions
              - states:ListStateMachines
              - states:ListExecutions
              # AppSync
              - appsync:ListGraphqlApis
              - appsync:GetApiCache
              # Transfer Family
              - transfer:ListServers
              - transfer:ListUsers
              - transfer:ListWebApps
              - transfer:DescribeWebApp
            Resource: '*'

          - Sid: AllowWasteDetectionManagement
            Effect: Allow
            Action:
              # CloudWatch
              - cloudwatch:GetMetricStatistics
              - cloudwatch:GetMetricData
              - cloudwatch:ListDashboards
              - cloudwatch:ListMetrics
              - logs:DescribeLogGroups
              - logs:DescribeLogStreams
              # CloudTrail (for detecting duplicate trails and storage waste)
              - cloudtrail:DescribeTrails
              - cloudtrail:GetTrailStatus
              - cloudtrail:GetEventSelectors
              # Secrets Manager
              - secretsmanager:ListSecrets
              # KMS
              - kms:ListKeys
              - kms:DescribeKey
              - kms:ListAliases
              # WorkSpaces
              - workspaces:DescribeWorkspaces
              - workspaces:DescribeWorkspacesConnectionStatus
              - workspaces:DescribeWorkspaceBundles
              - workspaces:DescribeWorkspacesPools
            Resource: '*'

          # DynamoDB Auto Scaling detection
          - Sid: AllowWasteDetectionAutoScaling
            Effect: Allow
            Action:
              - application-autoscaling:DescribeScalableTargets
              - application-autoscaling:DescribeScalingPolicies
            Resource: '*'

          # ECR lifecycle policy detection
          - Sid: AllowWasteDetectionECRLifecycle
            Effect: Allow
            Action:
              - ecr:GetLifecyclePolicy
            Resource: '*'

          # Glue jobs and crawlers detection
          - Sid: AllowWasteDetectionGlueJobs
            Effect: Allow
            Action:
              - glue:GetJobs
              - glue:GetCrawlers
              - glue:GetDatabases
              - glue:GetTables
              - glue:GetJobRuns
              - glue:GetCrawlerMetrics
            Resource: '*'

  # ============================================================================
  # One-Click Connect Callback (CLO-208)
  # ============================================================================
  # Reports the created role back to CloudWise automatically so the user never
  # copies ARNs by hand. Only created when CloudWise prefilled the ServiceToken
  # (one-click quick-create flow). The callback Lambda validates the single-use
  # ExternalId and ALWAYS answers CloudFormation, so the stack never hangs.
  CloudWiseConnectCallback:
    Type: Custom::CloudWiseConnectCallback
    Condition: HasConnectCallback
    DependsOn:
      - CloudWiseCostPolicy
      - CostReportsBucketPolicy
    Properties:
      ServiceToken: !Ref CallbackServiceToken
      SessionId: !Ref ConnectSessionId
      ConnectSecret: !Ref ConnectSecret
      RoleArn: !GetAtt CloudWiseAccessRole.Arn
      AccountId: !Ref AWS::AccountId
      Region: !Ref AWS::Region
      TemplateKind: monitoring
      TemplateVersion: "1.38.0"
      CurBucket: !Ref CostReportsBucket
      # MUST match CostUsageReport.ReportName / CostUsageDataExport.Name — this
      # is what CloudWise stores as the account's cur_report_name.
      CurReportName: !If
        - HasResourceSuffix
        - !Sub 'CloudWiseReports-${AWS::AccountId}-${ResourceSuffix}'
        - !Sub 'CloudWiseReports-${AWS::AccountId}'
      CurReportPrefix: !If [IsCUR1, "daily-v1", "daily-v2"]

Outputs:
  CloudWiseRoleArn:
    Description: 'COPY THIS: CloudWise Access Role - paste this into CloudWise account setup'
    Value: !GetAtt CloudWiseAccessRole.Arn
    Export:
      Name: !Sub '${AWS::StackName}-CloudWiseRoleArn'

  BucketName:
    Description: 'COPY THIS: S3 Bucket name for cost processing (required)'
    Value: !Ref CostReportsBucket
    Export:
      Name: !Sub '${AWS::StackName}-BucketName'

  CURReportName:
    Description: 'COPY THIS: Cost and Usage Report name (required)'
    Value: !If
      - HasResourceSuffix
      - !Sub 'CloudWiseReports-${AWS::AccountId}-${ResourceSuffix}'
      - !Sub 'CloudWiseReports-${AWS::AccountId}'
    Export:
      Name: !Sub '${AWS::StackName}-CURReportName'

  SetupInstructions:
    Description: '🎉 Setup Complete - Next Steps'
    Value: !Sub
      - |
        Your AWS account is now ready for CloudWise! 🚀
        
        📋 COPY THESE THREE VALUES TO CLOUDWISE (ALL REQUIRED):
        
        1. CloudWise Access Role:
           ${CloudWiseAccessRole.Arn}
        
        2. S3 Bucket Name (Auto-generated):
           ${CostReportsBucket}
        
        3. CUR Report Name:
           ${CURReportName}
        
        ✅ What was AUTOMATICALLY configured for you:
        • ✨ Cost and Usage Reports (${CURLabel}) - no manual setup needed!
        • 🪣 S3 bucket with unique auto-generated name and proper permissions
        • 🔐 IAM role with secure CloudWise access permissions
        • 📊 Daily cost reports in CSV format (efficient & fast)
        • 🛡️ Security restrictions (IP allowlists, external ID validation)
        • 🔄 Automatic lifecycle rules (90-day retention)
        • 🔍 Waste Detection - find unused resources across your account
        
        ⏰ First cost report will be available in 24 hours
        📊 Cost reports location: s3://${CostReportsBucket}/${S3Prefix}/
        💰 Start seeing 99% cost reduction vs Cost Explorer API immediately!
        
        💡 Next: Return to CloudWise and paste the Role ARN in the "CloudWise Access Role" field!
      - CURLabel: !If [IsCUR1, "CUR 1.0 Legacy", "CUR 2.0 Data Exports"]
        S3Prefix: !If [IsCUR1, "daily-v1", "daily-v2"]
        CURReportName: !If
          - HasResourceSuffix
          - !Sub 'CloudWiseReports-${AWS::AccountId}-${ResourceSuffix}'
          - !Sub 'CloudWiseReports-${AWS::AccountId}'