Skip to content

infra(core): declare the R2 sccache bucket and its lifecycle rule - #912

Merged
athvin merged 2 commits into
mainfrom
ci/sccache-r2
Nov 8, 2026
Merged

athvin merged 2 commits into
mainfrom
ci/sccache-r2

Conversation

@athvin

@athvin athvin commented Nov 8, 2026 •

Copy link
Copy Markdown
Owner

Closes #910

Post-merge is part of this pull request. The ledger below records whether
the follow-up work actually happened. /land-pr closes it.

What

cloudflare_r2_bucket + cloudflare_r2_bucket_lifecycle in envs/core, plus
the cloudflare/cloudflare ~> 5.0 provider, plus the two values infra.yml's
apply leg needs to actually create them. First half of #909 — does not touch
rust.yml
, so merging this changes no CI behaviour.

CLOUDFLARE_API_TOKEN is already set as an Environment secret on
infra-apply-core, which is protected_branches: true — so a pull request
cannot read it even by editing a workflow. That is the property that replaces
S3's er-ci-sccache-read/-write role split, and it is the pattern
agent-fleet.md prescribes for secrets added since #439.

Why

S3 was fast and expensive ($209.32/mo of egress, $0.02 of storage, by CUR
per-resource). The Actions cache backend is cheap and slow: 25.1 min against 9.8,
because GitHub rate-limits cache writes per workflow run shared across every
job
and sccache installs no RetryLayer, so 3,763 of 4,927 writes were dropped
(mozilla/sccache#2821). R2 is the only option that is both — zero egress, and not
GitHub's cache service, so neither the quota nor the bug applies.

Proof

terraform fmt -check -recursive exit 0. Credential-free
init -backend=false + validate → Success! The configuration is valid.

And a real plan against the live account (read-only, -lock=false so it did
not take the shared state lock from CI or a peer session):

Plan: 2 to add, 0 to change, 0 to destroy.
  create  cloudflare_r2_bucket.sccache[0]
  create  cloudflare_r2_bucket_lifecycle.sccache[0]
+ r2_sccache_bucket   = "er-ci-sccache"
+ r2_sccache_endpoint = "https://9eefbe6b….r2.cloudflarestorage.com"

0 to destroy is the load-bearing number — it is the evidence that adding a
second provider to envs/core disturbed none of the existing AWS resources.

Token verified against /user/tokens/verify (active) and scoped correctly —
GET /accounts/{id}/r2/buckets returned success with 0 buckets.

Risk & rollback

Risk is close to nil while var.cloudflare_account_id is null: the file
instantiates nothing and no plan needs a Cloudflare credential. Rollback is
git revert; sccache.tf, the S3 bucket and both OIDC roles are deliberately
untouched and remain the real rollback for #909.

Post-merge ledger

Closed by: unclosed

  • main is green with this change on it — the merge SHA, and the run
    that proves it. A later head SHA with this commit as an ancestor counts;
    a cancelled run with zero jobs does not:
  • images built, or correctly never ran because nothing that goes into
    an image changed:
  • deploy converged — proved by a line the running process emitted, not
    by the image digest and not by the workflow conclusion:
  • the push-only surface no pull request can pre-test (deploy, drift,
    kind's nightly leg) is green, or knowingly red for a reason that is not
    this change:
  • the board card reached Done through the automation rather than by
    hand, and the issue closed:
  • follow-ups are open for everything deferred here — numbers: ci: move the sccache bucket to Cloudflare R2 (zero egress AND no per-run write quota) #909, infra: bring the Cloudflare zone under Terraform (and give CI a scoped read-only token) #908
  • what was learned is written down where the next session will find it
    (a skill, a reference, memory) — or nothing new was learned:

Specific to this change

  • The bucket actually exists, by GET /accounts/{id}/r2/buckets
    returning it — not by the apply's conclusion. A Terraform apply reporting
    success is not the same evidence:
  • drift stays quiet on the next nightly. This is the first Cloudflare
    resource in core, and drift runs without a CLOUDFLARE_API_TOKEN. If
    the opt-in gate works as designed it sees nothing; if it instead fails the
    whole-stack plan, that is the §14.2 failure mode arriving by a new route
    and it must be fixed before infra: bring the Cloudflare zone under Terraform (and give CI a scoped read-only token) #908:
  • The lifecycle rule is really in effect — read it back from the API
    rather than from state, because the resource supports neither destroy nor
    import, so state and reality can diverge with no way to reconcile:
  • Decide where cloudflare_account_id is supplied for the apply path —
    done in this PR: TF_VAR_cloudflare_account_id literal in infra.yml's
    apply leg, matching how rust.yml carries the AWS account id in
    SCCACHE_BUCKET. Not a secret; terraform.tfvars is gitignored so the
    tree is the right home.
  • The PR plan tier still does not preview R2 changes, and the apply leg
    creates them. The plan tier has no Cloudflare token, so r2.tf stays
    count = 0 there while the apply job's own re-plan has both the token and
    the var. Nothing lands unexamined — tf-destroy-guard.sh reads
    applyplan.txt first — but a reviewer cannot see it on the PR. This is
    the §14.2 tradeoff ses.tf already makes, and it is the strongest
    argument for infra: bring the Cloudflare zone under Terraform (and give CI a scoped read-only token) #908. Confirm the first apply's applyplan.txt shows the two
    creates and nothing else:
    deferred — #908
Context — plan, discoveries, measurements, files

Discoveries

  • The provider lockfile is a platform trap. terraform init on darwin wrote
    one h1: hash; CI runs linux and would have failed to verify. envs/dev
    already tracks 3 platforms and envs/prod 2, so core was the odd one out.
    Fixed with terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 cloudflare/cloudflare — scoped to the one provider so
    the aws pin (6.68.0, h1=1) is untouched.
  • cloudflare_r2_bucket_lifecycle is a one-way door, twice. The first real
    plan warned it "cannot be destroyed from Terraform … it will be present in the
    API until manually deleted", and the provider docs add that it does not support
    terraform import. Both are now in the file.
  • max_age is in seconds, where sccache.tf's S3 lifecycle took days.
  • location is honoured only at first creation and is best-effort — a
    delete-and-recreate under the same name keeps the original location, so this
    cannot be corrected by a taint.
  • The account id is not a secret: it appears in every dashboard URL and the
    S3 endpoint is derived from it, so it will sit in rust.yml in the clear.
    Only the API token needs protecting, which is why the provider reads it from
    the environment rather than from a variable.

Files

  • infra/terraform/envs/core/r2.tf — new
  • infra/terraform/envs/core/versions.tf — provider + provider "cloudflare" {}
  • infra/terraform/envs/core/.terraform.lock.hcl — cloudflare hashes, 2 platforms

@github-actions

github-actions Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

terraform plan

ea1ac66 · run log and full plans

env add change destroy
state-backend (plan only) 0 0 0
core 0 0 0
dev 0 0 0
prod 18 0 0

Planned with -refresh=false, so this is the config-versus-state diff and
not out-of-band drift. That is a security choice, not a speed one: a refreshing
plan reads secret values, and the plan role is assumable from any PR branch —
which can edit the workflow it runs under. Drift is caught at apply time, which
refreshes fully.

prod — 18 to add, 0 to change
module.eks.data.aws_iam_policy_document.node_trust: Reading...
data.aws_rds_engine_version.aurora_pg: Reading...
module.eks.data.aws_iam_policy_document.cluster_trust: Reading...
data.aws_iam_policy_document.eso_trust: Reading...
module.eks.data.aws_iam_policy_document.cluster_trust: Read complete after 0s [id=1029077455]
module.eks.data.aws_iam_policy_document.node_trust: Read complete after 0s [id=2851119427]
data.aws_iam_policy_document.eso_trust: Read complete after 0s [id=819195744]
data.aws_iam_policy_document.efs_csi_trust: Reading...
data.aws_iam_policy_document.efs_csi_trust: Read complete after 0s [id=819195744]
module.network.data.aws_region.current: Reading...
module.network.data.aws_availability_zones.available: Reading...
module.network.data.aws_region.current: Read complete after 0s [id=us-east-2]
data.aws_iam_policy_document.pod_trust: Reading...
data.aws_caller_identity.current: Reading...
data.aws_iam_policy_document.pod_trust: Read complete after 0s [id=819195744]
module.lake.data.aws_iam_policy_document.lake_tls_only: Reading...
module.lake.data.aws_iam_policy_document.lake_tls_only: Read complete after 0s [id=3960055703]
data.aws_caller_identity.current: Read complete after 0s [id=797781631727]
data.aws_iam_policy_document.lake_access: Reading...
data.aws_iam_policy_document.lake_access: Read complete after 0s [id=3734071059]
data.aws_iam_policy_document.eso: Reading...
data.aws_iam_policy_document.eso: Read complete after 0s [id=2178872705]
module.network.data.aws_availability_zones.available: Read complete after 0s [id=us-east-2]
data.aws_rds_engine_version.aurora_pg: Read complete after 0s [id=17.9]

Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  # aws_acm_certificate.edge will be created
  + resource "aws_acm_certificate" "edge" {
      + arn                       = (known after apply)
      + domain_name               = "dupezero.com"
      + domain_validation_options = [
          + {
              + domain_name           = "dupezero.com"
              + resource_record_name  = (known after apply)
              + resource_record_type  = (known after apply)
              + resource_record_value = (known after apply)
            },
          + {
              + domain_name           = "www.dupezero.com"
              + resource_record_name  = (known after apply)
              + resource_record_type  = (known after apply)
              + resource_record_value = (known after apply)
            },
        ]
      + id                        = (known after apply)
      + key_algorithm             = (known after apply)
      + not_after                 = (known after apply)
      + not_before                = (known after apply)
      + pending_renewal           = (known after apply)
      + private_key_wo            = (write-only attribute)
      + region                    = "us-east-2"
      + renewal_eligibility       = (known after apply)
      + renewal_summary           = (known after apply)
      + status                    = (known after apply)
      + subject_alternative_names = [
          + "dupezero.com",
          + "www.dupezero.com",
        ]
      + tags                      = {
          + "Name" = "er-prod-edge"
        }
      + tags_all                  = {
          + "Environment" = "prod"
          + "ManagedBy"   = "terraform"
          + "Name"        = "er-prod-edge"
          + "Project"     = "entity-resolution"
        }
      + type                      = (known after apply)
      + validation_emails         = (known after apply)
      + validation_method         = "DNS"

      + options (known after apply)
    }

  # aws_acm_certificate_validation.edge will be created
  + resource "aws_acm_certificate_validation" "edge" {
      + certificate_arn         = (known after apply)
      + id                      = (known after apply)
      + region                  = "us-east-2"
      + validation_record_fqdns = (known after apply)

      + timeouts {
          + create = "15m"
        }
    }

  # aws_lb.edge will be created
  + resource "aws_lb" "edge" {
      + arn                                                          = (known after apply)
      + arn_suffix                                                   = (known after apply)
      + client_keep_alive                                            = 3600
      + desync_mitigation_mode                                       = "defensive"
      + dns_name                                                     = (known after apply)
      + drop_invalid_header_fields                                   = true
      + enable_deletion_protection                                   = true
      + enable_http2                                                 = true
      + enable_prefix_for_ipv6_source_nat                            = (known after apply)
      + enable_tls_version_and_cipher_suite_headers                  = false
      + enable_waf_fail_open                                         = false
      + enable_xff_client_port                                       = false
      + enable_zonal_shift                                           = false
      + enforce_security_group_inbound_rules_on_private_link_traffic = (known after apply)
      + id                                                           = (known after apply)
      + idle_timeout                                                 = 60
      + internal                                                     = false
      + ip_address_type                                              = (known after apply)
      + load_balancer_type                                           = "application"
      + name                                                         = "er-prod-edge"
      + name_prefix                                                  = (known after apply)
      + preserve_host_header                                         = false
      + region                                                       = "us-east-2"
      + secondary_ips_auto_assigned_per_subnet                       = (known after apply)
      + security_groups                                              = (known after apply)
      + subnets                                                      = [
          + "subnet-02b8a601e5e1ee986",
          + "subnet-059bdc493f8e37257",
          + "subnet-0b19390cc3bc63620",
        ]
      + tags                                                         = {
          + "Name" = "er-prod-edge"
        }
      + tags_all                                                     = {
          + "Environment" = "prod"
          + "ManagedBy"   = "terraform"
          + "Name"        = "er-prod-edge"
          + "Project"     = "entity-resolution"
        }
      + vpc_id                                                       = (known after apply)
      + xff_header_processing_mode                                   = "append"
      + zone_id                                                      = (known after apply)

      + subnet_mapping (known after apply)
    }

  # aws_lb_listener.http_redirect will be created
  + resource "aws_lb_listener" "http_redirect" {
      + arn                                                                   = (known after apply)
      + id                                                                    = (known after apply)
      + load_balancer_arn                                                     = (known after apply)
      + port                                                                  = 80
      + protocol                                                              = "HTTP"
      + region                                                                = "us-east-2"
      + routing_http_request_x_amzn_mtls_clientcert_header_name               = (known after apply)
      + routing_http_request_x_amzn_mtls_clientcert_issuer_header_name        = (known after apply)
      + routing_http_request_x_amzn_mtls_clientcert_leaf_header_name          = (known after apply)
      + routing_http_request_x_amzn_mtls_clientcert_serial_number_header_name = (known after apply)
      + routing_http_request_x_amzn_mtls_clientcert_subject_header_name       = (known after apply)
      + routing_http_request_x_amzn_mtls_clientcert_validity_header_name      = (known after apply)
      + routing_http_request_x_amzn_tls_cipher_suite_header_name              = (known after apply)
      + routing_http_request_x_amzn_tls_version_header_name                   = (known after apply)
      + routing_http_response_access_control_allow_credentials_header_value   = (known after apply)
      + routing_http_response_access_control_allow_headers_header_value       = (known after apply)
      + routing_http_response_access_control_allow_methods_header_value       = (known after apply)
      + routing_http_response_access_control_allow_origin_header_value        = (known after apply)
      + routing_http_response_access_control_expose_headers_header_value      = (known after apply)
      + routing_http_response_access_control_max_age_header_value             = (known after apply)
      + routing_http_response_content_security_policy_header_value            = (known after apply)
      + routing_http_response_server_enabled                                  = (known after apply)
      + routing_http_response_strict_transport_security_header_value          = (known after apply)
      + routing_http_response_x_content_type_options_header_value             = (known after apply)
      + routing_http_response_x_frame_options_header_value                    = (known after apply)
      + ssl_policy                                                            = (known after apply)
      + tags_all                                                              = {
          + "Environment" = "prod"
          + "ManagedBy"   = "terraform"
          + "Project"     = "entity-resolution"
        }
      + tcp_idle_timeout_seconds                                              = (known after apply)

      + default_action {
          + order = (known after apply)
          + type  = "redirect"

          + redirect {
              + host        = "#{host}"
              + path        = "/#{path}"
              + port        = "443"
              + protocol    = "HTTPS"
              + query       = "#{query}"
              + status_code = "HTTP_301"
            }
        }

      + mutual_authentication (known after apply)
    }

  # aws_lb_listener.https will be created
  + resource "aws_lb_listener" "https" {
      + arn                                                                   = (known after apply)
      + certificate_arn                                                       = (known after apply)
      + id                                                                    = (known after apply)
      + load_balancer_arn                                                     = (known after apply)
      + port                                                                  = 443
      + protocol                                                              = "HTTPS"
      + region                                                                = "us-east-2"
      + routing_http_request_x_amzn_mtls_clientcert_header_name               = (known after apply)
      + routing_http_request_x_amzn_mtls_clientcert_issuer_header_name        = (known after apply)
      + routing_http_request_x_amzn_mtls_clientcert_leaf_header_name          = (known after apply)
      + routing_http_request_x_amzn_mtls_clientcert_serial_number_header_name = (known after apply)
      + routing_http_request_x_amzn_mtls_clientcert_subject_header_name       = (known after apply)
      + routing_http_request_x_amzn_mtls_clientcert_validity_header_name      = (known after apply)
      + routing_http_request_x_amzn_tls_cipher_suite_header_name              = (known after apply)
      + routing_http_request_x_amzn_tls_version_header_name                   = (known after apply)
      + routing_http_response_access_control_allow_credentials_header_value   = (known after apply)
      + routing_http_response_access_control_allow_headers_header_value       = (known after apply)
      + routing_http_response_access_control_allow_methods_header_value       = (known after apply)
      + routing_http_response_access_control_allow_origin_header_value        = (known after apply)
      + routing_http_response_access_control_expose_headers_header_value      = (known after apply)
      + routing_http_response_access_control_max_age_header_value             = (known after apply)
      + routing_http_response_content_security_policy_header_value            = (known after apply)
      + routing_http_response_server_enabled                                  = (known after apply)
      + routing_http_response_strict_transport_security_header_value          = (known after apply)
      + routing_http_response_x_content_type_options_header_value             = (known after apply)
      + routing_http_response_x_frame_options_header_value                    = (known after apply)
      + ssl_policy                                                            = "ELBSecurityPolicy-TLS13-1-2-2021-06"
      + tags_all                                                              = {
          + "Environment" = "prod"
          + "ManagedBy"   = "terraform"
          + "Project"     = "entity-resolution"
        }
      + tcp_idle_timeout_seconds                                              = (known after apply)

      + default_action {
          + order            = (known after apply)
          + target_group_arn = (known after apply)
          + type             = "forward"
        }

      + mutual_authentication (known after apply)
    }

  # aws_lb_listener_rule.www_to_apex will be created
  + resource "aws_lb_listener_rule" "www_to_apex" {
      + arn          = (known after apply)
      + id           = (known after apply)
      + listener_arn = (known after apply)
      + priority     = 100
      + region       = "us-east-2"
      + tags_all     = {
          + "Environment" = "prod"
          + "ManagedBy"   = "terraform"
          + "Project"     = "entity-resolution"
        }

      + action {
          + order = (known after apply)
          + type  = "redirect"

          + redirect {
              + host        = "dupezero.com"
              + path        = "/#{path}"
              + port        = "443"
              + protocol    = "HTTPS"
              + query       = "#{query}"
              + status_code = "HTTP_301"
            }
        }

      + condition {
          + host_header {
              + regex_values = []
              + values       = [
                  + "www.dupezero.com",
                ]
            }
        }
    }

  # aws_lb_target_group.web will be created
  + resource "aws_lb_target_group" "web" {
      + arn                                = (known after apply)
      + arn_suffix                         = (known after apply)
      + connection_termination             = (known after apply)
      + deregistration_delay               = "30"
      + id                                 = (known after apply)
      + ip_address_type                    = (known after apply)
      + lambda_multi_value_headers_enabled = false
      + load_balancer_arns                 = (known after apply)
      + load_balancing_algorithm_type      = (known after apply)
      + load_balancing_anomaly_mitigation  = (known after apply)
      + load_balancing_cross_zone_enabled  = (known after apply)
      + name                               = "er-prod-web"
      + name_prefix                        = (known after apply)
      + port                               = 3000
      + preserve_client_ip                 = (known after apply)
      + protocol                           = "HTTP"
      + protocol_version                   = (known after apply)
      + proxy_protocol_v2                  = false
      + region                             = "us-east-2"
      + slow_start                         = 0
      + tags                               = {
          + "Name" = "er-prod-web"
        }
      + tags_all                           = {
          + "Environment" = "prod"
          + "ManagedBy"   = "terraform"
          + "Name"        = "er-prod-web"
          + "Project"     = "entity-resolution"
        }
      + target_type                        = "ip"
      + vpc_id                             = "vpc-06ff8c290ccd6c06f"

      + health_check {
          + enabled             = true
          + healthy_threshold   = 2
          + interval            = 15
          + matcher             = "200"
          + path                = "/api/healthz"
          + port                = "traffic-port"
          + protocol            = "HTTP"
          + timeout             = 5
          + unhealthy_threshold = 3
        }

      + stickiness (known after apply)

      + target_failover (known after apply)

      + target_group_health (known after apply)

      + target_health_state (known after apply)
    }

  # aws_security_group.alb will be created
  + resource "aws_security_group" "alb" {
      + arn                    = (known after apply)
      + description            = "The internet-facing prod ALB: 80 and 443 from anywhere, egress to pod IPs."
      + egress                 = (known after apply)
      + id                     = (known after apply)
      + ingress                = (known after apply)
      + name                   = "er-prod-alb"
      + name_prefix            = (known after apply)
      + owner_id               = (known after apply)
      + region                 = "us-east-2"
      + revoke_rules_on_delete = false
      + tags                   = {
          + "Name" = "er-prod-alb"
        }
      + tags_all               = {
          + "Environment" = "prod"
          + "ManagedBy"   = "terraform"
          + "Name"        = "er-prod-alb"
          + "Project"     = "entity-resolution"
        }
      + vpc_id                 = "vpc-06ff8c290ccd6c06f"
    }

  # aws_vpc_security_group_egress_rule.alb_to_targets will be created
  + resource "aws_vpc_security_group_egress_rule" "alb_to_targets" {
      + arn                    = (known after apply)
      + cidr_ipv4              = "10.1.0.0/16"
      + description            = "To er-web pods in the private subnets"
      + from_port              = 3000
      + id                     = (known after apply)
      + ip_protocol            = "tcp"
      + region                 = "us-east-2"
      + security_group_id      = (known after apply)
      + security_group_rule_id = (known after apply)
      + tags_all               = {
          + "Environment" = "prod"
          + "ManagedBy"   = "terraform"
          + "Project"     = "entity-resolution"
        }
      + to_port                = 3000
    }

  # aws_vpc_security_group_ingress_rule.alb_http will be created
  + resource "aws_vpc_security_group_ingress_rule" "alb_http" {
      + arn                    = (known after apply)
      + cidr_ipv4              = "0.0.0.0/0"
      + description            = "HTTP from the internet, redirected to HTTPS by the listener"
      + from_port              = 80
      + id                     = (known after apply)
      + ip_protocol            = "tcp"
      + region                 = "us-east-2"
      + security_group_id      = (known after apply)
      + security_group_rule_id = (known after apply)
      + tags_all               = {
          + "Environment" = "prod"
          + "ManagedBy"   = "terraform"
          + "Project"     = "entity-resolution"
        }
      + to_port                = 80
    }

  # aws_vpc_security_group_ingress_rule.alb_https will be created
  + resource "aws_vpc_security_group_ingress_rule" "alb_https" {
      + arn                    = (known after apply)
      + cidr_ipv4              = "0.0.0.0/0"
      + description            = "HTTPS from the internet"
      + from_port              = 443
      + id                     = (known after apply)
      + ip_protocol            = "tcp"
      + region                 = "us-east-2"
      + security_group_id      = (known after apply)
      + security_group_rule_id = (known after apply)
      + tags_all               = {
          + "Environment" = "prod"
          + "ManagedBy"   = "terraform"
          + "Project"     = "entity-resolution"
        }
      + to_port                = 443
    }

  # aws_vpc_security_group_ingress_rule.nodes_from_alb will be created
  + resource "aws_vpc_security_group_ingress_rule" "nodes_from_alb" {
      + arn                          = (known after apply)
      + description                  = "er-web traffic from the prod ALB"
      + from_port                    = 3000
      + id                           = (known after apply)
      + ip_protocol                  = "tcp"
      + referenced_security_group_id = (known after apply)
      + region                       = "us-east-2"
      + security_group_id            = "sg-020c5aa2c80b3201c"
      + security_group_rule_id       = (known after apply)
      + tags_all                     = {
          + "Environment" = "prod"
          + "ManagedBy"   = "terraform"
          + "Project"     = "entity-resolution"
        }
      + to_port                      = 3000
    }

  # aws_wafv2_web_acl.edge will be created
  + resource "aws_wafv2_web_acl" "edge" {
      + application_integration_url = (known after apply)
      + arn                         = (known after apply)
      + capacity                    = (known after apply)
      + description                 = "Rate limits on the three unauthenticated write paths (§4.1)."
      + id                          = (known after apply)
      + lock_token                  = (known after apply)
      + name                        = "er-prod-edge"
      + name_prefix                 = (known after apply)
      + region                      = "us-east-2"
      + scope                       = "REGIONAL"
      + tags                        = {
          + "Name" = "er-prod-edge"
        }
      + tags_all                    = {
          + "Environment" = "prod"
          + "ManagedBy"   = "terraform"
          + "Name"        = "er-prod-edge"
          + "Project"     = "entity-resolution"
        }

      + default_action {
          + allow {
            }
        }

      + rule {
          + name     = "rate-invites"
          + priority = 30

          + action {
              + block {
                }
            }

          + statement {
              + rate_based_statement {
                  + aggregate_key_type    = "IP"
                  + evaluation_window_sec = 300
                  + limit                 = 50

                  + scope_down_statement {
                      + byte_match_statement {
                          + positional_constraint = "STARTS_WITH"
                          + search_string         = "/api/invites"

                          + field_to_match {
                              + uri_path {}
                            }

                          + text_transformation {
                              + priority = 0
                              + type     = "LOWERCASE"
                            }
                        }
                    }
                }
            }

          + visibility_config {
              + cloudwatch_metrics_enabled = true
              + metric_name                = "er-prod-rate-invites"
              + sampled_requests_enabled   = true
            }
        }
      + rule {
          + name     = "rate-login"
          + priority = 10

          + action {
              + block {
                }
            }

          + statement {
              + rate_based_statement {
                  + aggregate_key_type    = "IP"
                  + evaluation_window_sec = 300
                  + limit                 = 100

                  + scope_down_statement {
                      + byte_match_statement {
                          + positional_constraint = "STARTS_WITH"
                          + search_string         = "/api/auth/login"

                          + field_to_match {
                              + uri_path {}
                            }

                          + text_transformation {
                              + priority = 0
                              + type     = "LOWERCASE"
                            }
                        }
                    }
                }
            }

          + visibility_config {
              + cloudwatch_metrics_enabled = true
              + metric_name                = "er-prod-rate-login"
              + sampled_requests_enabled   = true
            }
        }
      + rule {
          + name     = "rate-password-reset"
          + priority = 20

          + action {
              + block {
                }
            }

          + statement {
              + rate_based_statement {
                  + aggregate_key_type    = "IP"
                  + evaluation_window_sec = 300
                  + limit                 = 20

                  + scope_down_statement {
                      + byte_match_statement {
                          + positional_constraint = "STARTS_WITH"
                          + search_string         = "/api/auth/password-reset"

                          + field_to_match {
                              + uri_path {}
                            }

                          + text_transformation {
                              + priority = 0
                              + type     = "LOWERCASE"
                            }
                        }
                    }
                }
            }

          + visibility_config {
              + cloudwatch_metrics_enabled = true
              + metric_name                = "er-prod-rate-password-reset"
              + sampled_requests_enabled   = true
            }
        }

      + visibility_config {
          + cloudwatch_metrics_enabled = true
          + metric_name                = "er-prod-edge"
          + sampled_requests_enabled   = true
        }
    }

  # aws_wafv2_web_acl_association.edge will be created
  + resource "aws_wafv2_web_acl_association" "edge" {
      + id           = (known after apply)
      + region       = "us-east-2"
      + resource_arn = (known after apply)
      + web_acl_arn  = (known after apply)
    }

  # cloudflare_dns_record.acm_validation["dupezero.com"] will be created
  + resource "cloudflare_dns_record" "acm_validation" {
      + content                 = (known after apply)
      + created_on              = (known after apply)
      + id                      = (known after apply)
      + include_shadow_metadata = false
      + meta                    = (known after apply)
      + modified_on             = (known after apply)
      + name                    = (known after apply)
      + proxiable               = (known after apply)
      + proxied                 = false
      + settings                = (known after apply)
      + tags                    = (known after apply)
      + tags_modified_on        = (known after apply)
      + ttl                     = 60
      + type                    = (known after apply)
      + zone_id                 = "2f036e2791d0b695a23145e5f4ae1fb7"
    }

  # cloudflare_dns_record.acm_validation["www.dupezero.com"] will be created
  + resource "cloudflare_dns_record" "acm_validation" {
      + content                 = (known after apply)
      + created_on              = (known after apply)
      + id                      = (known after apply)
      + include_shadow_metadata = false
      + meta                    = (known after apply)
      + modified_on             = (known after apply)
      + name                    = (known after apply)
      + proxiable               = (known after apply)
      + proxied                 = false
      + settings                = (known after apply)
      + tags                    = (known after apply)
      + tags_modified_on        = (known after apply)
      + ttl                     = 60
      + type                    = (known after apply)
      + zone_id                 = "2f036e2791d0b695a23145e5f4ae1fb7"
    }

  # cloudflare_dns_record.apex will be created
  + resource "cloudflare_dns_record" "apex" {
      + comment                 = "Terraform (envs/prod/edge.tf) — the prod ALB. DNS-only: AWS WAF is the edge."
      + comment_modified_on     = (known after apply)
      + content                 = (known after apply)
      + created_on              = (known after apply)
      + id                      = (known after apply)
      + include_shadow_metadata = false
      + meta                    = (known after apply)
      + modified_on             = (known after apply)
      + name                    = "dupezero.com"
      + proxiable               = (known after apply)
      + proxied                 = false
      + settings                = (known after apply)
      + tags                    = (known after apply)
      + tags_modified_on        = (known after apply)
      + ttl                     = 60
      + type                    = "CNAME"
      + zone_id                 = "2f036e2791d0b695a23145e5f4ae1fb7"
    }

  # cloudflare_dns_record.www will be created
  + resource "cloudflare_dns_record" "www" {
      + comment                 = "Terraform (envs/prod/edge.tf) — redirected to the apex by the ALB listener rule."
      + comment_modified_on     = (known after apply)
      + content                 = (known after apply)
      + created_on              = (known after apply)
      + id                      = (known after apply)
      + include_shadow_metadata = false
      + meta                    = (known after apply)
      + modified_on             = (known after apply)
      + name                    = "www.dupezero.com"
      + proxiable               = (known after apply)
      + proxied                 = false
      + settings                = (known after apply)
      + tags                    = (known after apply)
      + tags_modified_on        = (known after apply)
      + ttl                     = 60
      + type                    = "CNAME"
      + zone_id                 = "2f036e2791d0b695a23145e5f4ae1fb7"
    }

Plan: 18 to add, 0 to change, 0 to destroy.

Changes to Outputs:
  + edge_alb_dns_name      = (known after apply)
  + edge_certificate_arn   = (known after apply)
  + edge_target_group_arn  = (known after apply)
  + edge_web_acl_arn       = (known after apply)

bmoore813 and others added 2 commits November 8, 2026 15:38
First half of #909. Creates the bucket; does NOT repoint `rust.yml`, which
waits until the bucket exists and the two scoped credentials are in GitHub
secrets — splitting them avoids the race where `rust.yml` on `main` runs
against a bucket whose apply has not finished.

WHY R2, after two backends that each failed differently. S3 (#350) was fast and
expensive: runners sit outside AWS, so every read is billed internet egress and
no VPC endpoint can reach it — CUR 2.0 per-resource put `er-ci-sccache` /
`DataTransfer-Out-Bytes` at $209.32 of a $211.62 November S3 total, against
$0.02 of storage. The Actions cache backend (#893) was cheap and slow: per-hit
read latency roughly doubled (0.122s -> 0.242s), and GitHub rate-limits cache
writes PER WORKFLOW RUN shared across every job, while sccache's
`GHACache::build` installs no `RetryLayer` and counts the resulting 429 instead
of retrying (mozilla/sccache#2821, unfixed in the pinned 0.19.0). The first
`main` run dropped 3,763 writes and landed 1,164 — 24% success, ~27% mean hit
rate, 25.1 minutes against 9.8 on S3.

R2 is the only option that is both: zero egress, and not GitHub's cache service
so neither the 429 bug nor the per-run quota applies. ~$2/month.

Stated plainly because it is the one regression: the Actions backend gave
cache-poisoning protection free via branch scoping — verified on #893, all
1,137 entries on `refs/pull/893/merge`, none on `main`. R2 has no OIDC and no
IAM condition keys, so that is rebuilt from two scoped tokens and a `main`-only
environment in the follow-up.

Opt-in gated on `var.cloudflare_account_id` (null by default), the `ses.tf`
pattern and its reason: without a token the provider cannot authenticate and the
WHOLE `core` plan fails, leaving every resource that does plan cleanly
unchecked. The `count`s should come out when #908 gives CI a scoped read-only
token — the gate is worth more here than for SES, because this bucket is on the
critical path of every compile job.

Two provider caveats recorded in the file rather than left to be rediscovered,
both reported by the first real plan rather than guessed: the lifecycle resource
cannot be destroyed by Terraform and does not support `import`, and `max_age` is
in SECONDS here where the S3 rule took days.

`.terraform.lock.hcl` carries linux_amd64 AND darwin_arm64 hashes for the new
provider. A lockfile written only on darwin fails CI's init on linux, and
`envs/dev` and `envs/prod` already track multiple platforms.

Closes #910

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…unt id

Without these the apply job plans `envs/core` with no Cloudflare auth and
`var.cloudflare_account_id` null, so r2.tf stays `count = 0` and the bucket is
never created. The apply job re-plans to a file inside itself
(`scripts/ci/tf-apply-plan.sh`) rather than consuming the plan tier's artifact,
so these reach the plan that actually lands — and the destroy guard still reads
it before anything is applied.

`CLOUDFLARE_API_TOKEN` is an **Environment** secret on `infra-apply-core`, which
is `protected_branches: true`. A pull request therefore cannot read it even by
editing this workflow. That is the property replacing the
`er-ci-sccache-read`/`-write` role split S3 had, and it is the pattern
`agent-fleet.md` already prescribes for the secrets added after #439 gave up the
zero-secret invariant: environment-scoped to `main` rather than repository-wide.

The account id is NOT a secret and is deliberately in the tree: it appears in
every dashboard URL and the S3-API endpoint is derived from it, exactly as
`rust.yml` carries the AWS account id inside `SCCACHE_BUCKET`.

Set unconditionally rather than per-matrix-leg, which is the subtle part. Only
`envs/core` declares the variable and Terraform silently ignores a `TF_VAR_` for
an undeclared one — unlike `-var`, which errors. A `matrix.key == 'core' && … ||
''` expression would be actively wrong: it yields the empty STRING on the other
legs, and `"" != null`, so `local.r2_enabled` would flip true with no account id
to use.

Known gap, bounded and recorded on the pull request: the PR plan tier has no
Cloudflare token, so R2 changes are not previewed on a pull request even though
the apply leg creates them. That is the §14.2 tradeoff `envs/dev/ses.tf` already
makes, and #908 is what closes it by giving CI a scoped read-only token.

Closes #910

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@athvin
athvin merged commit be64c41 into main Nov 8, 2026
41 checks passed
athvin added a commit that referenced this pull request Nov 8, 2026
…just plan (#916) (#917)

`apply (core)` went red on be64c41 (#912) with

  400 {"code":9106,"message":"Missing X-Auth-Key, X-Auth-Email or
  Authorization headers"}

on `cloudflare_r2_bucket.sccache[0]`, so `main` has no R2 bucket. `plan (core)`
and the apply job's own plan-to-file step both passed; only the apply step
failed, because #912 set `CLOUDFLARE_API_TOKEN` and
`TF_VAR_cloudflare_account_id` on the plan-to-file step while the apply step
carries only `DIR`.

The asymmetry is not a Terraform quirk, it is the direct consequence of a
decision `versions.tf` records: VARIABLE values are baked into the saved plan,
but PROVIDER CREDENTIALS deliberately are not — which is precisely why the
provider reads the token from the environment rather than taking it as a
variable, since a variable would land in the plan file and in state. So the
credential is needed at plan time AND at apply time.

Both values move to the apply job's JOB-level `env:`, so the two steps cannot
disagree. `TF_VAR_cloudflare_account_id` was never the failure — it is in the
plan file — but it travels with the token because splitting them across steps is
the mechanism that produced this.

Also records the exception in this workflow's header, which asserts "NO
REPOSITORY SECRETS, by design and not by omission". The claim survives:
`CLOUDFLARE_API_TOKEN` is an ENVIRONMENT secret on `infra-apply-core`
(`protected_branches: true`), reachable by one job on `main`, and every
objection the header raises to a repository secret is about reach. What does not
survive is the expiry argument — a Cloudflare token is long-lived where every
AWS identity here lasts an hour, scoped to `Workers R2 Storage: Edit` on one
account. Cloudflare has no OIDC equivalent, so that is the floor rather than a
shortcut, and it is why #909 rebuilds the read/write split from two scoped
bucket tokens instead of federation.

Closes #916

Co-authored-by: bmoore813 <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
@athvin

athvin commented Nov 8, 2026

Copy link
Copy Markdown
Owner Author

Two findings from landing #555's prod edge, which added a second Cloudflare consumer to this workflow.

1. apply (core) is red, and it is this PR's to resolve

Run 42522098678, apply (core):

cloudflare_r2_bucket.sccache[0]: Creating...
Error: failed to make http request
  with cloudflare_r2_bucket.sccache[0], on r2.tf line 57
  "https://api.cloudflare.com/client/v4/accounts/9eefbe6bc92d11b2bb4e962494765a4c/r2/buckets":
  400 {"success":false,"errors":[{"code":9106,"message":"Missing ...

It has been failing since its own merge (be64c41e, 20:47:45), before any of my fixes. The infra-apply-core Environment secret is NOT missing — I checked, gh api .../environments/infra-apply-core/secrets lists CLOUDFLARE_API_TOKEN, and the log shows it resolving as *** on the core leg. So it is populated and the value does not authenticate. 9106 is specifically no authorization header sent, which a whitespace-only or placeholder value produces; a wrong-but-real token would give 9109.

Worth knowing while diagnosing: the plan step passing proves nothing here. plan makes no provider call for a resource that will be created, so the R2 resources were never authenticated against until apply.

A trailing newline is the likeliest cause — pasted into a secret it rides into the Authorization header and fails exactly like an absent token. #919 now trims on the way through, so if that is it, #919 alone may fix this leg too; if the value is a placeholder, it still needs re-setting.

2. #919 changes how this workflow sets that variable

The job-level env: here collided with the prod leg. A job-level env: takes precedence over $GITHUB_ENV, so CLOUDFLARE_API_TOKEN being empty on non-core legs silently shadowed the token the prod step exported — the export logged success and the next step saw nothing.

The reasoning in your comment was correct when written ("Empty on dev and prod, which need no Cloudflare credential"); envs/prod getting DNS records is what invalidated it.

#919 removes the job-level assignment and makes scripts/ci/tf-cloudflare-token.sh the only setter, choosing a source per leg: your Environment secret on core, unchanged, and Secrets Manager on prod. Your scoping property is preserved — the secret still resolves only on infra-apply-core under protected_branches: true.

Kept as two tokens on purpose, which I measured rather than assumed: the zone-scoped prod token returns 9109 on /accounts/<id> and 10000 on /r2/buckets, so it cannot do core's work, and one shared token would need both scopes and be broader than either leg. The header's "ONE NON-AWS CREDENTIAL EXISTS" paragraph is updated to describe both.

athvin added a commit that referenced this pull request Nov 8, 2026
… token never applied

Two Cloudflare credential mechanisms landed within nine minutes of each other
and collided. #912 set `CLOUDFLARE_API_TOKEN` as a job-level `env:` from the
`infra-apply-core` Environment secret; #911 added a step exporting it from
Secrets Manager for the prod leg. A job-level `env:` takes precedence over
`$GITHUB_ENV`, so the value that is empty on the prod leg shadowed the token the
step had just written — and `apply (prod)` failed with Cloudflare `9106`, no
authorization header at all, on the line after the export step reported success.

Precedence was the bug, not the fetch. Verified the fetch itself is sound: the
step logged `exported CLOUDFLARE_API_TOKEN ... (53 chars)`, and the same token
with an empty `provider "cloudflare" {}` block authenticates locally against
provider 5.28.1 — the version CI locks — returning the zone name.

#912's reasoning was correct when written. It says the value is "empty on dev
and prod, which need no Cloudflare credential", and that stopped being true the
moment envs/prod got DNS records.

TWO TOKENS, NOT ONE, and this is the part worth keeping. core creates an R2
bucket and needs `Workers R2 Storage: Edit` on the ACCOUNT; prod writes DNS and
needs `Zone DNS: Edit` on ONE zone. Measured: the zone-scoped token returns
`9109` on `/accounts/<id>` and `10000` on `/accounts/<id>/r2/buckets`, so it
cannot do core's work, and a shared token would have to carry both scopes and be
strictly broader than either leg needs.

So: one variable, one setter, source chosen per leg. The script takes the
Environment secret when it is non-empty (core) and falls through to Secrets
Manager otherwise (prod), and it is the only thing in the workflow that assigns
`CLOUDFLARE_API_TOKEN`. Both branches are self-tested, including that the
fall-through FAILS rather than silently exporting nothing, and that a token
pasted with a trailing newline is trimmed — untrimmed it would ride into the
Authorization header and fail exactly like an absent one.

This does not fix `apply (core)`, which fails the same way for its own reason:
its Environment secret exists and is populated, but the value does not
authenticate. That is #910/#912's to resolve and it was already failing on its
own merge, before this.

No ticket: this reconciles two merged pull requests rather than adding scope.

Co-authored-by: bmoore813 <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

infra: declare the R2 sccache bucket and its lifecycle rule in Terraform

2 participants