# Muster Drill connector (docs/architecture.md, connector/README.md).
#
# The checker runs in Muster Drill's AWS account. This stack creates, in your account, only:
# - the IAM roles the checker may assume, each with a trust policy that names one Muster Drill role
#   and requires your ExternalId;
# - EventBridge rules that forward AWS Backup restore events (and, optionally, create calls by your
#   backup vendor's role) to Muster Drill's event bus;
# - optionally, the two SSM documents that EC2 layer 1 runs (Linux and Windows), the RDS probe function
#   in your VPC, and the EBS reader function. Both functions run code you can read (connector/probe, connector/ebsreader),
#   pinned by SHA-256, and answer Muster Drill with counts and statuses only.
#
# MusterDrill-Read is always created and MusterDrill-Validate is on by default (EnableValidate); every
# other role is off until you turn it on. Deploy once with CreateRoles=true
# (IAM roles are global), then once more in each other region where restores land, with
# CreateRoles=false.
#
# Intrinsic functions use the long form (Ref:, Fn::Sub:) so the file parses as plain YAML.
AWSTemplateFormatVersion: "2010-09-09"
Description: >-
  Muster Drill connector 1.0.1. Roles that let Muster Drill check restored copies in this account,
  and rules that forward AWS Backup restore events to it. See connector/README.md.

Metadata:
  MusterDrill:
    ConnectorVersion: "1.0.1"
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: "1. Connection (values from Muster Drill)"
        Parameters:
          - ExternalId
          - MusterDrillRoleArn
          - MusterDrillEventBusArn
      - Label:
          default: "2. Where"
        Parameters:
          - CreateRoles
          - AllowedRegions
      - Label:
          default: "3. Optional access (each is off until you turn it on)"
        Parameters:
          - EnableValidate
          - EnableEbsReader
          - EnableEc2Script
          - ReadConsoleOutput
          - RequireCheckTag
          - KmsKeyArns
      - Label:
          default: "4. Events sent to Muster Drill"
        Parameters:
          - ForwardBackupEvents
          - VendorRoleArns
      - Label:
          default: "5. Private RDS copies (optional probe in your VPC)"
        Parameters:
          - EnableRdsProbe
          - RdsVpcId
          - RdsSubnetIds
          - RdsPort
          - RdsRestoreSecurityGroupId
          - RdsLoginSecretArn
          - RdsRulesS3Uri
          - ProbeCodeBucket
          - ProbeCodeKey
          - ProbeCodeSha256
      - Label:
          default: "6. EBS reader code (values from Muster Drill)"
        Parameters:
          - EbsReaderCodeKey
          - EbsReaderCodeSha256
    ParameterLabels:
      ExternalId:
        default: External ID
      MusterDrillRoleArn:
        default: Muster Drill checker role
      MusterDrillEventBusArn:
        default: Muster Drill event bus
      CreateRoles:
        default: Create the IAM roles in this stack?
      AllowedRegions:
        default: Regions the roles may act in
      EnableValidate:
        default: Write restore testing results (MusterDrill-Validate)
      EnableEbsReader:
        default: Check EBS volumes with the in-account reader (MusterDrill-EbsReader)
      EnableEc2Script:
        default: Run the read-only script on restored instances (MusterDrill-Ec2Script)
      ReadConsoleOutput:
        default: Read the console output of restored instances
      RequireCheckTag:
        default: Act only on resources tagged muster-drill:check
      KmsKeyArns:
        default: KMS keys Muster Drill may decrypt with (MusterDrill-KmsUse)
      ForwardBackupEvents:
        default: Forward AWS Backup restore events
      VendorRoleArns:
        default: Your backup vendor's restore roles
      EnableRdsProbe:
        default: Create the RDS probe (MusterDrill-RdsProbe)
      RdsVpcId:
        default: VPC your RDS restores go into
      RdsSubnetIds:
        default: Private subnets for the probe
      RdsPort:
        default: Database port
      RdsRestoreSecurityGroupId:
        default: Security group of restored copies
      RdsLoginSecretArn:
        default: Read-only database login (secret)
      RdsRulesS3Uri:
        default: Rules file (optional)
      ProbeCodeBucket:
        default: Code bucket (probe and EBS reader)
      ProbeCodeKey:
        default: Probe code key
      ProbeCodeSha256:
        default: Probe code SHA-256
      EbsReaderCodeKey:
        default: EBS reader code key
      EbsReaderCodeSha256:
        default: EBS reader code SHA-256

