provider "aws" {
  region = var.aws_region
}

# Terraform backends cannot contain interpolations
terraform {
  backend "s3" {
    bucket  = "shared-orcd-terraform-state"
    key     = "shared/ecr/enhanced-scanning/terraform.tfstate"
    region  = "us-east-1"
    encrypt = "true"
  }
}

data "aws_caller_identity" "current" {}

resource "aws_inspector2_enabler" "ecr" {
  account_ids    = [data.aws_caller_identity.current.account_id]
  resource_types = ["ECR", "EC2"]
}

resource "aws_ecr_registry_scanning_configuration" "configuration" {
  scan_type = "ENHANCED"

  rule {
    scan_frequency = "SCAN_ON_PUSH"
    repository_filter {
      filter      = "*"
      filter_type = "WILDCARD"
    }
  }
}

data "aws_iam_policy_document" "assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type = "AWS"

      identifiers = [
        "arn:aws:iam::437795906767:role/prod-jenkins-aws-pipeline-agent",
      ]
    }
  }
}

resource "aws_iam_role" "ecr_scan_role" {
  name               = "ecr-scan-role"
  assume_role_policy = data.aws_iam_policy_document.assume_role_policy.json
  tags               = local.tags
}

data "aws_iam_policy_document" "ecr_scan_policy_document" {
  statement {
    sid    = "AllowECROperations"
    effect = "Allow"

    actions = [
      "ecr:DescribeImages",
      "inspector-scan:ScanSbom",
    ]

    resources = ["*"]
  }
}

resource "aws_iam_policy" "ecr_scan_policy" {
  name        = "ecr-scan-policy"
  description = "Policy which grants access to scan images with Inspector"
  policy      = data.aws_iam_policy_document.ecr_scan_policy_document.json
  tags        = local.tags
}

resource "aws_iam_role_policy_attachment" "ecr_scan_role_policy_attachment" {
  role       = aws_iam_role.ecr_scan_role.id
  policy_arn = aws_iam_policy.ecr_scan_policy.arn
}
