AWSTemplateFormatVersion: "2010-09-09"

Description: >-
  Valkan Discovery role for one AWS account. Valkan's one-click connect opens this
  template with every parameter filled in; you can also create the stack
  yourself. Creates one IAM role that only the principal below can assume, and
  only with the External ID. Its permissions are those of Valkan's AWS permission
  policy (the setup guide, step 3), which change nothing in your account. No
  custom resource or Lambda; nothing calls out.

Parameters:
  ValkanPrincipalArn:
    Type: String
    Description: >-
      The only identity this role trusts: an IAM role or user ARN, never an STS
      assumed-role session ARN. One-click connect fills in Valkan's principal; for
      your own stack, use your valkan-bootstrap user's ARN.
    AllowedPattern: '^arn:aws:iam::\d{12}:(role|user)/.+$'

  ExternalId:
    Type: String
    Description: >-
      The trust policy refuses AssumeRole without it. One-click connect fills in
      the value Valkan generated; for your own stack, use a random value and enter
      the same one in Valkan.
    NoEcho: true
    MinLength: 2

  RoleName:
    Type: String
    Default: ValkanDiscoveryReadOnly
    Description: >-
      The role's name. One-click connect fills in ValkanDiscoveryReadOnly-<suffix>
      and derives the role ARN from it, so keep that value; for your own stack,
      keep the default.
    AllowedPattern: "^ValkanDiscoveryReadOnly(-[a-f0-9]{6})?$"

Resources:
  ValkanDiscoveryReadOnlyRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Ref RoleName
      Description: >-
        Read-only role assumed by Valkan Discovery to scan this account for AI
        agents and non-human identities. Read-only only.
      MaxSessionDuration: 3600
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Sid: ValkanAssume
            Effect: Allow
            Principal:
              AWS: !Ref ValkanPrincipalArn
            Action: "sts:AssumeRole"
            Condition:
              StringEquals:
                sts:ExternalId: !Ref ExternalId
      Policies:
        - PolicyName: ValkanDiscoveryReadOnly
          # The same statements as Valkan's AWS permission policy (the setup
          # guide, step 3). Nothing here creates, changes or deletes anything.
          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"

              # AWS Organizations management accounts: lets Valkan enter the
              # read-only role in each member account. It reaches only a member
              # role of this name whose trust policy admits this role.
              - Sid: ValkanAssumeMemberRoles
                Effect: Allow
                Action: "sts:AssumeRole"
                Resource: "arn:aws:iam::*:role/ValkanDiscoveryReadOnly"

Outputs:
  RoleArn:
    Description: ARN of the read-only role. Valkan derives it from the account ID.
    Value: !GetAtt ValkanDiscoveryReadOnlyRole.Arn