Parameters:
  ExternalId:
    Type: String
    Default: ""
    AllowedPattern: "^([A-Za-z0-9_+=,.@:/-]{32,1224})?$"
    Description: >-
      The External ID Muster Drill gave you (at least 32 characters). Every role requires it when Muster
      Drill assumes it. Needed when CreateRoles is true.
  MusterDrillRoleArn:
    Type: String
    Default: arn:aws:iam::203679766532:role/muster-drill/MusterDrillChecker
    AllowedPattern: "^arn:aws:iam::[0-9]{12}:role/muster-drill/[A-Za-z0-9+=,.@_-]{1,64}$"
    Description: >-
      The one Muster Drill role your roles trust. Keep the default. An account root ARN is refused.
  MusterDrillEventBusArn:
    Type: String
    Default: arn:aws:events:ap-south-1:203679766532:event-bus/muster-drill-ingest
    AllowedPattern: "^arn:aws:events:[a-z0-9-]+:[0-9]{12}:event-bus/[A-Za-z0-9._-]{1,256}$"
    Description: Muster Drill's event bus. Keep the default.
  CreateRoles:
    Type: String
    Default: "true"
    AllowedValues: ["true", "false"]
    Description: >-
      "true" in the first region you deploy to. IAM roles are global, so use "false" in every other region:
      that stack creates only the event rules and, with EnableEc2Script, the SSM document.
  AllowedRegions:
    Type: CommaDelimitedList
    Default: ""
    Description: >-
      Regions where Muster Drill's roles may act, comma-separated, for example ap-south-1,eu-west-1. Every
      permission carries an aws:RequestedRegion condition. Empty means this stack's region only.

  EnableValidate:
    Type: String
    Default: "true"
    AllowedValues: ["false", "true"]
    Description: >-
      "true" creates MusterDrill-Validate, which writes the result of a check back to AWS Backup restore
      testing (backup:PutRestoreValidationResult). Nothing else.
  EnableEbsReader:
    Type: String
    Default: "false"
    AllowedValues: ["false", "true"]
    Description: >-
      "true" creates the EBS reader: a function in this account that reads sampled snapshot blocks through the
      EBS direct APIs with its own role, may create and delete only snapshots tagged muster-drill-reader=true,
      and answers counts and pass or fail only. No block leaves this account. MusterDrill-EbsReader may invoke
      its pinned version only. Needs CreateRoles.
  EnableEc2Script:
    Type: String
    Default: "false"
    AllowedValues: ["false", "true"]
    Description: >-
      "true" creates the SSM documents MusterDrill-Layer1Linux and MusterDrill-Layer1Windows (in this region) and, with CreateRoles,
      MusterDrill-Ec2Script, which may run those two documents only. Read the scripts in this template first.
  ReadConsoleOutput:
    Type: String
    Default: "false"
    AllowedValues: ["false", "true"]
    Description: >-
      "true" adds ec2:GetConsoleOutput to MusterDrill-Read, to look for boot errors. Console output can hold
      anything your instances print at boot. Muster Drill keeps only the names of the errors it matched.
  RequireCheckTag:
    Type: String
    Default: "false"
    AllowedValues: ["false", "true"]
    Description: >-
      "true" limits MusterDrill-Ec2Script to instances, and the EBS reader's snapshots to volumes, that carry
      the tag key muster-drill:check. Your restores must then set that tag.
  KmsKeyArns:
    Type: CommaDelimitedList
    Default: ""
    Description: >-
      Customer-managed KMS key ARNs, comma-separated, for encrypted snapshots and the login secret. They go
      in MusterDrill-KmsUse, attached to the EBS reader's and the probe's own roles (never to a role Muster
      Drill assumes), and usable only through EBS and Secrets Manager. Each key's policy must allow them too.
      Empty adds no KMS access.

  ForwardBackupEvents:
    Type: String
    Default: "true"
    AllowedValues: ["true", "false"]
    Description: >-
      "true" forwards AWS Backup "Restore Job State Change" events (COMPLETED or FAILED, including restore
      testing) from this region to Muster Drill. No other AWS Backup event is sent.
  VendorRoleArns:
    Type: CommaDelimitedList
    Default: ""
    Description: >-
      Optional. ARNs of the roles your backup vendor restores with, exactly as IAM shows them (with the path).
      Their create calls (RunInstances, CreateVolume, RegisterImage, CompleteSnapshot, CreateDBInstance,
      RestoreDBInstance*) are forwarded to Muster Drill. Needs a CloudTrail trail that logs management events.

  EnableRdsProbe:
    Type: String
    Default: "false"
    AllowedValues: ["false", "true"]
    Description: >-
      "true" creates the RDS probe: a small function in your VPC that logs in read-only to restored copies and
      returns totals only, and MusterDrill-RdsProbe, which may invoke that function only. Needs CreateRoles.
  RdsVpcId:
    Type: String
    Default: ""
    AllowedPattern: "^(vpc-[0-9a-f]{8,17})?$"
    Description: The VPC your RDS restores go into.
  RdsSubnetIds:
    Type: CommaDelimitedList
    Default: ""
    Description: >-
      Private subnets in RdsVpcId for the probe, comma-separated. They need a route to Secrets Manager (a VPC
      endpoint or a NAT), and to S3 if you set RdsRulesS3Uri.
  RdsPort:
    Type: Number
    Default: 5432
    MinValue: 1150
    MaxValue: 65535
    Description: Database port of restored copies (PostgreSQL 5432, MySQL and MariaDB 3306).
  RdsRestoreSecurityGroupId:
    Type: String
    Default: ""
    AllowedPattern: "^(sg-[0-9a-f]{8,17})?$"
    Description: >-
      Recommended. The security group your restore settings give restored copies. The probe may then connect
      only to that group, never to your production databases. Empty allows the database port to any address.
  RdsLoginSecretArn:
    Type: String
    Default: ""
    AllowedPattern: "^(arn:aws[a-z-]*:secretsmanager:[a-z0-9-]+:[0-9]{12}:secret:[A-Za-z0-9/_+=.@-]+)?$"
    Description: >-
      A Secrets Manager secret with {"username", "password", "dbname"} for a read-only login that exists in
      your source database. Only the probe reads it. It never leaves your account.
  RdsRulesS3Uri:
    Type: String
    Default: ""
    AllowedPattern: "^(s3://[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]/[^*?]{1,1024})?$"
    Description: >-
      Optional. Your rules file (expected tables, row counts, freshness, SQL rules) as s3://bucket/key. Only the
      probe reads it. Muster Drill never sends SQL to the probe.
  ProbeCodeBucket:
    Type: String
    Default: muster-drill-code-ap-south-1
    AllowedPattern: "^([a-z0-9][a-z0-9.-]{1,61}[a-z0-9])?$"
    Description: >-
      Muster Drill's public release bucket in this region, holding the probe's and the EBS reader's zips. The
      published template's default is that bucket; keep it.
  ProbeCodeKey:
    Type: String
    Default: muster-drill/connector/1.0.1/rds-probe.zip
    Description: The probe's zip in ProbeCodeBucket. The published template's default is this version's zip; keep it.
  # connector/build.py builds the zips reproducibly and writes their hashes here (--update-template); CI
  # rebuilds them and fails if these defaults differ.
  ProbeCodeSha256:
    Type: String
    Default: "QaikvxC6oT+OiwSmeGLH+najYBerfwEnbqhKU9dyXKY="
    AllowedPattern: "^([A-Za-z0-9+/]{43}=)?$"
    Description: >-
      Base64 SHA-256 of the probe zip (connector/build.py prints it). The stack fails if the zip does not match,
      and MusterDrill-RdsProbe may invoke only that version.
  EbsReaderCodeKey:
    Type: String
    Default: muster-drill/connector/1.0.1/ebs-reader.zip
    Description: The EBS reader's zip in ProbeCodeBucket. The published template's default is this version's zip; keep it.
  EbsReaderCodeSha256:
    Type: String
    Default: "i6Ubk5ZhvG4dVRIflU5i8lVjTq8tZJm5uk16jErkoTs="
    AllowedPattern: "^([A-Za-z0-9+/]{43}=)?$"
    Description: >-
      Base64 SHA-256 of the EBS reader zip (connector/build.py prints it). The stack fails if the zip does not
      match, and MusterDrill-EbsReader may invoke only that version.

Rules:
  RolesNeedAnExternalId:
    RuleCondition:
      Fn::Equals: [Ref: CreateRoles, "true"]
    Assertions:
      - Assert:
          Fn::Not:
            - Fn::Equals: [Ref: ExternalId, ""]
        AssertDescription: Set ExternalId (from Muster Drill) when CreateRoles is "true".

  ProbeNeedsItsSettings:
    RuleCondition:
      Fn::Equals: [Ref: EnableRdsProbe, "true"]
    Assertions:
      - Assert:
          Fn::Equals: [Ref: CreateRoles, "true"]
        AssertDescription: The RDS probe is created only in the stack with CreateRoles "true".
      - Assert:
          Fn::Not:
            - Fn::Equals: [Ref: RdsVpcId, ""]
        AssertDescription: Set RdsVpcId when EnableRdsProbe is "true".
      # Rules allow no Fn::Join; an empty CommaDelimitedList is [""] (spike 13).
      - Assert:
          Fn::Not:
            - Fn::EachMemberEquals: [Ref: RdsSubnetIds, ""]
        AssertDescription: Set RdsSubnetIds when EnableRdsProbe is "true".
      - Assert:
          Fn::Not:
            - Fn::Equals: [Ref: RdsLoginSecretArn, ""]
        AssertDescription: Set RdsLoginSecretArn when EnableRdsProbe is "true".
      - Assert:
          Fn::Not:
            - Fn::Equals: [Ref: ProbeCodeBucket, ""]
        AssertDescription: Set ProbeCodeBucket when EnableRdsProbe is "true".
      - Assert:
          Fn::Not:
            - Fn::Equals: [Ref: ProbeCodeSha256, ""]
        AssertDescription: Set ProbeCodeSha256 when EnableRdsProbe is "true".

  EbsReaderNeedsItsSettings:
    RuleCondition:
      Fn::Equals: [Ref: EnableEbsReader, "true"]
    Assertions:
      - Assert:
          Fn::Equals: [Ref: CreateRoles, "true"]
        AssertDescription: The EBS reader is created only in the stack with CreateRoles "true".
      - Assert:
          Fn::Not:
            - Fn::Equals: [Ref: ProbeCodeBucket, ""]
        AssertDescription: Set ProbeCodeBucket when EnableEbsReader is "true".
      - Assert:
          Fn::Not:
            - Fn::Equals: [Ref: EbsReaderCodeSha256, ""]
        AssertDescription: Set EbsReaderCodeSha256 when EnableEbsReader is "true".

