diff --git a/README.md b/README.md index 531d2ef..8a6c000 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,16 @@ Deployments are fully automated via GitHub Actions. There is nothing to build or > **Note:** `dev` and `qa` share the same GCP project (`gbfs-validator-staging`). Each environment gets its own Cloud Run service, Artifact Registry path, runtime service account, and Terraform state. `prod` lives in a separate dedicated project. +### Request path + +``` +client -> Cloudflare (mobilitydatabase.org zone) -> Worker mobilitydata-sites -> Cloud Run (run.app, IAM-protected) +``` + +- The public hostnames are served by the `mobilitydata-sites` Cloudflare Worker ([MobilityData/org-cloudflare-workers](https://github.com/MobilityData/org-cloudflare-workers), `sites/gbfs.api.mobilitydatabase.org/`). It accepts only `POST /validate` (plus the CORS preflight), checks the request, rate limits per IP and forwards it with an ID token of the `gbfs-edge-{env}` service account. Everything else gets a 404 at the edge and never starts a Cloud Run instance. +- Once the legacy load balancer is removed (follow-up change), Cloud Run only accepts requests signed by `gbfs-edge-{env}` (`roles/run.invoker`); until then the public `allUsers` invoker stays and the run.app URL is publicly reachable. Cloud Run uses request-based billing and is capped at 20 instances of 5 concurrent validations (4 vCPU, 4 GiB) in prod and 1 in dev/qa (`gbfs-validator/function_config.json`). Request limits and capacity: [docs/edge-cutover.md](docs/edge-cutover.md#limits-and-capacity). The validator's built-in Swagger UI is turned off; the API docs are on [GitHub Pages](https://mobilitydata.github.io/gbfs-validator-java/SwaggerUI/index.html). +- The GCP load balancer and Cloud Armor are kept only during the cutover (`legacy_load_balancer_enabled`) and removed in a follow-up change. See [docs/edge-cutover.md](docs/edge-cutover.md) for the two-step rollout and the manual steps (Worker secrets, DNS, cleanup). + ### Manual deployment The staging and prod workflows can be triggered manually from the [GitHub Actions UI](https://github.com/MobilityData/gbfs-validator-java-infra/actions). @@ -98,10 +108,9 @@ Create a Firebase project and link it to the GCP project. Create OAuth client credentials via the [APIs & Services > Credentials](https://console.cloud.google.com/apis/credentials) page. These credentials will be passed as Terraform variables. -### 5. Create SSL Certificates +### 5. TLS -Google-managed SSL certificates are created automatically by `scripts/setup-environment.sh` (step 11 below). -They provision once the DNS A/AAAA records are in place and the load balancer is deployed. +Nothing to do: Cloudflare terminates TLS for the public hostname, and Cloud Run serves its run.app URL over TLS. ### 6. Enable and Configure Identity Platform @@ -148,22 +157,11 @@ This script: - Creates the deployer service account and grants IAM roles - Enables required Google APIs - Creates (or verifies) the shared Artifact Registry repository -- Creates global static IPv4 and IPv6 addresses for the load balancer (`{env}-lb-ipv4`, `{env}-lb-ipv6`) -- Creates a Google-managed SSL certificate for `{env}.gbfs.api.mobilitydatabase.org` +- Creates the legacy load balancer's static IPs (`{env}-lb-ipv4`, `{env}-lb-ipv6`) and SSL certificate, needed only while `legacy_load_balancer_enabled` is true -At the end it prints the IP addresses you will need for DNS. - -### 11a. Create DNS Records - -After running the setup script, ask your DNS administrator (Cloudflare) to create: - -| Type | Name | Value | -|---|---|---| -| `A` | `{env}.gbfs.api.mobilitydatabase.org` | IPv4 printed by the script | -| `AAAA` | `{env}.gbfs.api.mobilitydatabase.org` | IPv6 printed by the script | +### 11a. Connect the Cloudflare edge -> **Note:** DNS proxy must be **disabled** (grey cloud in Cloudflare) to allow Google-managed cert provisioning. -> The SSL certificate will complete provisioning automatically once DNS resolves to the load balancer IP. +After the first Terraform deploy of the environment, follow [docs/edge-cutover.md](docs/edge-cutover.md): create the edge service account key, add the Worker secrets, and hand `{env}.gbfs.api.mobilitydatabase.org` to the Worker as a Workers Custom Domain (delete its old DNS records; the Custom Domain creates its own record and certificate). ### 12. Generate a Deployer Service Account Key (for CI) diff --git a/docs/edge-cutover.md b/docs/edge-cutover.md new file mode 100644 index 0000000..4d3df21 --- /dev/null +++ b/docs/edge-cutover.md @@ -0,0 +1,78 @@ +# Cloudflare edge cutover + +``` +client -> Cloudflare Worker (mobilitydata-sites) -> Cloud Run +``` + +The Worker ([org-cloudflare-workers](https://github.com/MobilityData/org-cloudflare-workers), `sites/gbfs.api.mobilitydatabase.org/`) only lets `POST /validate` through and calls Cloud Run as the `gbfs-edge-{env}` service account. It replaces the GCP load balancer and Cloud Armor. + +| Env | Hostname | GCP project | +|---|---|---| +| dev | `dev.gbfs.api.mobilitydatabase.org` | `gbfs-validator-staging` | +| qa | `qa.gbfs.api.mobilitydatabase.org` | `gbfs-validator-staging` | +| prod | `gbfs.api.mobilitydatabase.org` | `gbfs-validator-prod` | + +## Limits and capacity + +| Limit | Value | Change it in | +|---|---|---| +| Requests per IP | 5/min per Cloudflare location, then 429 | Worker `wrangler.jsonc` | +| Request body | 16 KB, then 413 | Worker `handler.js` | +| Validations per instance | 5 at once | `gbfs-validator/function_config.json` | +| Instances | prod 20 (100 at once), dev/qa 1 (5 at once) | same file | +| Instance size | 4 vCPU, 4 GiB, JVM heap 75% | same file | +| Timeout | 90 s (Cloudflare cuts at 100 s) | same file | + +Why: without the heap setting Java uses only 25% of memory and large feeds (8-12 MB) failed with `OutOfMemoryError`; 8 large validations used 1.75 GiB, so 4 GiB leaves headroom. Validation is CPU-bound (about 12 s of CPU per 12 MB feed): on 4 vCPU, 10 large feeds at once took up to 82 s against the 90 s timeout, so 5 per instance. + +Other changes: Swagger UI is off on Cloud Run (docs move to [GitHub Pages](https://mobilitydata.github.io/gbfs-validator-java/SwaggerUI/index.html)); `feedUrl` must be a public http(s) URL. + +## Before + +- [ ] Cloudflare, Security rules, "Challenge abusive countries": append `and not (http.host contains "gbfs.api.mobilitydatabase.org")`. +- [ ] Release gbfs-validator-java with `loader.public-network-only` (blocks private addresses and local files). +- [ ] Don't enable Bot Fight Mode on the zone (it would block API clients). +- [ ] Add budget alerts (25 CAD prod, 15 CAD staging); the run.app URL is public until the follow-up: + + ```bash + gcloud billing budgets create --billing-account= --display-name="gbfs-validator-prod" --budget-amount=25CAD --filter-projects=projects/gbfs-validator-prod --threshold-rule=percent=0.5 --threshold-rule=percent=1.0 + ``` + +## Cutover + +1. **Deploy this repo** to dev, qa and prod (prod with the new `app_version`). Nothing goes down: the old load balancer stays while `legacy_load_balancer_enabled = true`. + +2. **Add Worker secrets** (once per env; `DEV` shown). If `wrangler` fails, delete the key it created (`gcloud iam service-accounts keys list --iam-account=...`). To rotate: new key, update the secret, delete the old key. + + ```bash + gcloud iam service-accounts keys create /dev/stdout --iam-account=gbfs-edge-dev@gbfs-validator-staging.iam.gserviceaccount.com | npx wrangler secret put GBFS_VALIDATOR_DEV_SA_KEY --name mobilitydata-sites + gcloud run services describe dev-gbfs-validator-api --region northamerica-northeast1 --project gbfs-validator-staging --format='value(status.url)' | npx wrangler secret put GBFS_VALIDATOR_DEV_URL --name mobilitydata-sites + ``` + +3. **Switch dev and qa:** delete the A/AAAA records of `dev.gbfs.api` and `qa.gbfs.api` in Cloudflare DNS, then merge the Worker PR right away. Its Custom Domains create the new DNS records and certificates (a few minutes of downtime). + +4. **Check:** + + ```bash + curl -s -o /dev/null -w '%{http_code}\n' https://dev.gbfs.api.mobilitydatabase.org/ + curl -s -X POST https://dev.gbfs.api.mobilitydatabase.org/validate -H 'Content-Type: application/json' -d '{"feedUrl":"https://gbfs.lyft.com/gbfs/2.3/bay/gbfs.json"}' | head -c 200 + ``` + + Expect `404`, then a validation report. + + **Rollback** if the Worker deploy fails: recreate the grey-cloud (DNS only) A/AAAA records with the addresses of `{env}-lb-ipv4` / `{env}-lb-ipv6` (`gcloud compute addresses list --global --project `). + +5. **Switch prod** the same way, with a Worker PR that adds `gbfs.api.mobilitydatabase.org`. + +## After + +- [ ] Set `legacy_load_balancer_enabled = false` and deploy. The run.app URL then returns 403 to anyone but the Worker. +- [ ] Delete the old static IPs and certificates (they keep billing), then remove their creation from `scripts/setup-environment.sh` (rerunning it recreates them): + + ```bash + for env in dev qa; do gcloud compute addresses delete $env-lb-ipv4 $env-lb-ipv6 --global --project gbfs-validator-staging; gcloud compute ssl-certificates delete $env-gbfs-api-mobilitydatabase-org --global --project gbfs-validator-staging; done + gcloud compute addresses delete prod-lb-ipv4 prod-lb-ipv6 --global --project gbfs-validator-prod + gcloud compute ssl-certificates delete prod-gbfs-api-mobilitydatabase-org --global --project gbfs-validator-prod + ``` + +- [ ] Remove `roles/compute.loadBalancerAdmin` and `roles/compute.securityAdmin` from the deployer service accounts. diff --git a/gbfs-validator/function_config.json b/gbfs-validator/function_config.json index 506e53a..2c3e10e 100644 --- a/gbfs-validator/function_config.json +++ b/gbfs-validator/function_config.json @@ -2,12 +2,14 @@ "name_suffix": "gbfs-validator-api", "description": "API containing the GBFS validator", "entry_point": "org.entur.gbfs.validator.api.handler.OpenApiGeneratorApplication", - "timeout": 540, - "available_memory": "1Gi", + "timeout": 90, + "available_memory": "4Gi", "trigger_http": true, "ingress_settings": "ALLOW_ALL", - "max_instance_request_concurrency": 1, - "max_instance_count": 5, + "max_instance_request_concurrency": 5, + "max_instance_count": 20, + "max_instance_count_non_prod": 1, "min_instance_count": 0, - "available_cpu": 1 + "available_cpu": 4, + "java_tool_options": "-XX:MaxRAMPercentage=75" } diff --git a/infra/cloud-run-service/cloud-run-main.tf b/infra/cloud-run-service/cloud-run-main.tf index 524f993..97a765e 100644 --- a/infra/cloud-run-service/cloud-run-main.tf +++ b/infra/cloud-run-service/cloud-run-main.tf @@ -30,6 +30,9 @@ terraform { locals { gbfs_validator_config = jsondecode(file("${path.module}/../../gbfs-validator/function_config.json")) artifact_registry_repo = "${var.artifact_registry_repo}/${var.environment}" + # The instance cap bounds compute spend: with request-based billing an idle instance costs + # nothing. It does not cap egress or logging, and Cloud Run can briefly exceed it during a rollout. + max_instance_count = var.environment == "prod" ? local.gbfs_validator_config.max_instance_count : local.gbfs_validator_config.max_instance_count_non_prod } provider "google" { @@ -47,10 +50,22 @@ data "archive_file" "source_zip" { resource "google_cloud_run_v2_service" "gbfs_validator_api" { name = "${var.environment}-${local.gbfs_validator_config.name_suffix}" location = var.gcp_region - ingress = "INGRESS_TRAFFIC_INTERNAL_LOAD_BALANCER" + # Public traffic reaches the service through the Cloudflare Worker (mobilitydata-sites in + # MobilityData/org-cloudflare-workers), which calls the run.app URL with an ID token of the + # edge service account. Ingress is open, but only that service account may invoke (see below). + # The legacy load balancer also works with this ingress during the cutover. + ingress = "INGRESS_TRAFFIC_ALL" template { - service_account = var.gbfs_validator_service_account_email + service_account = var.gbfs_validator_service_account_email + timeout = "${local.gbfs_validator_config.timeout}s" + max_instance_request_concurrency = local.gbfs_validator_config.max_instance_request_concurrency + + scaling { + min_instance_count = local.gbfs_validator_config.min_instance_count + max_instance_count = local.max_instance_count + } + containers { image = "${var.gcp_region}-docker.pkg.dev/${var.project_id}/${local.artifact_registry_repo}/${var.gbfs_api_service}:${var.gbfs_api_image_version}" resources { @@ -58,6 +73,27 @@ resource "google_cloud_run_v2_service" "gbfs_validator_api" { cpu = local.gbfs_validator_config.available_cpu memory = local.gbfs_validator_config.available_memory } + # Request-based billing: CPU is billed only while a request is processed (and during + # startup). Instance-based billing kept an idle instance billed after every bot hit. + cpu_idle = true + # Faster Spring Boot cold starts when scaling from zero. + startup_cpu_boost = true + } + # Without it the JVM caps its heap at 25% of the container memory, and large feeds fail with + # OutOfMemoryError while most of the memory is unused (load test in docs/edge-cutover.md). + env { + name = "JAVA_TOOL_OPTIONS" + value = local.gbfs_validator_config.java_tool_options + } + # The validator ships Swagger UI (springdoc) for whoever runs it. Our deployment serves + # only POST /validate; the public API docs are on GitHub Pages (MobilityData/gbfs-validator-java). + env { + name = "SPRINGDOC_SWAGGERUI_ENABLED" + value = "false" + } + env { + name = "SPRINGDOC_APIDOCS_ENABLED" + value = "false" } } } @@ -69,10 +105,28 @@ resource "google_cloud_run_v2_service" "gbfs_validator_api" { } +# Public invoker for the legacy load balancer, only during the Cloudflare edge cutover +# (var.allow_unauthenticated). Removed with it in the follow-up change. resource "google_cloud_run_service_iam_member" "gbfs_validator_invoker" { + count = var.allow_unauthenticated ? 1 : 0 project = var.project_id location = var.gcp_region service = google_cloud_run_v2_service.gbfs_validator_api.name role = "roles/run.invoker" member = "allUsers" +} + +moved { + from = google_cloud_run_service_iam_member.gbfs_validator_invoker + to = google_cloud_run_service_iam_member.gbfs_validator_invoker[0] +} + +# Once the cutover is done, only the edge service account may invoke the service. Requests to +# the run.app URL without its ID token are rejected by Cloud Run IAM before reaching the container. +resource "google_cloud_run_service_iam_member" "gbfs_validator_edge_invoker" { + project = var.project_id + location = var.gcp_region + service = google_cloud_run_v2_service.gbfs_validator_api.name + role = "roles/run.invoker" + member = "serviceAccount:${var.edge_service_account_email}" } \ No newline at end of file diff --git a/infra/cloud-run-service/vars.tf b/infra/cloud-run-service/vars.tf index 61d1dbd..00e2532 100644 --- a/infra/cloud-run-service/vars.tf +++ b/infra/cloud-run-service/vars.tf @@ -69,4 +69,15 @@ variable "artifact_registry_repo" { type = string description = "Artifact Registry repository name (e.g. gbfs-validator-staging)" default = "gbfs-validator-staging" -} \ No newline at end of file +} + +variable "edge_service_account_email" { + type = string + description = "Service account the Cloudflare Worker uses to invoke the Cloud Run service" +} + +variable "allow_unauthenticated" { + type = bool + description = "Keep the public (allUsers) invoker, needed by the legacy load balancer during the Cloudflare edge cutover" + default = false +} diff --git a/infra/main.tf b/infra/main.tf index 8bc0082..c9b4dd0 100644 --- a/infra/main.tf +++ b/infra/main.tf @@ -41,12 +41,34 @@ module "cloud_run" { gbfs_validator_service_account_email = google_service_account.gbfs_validator_service_account.email gbfs_api_image_version = var.gbfs_api_image_version artifact_registry_repo = var.artifact_registry_repo + edge_service_account_email = google_service_account.gbfs_edge_service_account.email + allow_unauthenticated = var.legacy_load_balancer_enabled } +# Legacy entry point, kept only until the hostnames point at the Cloudflare Worker +# (var.legacy_load_balancer_enabled, docs/edge-cutover.md). Remove this block, the moved block +# and infra/load-balancer/ in the follow-up change that sets the variable to false. module "load_balancer" { + count = var.legacy_load_balancer_enabled ? 1 : 0 source = "./load-balancer" project_id = var.project_id environment = var.environment cloud_run_service_name = module.cloud_run.cloud_run_service_name } +# The module gained a count: keep the existing load balancer instead of recreating it. +moved { + from = module.load_balancer + to = module.load_balancer[0] +} + +# Identity of the Cloudflare Worker that fronts the API (mobilitydata-sites in +# MobilityData/org-cloudflare-workers). It holds roles/run.invoker on the Cloud Run service +# and nothing else. Its key is created once with gcloud and stored as a Worker secret, so it +# never lands in Terraform state (see docs/edge-cutover.md). +resource "google_service_account" "gbfs_edge_service_account" { + project = var.project_id + account_id = "gbfs-edge-${var.environment}" + display_name = "GBFS Validator Cloudflare edge (${var.environment})" +} + diff --git a/infra/outputs.tf b/infra/outputs.tf new file mode 100644 index 0000000..c47ffde --- /dev/null +++ b/infra/outputs.tf @@ -0,0 +1,26 @@ +# +# MobilityData 2025 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# Values the Cloudflare Worker needs as secrets (see docs/edge-cutover.md). +output "cloud_run_url" { + description = "run.app URL the Cloudflare Worker forwards validation requests to" + value = module.cloud_run.function_url +} + +output "edge_service_account_email" { + description = "Service account whose key the Cloudflare Worker uses to invoke Cloud Run" + value = google_service_account.gbfs_edge_service_account.email +} diff --git a/infra/vars.tf b/infra/vars.tf index cee82e5..431be5c 100644 --- a/infra/vars.tf +++ b/infra/vars.tf @@ -74,3 +74,13 @@ variable "artifact_registry_repo" { description = "Artifact Registry repository name shared across staging environments (e.g. gbfs-validator-staging)" default = "gbfs-validator-staging" } + +# Two-step rollout of the Cloudflare edge (docs/edge-cutover.md). While true, the old load +# balancer, Cloud Armor and the public (allUsers) invoker stay in place next to the edge +# invoker, so the hostnames keep working until their DNS records point at the Worker. +# Set to false in a follow-up change once every environment has been cut over. +variable "legacy_load_balancer_enabled" { + type = bool + description = "Keep the legacy load balancer and public invoker during the Cloudflare edge cutover" + default = true +} diff --git a/scripts/setup-deployer-sa-permissions.sh b/scripts/setup-deployer-sa-permissions.sh index ed5e298..3f5a8e3 100755 --- a/scripts/setup-deployer-sa-permissions.sh +++ b/scripts/setup-deployer-sa-permissions.sh @@ -54,10 +54,11 @@ ROLES=( # Cloud Run — create/update/delete services roles/run.admin - # Compute — load balancer, NEG, URL maps, forwarding rules + # Compute: load balancer and Cloud Armor. No longer used since the Cloudflare edge + # replaced the load balancer, but still needed by the first apply after the cutover, + # which destroys the old load balancer resources. Remove both roles once every + # environment has been cut over (see docs/edge-cutover.md). roles/compute.loadBalancerAdmin - - # Compute — Cloud Armor security policies roles/compute.securityAdmin # IAM — create service accounts (for Cloud Run runtime SA) @@ -69,7 +70,7 @@ ROLES=( # IAM — attach SAs to Cloud Run services roles/iam.serviceAccountUser - # IAM — set IAM policies (e.g. allUsers invoker on Cloud Run) + # IAM - set IAM policies (e.g. the edge service account as Cloud Run invoker) roles/resourcemanager.projectIamAdmin # Storage — read/write Terraform state bucket diff --git a/scripts/setup-environment.sh b/scripts/setup-environment.sh index f4f142b..4656a9f 100755 --- a/scripts/setup-environment.sh +++ b/scripts/setup-environment.sh @@ -239,7 +239,10 @@ done echo "🎉 Setup complete for project $PROJECT_ID" -# === Global LB IP addresses === +# === Legacy load balancer: global IP addresses and SSL certificate === +# Still read by the load_balancer Terraform module while legacy_load_balancer_enabled is true +# (Cloudflare edge cutover, docs/edge-cutover.md). Remove this block, and the compute and +# certificatemanager APIs above, in the follow-up change that sets it to false. IPV4_NAME="${ENVIRONMENT}-lb-ipv4" IPV6_NAME="${ENVIRONMENT}-lb-ipv6" @@ -287,9 +290,8 @@ echo "" echo "==========================================" echo " ✅ Bootstrap complete for: ${ENVIRONMENT}" echo "" -echo " Next: create DNS records for ${DOMAIN}:" -echo " A ${IPV4}" -echo " AAAA ${IPV6}" -echo "" -echo " SSL cert provisions automatically once DNS resolves." +echo " Public traffic for ${DOMAIN} goes through the Cloudflare Worker" +echo " (mobilitydata-sites in MobilityData/org-cloudflare-workers) as a Workers Custom Domain." +echo " After the first Terraform deploy, follow docs/edge-cutover.md to connect it." +echo " The IPs and certificate above only serve the legacy load balancer during the cutover." echo "=========================================="