# guardrail-baseline / gcp / t0 "Quick start"
#
# Four organisation policy constraints on one project: no service account keys,
# no public buckets, OS Login required for SSH, and no external IP addresses on
# VMs. Each one makes a common mistake impossible, so there is nothing to alert
# on afterwards.
#
# The project must belong to an organisation, and you need the Organization
# Policy Administrator role, which can only be granted at organisation level.
#
# Change the project below, then:
#   gcloud auth application-default login
#   terraform init && terraform apply
#
# Verify:
#   gcloud iam service-accounts keys create /tmp/k.json --iam-account <any service account>
#   Expect: FAILED_PRECONDITION, key creation is not allowed.

locals {
  project_id = "your-project-id" # change me
}

terraform {
  required_version = ">= 1.6"
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 8.0"
    }
  }
}

provider "google" {
  project = local.project_id
}

resource "google_project_service" "orgpolicy" {
  service            = "orgpolicy.googleapis.com"
  disable_on_destroy = false
}

# A leaked service account key works from anywhere until someone deletes it.
# Workload identity federation replaces most reasons to create one.
resource "google_org_policy_policy" "no_service_account_keys" {
  name       = "projects/${local.project_id}/policies/iam.disableServiceAccountKeyCreation"
  parent     = "projects/${local.project_id}"
  depends_on = [google_project_service.orgpolicy]
  spec {
    rules {
      enforce = "TRUE"
    }
  }
}

resource "google_org_policy_policy" "no_public_buckets" {
  name       = "projects/${local.project_id}/policies/storage.publicAccessPrevention"
  parent     = "projects/${local.project_id}"
  depends_on = [google_project_service.orgpolicy]
  spec {
    rules {
      enforce = "TRUE"
    }
  }
}

# SSH through OS Login uses Google identities and IAM, so access ends when the
# person's access ends. Keys pasted into metadata outlive both.
resource "google_org_policy_policy" "require_os_login" {
  name       = "projects/${local.project_id}/policies/compute.requireOsLogin"
  parent     = "projects/${local.project_id}"
  depends_on = [google_project_service.orgpolicy]
  spec {
    rules {
      enforce = "TRUE"
    }
  }
}

resource "google_org_policy_policy" "no_external_ips" {
  name       = "projects/${local.project_id}/policies/compute.vmExternalIpAccess"
  parent     = "projects/${local.project_id}"
  depends_on = [google_project_service.orgpolicy]
  spec {
    rules {
      deny_all = "TRUE"
    }
  }
}