Conditions:
  CreatesRoles:
    Fn::Equals: [Ref: CreateRoles, "true"]
  HasRegions:
    Fn::Not:
      - Fn::Equals: [Fn::Join: ["", Ref: AllowedRegions], ""]
  WantValidate:
    Fn::And:
      - Condition: CreatesRoles
      - Fn::Equals: [Ref: EnableValidate, "true"]
  WantEbsReader:
    Fn::And:
      - Condition: CreatesRoles
      - Fn::Equals: [Ref: EnableEbsReader, "true"]
  WantEc2Document:
    Fn::Equals: [Ref: EnableEc2Script, "true"]
  WantEc2Role:
    Fn::And:
      - Condition: CreatesRoles
      - Condition: WantEc2Document
  WantConsoleOutput:
    Fn::Equals: [Ref: ReadConsoleOutput, "true"]
  WantCheckTag:
    Fn::Equals: [Ref: RequireCheckTag, "true"]
  HasKmsKeys:
    Fn::And:
      - Condition: CreatesRoles
      - Fn::Not:
          - Fn::Equals: [Fn::Join: ["", Ref: KmsKeyArns], ""]
  WantProbe:
    Fn::And:
      - Condition: CreatesRoles
      - Fn::Equals: [Ref: EnableRdsProbe, "true"]
  HasRestoreGroup:
    Fn::Not:
      - Fn::Equals: [Ref: RdsRestoreSecurityGroupId, ""]
  HasRules:
    Fn::And:
      - Condition: WantProbe
      - Fn::Not:
          - Fn::Equals: [Ref: RdsRulesS3Uri, ""]
  WantBackupEvents:
    Fn::Equals: [Ref: ForwardBackupEvents, "true"]
  HasVendorRoles:
    Fn::Not:
      - Fn::Equals: [Fn::Join: ["", Ref: VendorRoleArns], ""]

