AWSTemplateFormatVersion: '2010-09-09'
Description: >
  EBS Fast Snapshot Restore Review Remediator.
  Purpose-specific, opt-in remediation module for reviewing EBS Fast Snapshot Restore
  configuration across enabled AWS Regions. Optional remediation disables approved
  Fast Snapshot Restore entries by snapshot and Availability Zone.

Parameters:
  ProjectName:
    Type: String
    Default: ebs-fsr-review
    Description: Short base name used for created resources.

  TargetRegionsCsv:
    Type: String
    Default: all-enabled
    Description: Comma-separated AWS Regions to scan, or all-enabled to scan all enabled Regions.

  ExcludedRegionsCsv:
    Type: String
    Default: ap-northeast-3
    Description: Comma-separated AWS Regions to exclude from scanning/remediation.

  DryRun:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: When true, only report what would happen. When false, perform eligible approved actions.

  ActionMode:
    Type: String
    Default: review-only
    AllowedValues:
      - review-only
      - disable-approved-fsr
    Description: review-only never changes resources. disable-approved-fsr disables Fast Snapshot Restore for approved entries.

  MinimumFsrAgeDays:
    Type: Number
    Default: 7
    Description: Fast Snapshot Restore entry must be enabled for at least this many days before disable consideration.

  RequireApprovalTag:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Disabling FSR requires ApprovalTagKey=ApprovalTagValue on the snapshot when true.

  ApprovalTagKey:
    Type: String
    Default: CostOptApproved
    Description: Snapshot tag key required when RequireApprovalTag is true.

  ApprovalTagValue:
    Type: String
    Default: 'true'
    Description: Snapshot tag value required when RequireApprovalTag is true.

  IgnoreTagKeysCsv:
    Type: String
    Default: CostOptIgnore,DoNotDisable,DoNotModify,DoNotDelete,ComplianceHold,LegalHold,Production,prod
    Description: Comma-separated snapshot tag keys that prevent disabling FSR.

  IgnoreTagPairsCsv:
    Type: String
    Default: CostOptIgnore=true,DoNotDisable=true,DoNotModify=true,DoNotDelete=true,ComplianceHold=true,LegalHold=true,Environment=Production,Environment=Prod
    Description: Comma-separated snapshot tag key=value pairs that prevent disabling FSR.

  IncludeSnapshotIdPrefixesCsv:
    Type: String
    Default: ''
    Description: Optional comma-separated snapshot ID prefixes to include. Leave blank to include all.

  ExcludeSnapshotIdPrefixesCsv:
    Type: String
    Default: ''
    Description: Optional comma-separated snapshot ID prefixes to exclude.

  IncludeOnlyEnabledState:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: When true, only FSR entries in enabled state can be considered for disabling.

  MaxFsrEntriesPerRun:
    Type: Number
    Default: 50
    Description: Safety limit. 0 means no limit. Recommended actual action batch is 1 to 10.

  ContinueOnAccessDenied:
    Type: String
    Default: 'true'
    AllowedValues: ['true', 'false']
    Description: Continue scanning other Regions/snapshots when blocked by IAM/SCP.

  ScheduleEnabled:
    Type: String
    Default: 'false'
    AllowedValues: ['true', 'false']
    Description: Whether to create an enabled EventBridge schedule.

  ScheduleExpression:
    Type: String
    Default: rate(30 days)
    Description: EventBridge schedule expression used when ScheduleEnabled is true.

Conditions:
  IsScheduleEnabled: !Equals [!Ref ScheduleEnabled, 'true']

