# data-perimeter / gcp / t0 "Quick start"
#
# A VPC Service Controls perimeter around one project. Cloud Storage and
# BigQuery inside it refuse calls from outside, and refuse to send data to
# resources outside, whatever IAM allows. Stolen credentials still work, but
# only from inside, and data cannot be copied to the attacker's own project.
#
# The perimeter lives in its own access policy, scoped to this one project, so
# it cannot clash with perimeters your organisation already has. Creating it
# needs the Access Context Manager Admin role on the organisation.
#
# A perimeter also refuses you when you work from outside it, including in the
# console. The one ingress rule below lets the operator named here in.
#
# Change the three values below, then:
#   gcloud auth application-default login
#   terraform init && terraform apply
#
# Verify, after up to 30 minutes for it to take effect:
#   gcloud storage cp gs://<bucket in this project>/<object> gs://<bucket in another project>/
#   Expect: refused, with a message naming VPC Service Controls.

locals {
  org_id     = "123456789012"         # change me: gcloud organizations list
  project_id = "your-project-id"      # change me: the project to protect
  operator   = "user:you@example.com" # change me
}

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

provider "google" {
  project = local.project_id
}

data "google_project" "protected" {
  project_id = local.project_id
}

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

resource "google_access_context_manager_access_policy" "scoped" {
  parent     = "organizations/${local.org_id}"
  title      = "data-perimeter-${local.project_id}"
  scopes     = ["projects/${data.google_project.protected.number}"]
  depends_on = [google_project_service.acm]
}

resource "google_access_context_manager_service_perimeter" "project" {
  parent = "accessPolicies/${google_access_context_manager_access_policy.scoped.name}"
  name   = "accessPolicies/${google_access_context_manager_access_policy.scoped.name}/servicePerimeters/protect_${replace(local.project_id, "-", "_")}"
  title  = "protect-${local.project_id}"

  status {
    resources           = ["projects/${data.google_project.protected.number}"]
    restricted_services = ["storage.googleapis.com", "bigquery.googleapis.com"]

    # The operator may call in from anywhere. Copying data out still needs
    # an egress rule, and there is none.
    ingress_policies {
      title = "operator"
      ingress_from {
        identities = [local.operator]
        sources {
          access_level = "*"
        }
      }
      ingress_to {
        resources = ["*"]
        operations {
          service_name = "*"
        }
      }
    }
  }
}