Resources:
  # ---- Ceiling for every role Muster Drill assumes ----
  # A permissions boundary: even if someone later attaches a broad policy (AdministratorAccess) to one
  # of the MusterDrill-* roles, that role can still call only these actions.
  AssumedRoleBoundary:
    Type: AWS::IAM::ManagedPolicy
    Condition: CreatesRoles
    Properties:
      ManagedPolicyName: MusterDrill-Boundary
      Path: /muster-drill/
      Description: >-
        Permissions boundary for the roles Muster Drill assumes. The most any of them can ever do, whatever
        policy is attached.
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: CeilingForMusterDrillRoles
            Effect: Allow
            Action:
              - ec2:DescribeInstances
              - ec2:DescribeInstanceStatus
              - ec2:DescribeVolumes
              - ec2:DescribeSnapshots
              - ec2:DescribeSecurityGroups
              - ec2:GetConsoleOutput
              - rds:DescribeDBInstances
              - rds:DescribeDBClusters
              - backup:DescribeRecoveryPoint
              - tag:GetResources
              - ssm:SendCommand
              - ssm:GetCommandInvocation
              - ssm:DescribeInstanceInformation
              - backup:PutRestoreValidationResult
              - lambda:InvokeFunction
            Resource: "*"
            # The regions cap too: with a broad policy attached, a boundary without this let calls run in any
            # region (spike 27, CS30).
            Condition:
              StringEquals:
                aws:RequestedRegion:
                  Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]

  # ---- MusterDrill-Read (always) ----
  ReadRole:
    Type: AWS::IAM::Role
    Condition: CreatesRoles
    Properties:
      RoleName: MusterDrill-Read
      Path: /muster-drill/
      Description: >-
        Lets Muster Drill read the settings of EC2 instances, EBS volumes and snapshots, RDS databases and AWS
        Backup recovery points, and find resources by tag. It cannot read data or change anything.
      MaxSessionDuration: 3600
      PermissionsBoundary:
        Ref: AssumedRoleBoundary
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: MusterDrillCheckerWithExternalId
            Effect: Allow
            Principal:
              AWS:
                Ref: MusterDrillRoleArn
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId:
                  Ref: ExternalId
              StringLike:
                sts:RoleSessionName: "muster-drill-*"
      Policies:
        - PolicyName: read
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Sid: DescribeOnly
                Effect: Allow
                Action:
                  - ec2:DescribeInstances
                  - ec2:DescribeInstanceStatus
                  - ec2:DescribeVolumes
                  - ec2:DescribeSnapshots
                  - ec2:DescribeSecurityGroups
                  - rds:DescribeDBInstances
                  - rds:DescribeDBClusters
                  - backup:DescribeRecoveryPoint
                  - tag:GetResources
                Resource: "*"  # these calls take no resource, or none narrower than the account
                Condition:
                  StringEquals:
                    aws:RequestedRegion:
                      Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
              - Fn::If:
                  - WantConsoleOutput
                  - Sid: ConsoleOutput
                    Effect: Allow
                    Action: ec2:GetConsoleOutput
                    Resource:
                      Fn::Sub: "arn:${AWS::Partition}:ec2:*:${AWS::AccountId}:instance/*"
                    Condition:
                      StringEquals:
                        aws:RequestedRegion:
                          Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
                  - Ref: AWS::NoValue
      Tags:
        - Key: muster-drill:connector-version
          Value: "1.0.1"

  # ---- MusterDrill-Validate (on by default, EnableValidate) ----
  ValidateRole:
    Type: AWS::IAM::Role
    Condition: WantValidate
    Properties:
      RoleName: MusterDrill-Validate
      Path: /muster-drill/
      Description: >-
        Lets Muster Drill write the result of its check to an AWS Backup restore testing job. Nothing else.
      MaxSessionDuration: 3600
      PermissionsBoundary:
        Ref: AssumedRoleBoundary
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: MusterDrillCheckerWithExternalId
            Effect: Allow
            Principal:
              AWS:
                Ref: MusterDrillRoleArn
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId:
                  Ref: ExternalId
              StringLike:
                sts:RoleSessionName: "muster-drill-*"
      Policies:
        - PolicyName: validate
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Sid: WriteRestoreTestingResult
                Effect: Allow
                Action: backup:PutRestoreValidationResult
                Resource: "*"  # the action supports no resource type and no condition key (SECURITY.md F7)
                Condition:
                  StringEquals:
                    aws:RequestedRegion:
                      Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
      Tags:
        - Key: muster-drill:connector-version
          Value: "1.0.1"

  # ---- MusterDrill-EbsReader (opt-in) ----
  # EBS layer 1 inside your account (docs/architecture.md section 9, decision 1). The reader function
  # reads sampled snapshot blocks with its own role and answers counts and pass or fail only, so no
  # block reaches Muster Drill. Muster Drill's role may invoke this one hash-pinned version, nothing else,
  # and holds none of the snapshot, EBS or KMS permissions.
  EbsReaderLogGroup:
    Type: AWS::Logs::LogGroup
    Condition: WantEbsReader
    Properties:
      LogGroupName: /aws/lambda/MusterDrill-EbsReader
      RetentionInDays: 30

  EbsReaderFunctionRole:
    Type: AWS::IAM::Role
    Condition: WantEbsReader
    Properties:
      RoleName: MusterDrill-EbsReaderFunction
      Path: /muster-drill/
      Description: >-
        The EBS reader function's own role. Muster Drill cannot assume it. It reads snapshot blocks through the
        EBS direct APIs, snapshots a volume under its own tag, and deletes only snapshots carrying that tag.
      MaxSessionDuration: 3600
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: LambdaOnly
            Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        Fn::If:
          - HasKmsKeys
          - - Ref: KmsUsePolicy
          - Ref: AWS::NoValue
      Policies:
        - PolicyName: ebs-reader
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Sid: DescribeVolumesAndSnapshots
                Effect: Allow
                Action:
                  - ec2:DescribeVolumes
                  - ec2:DescribeSnapshots
                Resource: "*"  # these calls take no resource
                Condition:
                  StringEquals:
                    aws:RequestedRegion:
                      Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
              - Sid: ReadSnapshotBlocks
                Effect: Allow
                Action:
                  - ebs:ListSnapshotBlocks
                  - ebs:ListChangedBlocks
                  - ebs:GetSnapshotBlock
                Resource:
                  Fn::Sub: "arn:${AWS::Partition}:ec2:*::snapshot/*"
                Condition:
                  StringEquals:
                    aws:RequestedRegion:
                      Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
              - Sid: SnapshotAVolume
                Effect: Allow
                Action: ec2:CreateSnapshot
                Resource:
                  Fn::Sub: "arn:${AWS::Partition}:ec2:*:${AWS::AccountId}:volume/*"
                Condition:
                  Fn::If:
                    - WantCheckTag
                    - StringEquals:
                        aws:RequestedRegion:
                          Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
                      "Null":
                        aws:ResourceTag/muster-drill:check: "false"
                    - StringEquals:
                        aws:RequestedRegion:
                          Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
              - Sid: OnlyItsOwnTaggedSnapshots
                Effect: Allow
                Action: ec2:CreateSnapshot
                Resource:
                  Fn::Sub: "arn:${AWS::Partition}:ec2:*::snapshot/*"
                Condition:
                  StringEquals:
                    aws:RequestTag/muster-drill-reader: "true"
                    aws:RequestedRegion:
                      Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
              - Sid: TagOnlyWhileCreatingASnapshot
                Effect: Allow
                Action: ec2:CreateTags
                Resource:
                  Fn::Sub: "arn:${AWS::Partition}:ec2:*::snapshot/*"
                Condition:
                  StringEquals:
                    ec2:CreateAction: CreateSnapshot
                    aws:RequestedRegion:
                      Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
              - Sid: DeleteOnlyItsOwnSnapshots
                Effect: Allow
                Action: ec2:DeleteSnapshot
                Resource:
                  Fn::Sub: "arn:${AWS::Partition}:ec2:*::snapshot/*"
                Condition:
                  StringEquals:
                    aws:ResourceTag/muster-drill-reader: "true"
                    aws:RequestedRegion:
                      Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
              - Sid: WriteItsOwnLogs
                Effect: Allow
                Action:
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource:
                  Fn::Sub: "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/MusterDrill-EbsReader:*"
      Tags:
        - Key: muster-drill:connector-version
          Value: "1.0.1"

  EbsReaderFunction:
    Metadata:
      cfn-lint:  # W1030/W1031: the empty default is refused by the EbsReaderNeedsItsSettings rule, which cfn-lint does not read
        config:
          ignore_checks: [W1030, W1031]
    Type: AWS::Lambda::Function
    Condition: WantEbsReader
    DependsOn: EbsReaderLogGroup
    Properties:
      FunctionName: MusterDrill-EbsReader
      # The connector version is in the description so that every connector update changes the function's
      # configuration: Lambda publishes a new version only when the code or the configuration changed.
      Description: Muster Drill EBS reader, connector 1.0.1. Reads sampled snapshot blocks here and answers counts and pass or fail only.
      Runtime: python3.12
      Handler: muster_ebsreader.handler.lambda_handler
      Code:
        S3Bucket:
          Ref: ProbeCodeBucket
        S3Key:
          Ref: EbsReaderCodeKey
      Role:
        Fn::GetAtt: [EbsReaderFunctionRole, Arn]
      Timeout: 120
      MemorySize: 256
      Environment:
        Variables:
          ALLOWED_REGIONS:
            Fn::Join: [",", Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]]
      Tags:
        - Key: muster-drill:connector-version
          Value: "1.0.1"

  # Publishing fails unless the code matches EbsReaderCodeSha256, so a changed zip cannot run.
  # A version keeps the settings it was published with, and CloudFormation publishes a new one only when a
  # property here changes. The description names the reader's settings, so changing AllowedRegions
  # publishes a new version (spike 29, finding 1). Lambda limits it to 256 characters.
  EbsReaderVersion:
    Type: AWS::Lambda::Version
    Condition: WantEbsReader
    Properties:
      FunctionName:
        Ref: EbsReaderFunction
      CodeSha256:
        Ref: EbsReaderCodeSha256
      Description:
        Fn::Sub:
          - "Muster Drill may invoke only this version. Regions: ${Regions}"
          - Regions:
              Fn::Join: [",", Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]]

  EbsReaderRole:
    Type: AWS::IAM::Role
    Condition: WantEbsReader
    Properties:
      RoleName: MusterDrill-EbsReader
      Path: /muster-drill/
      Description: >-
        Lets Muster Drill invoke one published version of the EBS reader function, and nothing else. It cannot
        read snapshot blocks, create or delete snapshots, or use a KMS key itself.
      MaxSessionDuration: 3600
      PermissionsBoundary:
        Ref: AssumedRoleBoundary
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: MusterDrillCheckerWithExternalId
            Effect: Allow
            Principal:
              AWS:
                Ref: MusterDrillRoleArn
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId:
                  Ref: ExternalId
              StringLike:
                sts:RoleSessionName: "muster-drill-*"
      Policies:
        - PolicyName: invoke-ebs-reader
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Sid: InvokeThePinnedReaderVersionOnly
                Effect: Allow
                Action: lambda:InvokeFunction
                Resource:
                  Ref: EbsReaderVersion
                Condition:
                  StringEquals:
                    aws:RequestedRegion:
                      Ref: AWS::Region
      Tags:
        - Key: muster-drill:connector-version
          Value: "1.0.1"

  # ---- MusterDrill-Ec2Script (opt-in) ----
  # The whole script EC2 layer 1 runs. It takes no parameters, so Muster Drill cannot change what
  # runs: only you can, by updating this stack. Identical to SCRIPT in mvp/src/checker/ec2_deep.py
  # (tests/test_connector.py pins it).
  Ec2ScriptDocument:
    Type: AWS::SSM::Document
    Condition: WantEc2Document
    Properties:
      Name: MusterDrill-Layer1Linux
      DocumentType: Command
      UpdateMethod: NewVersion
      Content:
        schemaVersion: "2.2"
        description: >-
          Muster Drill EC2 layer 1. Read only: lists fstab mounts that are not mounted, failed systemd units,
          and the age of the newest file from before the boot. Writes nothing. Takes no parameters.
        mainSteps:
          - action: aws:runShellScript
            name: MusterDrillReadOnlyChecks
            precondition:
              StringEquals: [platformType, Linux]
            inputs:
              timeoutSeconds: "60"
              runCommand:
                - |
                  #!/bin/sh
                  # Muster Drill EC2 layer 1. Reads only; writes nothing.
                  missing=""
                  while read -r dev mnt fstype opts rest; do
                    case "$dev" in ''|\#*) continue ;; esac
                    case "$fstype" in swap|none) continue ;; esac
                    case "$opts" in *noauto*) continue ;; esac
                    if ! grep -qs " $mnt " /proc/mounts; then missing="$missing $mnt"; fi
                  done < /etc/fstab
                  echo "mounts_missing=${missing# }"
                  if command -v systemctl >/dev/null 2>&1; then
                    failed=$(systemctl list-units --state=failed --no-legend --plain 2>/dev/null | awk '{print $1}' | tr '\n' ' ')
                    echo "services_failed=${failed% }"
                  else
                    echo "services_failed=unknown"
                  fi
                  boot=$(stat -c %Y /proc/1 2>/dev/null)
                  echo "boot_epoch=${boot}"
                  newest=$(timeout 20 find / -xdev -type f ! -newer /proc/1 \
                    ! -path '/proc/*' ! -path '/sys/*' ! -path '/var/log/*' ! -path '/tmp/*' ! -path '/var/tmp/*' \
                    -printf '%T@\n' 2>/dev/null | sort -n | tail -1)
                  echo "newest_file_epoch=${newest%%.*}"
      Tags:
        - Key: muster-drill:connector-version
          Value: "1.0.1"

  # The Windows script (WINDOWS_SCRIPT in mvp/src/checker/ec2_deep.py, spike 22, CS25), run with PowerShell.
  # Same rules: read only, no parameters, and tests/test_connector.py keeps it equal to the code.
  Ec2WindowsScriptDocument:
    Type: AWS::SSM::Document
    Condition: WantEc2Document
    Properties:
      Name: MusterDrill-Layer1Windows
      DocumentType: Command
      UpdateMethod: NewVersion
      Content:
        schemaVersion: "2.2"
        description: >-
          Muster Drill EC2 layer 1 for Windows. Read only: disks offline or read-only and unhealthy volumes,
          automatic services that failed, the age of the newest file from before the boot, and the count and
          sources of errors in the System log since boot. Writes nothing. Takes no parameters.
        mainSteps:
          - action: aws:runPowerShellScript
            name: MusterDrillReadOnlyChecksWindows
            precondition:
              StringEquals: [platformType, Windows]
            inputs:
              timeoutSeconds: "60"
              runCommand:
                - |
                  # Muster Drill EC2 layer 1 for Windows. Reads only; writes nothing.
                  $ErrorActionPreference = 'Stop'
                  $ProgressPreference = 'SilentlyContinue'
                  Write-Output 'platform=windows'
                  $os = Get-CimInstance -ClassName Win32_OperatingSystem
                  $bootLocal = $os.LastBootUpTime
                  $boot = $bootLocal.ToUniversalTime()
                  try {
                    $bad = @()
                    foreach ($d in @(Get-Disk)) {
                      if ($d.IsOffline) { $bad += ('disk{0}:offline' -f $d.Number) }
                      elseif ($d.IsReadOnly) { $bad += ('disk{0}:read-only' -f $d.Number) }
                    }
                    foreach ($v in @(Get-Volume | Where-Object { $_.DriveLetter -and $_.DriveType -eq 'Fixed' })) {
                      if ($v.HealthStatus -ne 'Healthy') { $bad += ('{0}:{1}' -f $v.DriveLetter, $v.HealthStatus) }
                    }
                    Write-Output ('mounts_missing=' + ($bad -join ' '))
                  } catch { Write-Output 'mounts_missing=unknown' }
                  try {
                    # Names in the Service Control Manager's errors since boot (failed to start, timed out, ended with an error).
                    $scm = @()
                    try {
                      $scm = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Service Control Manager'; Level = 1, 2; StartTime = $bootLocal } -MaxEvents 200 |
                        ForEach-Object { $_.Properties | ForEach-Object { [string]$_.Value } })
                    } catch { }
                    # Stopped automatic services that failed: named in those errors, or with an error exit code. EC2Launch,
                    # AWSLiteAgent and StateRepository stop with exit code 0 by design; delayed and trigger starts may not have run.
                    $keys = 'HKLM:\SYSTEM\CurrentControlSet\Services'
                    $stopped = @(Get-CimInstance -ClassName Win32_Service -Filter "StartMode='Auto' AND State!='Running'" |
                      Where-Object { ($scm -contains $_.DisplayName -or $scm -contains $_.Name) -or
                                     ($_.ExitCode -ne 0 -and -not $_.DelayedAutoStart -and -not (Test-Path -LiteralPath (Join-Path (Join-Path $keys $_.Name) 'TriggerInfo'))) } |
                      ForEach-Object { $_.Name -replace '\s', '_' } | Sort-Object)
                    Write-Output ('services_failed=' + ($stopped -join ' '))
                  } catch { Write-Output 'services_failed=unknown' }
                  Write-Output ('boot_epoch=' + ([DateTimeOffset]$boot).ToUnixTimeSeconds())
                  $deadline = [datetime]::UtcNow.AddSeconds(10)
                  $newest = [datetime]::MinValue
                  $sysRoot = $env:SystemDrive + '\'
                  $skip = @('Windows', 'ProgramData', '$Recycle.Bin', 'System Volume Information', 'Recovery', 'Config.Msi', 'Windows.old')
                  $todo = [System.Collections.Generic.Queue[object]]::new()
                  $roots = @(Get-CimInstance -ClassName Win32_LogicalDisk -Filter 'DriveType=3' | ForEach-Object { $_.DeviceID + '\' } |
                    Sort-Object { $_ -eq $sysRoot })
                  foreach ($r in $roots) { $todo.Enqueue(@([System.IO.DirectoryInfo]::new($r), 0)) }
                  $n = 0
                  while ($todo.Count -gt 0 -and [datetime]::UtcNow -lt $deadline) {
                    $item = $todo.Dequeue(); $dir = $item[0]; $depth = $item[1]
                    $sysTop = ($depth -eq 0 -and $dir.FullName -eq $sysRoot)
                    if (-not $sysTop) {
                      try {
                        foreach ($f in $dir.EnumerateFiles()) {
                          $t = $f.LastWriteTimeUtc
                          if ($t -lt $boot -and $t -gt $newest) { $newest = $t }
                          $n++
                          if ($n % 2000 -eq 0 -and [datetime]::UtcNow -ge $deadline) { break }
                        }
                      } catch { }
                    }
                    if ($depth -lt 8) {
                      try {
                        foreach ($s in $dir.EnumerateDirectories()) {
                          if ($s.Attributes -band [System.IO.FileAttributes]::ReparsePoint) { continue }
                          if ($sysTop -and $skip -contains $s.Name) { continue }
                          $todo.Enqueue(@($s, ($depth + 1)))
                        }
                      } catch { }
                    }
                  }
                  if ($newest -gt [datetime]::MinValue) { Write-Output ('newest_file_epoch=' + ([DateTimeOffset]$newest).ToUnixTimeSeconds()) }
                  else { Write-Output 'newest_file_epoch=' }
                  try {
                    $events = @(Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 1, 2; StartTime = $bootLocal } -MaxEvents 200)
                  } catch {
                    if ($_.FullyQualifiedErrorId -like 'NoMatchingEventsFound*') { $events = @() } else { $events = $null }
                  }
                  if ($null -eq $events) { Write-Output 'boot_errors=unknown' }
                  else {
                    # A copy of a running instance always logs an unexpected shutdown at first boot: the snapshot was its last moment.
                    $events = @($events | Where-Object { -not (($_.ProviderName -eq 'Microsoft-Windows-Kernel-Power' -and $_.Id -eq 41) -or
                                                                ($_.ProviderName -eq 'EventLog' -and $_.Id -eq 6008)) })
                    Write-Output ('boot_errors=' + $events.Count)
                    $sources = @($events | ForEach-Object { '{0} {1}' -f $_.ProviderName, $_.Id } | Select-Object -Unique | Select-Object -First 10)
                    Write-Output ('boot_error_sources=' + ($sources -join ';'))
                  }
                  exit 0
      Tags:
        - Key: muster-drill:connector-version
          Value: "1.0.1"

  Ec2ScriptRole:
    Type: AWS::IAM::Role
    Condition: WantEc2Role
    Properties:
      RoleName: MusterDrill-Ec2Script
      Path: /muster-drill/
      Description: >-
        Lets Muster Drill run the SSM documents MusterDrill-Layer1Linux and MusterDrill-Layer1Windows, and no other document, on an instance,
        and read the result. The document is read only and takes no parameters.
      MaxSessionDuration: 3600
      PermissionsBoundary:
        Ref: AssumedRoleBoundary
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: MusterDrillCheckerWithExternalId
            Effect: Allow
            Principal:
              AWS:
                Ref: MusterDrillRoleArn
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId:
                  Ref: ExternalId
              StringLike:
                sts:RoleSessionName: "muster-drill-*"
      Policies:
        - PolicyName: ec2-script
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Sid: RunOnlyTheConnectorDocument
                Effect: Allow
                Action: ssm:SendCommand
                Resource:
                  - Fn::Sub: "arn:${AWS::Partition}:ssm:*:${AWS::AccountId}:document/MusterDrill-Layer1Linux"
                  - Fn::Sub: "arn:${AWS::Partition}:ssm:*:${AWS::AccountId}:document/MusterDrill-Layer1Windows"
                Condition:
                  StringEquals:
                    aws:RequestedRegion:
                      Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
              - Sid: OnInstancesInThisAccount
                Effect: Allow
                Action: ssm:SendCommand
                Resource:
                  Fn::Sub: "arn:${AWS::Partition}:ec2:*:${AWS::AccountId}:instance/*"
                Condition:
                  Fn::If:
                    - WantCheckTag
                    - StringEquals:
                        aws:RequestedRegion:
                          Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
                      "Null":
                        aws:ResourceTag/muster-drill:check: "false"
                    - StringEquals:
                        aws:RequestedRegion:
                          Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
              - Sid: ReadAgentStateAndResult
                Effect: Allow
                Action:
                  - ssm:DescribeInstanceInformation
                  - ssm:GetCommandInvocation
                Resource: "*"  # neither call supports a resource type
                Condition:
                  StringEquals:
                    aws:RequestedRegion:
                      Fn::If: [HasRegions, Ref: AllowedRegions, [Ref: "AWS::Region"]]
      Tags:
        - Key: muster-drill:connector-version
          Value: "1.0.1"

  # ---- MusterDrill-KmsUse (a policy, not a role) ----
  # KMS checks the session that makes the EBS or Secrets Manager call, so the key permissions must sit
  # on that role: the EBS reader's and the probe's own roles, never a role Muster Drill assumes. Usable
  # only through those services.
  KmsUsePolicy:
    Type: AWS::IAM::ManagedPolicy
    Condition: HasKmsKeys
    Properties:
      ManagedPolicyName: MusterDrill-KmsUse
      Path: /muster-drill/
      Description: >-
        Decrypt with the listed customer-managed keys, only through EBS and Secrets Manager. Attached to
        MusterDrill-EbsReaderFunction and MusterDrill-RdsProbeFunction.
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: DecryptOnlyThroughEbsOrSecretsManager
            Effect: Allow
            Action: kms:Decrypt
            Resource:
              Ref: KmsKeyArns
            # The EBS direct APIs present ec2.<region>, not ebs.<region> (spike 27, CS30).
            Condition:
              StringLike:
                kms:ViaService:
                  - ec2.*.amazonaws.com
                  - secretsmanager.*.amazonaws.com
          # The EBS direct APIs call DescribeKey first; without it they answer ResourceNotFoundException (spike 27).
          - Sid: DescribeListedKeys
            Effect: Allow
            Action: kms:DescribeKey
            Resource:
              Ref: KmsKeyArns

  # ---- MusterDrill-RdsProbe (opt-in) ----
  # The probe runs in your VPC with its own role. It reads the login secret itself, connects read-only
  # with verified TLS, runs only the queries in its code and the rules file in your bucket, and returns
  # totals and pass or fail. Muster Drill's role may invoke this one hash-pinned version and nothing else.
  ProbeSecurityGroup:
    Metadata:
      cfn-lint:  # W103x: the empty defaults are refused by the ProbeNeedsItsSettings rule, which cfn-lint does not read
        config:
          ignore_checks: [W1030, W1031, W1033]
    Type: AWS::EC2::SecurityGroup
    Condition: WantProbe
    Properties:
      GroupDescription: Muster Drill RDS probe. Allow the database port from this group on restored copies only.
      VpcId:
        Ref: RdsVpcId
      SecurityGroupEgress:
        - Fn::If:
            - HasRestoreGroup
            - IpProtocol: tcp
              FromPort:
                Ref: RdsPort
              ToPort:
                Ref: RdsPort
              DestinationSecurityGroupId:
                Ref: RdsRestoreSecurityGroupId
              Description: Database port of restored copies only
            - IpProtocol: tcp
              FromPort:
                Ref: RdsPort
              ToPort:
                Ref: RdsPort
              CidrIp: 0.0.0.0/0
              Description: Database port
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
          Description: HTTPS to Secrets Manager and S3 (VPC endpoints or NAT)
      Tags:
        - Key: Name
          Value: MusterDrill-RdsProbe

  ProbeLogGroup:
    Type: AWS::Logs::LogGroup
    Condition: WantProbe
    Properties:
      LogGroupName: /aws/lambda/MusterDrill-RdsProbe
      RetentionInDays: 30

  ProbeFunctionRole:
    Metadata:
      cfn-lint:  # W103x: the empty defaults are refused by the ProbeNeedsItsSettings rule, which cfn-lint does not read
        config:
          ignore_checks: [W1030, W1031, W1033]
    Type: AWS::IAM::Role
    Condition: WantProbe
    Properties:
      RoleName: MusterDrill-RdsProbeFunction
      Path: /muster-drill/
      Description: >-
        The RDS probe function's own role. Muster Drill cannot assume it. It reads the login secret and the
        rules file, and manages the function's network interfaces in its subnets and writes its own logs.
      MaxSessionDuration: 3600
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: LambdaOnly
            Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
            Action: sts:AssumeRole
      # Until 1.0.1 this role had AWS's AWSLambdaVPCAccessExecutionRole, which allows the same network
      # interface actions on any resource and logs:CreateLogGroup. The statements under "probe" below
      # replace it, scoped to the probe's subnets, security group, region and log group.
      ManagedPolicyArns:
        - Fn::If:
            - HasKmsKeys
            - Ref: KmsUsePolicy
            - Ref: AWS::NoValue
      Policies:
        - PolicyName: probe
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Sid: WriteItsOwnLogs
                Effect: Allow
                Action:
                  - logs:CreateLogStream
                  - logs:PutLogEvents
                Resource:
                  Fn::Sub: "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/MusterDrill-RdsProbe:*"
              # Lambda creates the function's network interfaces with this role, in the subnets and the
              # security group the function names.
              - Sid: CreateInterfacesInItsSubnetsOnly
                Effect: Allow
                Action: ec2:CreateNetworkInterface
                # Fn::Join takes only a literal separator, so the subnet ARNs leave region and account as *.
                # Subnet IDs are unique, and the interface itself must be in this region and account.
                Resource:
                  Fn::Split:
                    - ","
                    - Fn::Sub:
                        - "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:network-interface/*,arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:security-group/${ProbeSecurityGroup.GroupId},arn:*:ec2:*:*:subnet/${Subnets}"
                        - Subnets:
                            Fn::Join: [",arn:*:ec2:*:*:subnet/", Ref: RdsSubnetIds]
              # Lambda checks these before it changes the function's network settings and refuses a
              # network-interface/* resource ("does not have permissions to call DeleteNetworkInterface",
              # connector 1.0.1 sandbox test), so they keep Resource "*", in this region only.
              - Sid: ManageInterfacesInThisRegion
                Effect: Allow
                Action:
                  - ec2:DeleteNetworkInterface
                  - ec2:AssignPrivateIpAddresses
                  - ec2:UnassignPrivateIpAddresses
                Resource: "*"
                Condition:
                  StringEquals:
                    aws:RequestedRegion:
                      Ref: AWS::Region
              - Sid: DescribeActionsHaveNoResourceScope
                Effect: Allow
                Action:
                  - ec2:DescribeNetworkInterfaces
                  - ec2:DescribeSubnets
                Resource: "*"
                Condition:
                  StringEquals:
                    aws:RequestedRegion:
                      Ref: AWS::Region
              - Sid: ReadTheLoginSecret
                Effect: Allow
                Action: secretsmanager:GetSecretValue
                Resource:  # Fn::Sub, not Ref, so cfn-lint's warning on the empty default lands on this resource, where it is suppressed
                  Fn::Sub: "${RdsLoginSecretArn}"
              - Fn::If:
                  - HasRules
                  - Sid: ReadTheRulesFile
                    Effect: Allow
                    Action: s3:GetObject
                    Resource:
                      Fn::Sub:
                        - "arn:${AWS::Partition}:s3:::${Path}"
                        - Path:
                            Fn::Select: [1, Fn::Split: ["s3://", Ref: RdsRulesS3Uri]]
                  - Ref: AWS::NoValue
      Tags:
        - Key: muster-drill:connector-version
          Value: "1.0.1"

  ProbeFunction:
    Metadata:
      cfn-lint:  # W103x: the empty defaults are refused by the ProbeNeedsItsSettings rule, which cfn-lint does not read
        config:
          ignore_checks: [W1030, W1031, W1033]
    Type: AWS::Lambda::Function
    Condition: WantProbe
    DependsOn: ProbeLogGroup
    Properties:
      FunctionName: MusterDrill-RdsProbe
      # The connector version is in the description for the reason given on EbsReaderFunction.
      Description: Muster Drill RDS probe, connector 1.0.1. Logs in read-only to restored copies and returns totals only.
      Runtime: python3.12
      Handler: muster_probe.handler.lambda_handler
      Code:
        S3Bucket:
          Ref: ProbeCodeBucket
        S3Key:
          Ref: ProbeCodeKey
      Role:
        Fn::GetAtt: [ProbeFunctionRole, Arn]
      Timeout: 60
      MemorySize: 256
      Environment:
        Variables:
          RDS_LOGIN_SECRET_ARN:
            Ref: RdsLoginSecretArn
          RDS_RULES_URI:
            Ref: RdsRulesS3Uri
          RDS_PORT:  # the probe refuses a request for any other port
            Fn::Sub: "${RdsPort}"
      VpcConfig:
        SubnetIds:  # Split and Join for the same reason as the secret above
          Fn::Split: [",", Fn::Join: [",", Ref: RdsSubnetIds]]
        SecurityGroupIds:
          - Fn::GetAtt: [ProbeSecurityGroup, GroupId]
      Tags:
        - Key: muster-drill:connector-version
          Value: "1.0.1"

  # Publishing fails unless the code matches ProbeCodeSha256, so a changed zip cannot run.
  ProbeVersion:
    Type: AWS::Lambda::Version
    Condition: WantProbe
    Properties:
      FunctionName:
        Ref: ProbeFunction
      CodeSha256:
        Ref: ProbeCodeSha256
      # The probe's settings, so that changing one publishes a new version (see EbsReaderVersion). Shortened
      # to fit Lambda's 256 characters: subnet IDs without "subnet-", the secret as region:account:name,
      # the rules file without "s3://". A changed VPC changes the subnets too.
      Description:
        Fn::Sub:
          - "Muster Drill may invoke only this version. Port ${RdsPort}; subnets ${Subnets}; secret ${Secret}; rules ${Rules}"
          - Subnets:
              Fn::Join: ["", Fn::Split: ["subnet-", Fn::Join: [",", Ref: RdsSubnetIds]]]
            Secret:
              Fn::Join:
                - ":"
                - - Fn::Select: [3, Fn::Split: [":", Ref: RdsLoginSecretArn]]
                  - Fn::Select: [4, Fn::Split: [":", Ref: RdsLoginSecretArn]]
                  - Fn::Select: [6, Fn::Split: [":", Ref: RdsLoginSecretArn]]
            Rules:
              Fn::If: [HasRules, Fn::Select: [1, Fn::Split: ["s3://", Ref: RdsRulesS3Uri]], none]

  RdsProbeRole:
    Type: AWS::IAM::Role
    Condition: WantProbe
    Properties:
      RoleName: MusterDrill-RdsProbe
      Path: /muster-drill/
      Description: >-
        Lets Muster Drill invoke one published version of the RDS probe function, and nothing else. It cannot
        read the login secret or connect to a database itself.
      MaxSessionDuration: 3600
      PermissionsBoundary:
        Ref: AssumedRoleBoundary
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: MusterDrillCheckerWithExternalId
            Effect: Allow
            Principal:
              AWS:
                Ref: MusterDrillRoleArn
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId:
                  Ref: ExternalId
              StringLike:
                sts:RoleSessionName: "muster-drill-*"
      Policies:
        - PolicyName: invoke-probe
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Sid: InvokeThePinnedProbeVersionOnly
                Effect: Allow
                Action: lambda:InvokeFunction
                Resource:
                  Ref: ProbeVersion
                Condition:
                  StringEquals:
                    aws:RequestedRegion:
                      Ref: AWS::Region
      Tags:
        - Key: muster-drill:connector-version
          Value: "1.0.1"

  # ---- Events to Muster Drill ----
  # EventBridge uses this role to put matching events on Muster Drill's bus, and only there.
  EventForwarderRole:
    Type: AWS::IAM::Role
    Condition: CreatesRoles
    Properties:
      RoleName: MusterDrill-EventForwarder
      Path: /muster-drill/
      Description: >-
        Used by EventBridge in this account to send the matching events to Muster Drill's event bus. Muster
        Drill cannot assume it.
      MaxSessionDuration: 3600
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: EventBridgeInThisAccountOnly
            Effect: Allow
            Principal:
              Service: events.amazonaws.com
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                aws:SourceAccount:
                  Ref: AWS::AccountId
      Policies:
        - PolicyName: forward
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Sid: PutOnMusterDrillBusOnly
                Effect: Allow
                Action: events:PutEvents
                Resource:
                  Ref: MusterDrillEventBusArn
      Tags:
        - Key: muster-drill:connector-version
          Value: "1.0.1"

  # Event shape: https://docs.aws.amazon.com/aws-backup/latest/devguide/eventbridge.html
  # Restore testing jobs send the same event, with restoreTestingPlanArn (spikes 10, 17, 19).
  BackupRestoreEventsRule:
    Type: AWS::Events::Rule
    Condition: WantBackupEvents
    Properties:
      Name: muster-drill-backup-restores
      Description: Finished AWS Backup restore jobs (including restore testing), sent to Muster Drill
      State: ENABLED
      EventPattern:
        source:
          - aws.backup
        detail-type:
          - Restore Job State Change
        detail:
          status:
            - COMPLETED
            - FAILED
      Targets:
        - Id: muster-drill
          Arn:
            Ref: MusterDrillEventBusArn
          RoleArn:
            Fn::If:
              - CreatesRoles
              - Fn::GetAtt: [EventForwarderRole, Arn]
              - Fn::Sub: "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/muster-drill/MusterDrill-EventForwarder"

  # CloudTrail events reach EventBridge only with a trail that logs them (spike 1). The rule matches
  # on the vendor role's ARN with its path (spike 16), and only the create calls below.
  VendorCreateCallsRule:
    Type: AWS::Events::Rule
    Condition: HasVendorRoles
    Properties:
      Name: muster-drill-vendor-create-calls
      Description: Create calls by your backup vendor's restore roles, sent to Muster Drill
      State: ENABLED
      EventPattern:
        detail-type:
          - AWS API Call via CloudTrail
        detail:
          eventSource:
            - ec2.amazonaws.com
            - ebs.amazonaws.com
            - rds.amazonaws.com
          eventName:
            - RunInstances
            - CreateVolume
            - RegisterImage
            - CompleteSnapshot
            - CreateDBInstance
            - RestoreDBInstanceFromDBSnapshot
            - RestoreDBInstanceToPointInTime
            - RestoreDBInstanceFromS3
          userIdentity:
            sessionContext:
              sessionIssuer:
                arn:
                  Ref: VendorRoleArns
      Targets:
        - Id: muster-drill
          Arn:
            Ref: MusterDrillEventBusArn
          RoleArn:
            Fn::If:
              - CreatesRoles
              - Fn::GetAtt: [EventForwarderRole, Arn]
              - Fn::Sub: "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/muster-drill/MusterDrill-EventForwarder"