Resources:
  RemediatorRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: EbsFastSnapshotRestoreReviewPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: DiscoverRegions
                Effect: Allow
                Action:
                  - ec2:DescribeRegions
                Resource: '*'
              - Sid: ReadFastSnapshotRestore
                Effect: Allow
                Action:
                  - ec2:DescribeFastSnapshotRestores
                  - ec2:DescribeSnapshots
                  - ec2:DescribeTags
                Resource: '*'
              - Sid: DisableApprovedFastSnapshotRestore
                Effect: Allow
                Action:
                  - ec2:DisableFastSnapshotRestores
                Resource: '*'

  RemediatorFunction:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Ref ProjectName
      Description: Purpose-specific Lambda for EBS Fast Snapshot Restore review and guarded disablement.
      Runtime: python3.12
      Handler: index.handler
      Timeout: 900
      MemorySize: 512
      Role: !GetAtt RemediatorRole.Arn
      Environment:
        Variables:
          TARGET_REGIONS_CSV: !Ref TargetRegionsCsv
          EXCLUDED_REGIONS_CSV: !Ref ExcludedRegionsCsv
          DRY_RUN: !Ref DryRun
          ACTION_MODE: !Ref ActionMode
          MINIMUM_FSR_AGE_DAYS: !Ref MinimumFsrAgeDays
          REQUIRE_APPROVAL_TAG: !Ref RequireApprovalTag
          APPROVAL_TAG_KEY: !Ref ApprovalTagKey
          APPROVAL_TAG_VALUE: !Ref ApprovalTagValue
          IGNORE_TAG_KEYS_CSV: !Ref IgnoreTagKeysCsv
          IGNORE_TAG_PAIRS_CSV: !Ref IgnoreTagPairsCsv
          INCLUDE_SNAPSHOT_ID_PREFIXES_CSV: !Ref IncludeSnapshotIdPrefixesCsv
          EXCLUDE_SNAPSHOT_ID_PREFIXES_CSV: !Ref ExcludeSnapshotIdPrefixesCsv
          INCLUDE_ONLY_ENABLED_STATE: !Ref IncludeOnlyEnabledState
          MAX_FSR_ENTRIES_PER_RUN: !Ref MaxFsrEntriesPerRun
          CONTINUE_ON_ACCESS_DENIED: !Ref ContinueOnAccessDenied
      Code:
        ZipFile: |
          import json
          import os
          import traceback
          from datetime import datetime, timezone

          import boto3
          from botocore.exceptions import ClientError

          def utc_now():
              return datetime.now(timezone.utc)

          def utc_now_iso():
              return utc_now().isoformat()

          def env_bool(name, default=False):
              return os.environ.get(name, str(default)).strip().lower() in ('1', 'true', 'yes', 'y')

          def env_int(name, default=0):
              try:
                  return int(os.environ.get(name, str(default)).strip())
              except Exception:
                  return default

          def split_csv(value):
              if value is None:
                  return []
              return [x.strip() for x in str(value).split(',') if x.strip()]

          def parse_tag_pairs(value):
              pairs = {}
              for item in split_csv(value):
                  if '=' not in item:
                      continue
                  key, val = item.split('=', 1)
                  if key.strip():
                      pairs[key.strip()] = val.strip()
              return pairs

          def age_days(dt):
              if not dt:
                  return None
              if dt.tzinfo is None:
                  dt = dt.replace(tzinfo=timezone.utc)
              return (utc_now() - dt).days

          def get_enabled_regions(excluded_regions):
              requested = os.environ.get('TARGET_REGIONS_CSV', 'all-enabled').strip()
              if requested and requested.lower() != 'all-enabled':
                  regions = split_csv(requested)
              else:
                  ec2 = boto3.client('ec2', region_name=os.environ.get('AWS_REGION', 'us-east-1'))
                  response = ec2.describe_regions(AllRegions=False)
                  regions = sorted([r['RegionName'] for r in response.get('Regions', [])])
              return [r for r in regions if r not in excluded_regions]

          def tags_to_dict(tags):
              return {t.get('Key'): t.get('Value', '') for t in tags or [] if t.get('Key')}

          def has_ignore_tag(tags, ignore_keys, ignore_pairs):
              for key in ignore_keys:
                  if key in tags:
                      return True, 'ignore_tag_key=' + key
              for key, value in ignore_pairs.items():
                  if tags.get(key) == value:
                      return True, 'ignore_tag_pair=' + key + '=' + value
              return False, ''

          def has_approval_tag(tags, settings):
              if not settings['require_approval_tag']:
                  return True
              return tags.get(settings['approval_tag_key']) == settings['approval_tag_value']

          def id_included(snapshot_id, include_prefixes):
              if not include_prefixes:
                  return True
              return any((snapshot_id or '').startswith(prefix) for prefix in include_prefixes)

          def id_excluded(snapshot_id, exclude_prefixes):
              if not exclude_prefixes:
                  return False
              return any((snapshot_id or '').startswith(prefix) for prefix in exclude_prefixes)

          def describe_fast_snapshot_restores(ec2):
              entries = []
              try:
                  paginator = ec2.get_paginator('describe_fast_snapshot_restores')
                  for page in paginator.paginate():
                      entries.extend(page.get('FastSnapshotRestores', []))
                  return entries
              except Exception:
                  # Some botocore versions do not expose a paginator here.
                  kwargs = {}
                  while True:
                      page = ec2.describe_fast_snapshot_restores(**kwargs)
                      entries.extend(page.get('FastSnapshotRestores', []))
                      token = page.get('NextToken')
                      if not token:
                          break
                      kwargs['NextToken'] = token
                  return entries

          def snapshot_details(ec2, snapshot_id):
              try:
                  response = ec2.describe_snapshots(SnapshotIds=[snapshot_id])
                  snaps = response.get('Snapshots', [])
                  if not snaps:
                      return {}, {}, None
                  snap = snaps[0]
                  tags = tags_to_dict(snap.get('Tags', []))
                  details = {
                      'snapshot_id': snapshot_id,
                      'description': snap.get('Description'),
                      'owner_id': snap.get('OwnerId'),
                      'encrypted': snap.get('Encrypted'),
                      'kms_key_id': snap.get('KmsKeyId'),
                      'volume_id': snap.get('VolumeId'),
                      'volume_size_gib': snap.get('VolumeSize'),
                      'start_time': str(snap.get('StartTime')) if snap.get('StartTime') else None,
                      'snapshot_state': snap.get('State'),
                      'storage_tier': snap.get('StorageTier'),
                      'tags': tags
                  }
                  return details, tags, None
              except ClientError as e:
                  return {}, {}, e

          def scan_region(region, settings):
              ec2 = boto3.client('ec2', region_name=region)
              result = {
                  'region': region,
                  'evaluated_fsr_entries': 0,
                  'fsr_entries': 0,
                  'enabled_fsr_entries': 0,
                  'non_enabled_fsr_entries': 0,
                  'eligible': 0,
                  'would_disable_fsr': 0,
                  'disabled_fsr': 0,
                  'skipped_not_enabled': 0,
                  'skipped_too_new': 0,
                  'skipped_include_prefix': 0,
                  'skipped_exclude_prefix': 0,
                  'skipped_missing_approval_tag': 0,
                  'skipped_ignore_tag': 0,
                  'snapshot_describe_access_denied': 0,
                  'access_denied': 0,
                  'failed': 0,
                  'failures': [],
                  'candidates': [],
                  'disabled_entries': []
              }

              try:
                  entries = describe_fast_snapshot_restores(ec2)
              except ClientError as e:
                  code = e.response.get('Error', {}).get('Code', 'Unknown')
                  message = e.response.get('Error', {}).get('Message', str(e))
                  result['failures'].append({'operation': 'DescribeFastSnapshotRestores', 'error_code': code, 'error_message': message})
                  if code in ('AccessDenied', 'AccessDeniedException') or 'explicit deny' in message.lower():
                      result['access_denied'] += 1
                  else:
                      result['failed'] += 1
                  if not settings['continue_on_access_denied']:
                      raise
                  return result

              for entry in entries:
                  if settings['max_fsr_entries_per_run'] and (result['would_disable_fsr'] + result['disabled_fsr']) >= settings['max_fsr_entries_per_run']:
                      result['stopped_due_to_max_fsr_entries_per_run'] = True
                      return result

                  result['evaluated_fsr_entries'] += 1
                  result['fsr_entries'] += 1

                  snapshot_id = entry.get('SnapshotId')
                  az = entry.get('AvailabilityZone')
                  state = entry.get('State')
                  state_transition_reason = entry.get('StateTransitionReason')
                  owner_id = entry.get('OwnerId')
                  enabling_time = entry.get('EnablingTime')
                  fsr_age = age_days(enabling_time)

                  if state == 'enabled':
                      result['enabled_fsr_entries'] += 1
                  else:
                      result['non_enabled_fsr_entries'] += 1

                  snap_details, tags, snap_error = snapshot_details(ec2, snapshot_id)

                  item = {
                      'snapshot_id': snapshot_id,
                      'availability_zone': az,
                      'region': region,
                      'state': state,
                      'state_transition_reason': state_transition_reason,
                      'owner_id': owner_id,
                      'enabling_time': str(enabling_time) if enabling_time else None,
                      'fsr_age_days': fsr_age,
                      'snapshot': snap_details,
                      'tags': tags
                  }

                  if snap_error:
                      code = snap_error.response.get('Error', {}).get('Code', 'Unknown')
                      message = snap_error.response.get('Error', {}).get('Message', str(snap_error))
                      item['snapshot_describe_error'] = {'error_code': code, 'error_message': message}
                      if code in ('AccessDenied', 'AccessDeniedException', 'UnauthorizedOperation') or 'explicit deny' in message.lower():
                          result['snapshot_describe_access_denied'] += 1
                      else:
                          result['failed'] += 1

                  if not id_included(snapshot_id, settings['include_snapshot_id_prefixes']):
                      result['skipped_include_prefix'] += 1
                      continue

                  if id_excluded(snapshot_id, settings['exclude_snapshot_id_prefixes']):
                      result['skipped_exclude_prefix'] += 1
                      item['action'] = 'skipped_exclude_prefix'
                      result['candidates'].append(item)
                      continue

                  if settings['include_only_enabled_state'] and state != 'enabled':
                      result['skipped_not_enabled'] += 1
                      item['action'] = 'skipped_not_enabled'
                      result['candidates'].append(item)
                      continue

                  if fsr_age is not None and fsr_age < settings['minimum_fsr_age_days']:
                      result['skipped_too_new'] += 1
                      item['action'] = 'skipped_too_new'
                      result['candidates'].append(item)
                      continue

                  ignore, reason = has_ignore_tag(tags, settings['ignore_tag_keys'], settings['ignore_tag_pairs'])
                  if ignore:
                      result['skipped_ignore_tag'] += 1
                      item['action'] = 'skipped_ignore_tag'
                      item['reason'] = reason
                      result['candidates'].append(item)
                      continue

                  if not has_approval_tag(tags, settings):
                      result['skipped_missing_approval_tag'] += 1
                      item['action'] = 'skipped_missing_approval_tag'
                      item['required_tag'] = settings['approval_tag_key'] + '=' + settings['approval_tag_value']
                      result['candidates'].append(item)
                      continue

                  result['eligible'] += 1

                  if settings['action_mode'] != 'disable-approved-fsr':
                      item['action'] = 'review_only_candidate'
                      result['candidates'].append(item)
                      continue

                  item['action'] = 'would_disable_fsr' if settings['dry_run'] else 'disable_fsr'

                  if settings['dry_run']:
                      result['would_disable_fsr'] += 1
                      result['candidates'].append(item)
                      continue

                  try:
                      ec2.disable_fast_snapshot_restores(
                          AvailabilityZones=[az],
                          SourceSnapshotIds=[snapshot_id]
                      )
                      result['disabled_fsr'] += 1
                      result['disabled_entries'].append(item)
                  except ClientError as e:
                      code = e.response.get('Error', {}).get('Code', 'Unknown')
                      message = e.response.get('Error', {}).get('Message', str(e))
                      result['failures'].append({
                          'snapshot_id': snapshot_id,
                          'availability_zone': az,
                          'operation': 'DisableFastSnapshotRestores',
                          'error_code': code,
                          'error_message': message
                      })
                      if code in ('AccessDenied', 'AccessDeniedException', 'UnauthorizedOperation') or 'explicit deny' in message.lower():
                          result['access_denied'] += 1
                      else:
                          result['failed'] += 1
                      if not settings['continue_on_access_denied']:
                          raise

              return result

          def handler(event, context):
              settings = {
                  'excluded_regions': split_csv(os.environ.get('EXCLUDED_REGIONS_CSV', '')),
                  'dry_run': env_bool('DRY_RUN', True),
                  'action_mode': os.environ.get('ACTION_MODE', 'review-only'),
                  'minimum_fsr_age_days': env_int('MINIMUM_FSR_AGE_DAYS', 7),
                  'require_approval_tag': env_bool('REQUIRE_APPROVAL_TAG', True),
                  'approval_tag_key': os.environ.get('APPROVAL_TAG_KEY', 'CostOptApproved'),
                  'approval_tag_value': os.environ.get('APPROVAL_TAG_VALUE', 'true'),
                  'ignore_tag_keys': split_csv(os.environ.get('IGNORE_TAG_KEYS_CSV', '')),
                  'ignore_tag_pairs': parse_tag_pairs(os.environ.get('IGNORE_TAG_PAIRS_CSV', '')),
                  'include_snapshot_id_prefixes': split_csv(os.environ.get('INCLUDE_SNAPSHOT_ID_PREFIXES_CSV', '')),
                  'exclude_snapshot_id_prefixes': split_csv(os.environ.get('EXCLUDE_SNAPSHOT_ID_PREFIXES_CSV', '')),
                  'include_only_enabled_state': env_bool('INCLUDE_ONLY_ENABLED_STATE', True),
                  'max_fsr_entries_per_run': env_int('MAX_FSR_ENTRIES_PER_RUN', 50),
                  'continue_on_access_denied': env_bool('CONTINUE_ON_ACCESS_DENIED', True),
              }

              if isinstance(event, dict):
                  for key in ('dry_run', 'require_approval_tag', 'include_only_enabled_state'):
                      if key in event:
                          settings[key] = bool(event[key])
                  if 'action_mode' in event:
                      settings['action_mode'] = str(event['action_mode'])
                  for key in ('minimum_fsr_age_days', 'max_fsr_entries_per_run'):
                      if key in event:
                          settings[key] = int(event[key])
                  if 'target_regions' in event and event['target_regions']:
                      os.environ['TARGET_REGIONS_CSV'] = ','.join(event['target_regions'])
                  if 'excluded_regions' in event and event['excluded_regions']:
                      settings['excluded_regions'] = list(event['excluded_regions'])

              if settings['action_mode'] not in ('review-only', 'disable-approved-fsr'):
                  settings['action_mode'] = 'review-only'

              summary = {
                  'started_at': utc_now_iso(),
                  'dry_run': settings['dry_run'],
                  'action_mode': settings['action_mode'],
                  'minimum_fsr_age_days': settings['minimum_fsr_age_days'],
                  'require_approval_tag': settings['require_approval_tag'],
                  'approval_tag': settings['approval_tag_key'] + '=' + settings['approval_tag_value'],
                  'include_only_enabled_state': settings['include_only_enabled_state'],
                  'max_fsr_entries_per_run': settings['max_fsr_entries_per_run'],
                  'excluded_regions': settings['excluded_regions'],
                  'regions': [],
                  'totals': {
                      'evaluated_fsr_entries': 0,
                      'fsr_entries': 0,
                      'enabled_fsr_entries': 0,
                      'non_enabled_fsr_entries': 0,
                      'eligible': 0,
                      'would_disable_fsr': 0,
                      'disabled_fsr': 0,
                      'skipped_not_enabled': 0,
                      'skipped_too_new': 0,
                      'skipped_include_prefix': 0,
                      'skipped_exclude_prefix': 0,
                      'skipped_missing_approval_tag': 0,
                      'skipped_ignore_tag': 0,
                      'snapshot_describe_access_denied': 0,
                      'access_denied': 0,
                      'failed': 0
                  },
                  'region_results': []
              }

              try:
                  regions = get_enabled_regions(settings['excluded_regions'])
                  summary['regions'] = regions
                  for region in regions:
                      try:
                          rr = scan_region(region, settings)
                      except Exception as e:
                          rr = {
                              'region': region,
                              'evaluated_fsr_entries': 0,
                              'fsr_entries': 0,
                              'enabled_fsr_entries': 0,
                              'non_enabled_fsr_entries': 0,
                              'eligible': 0,
                              'would_disable_fsr': 0,
                              'disabled_fsr': 0,
                              'skipped_not_enabled': 0,
                              'skipped_too_new': 0,
                              'skipped_include_prefix': 0,
                              'skipped_exclude_prefix': 0,
                              'skipped_missing_approval_tag': 0,
                              'skipped_ignore_tag': 0,
                              'snapshot_describe_access_denied': 0,
                              'access_denied': 0,
                              'failed': 1,
                              'failures': [{'error_code': type(e).__name__, 'error_message': str(e), 'trace': traceback.format_exc()}],
                              'candidates': [],
                              'disabled_entries': []
                          }
                      summary['region_results'].append(rr)
                      for key in summary['totals']:
                          summary['totals'][key] += int(rr.get(key, 0) or 0)
              finally:
                  summary['ended_at'] = utc_now_iso()
                  print(json.dumps(summary, indent=2, default=str))
              return summary

  RemediatorScheduleRule:
    Type: AWS::Events::Rule
    Condition: IsScheduleEnabled
    Properties:
      Name: !Sub '${ProjectName}-schedule'
      Description: Scheduled run for EBS Fast Snapshot Restore Review Remediator.
      ScheduleExpression: !Ref ScheduleExpression
      State: ENABLED
      Targets:
        - Arn: !GetAtt RemediatorFunction.Arn
          Id: EbsFsrReviewTarget
          Input: '{"source":"eventbridge-schedule","dry_run":true,"action_mode":"review-only"}'

  RemediatorSchedulePermission:
    Type: AWS::Lambda::Permission
    Condition: IsScheduleEnabled
    Properties:
      FunctionName: !Ref RemediatorFunction
      Action: lambda:InvokeFunction
      Principal: events.amazonaws.com
      SourceArn: !GetAtt RemediatorScheduleRule.Arn

Outputs:
  RemediatorFunctionName:
    Description: Lambda function name.
    Value: !Ref RemediatorFunction

  RemediatorFunctionArn:
    Description: Lambda function ARN.
    Value: !GetAtt RemediatorFunction.Arn

  DryRunSetting:
    Description: Current DryRun setting.
    Value: !Ref DryRun

  ActionModeSetting:
    Description: Current ActionMode setting.
    Value: !Ref ActionMode

  ManualReviewExample:
    Description: Example manual review invocation payload.
    Value: !Sub 'aws lambda invoke --function-name ${RemediatorFunction} --cli-binary-format raw-in-base64-out --payload ''{"dry_run":true,"action_mode":"review-only","require_approval_tag":false}'' response.json'
