AWSTemplateFormatVersion: "2010-09-09"

Description: >-
  Valkan Discovery role for AWS Organizations member accounts, deployed as a
  CloudFormation StackSet. Creates one IAM role that only the management
  account's Valkan role can assume, and only with that connection's External ID.
  Its permissions are the read-only actions of Valkan's AWS permission policy; it
  cannot assume other roles. It is not OrganizationAccountAccessRole.

Parameters:
  ManagementRoleArn:
    Type: String
    Description: >-
      ARN of the role Valkan connects with in the management account, for example
      arn:aws:iam::<management-account-id>:role/ValkanDiscoveryReadOnly. Not the
      bootstrap user and not OrganizationAccountAccessRole: with the wrong ARN,
      Valkan cannot enter any member account.
    AllowedPattern: "^arn:aws:iam::\\d{12}:role/.+$"

  ExternalId:
    Type: String
    Description: >-
      The External ID of the management account's Valkan connection. Valkan uses
      the same value to enter this role, and the trust policy refuses it without.
    NoEcho: true
    MinLength: 2

  RoleName:
    Type: String
    Default: ValkanDiscoveryReadOnly
    Description: >-
      The member role's name. Valkan looks for ValkanDiscoveryReadOnly in each
      member account, so keep the default.

Resources:
  ValkanDiscoveryReadOnlyRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Ref RoleName
      Description: >-
        Read-only role assumed by the Valkan Discovery management account to scan
        this member account for AI agents / non-human identities. Read-only only.
      MaxSessionDuration: 3600
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: ValkanManagementChainedAssume
            Effect: Allow
            Principal:
              AWS: !Ref ManagementRoleArn
            Action: "sts:AssumeRole"
            Condition:
              StringEquals:
                sts:ExternalId: !Ref ExternalId
      Policies:
        - PolicyName: ValkanDiscoveryReadOnly
          # The read-only statements of Valkan's AWS permission policy. A member
          # role needs no grant to assume other roles, so it has none.
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Sid: ValkanDiscovery
                Effect: Allow
                Action:
                  - "sts:GetCallerIdentity"

                  - "organizations:DescribeOrganization"
                  - "organizations:ListAccounts"
                  - "organizations:ListParents"
                  - "organizations:ListPoliciesForTarget"
                  - "organizations:DescribePolicy"

                  - "iam:ListRoles"
                  - "iam:GetRole"
                  - "iam:GetInstanceProfile"
                  - "iam:ListUsers"
                  - "iam:ListGroups"
                  - "iam:ListAccessKeys"
                  - "iam:GetAccessKeyLastUsed"
                  - "iam:ListMFADevices"
                  - "iam:GetLoginProfile"
                  - "iam:GetAccountSummary"
                  - "iam:ListServiceSpecificCredentials"
                  - "iam:ListSSHPublicKeys"
                  - "iam:ListSigningCertificates"
                  - "iam:ListPolicies"
                  - "iam:GetPolicy"
                  - "iam:GetPolicyVersion"
                  - "iam:ListEntitiesForPolicy"
                  - "iam:ListAttachedRolePolicies"
                  - "iam:ListRolePolicies"
                  - "iam:GetRolePolicy"
                  - "iam:ListAttachedUserPolicies"
                  - "iam:ListUserPolicies"
                  - "iam:GetUserPolicy"
                  - "iam:ListUserTags"
                  - "iam:ListRoleTags"
                  - "iam:ListGroupsForUser"
                  - "iam:ListAttachedGroupPolicies"
                  - "iam:ListGroupPolicies"
                  - "iam:GetGroupPolicy"

                  - "bedrock:ListFoundationModels"
                  - "bedrock:ListCustomModels"
                  - "bedrock:ListProvisionedModelThroughputs"
                  - "bedrock:ListGuardrails"
                  # Only the PII entity types a guardrail filters are kept (healthcare policies).
                  - "bedrock:GetGuardrail"
                  - "bedrock:GetModelInvocationLoggingConfiguration"

                  - "bedrock:ListAgents"
                  - "bedrock:GetAgent"
                  - "bedrock:ListAgentActionGroups"
                  - "bedrock:GetAgentActionGroup"
                  - "bedrock:ListAgentKnowledgeBases"
                  - "bedrock:ListAgentCollaborators"
                  - "bedrock:ListTagsForResource"

                  - "bedrock-agentcore:ListAgentRuntimes"
                  - "bedrock-agentcore:GetAgentRuntime"
                  - "bedrock-agentcore:ListGateways"
                  - "bedrock-agentcore:GetGateway"
                  - "bedrock-agentcore:ListGatewayTargets"
                  - "bedrock-agentcore:GetGatewayTarget"

                  - "sagemaker:ListEndpoints"
                  - "sagemaker:DescribeEndpoint"
                  - "sagemaker:ListModels"

                  - "qbusiness:ListApplications"
                  - "qbusiness:ListRetrievers"
                  - "qbusiness:ListDataSources"
                  - "qbusiness:ListWebExperiences"

                  - "lambda:ListFunctions"
                  - "lambda:GetFunction"

                  - "ecs:ListClusters"
                  - "ecs:ListServices"
                  - "ecs:DescribeServices"
                  - "ecs:DescribeTaskDefinition"

                  - "events:DescribeEventBus"

                  - "cloudtrail:ListTrails"
                  - "cloudtrail:DescribeTrails"
                  - "cloudtrail:GetEventSelectors"
                  - "cloudtrail:LookupEvents"
                  - "cloudwatch:ListMetrics"
                  - "cloudwatch:GetMetricData"

                  - "s3:ListAllMyBuckets"
                  # Only the valkan-data-class tag is kept (healthcare policies).
                  - "s3:GetBucketTagging"
                  - "s3:GetLifecycleConfiguration"
                  - "s3:GetBucketLocation"
                  - "logs:DescribeLogGroups"
                  - "dynamodb:ListTables"
                  - "secretsmanager:ListSecrets"

                  - "identitystore:GetUserId"
                  - "identitystore:DescribeUser"
                  - "identitystore:ListUsers"
                  - "identitystore:ListGroups"
                  - "identitystore:ListGroupMembershipsForMember"
                  - "sso:ListInstances"
                  - "sso:ListPermissionSets"
                  - "sso:DescribePermissionSet"
                  - "sso:ListAccountAssignments"
                  - "sso:ListAccountAssignmentsForPrincipal"

                  # DNS visibility (optional capability — the connector reports a
                  # blind spot rather than failing when these are absent).
                  - "route53resolver:ListResolverQueryLogConfigs"
                  - "route53resolver:ListResolverQueryLogConfigAssociations"
                  - "ec2:DescribeVpcs"
                  - "ec2:DescribeNetworkInterfaces"
                  - "ec2:DescribeInstances"

                  # Network exposure (optional capability — a denial is reported as a
                  # permission gap and leaves how a VM is reached unknown).
                  - "ec2:DescribeSecurityGroups"
                  - "ec2:DescribeRouteTables"
                  - "ec2:DescribeVpcPeeringConnections"
                  - "elasticloadbalancing:DescribeLoadBalancers"
                  - "elasticloadbalancing:DescribeTargetGroups"
                  - "elasticloadbalancing:DescribeTargetHealth"
                  - "elasticloadbalancing:DescribeListeners"
                  # Where each ALB writes its access logs (attack patterns).
                  - "elasticloadbalancing:DescribeLoadBalancerAttributes"
                  # Where each WAF web ACL sends its logs (attack patterns).
                  - "wafv2:ListLoggingConfigurations"
                  # Where each CloudFront distribution writes its access logs. Reading
                  # them needs a grant the customer adds per log.
                  - "cloudfront:ListDistributions"
                  - "cloudfront:GetDistributionConfig"
                  - "route53:ListHostedZones"
                  - "route53:ListResourceRecordSets"

                  # EKS control plane — the Kubernetes identity tier
                  # (ServiceAccount -> IAM role via Pod Identity / IRSA).
                  - "eks:ListClusters"
                  - "eks:DescribeCluster"
                  - "eks:ListPodIdentityAssociations"
                  - "eks:DescribePodIdentityAssociation"

                  # Managed databases. ONE rds: prefix covers RDS, Aurora,
                  # DocumentDB and Neptune — DocDB and Neptune both sign as
                  # "rds" in the AWS service model, so there is no docdb: or
                  # neptune: grant to ask for. Redshift is separate. Tags come
                  # back inline (TagList / Tags), so no ListTagsForResource.
                  - "rds:DescribeDBInstances"
                  - "rds:DescribeDBClusters"
                  - "redshift:DescribeClusters"
                  - "es:ListDomainNames"
                Resource: "*"

              # Reading the DNS query logs themselves is scoped to the log-group
              # prefixes Valkan recommends, NOT account-wide. A pre-existing
              # resolver config writing somewhere else degrades to a
              # permission gap, which is the intended trade. The
              # aws-waf-logs-* groups are WAF's: AWS requires that name prefix.
              - Sid: ValkanDnsQueryLogs
                Effect: Allow
                Action:
                  - "logs:FilterLogEvents"
                Resource:
                  - "arn:aws:logs:*:*:log-group:/aws/route53resolver/*"
                  - "arn:aws:logs:*:*:log-group:/aws/route53resolver/*:*"
                  - "arn:aws:logs:*:*:log-group:/valkan/*"
                  - "arn:aws:logs:*:*:log-group:/valkan/*:*"
                  - "arn:aws:logs:*:*:log-group:aws-waf-logs-*"
                  - "arn:aws:logs:*:*:log-group:aws-waf-logs-*:*"

              # ALB access logs, read for attack patterns (spikes of 401/403, a 429
              # followed by path variants). Scoped to the AWSLogs/.../elasticloadbalancing/
              # keys ALB writes, with or without a bucket prefix; no other object
              # in any bucket is readable.
              - Sid: ValkanLoadBalancerAccessLogs
                Effect: Allow
                Action:
                  - "s3:ListBucket"
                Resource: "arn:aws:s3:::*"
                Condition:
                  StringLike:
                    "s3:prefix":
                      - "AWSLogs/*/elasticloadbalancing/*"
                      - "*/AWSLogs/*/elasticloadbalancing/*"
              - Sid: ValkanLoadBalancerAccessLogObjects
                Effect: Allow
                Action:
                  - "s3:GetObject"
                Resource: "arn:aws:s3:::*/AWSLogs/*/elasticloadbalancing/*"

              # WAF logs in S3, read for the same attack patterns. AWS requires a WAF
              # log bucket's name to start with aws-waf-logs-, so no other bucket
              # is readable.
              - Sid: ValkanWafLogs
                Effect: Allow
                Action:
                  - "s3:ListBucket"
                  - "s3:GetObject"
                Resource:
                  - "arn:aws:s3:::aws-waf-logs-*"
                  - "arn:aws:s3:::aws-waf-logs-*/*"

              # Where each API Gateway stage writes its access logs. API Gateway's
              # IAM verbs are HTTP methods; GET is its read. Scoped to REST and
              # HTTP/WebSocket APIs (their stages included), nothing else.
              - Sid: ValkanApiGatewayStages
                Effect: Allow
                Action:
                  - "apigateway:GET"
                Resource:
                  - "arn:aws:apigateway:*::/restapis"
                  - "arn:aws:apigateway:*::/restapis/*/stages"
                  - "arn:aws:apigateway:*::/apis"
                  - "arn:aws:apigateway:*::/apis/*/stages"

Outputs:
  RoleArn:
    Description: ARN of the provisioned read-only member role.
    Value: !GetAtt ValkanDiscoveryReadOnlyRole.Arn
  RoleName:
    Description: Name of the provisioned read-only member role.
    Value: !Ref RoleName