Outputs:
  ConnectorVersion:
    Description: The connector version. Give it to Muster Drill with the role ARNs.
    Value: "1.0.1"
  ReadRoleArn:
    Condition: CreatesRoles
    Description: MusterDrill-Read. Give it to Muster Drill.
    Value:
      Fn::GetAtt: [ReadRole, Arn]
  ValidateRoleArn:
    Condition: WantValidate
    Description: MusterDrill-Validate. Give it to Muster Drill.
    Value:
      Fn::GetAtt: [ValidateRole, Arn]
  EbsReaderRoleArn:
    Condition: WantEbsReader
    Description: MusterDrill-EbsReader. Give it to Muster Drill.
    Value:
      Fn::GetAtt: [EbsReaderRole, Arn]
  EbsReaderVersionArn:
    Condition: WantEbsReader
    Description: The EBS reader version Muster Drill may invoke. Give it to Muster Drill.
    Value:
      Ref: EbsReaderVersion
  Ec2ScriptRoleArn:
    Condition: WantEc2Role
    Description: MusterDrill-Ec2Script. Give it to Muster Drill.
    Value:
      Fn::GetAtt: [Ec2ScriptRole, Arn]
  Ec2ScriptDocumentName:
    Condition: WantEc2Document
    Description: The SSM document EC2 layer 1 runs in this region.
    Value:
      Ref: Ec2ScriptDocument
  Ec2WindowsScriptDocumentName:
    Condition: WantEc2Document
    Description: The SSM document EC2 layer 1 runs on Windows in this region.
    Value:
      Ref: Ec2WindowsScriptDocument
  RdsProbeRoleArn:
    Condition: WantProbe
    Description: MusterDrill-RdsProbe. Give it to Muster Drill.
    Value:
      Fn::GetAtt: [RdsProbeRole, Arn]
  RdsProbeVersionArn:
    Condition: WantProbe
    Description: The probe version Muster Drill may invoke. Give it to Muster Drill.
    Value:
      Ref: ProbeVersion
  RdsProbeSecurityGroupId:
    Condition: WantProbe
    Description: >-
      The probe's security group. Allow the database port from it in the security group your restores use,
      and nowhere else.
    Value:
      Fn::GetAtt: [ProbeSecurityGroup, GroupId]
  ConnectorSummary:
    Description: Paste this into Muster Drill to finish the connection.
    Value:
      Fn::Sub:
        - '{"connector_version":"1.0.1","account":"${AWS::AccountId}","region":"${AWS::Region}","roles_here":${Here},"read":"${Read}","validate":"${Validate}","ebs_reader":"${Ebs}","ebs_reader_version":"${EbsVer}","ec2_script":"${Ec2}","ec2_windows_document":"${WinDoc}","rds_probe":"${Probe}","rds_probe_version":"${ProbeVer}"}'
        - Here:
            Ref: CreateRoles
          Read:
            Fn::If: [CreatesRoles, Fn::GetAtt: [ReadRole, Arn], ""]
          Validate:
            Fn::If: [WantValidate, Fn::GetAtt: [ValidateRole, Arn], ""]
          Ebs:
            Fn::If: [WantEbsReader, Fn::GetAtt: [EbsReaderRole, Arn], ""]
          EbsVer:
            Fn::If: [WantEbsReader, Ref: EbsReaderVersion, ""]
          Ec2:
            Fn::If: [WantEc2Role, Fn::GetAtt: [Ec2ScriptRole, Arn], ""]
          WinDoc:
            Fn::If: [WantEc2Document, Ref: Ec2WindowsScriptDocument, ""]
          Probe:
            Fn::If: [WantProbe, Fn::GetAtt: [RdsProbeRole, Arn], ""]
          ProbeVer:
            Fn::If: [WantProbe, Ref: ProbeVersion, ""]
