data "aws_iam_policy_document" "kms_key_policy" {
  statement {
    sid       = "Enable IAM User Permissions"
    effect    = "Allow"
    actions   = ["kms:*"]
    resources = ["*"]

    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"]
    }
  }

  statement {
    sid    = "Allow IAM User Access"
    effect = "Allow"
    actions = [
      "kms:Encrypt",
      "kms:Decrypt",
      "kms:ReEncrypt*",
      "kms:GenerateDataKey*",
      "kms:DescribeKey"
    ]
    resources = ["*"]

    principals {
      type        = "AWS"
      identifiers = [aws_iam_user.k8s_secrets_user.arn]
    }

    condition {
      # Only allow from specific IP addresses
      test     = "IpAddress"
      variable = "aws:SourceIp"
      values   = ["${join(",", local.instance_ips)}"]
    }
  }
}

resource "aws_kms_key" "k8s_secrets" {
  description             = "KMS key for encrypting Kubernetes secrets"
  deletion_window_in_days = 30
  enable_key_rotation     = true

  policy = data.aws_iam_policy_document.kms_key_policy.json
}

resource "aws_iam_user" "k8s_secrets_user" {
  name = "alexpires-me-microk8s"
}

resource "aws_iam_access_key" "k8s_secrets_user_key" {
  user = aws_iam_user.k8s_secrets_user.name
}

data "aws_iam_policy_document" "k8s_secrets_user_policy" {
  statement {
    effect = "Allow"

    actions = [
      "kms:Encrypt",
      "kms:Decrypt",
      "kms:ReEncrypt*",
      "kms:GenerateDataKey*",
      "kms:DescribeKey"
    ]

    resources = [aws_kms_key.k8s_secrets.arn]
    condition {
      # Only allow from specific IP addresses
      test     = "IpAddress"
      variable = "aws:SourceIp"
      values   = ["${join(",", local.instance_ips)}"]
    }
  }
}

resource "aws_iam_user_policy" "k8s_secrets_user_policy" {
  name   = "alexpires-me-microk8s-policy"
  user   = aws_iam_user.k8s_secrets_user.name
  policy = data.aws_iam_policy_document.k8s_secrets_user_policy.json
}

