# brokered-shell-access / gcp / t0 "Quick start"
#
# SSH to VMs with no external IP address, through Identity-Aware Proxy. The
# only way in on port 22 is Google's IAP range, and only the person named here
# may open a tunnel. Each tunnel is checked against their Google identity.
#
# Change the three values below, then:
#   gcloud auth application-default login
#   terraform init && terraform apply
#
# Give a VM the network tag iap-ssh, then:
#   gcloud compute ssh <vm> --zone <zone> --tunnel-through-iap
#
# Verify: the VM has no external IP, the only rule allowing port 22 names the
# IAP range, and anyone not named here is refused.

locals {
  project_id = "your-project-id"      # change me
  network    = "default"              # change me: the VPC network your VMs use
  operator   = "user:you@example.com" # change me: or group:ops@example.com
}

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

provider "google" {
  project = local.project_id
}

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

# IAP's forwarders connect from this range, and nothing else is allowed in.
resource "google_compute_firewall" "iap_ssh" {
  name          = "allow-ssh-from-iap-only"
  network       = local.network
  direction     = "INGRESS"
  priority      = 1000
  source_ranges = ["35.235.240.0/20"]
  target_tags   = ["iap-ssh"]
  allow {
    protocol = "tcp"
    ports    = ["22"]
  }
}

resource "google_project_iam_member" "tunnel" {
  project    = local.project_id
  role       = "roles/iap.tunnelResourceAccessor"
  member     = local.operator
  depends_on = [google_project_service.iap]
}

# Signing in to the VM itself goes through OS Login, so access follows the
# Google identity and ends when it does.
resource "google_project_iam_member" "os_login" {
  project = local.project_id
  role    = "roles/compute.osLogin"
  member  = local.operator
}

resource "google_compute_project_metadata_item" "os_login" {
  key   = "enable-oslogin"
  value = "TRUE"
}

output "verify" {
  description = "Commands that prove the setup."
  value       = <<-EOT
    gcloud compute ssh <vm> --zone <zone> --tunnel-through-iap          # opens, as ${local.operator}
    gcloud compute instances describe <vm> --zone <zone> --format="value(networkInterfaces[0].accessConfigs)"   # empty: no external IP
    gcloud compute firewall-rules list --filter="allowed[].ports:22" --format="table(name,sourceRanges.list())"  # only 35.235.240.0/20
  EOT
}
