AWSTemplateFormatVersion: 2010-09-09
Description: This template deploys the roles needed for the AIML Security Assessment to run in each member account.

Parameters:
  ManagementAccountID:
    Description: "Specifies the account ID where AIML Security Assessment will run from."
    Type: String
    Default: "012345678910"
    AllowedPattern: \d{12}
    ConstraintDescription: Enter the 12 digit account ID with no spaces.

Resources:
  MemberRole:
    Type: "AWS::IAM::Role"
    Properties:
      Path: "/service-role/"
      RoleName: AIMLSecurityMemberRole
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              AWS: !Sub "arn:${AWS::Partition}:iam::${ManagementAccountID}:root"
            Action:
              - "sts:AssumeRole"
            Condition:
              ArnEquals:
                aws:PrincipalArn: !Sub arn:${AWS::Partition}:iam::${ManagementAccountID}:role/service-role/MultiAccountCodeBuildRole
      Policies:
        - PolicyName: AIMLSecurityAssessmentPermissions
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              # IAM Permissions for assessment
              - Effect: Allow
                Action:
                  - iam:ListRoles
                  - iam:ListUsers
                  - iam:ListAttachedRolePolicies
                  - iam:ListAttachedUserPolicies
                  - iam:ListRolePolicies
                  - iam:ListUserPolicies
                  - iam:GetRolePolicy
                  - iam:GetUserPolicy
                  - iam:GetPolicy
                  - iam:GetPolicyVersion
                  - iam:GenerateServiceLastAccessedDetails
                  - iam:GetServiceLastAccessedDetails
                  - iam:GetRole
                  - sts:GetCallerIdentity
                Resource: "*"
              # Bedrock Assessment Permissions
              - Effect: Allow
                Action:
                  - bedrock:ListGuardrails
                  - bedrock:GetGuardrail
                  - bedrock:GetModelInvocationLoggingConfiguration
                  - bedrock:ListCustomModels
                  - bedrock:GetCustomModel
                  - bedrock:GetModelCustomizationJob
                  - bedrock:ListFlows
                  - bedrock:GetFlow
                Resource: "*"
              # Bedrock Agent Permissions (Agents for Amazon Bedrock)
              - Effect: Allow
                Action:
                  - bedrock:ListPrompts
                  - bedrock:GetPrompt
                  - bedrock:ListAgents
                  - bedrock:GetAgent
                Resource: "*"
              # Bedrock Agent Service Permissions (Knowledge Bases, Flows)
              - Effect: Allow
                Action:
                  - bedrock-agent:ListKnowledgeBases
                  - bedrock-agent:GetKnowledgeBase
                  - bedrock-agent:ListFlows
                  - bedrock-agent:GetFlow
                Resource: "*"
              # Bedrock AgentCore Permissions
              - Effect: Allow
                Action:
                  - bedrock-agentcore:ListAgentRuntimes
                  - bedrock-agentcore:GetAgentRuntime
                  - bedrock-agentcore:ListMemories
                  - bedrock-agentcore:GetMemory
                  - bedrock-agentcore:ListGateways
                  - bedrock-agentcore:GetGateway
                  - bedrock-agentcore:ListPolicyEngines
                  - bedrock-agentcore:GetPolicyEngine
                  - bedrock-agentcore:GetAgentRuntimeResourcePolicy
                  - bedrock-agentcore:GetGatewayResourcePolicy
                Resource: "*"
              # SageMaker Assessment Permissions
              - Effect: Allow
                Action:
                  - sagemaker:ListNotebookInstances
                  - sagemaker:DescribeNotebookInstance
                  - sagemaker:ListDomains
                  - sagemaker:DescribeDomain
                  - sagemaker:ListTrainingJobs
                  - sagemaker:DescribeTrainingJob
                  - sagemaker:ListModelPackageGroups
                  - sagemaker:ListModelPackages
                  - sagemaker:DescribeModelPackage
                  - sagemaker:ListFeatureGroups
                  - sagemaker:DescribeFeatureGroup
                  - sagemaker:ListPipelines
                  - sagemaker:ListPipelineExecutions
                  - sagemaker:ListProcessingJobs
                  - sagemaker:DescribeProcessingJob
                  - sagemaker:ListMonitoringSchedules
                  - sagemaker:DescribeMonitoringSchedule
                  - sagemaker:ListModels
                  - sagemaker:DescribeModel
                  - sagemaker:ListEndpoints
                  - sagemaker:DescribeEndpoint
                  - sagemaker:ListDataQualityJobDefinitions
                  - sagemaker:DescribeDataQualityJobDefinition
                  # Additional SageMaker Security Hub Controls (SM.10-15)
                  - sagemaker:ListTransformJobs
                  - sagemaker:DescribeTransformJob
                  - sagemaker:ListHyperParameterTuningJobs
                  - sagemaker:DescribeHyperParameterTuningJob
                  - sagemaker:ListCompilationJobs
                  - sagemaker:DescribeCompilationJob
                  - sagemaker:ListAutoMLJobs
                  - sagemaker:DescribeAutoMLJob
                  # Model Governance Permissions
                  - sagemaker:ListExperiments
                  - sagemaker:DescribeExperiment
                  - sagemaker:ListTrials
                  - sagemaker:DescribeTrial
                  - sagemaker:ListAssociations
                Resource: "*"
              # CloudTrail Permissions
              - Effect: Allow
                Action:
                  - cloudtrail:ListTrails
                  - cloudtrail:GetTrail
                  - cloudtrail:GetEventSelectors
                  - cloudtrail:GetTrailStatus
                Resource: "*"
              # Lambda Permissions
              - Effect: Allow
                Action:
                  - lambda:ListFunctions
                Resource: "*"
              # ECS Permissions
              - Effect: Allow
                Action:
                  - ecs:ListClusters
                  - ecs:ListTasks
                  - ecs:DescribeTasks
                Resource: "*"
              # EC2 Permissions
              - Effect: Allow
                Action:
                  - ec2:DescribeVpcEndpoints
                  - ec2:DescribeVpcs
                  - ec2:DescribeSubnets
                  - ec2:DescribeRouteTables
                  - ec2:DescribeNatGateways
                Resource: "*"
              # ECR Permissions
              - Effect: Allow
                Action:
                  - ecr:DescribeRepositories
                  - ecr:GetRepositoryPolicy
                Resource: "*"
              # CloudWatch Logs Permissions
              - Effect: Allow
                Action:
                  - logs:DescribeLogGroups
                  - logs:DescribeLogStreams
                Resource: "*"
              # S3 Bucket Permissions for encryption checks
              - Effect: Allow
                Action:
                  - s3:GetBucketEncryption
                  - s3:GetBucketVersioning
                  - s3:GetBucketTagging
                  - s3:HeadBucket
                Resource: "arn:aws:s3:::*"
              # KMS Permissions
              - Effect: Allow
                Action:
                  - kms:DescribeKey
                  - kms:ListAliases
                Resource: "*"
              # GuardDuty Permissions
              - Effect: Allow
                Action:
                  - guardduty:ListDetectors
                  - guardduty:GetDetector
                  - guardduty:GetFindings
                  - guardduty:ListFindings
                  - guardduty:GetFindingsStatistics
                  - guardduty:ListPublishingDestinations
                  - guardduty:ListTagsForResource
                  - guardduty:GetMemberDetectors
                  - guardduty:DescribeMalwareScans
                  - guardduty:GetRemainingFreeTrialDays
                  - guardduty:GetUsageStatistics
                Resource: "*"
              # Allow access to central assessment bucket
              - Effect: Allow
                Action:
                  - s3:GetObject
                  - s3:PutObject
                  - s3:DeleteObject
                  - s3:ListBucket
                Resource:
                  - "arn:aws:s3:::*aiml*security*assessment*"
                  - "arn:aws:s3:::*aiml*security*assessment*/*"
              # Allow Lambda execution roles to access central bucket
              - Effect: Allow
                Action:
                  - sts:AssumeRole
                Resource: "arn:aws:iam::*:role/aiml-security-*"
              # SAM/CloudFormation deployment permissions (required for multi-account flow)
              - Effect: Allow
                Action:
                  - cloudformation:CreateStack
                  - cloudformation:UpdateStack
                  - cloudformation:DeleteStack
                  - cloudformation:DescribeStacks
                  - cloudformation:DescribeStackEvents
                  - cloudformation:GetTemplate
                  - cloudformation:CreateChangeSet
                  - cloudformation:DescribeChangeSet
                  - cloudformation:ExecuteChangeSet
                  - cloudformation:DeleteChangeSet
                  - cloudformation:GetTemplateSummary
                  - cloudformation:ListStackResources
                Resource:
                  - !Sub "arn:${AWS::Partition}:cloudformation:*:${AWS::AccountId}:stack/aiml-security-*/*"
                  - !Sub "arn:${AWS::Partition}:cloudformation:*:${AWS::AccountId}:stack/aws-sam-cli-managed-default/*"
              - Effect: Allow
                Action:
                  - cloudformation:GetTemplateSummary
                  - cloudformation:CreateChangeSet
                Resource:
                  - !Sub "arn:${AWS::Partition}:cloudformation:*:aws:transform/Serverless-2016-10-31"
              # Lambda deployment permissions
              - Effect: Allow
                Action:
                  - lambda:CreateFunction
                  - lambda:DeleteFunction
                  - lambda:GetFunction
                  - lambda:GetFunctionConfiguration
                  - lambda:UpdateFunctionCode
                  - lambda:UpdateFunctionConfiguration
                  - lambda:AddPermission
                  - lambda:RemovePermission
                  - lambda:TagResource
                  - lambda:UntagResource
                  - lambda:ListTags
                  - lambda:InvokeFunction
                Resource:
                  - !Sub "arn:${AWS::Partition}:lambda:*:${AWS::AccountId}:function:aiml-security-*"
              # IAM role management for SAM-deployed Lambda roles
              - Effect: Allow
                Action:
                  - iam:CreateRole
                  - iam:DeleteRole
                  - iam:GetRole
                  - iam:PassRole
                  - iam:AttachRolePolicy
                  - iam:DetachRolePolicy
                  - iam:PutRolePolicy
                  - iam:DeleteRolePolicy
                  - iam:GetRolePolicy
                  - iam:TagRole
                  - iam:UntagRole
                Resource:
                  - !Sub "arn:${AWS::Partition}:iam::${AWS::AccountId}:role/aiml-security-*"
              # Step Functions deployment permissions
              - Effect: Allow
                Action:
                  - states:CreateStateMachine
                  - states:DeleteStateMachine
                  - states:DescribeStateMachine
                  - states:UpdateStateMachine
                  - states:TagResource
                  - states:UntagResource
                  - states:StartExecution
                  - states:DescribeExecution
                  - states:ListExecutions
                Resource:
                  - !Sub "arn:${AWS::Partition}:states:*:${AWS::AccountId}:stateMachine:AIMLAssessment*"
                  - !Sub "arn:${AWS::Partition}:states:*:${AWS::AccountId}:execution:AIMLAssessment*:*"
              # S3 permissions for SAM deployment artifacts and assessment results
              - Effect: Allow
                Action:
                  - s3:CreateBucket
                  - s3:DeleteBucket
                  - s3:PutBucketPolicy
                  - s3:GetBucketPolicy
                  - s3:DeleteBucketPolicy
                  - s3:PutBucketVersioning
                  - s3:GetBucketVersioning
                  - s3:PutBucketPublicAccessBlock
                  - s3:GetBucketPublicAccessBlock
                  - s3:PutBucketTagging
                  - s3:GetBucketTagging
                  - s3:PutEncryptionConfiguration
                  - s3:GetEncryptionConfiguration
                  - s3:GetBucketLocation
                  - s3:ListBucket
                  - s3:PutObject
                  - s3:GetObject
                  - s3:DeleteObject
                  - s3:DeleteObjectVersion
                Resource:
                  - "arn:aws:s3:::aiml-security-*"
                  - "arn:aws:s3:::aiml-security-*/*"
                  - "arn:aws:s3:::aws-sam-cli-managed-default-*"
                  - "arn:aws:s3:::aws-sam-cli-managed-default-*/*"

Outputs:
  MemberRoleArn:
    Description: ARN of the AIML Security Member Role
    Value: !GetAtt MemberRole.Arn
