# Connects an AWS account to YugmaLink with read-only access. Customers create it from the
# "Connect via AWS Console" link in YugmaLink, which fills in their connection's IDs.
#
# Every change to this file is published at its own URL (aws.js names it after its content). Stacks made
# from an earlier version keep working; to get new permissions, a customer updates their stack to the new
# URL (YugmaLink shows how where a permission is missing). Keep every change read-only, and never add
# access to the contents of files, databases or secrets.
AWSTemplateFormatVersion: '2010-09-09'
Description: >-
  Connects this AWS account to YugmaLink (https://www.yugmalink.com) with read-only access.
  Creates one IAM role that only YugmaLink can use, and only with this connection's External ID.
  It can read settings and metrics, never the contents of files. Delete this stack at any time to disconnect.

Parameters:
  ConnectionId:
    Type: String
    AllowedPattern: '[a-z0-9]{12}'
    ConstraintDescription: Use the value YugmaLink filled in.
    Description: Identifies this connection in YugmaLink. Filled in by YugmaLink.
  ExternalId:
    Type: String
    NoEcho: true
    AllowedPattern: '[a-f0-9]{64}'
    ConstraintDescription: Use the value YugmaLink filled in.
    Description: The code YugmaLink must present to use the role. Filled in by YugmaLink.

Rules:
  OnlyUsEast1:
    Assertions:
      - Assert: !Equals [!Ref 'AWS::Region', us-east-1]
        # No final period: CloudFormation adds ". Rollback requested by user." after it.
        AssertDescription: >-
          Create this stack in US East (N. Virginia), us-east-1: switch the console to that region,
          then create it again. The role it creates still covers every region

Resources:
  YugmaLinkRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub YugmaLink-${ConnectionId}
      Description: Read-only access for YugmaLink. Delete the YugmaLink stack to remove it.
      MaxSessionDuration: 3600
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              AWS: arn:aws:iam::247312186903:role/YugmaLinkConnector
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                'sts:ExternalId': !Ref ExternalId
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/job-function/ViewOnlyAccess
      Policies:
        - PolicyName: YugmaLinkReadOnly
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: CostAndUsage
                Effect: Allow
                Action:
                  - ce:Describe*
                  - ce:Get*
                  - ce:List*
                Resource: '*'
              # Metrics, alarms, and (Module 5) each alarm's state changes.
              - Sid: Metrics
                Effect: Allow
                Action:
                  - cloudwatch:DescribeAlarmHistory
                  - cloudwatch:DescribeAlarms
                  - cloudwatch:GetMetricData
                  - cloudwatch:GetMetricStatistics
                  - cloudwatch:ListMetrics
                Resource: '*'
              # Bucket settings: versioning, lifecycle rules, encryption, public access and unfinished
              # uploads. None of these can read what's stored in a bucket.
              - Sid: BucketSettings
                Effect: Allow
                Action:
                  - s3:GetAccountPublicAccessBlock
                  - s3:GetBucketAcl
                  - s3:GetBucketLocation
                  - s3:GetBucketOwnershipControls
                  - s3:GetBucketPolicyStatus
                  - s3:GetBucketPublicAccessBlock
                  - s3:GetBucketVersioning
                  - s3:GetEncryptionConfiguration
                  - s3:GetLifecycleConfiguration
                  - s3:ListBucketMultipartUploads
                Resource: '*'
              - Sid: AccountName
                Effect: Allow
                Action: iam:ListAccountAliases
                Resource: '*'
              # Security settings and findings: when access keys were last used, the password policy, KMS keys'
              # details and rotation, and GuardDuty's and Security Hub's findings, and whether GuardDuty's detector
              # is suspended (GetDetector, added 23 Nov 2026). None of these reads stored data, key material or secrets.
              - Sid: SecurityReads
                Effect: Allow
                Action:
                  - guardduty:GetDetector
                  - guardduty:GetFindings
                  - guardduty:ListDetectors
                  - guardduty:ListFindings
                  - iam:GetAccessKeyLastUsed
                  - iam:GetAccountPasswordPolicy
                  - kms:DescribeKey
                  - kms:GetKeyRotationStatus
                  - securityhub:DescribeHub
                  - securityhub:GetFindings
                Resource: '*'
              # Audit reads (added in Phase 3): IAM policies' contents and when roles were last used, IAM Access
              # Analyzer's findings, CloudFormation drift checks (they compare a stack with what's deployed, and
              # change nothing; a check reads each resource in the stack, so an IAM role's GetRole and GetRolePolicy
              # come with it), AWS Budgets, whether CloudTrail trails are logging, buckets' policies and access
              # logging, whether a security contact is set, whether Compute Optimizer is on, and the account's
              # service quotas (Module 12). AWS's own ReadOnlyAccess policy includes each one.
              - Sid: AuditReads
                Effect: Allow
                Action:
                  - access-analyzer:ListAnalyzers
                  - access-analyzer:ListFindings
                  - account:GetAlternateContact
                  - budgets:ViewBudget
                  - cloudformation:DescribeStackDriftDetectionStatus
                  - cloudformation:DescribeStackResourceDrifts
                  - cloudformation:DetectStackDrift
                  - cloudformation:DetectStackResourceDrift
                  - cloudtrail:GetEventSelectors
                  - cloudtrail:GetTrailStatus
                  - compute-optimizer:GetEnrollmentStatus
                  - iam:GetAccountAuthorizationDetails
                  - iam:GetRole
                  - iam:GetRolePolicy
                  - s3:GetBucketLogging
                  - s3:GetBucketPolicy
                  - servicequotas:GetAWSDefaultServiceQuota
                  - servicequotas:GetServiceQuota
                Resource: '*'

  # Tells YugmaLink the role exists, so the connection completes without copying anything.
  YugmaLinkConnection:
    Type: Custom::YugmaLinkConnection
    Properties:
      ServiceToken: arn:aws:sns:us-east-1:247312186903:yugmalink-connect
      ServiceTimeout: 300
      ConnectionId: !Ref ConnectionId
      ExternalId: !Ref ExternalId
      RoleArn: !GetAtt YugmaLinkRole.Arn
      AccountId: !Ref 'AWS::AccountId'

Outputs:
  RoleArn:
    Description: Paste this into YugmaLink only if it doesn't detect the connection by itself.
    Value: !GetAtt YugmaLinkRole.Arn
