AWSTemplateFormatVersion: '2010-09-09'
Description: >
  GhostHunter AI — Cross-Account Purge Role (Phase 2: Metadata Scan + Surgical Purge)
  Creates or updates the execution identity to allow both metadata analysis
  and autonomous remediation of confirmed orphan resources. Explicitly isolates
  production databases and core network configurations from modification.

Parameters:
  GhostHunterAccountId:
    Type: String
    Description: >
      The 12-digit AWS Account ID of the central GhostHunter service engine.
      Provided in your GhostHunter deployment dashboard.
    AllowedPattern: '^\d{12}$'
    ConstraintDescription: Must be a 12-digit AWS Account ID.

  ExternalId:
    Type: String
    Description: >
      A unique handshake token generated for your organization to prevent 
      Confused Deputy security compromises. Do not change this value.
    MinLength: 8
    MaxLength: 128

  RoleName:
    Type: String
    Default: GhostHunterScanner
    Description: >
      The structural identity mapping name for the integration. 
      Must match your Phase 1 execution naming convention.

Resources:
  GhostHunterRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Ref RoleName
      Description: Comprehensive metadata scan and surgical remediation role for GhostHunter AI
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              AWS: !Sub 'arn:aws:iam::${GhostHunterAccountId}:root'
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId: !Ref ExternalId

      Policies:
        # 1. Unified Scan Capabilities (Maintains Phase 1 Parity without ReadOnlyAccess overreach)
        - PolicyName: GhostHunterLeastPrivilegeScan
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - 'ec2:DescribeVolumes'
                  - 'ec2:DescribeSnapshots'
                  - 'ec2:DescribeAddresses'
                  - 'ec2:DescribeInstances'
                  - 'ec2:DescribeNatGateways'
                  - 'ec2:DescribeNetworkInterfaces'
                  - 'ec2:DescribeSecurityGroups'
                  - 'rds:DescribeDBInstances'
                  - 'rds:DescribeDBClusters'
                  - 'rds:DescribeDBSnapshots'
                  - 'elasticloadbalancing:DescribeLoadBalancers'
                  - 'elasticloadbalancing:DescribeTargetGroups'
                  - 'lambda:ListFunctions'
                  - 'lambda:GetFunctionConfiguration'
                  - 'logs:DescribeLogGroups'
                  - 's3:ListAllMyBuckets'
                  - 's3:ListBucket'
                  - 's3:GetBucketLocation'
                  - 's3:GetBucketTagging'
                  - 'cloudwatch:GetMetricStatistics'
                  - 'cloudwatch:ListMetrics'
                Resource: '*'

        # 2. Authorized Destruction Capabilities (Surgical Remediations Only)
        - PolicyName: GhostHunterSurgicalPurge
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - 'ec2:DeleteVolume'
                  - 'ec2:ReleaseAddress'
                  - 'ec2:DeleteSnapshot'
                  - 'ec2:DeleteSecurityGroup'
                  - 'ec2:DeleteNetworkInterface'
                  - 'ec2:TerminateInstances'
                  - 'rds:DeleteDBInstance'
                  - 'elasticloadbalancing:DeleteLoadBalancer'
                  - 'lambda:DeleteFunction'
                  - 'logs:PutRetentionPolicy'
                  # Authorized to clear contents for targeted bucket teardowns
                  - 's3:AbortMultipartUpload'
                  - 's3:DeleteObject'
                  - 's3:DeleteBucket'
                Resource: '*'

        # 3. Defensive Safeguards (Hard Hardcoded Boundaries to Assure Security Teams)
        - PolicyName: GhostHunterDenyWriteSafeguards
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Deny
                Action:
                  # Hard block on infrastructure creation/mutation
                  - 'ec2:RunInstances'
                  - 'ec2:CreateVpc'
                  - 'ec2:DeleteVpc'
                  - 'ec2:CreateSubnet'
                  - 'ec2:DeleteSubnet'
                  - 'ec2:CreateInternetGateway'
                  - 'ec2:DeleteInternetGateway'
                  - 'ec2:AttachVolume'
                  - 'ec2:AssignPrivateIpAddresses'
                  # Hard block on core production databases & global states
                  - 'rds:CreateDBInstance'
                  - 'rds:DeleteDBCluster'
                  - 'rds:ModifyDBInstance'
                  - 'rds:StopDBInstance'
                  - 'rds:RestoreDBInstanceFromDBSnapshot'
                  - 'dynamodb:DeleteTable'
                  - 'dynamodb:DeleteItem'
                  - 'dynamodb:PutItem'
                  # Hard block on account governance, auditing, and IAM escalation
                  - 'iam:*'
                  - 'organizations:*'
                  - 'cloudtrail:DeleteTrail'
                  - 'cloudtrail:StopLogging'
                  - 's3:PutBucketPolicy'
                  - 's3:PutObject' # Can delete leaking buckets/objects, but never plant files
                  - 'lambda:CreateFunction'
                  - 'lambda:UpdateFunctionCode'
                Resource: '*'

      Tags:
        - Key: ManagedBy
          Value: GhostHunterAI
        - Key: Purpose
          Value: CloudCostOptimization

Outputs:
  RoleArn:
    Description: >
      The cross-account identity string. Copy and paste this ARN 
      directly into your GhostHunter dashboard to transition to Phase 2.
    Value: !GetAtt GhostHunterRole.Arn
    Export:
      Name: !Sub '${AWS::StackName}-RoleArn'
