carlos / platform Public

infra: harden the #1007 guard (Astra R1)

The guard now reads every module file, allowlists every block, rejects
NotResource/NotAction and any unknown Resource value anywhere, and
requires the exact deployment_bucket_arn validation. A mutation test
proves each way the grant could come back fails it.

remote-host.md, bootstrap and agent comments no longer describe a
deployment-bucket grant for off-cloud boxes; the migration text names the
whole fleet-door setup, not just the tunnel variables.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 3256f57e029491d17c020898944ad5b8e1563408 parent d5a309b
6 files changed, +193 −46
  • infra/modules/region-remote-host/README.md +6 −6
  • infra/modules/region-remote-host/variables.tf +1 −1
  • infra/remote-host.md +6 −3
  • internal/host/agent.go +6 −6
  • internal/host/bootstrap.go +4 −3
  • internal/provision/remote_host_module_test.go +170 −27

CI cancelled — superseded by a newer push — run details

Intent

Attributed to this commit: 13.8 g CO₂e (1,833,695 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on close-direct-s3-fleet-writes, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/infra/modules/region-remote-host/README.md b/infra/modules/region-remote-host/README.md
index ffd0566f2..aa7a0d31e 100644
--- a/infra/modules/region-remote-host/README.md
+++ b/infra/modules/region-remote-host/README.md
@@ -6,9 +6,8 @@ inline policy and access key, limited to this region's data bucket and
nothing else (wrong-region-fails-at-IAM, the same residency property
`region-host` gives cloud hosts).
-Consumed by customer fleets (paulca/pi-fleet is the live example) and
-the platform's tito hq box. The module is reusable as-is for both — they
-differ only in account and variable values, not shape.
+Consumed by customer fleets and self-hosted operators' fleets from their
+own tofu roots, by git URL.
**The principal gets nothing on the platform's deployment bucket.** A fleet
box reads releases and status, and writes heartbeats, through the console's
@@ -19,9 +18,10 @@ The module used to grant read and write on the whole deployment bucket when
`deployment_bucket_arn` was set, for boxes on the pre-fleet-API agent. That
let a box rewrite any instance record in the bucket (#1007), so the grant is
gone. The variable stays only to fail a plan that still sets it. If your
-root sets it: remove it, and move the box to the fleet door
-(`CARLOS_TUNNEL_URL` and `CARLOS_TUNNEL_TOKEN`, no
-`CARLOS_DEPLOYMENT_BUCKET`).
+root sets it: remove it, and move the box to the fleet door. Register the
+box with `carlos fleets add-box`, set `CARLOS_FLEET` and the
+`CARLOS_TUNNEL_` variables, and unset `CARLOS_DEPLOYMENT_BUCKET`. The
+console's BYO fleet page has the full list.
**`access_key_status`** (`Active` by default) switches the host's access
key off without destroying it. Once you deactivate a key by hand, set this
diff --git a/infra/modules/region-remote-host/variables.tf b/infra/modules/region-remote-host/variables.tf
index edc232aab..3acc02829 100644
--- a/infra/modules/region-remote-host/variables.tf
+++ b/infra/modules/region-remote-host/variables.tf
@@ -15,7 +15,7 @@ variable "deployment_bucket_arn" {
validation {
condition = var.deployment_bucket_arn == ""
- error_message = "deployment_bucket_arn is no longer supported (#1007): it gave the box write access to every record in the deployment bucket. Remove it from your root, and move the box to the fleet door: set CARLOS_TUNNEL_URL and CARLOS_TUNNEL_TOKEN, and unset CARLOS_DEPLOYMENT_BUCKET."
+ error_message = "deployment_bucket_arn is no longer supported (#1007): it gave the box write access to every record in the deployment bucket. Remove it from your root and move the box to the fleet door: register it with carlos fleets add-box, set CARLOS_FLEET and the CARLOS_TUNNEL_ variables, and unset CARLOS_DEPLOYMENT_BUCKET."
}
}
diff --git a/infra/remote-host.md b/infra/remote-host.md
index dfe9fed54..fb4723fa4 100644
--- a/infra/remote-host.md
+++ b/infra/remote-host.md
@@ -10,9 +10,12 @@ GOOS-GOARCH — linux-arm64 or linux-amd64; a 32-bit OS resolves nothing).
## Steps
1. Provision the IAM principal + region data bucket
- (`infra/modules/region-remote-host`). Scope: deployment bucket + this
- host's own region bucket, and NOTHING else — wrong-region-fails-at-IAM
- holds off-cloud too. A scoped access key is acceptable to start; IAM
+ (`infra/modules/region-remote-host`). Scope: this host's own region
+ bucket and nothing else, so wrong-region-fails-at-IAM holds off-cloud
+ too. The key gets nothing on the platform's deployment bucket: the box
+ reads releases and writes heartbeats through the fleet door with its
+ tunnel token (#1007). Register the fleet and box first, as the console's
+ BYO fleet page (`/a/{sqid}/fleet/byo`) describes. A scoped access key is acceptable to start; IAM
Roles Anywhere is the long-term, hq-grade alternative (no long-lived
key on the box at all).
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 4f0b25aaa..183c52aa9 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -5692,12 +5692,12 @@ func OpenDeployStore(ctx context.Context) (release.Store, error) { return openDe
// selection rule can be tested without mutating process-wide env.
//
// Order is the whole contract (spec F5): a bucket or dir still set WINS,
-// before fleet identity is even consulted, so every platform box and every
-// grandfathered fleet box that still has bucket credentials keeps exactly
-// today's store, byte for byte. Only a box that resolves a fleet identity
-// AND has no bucket/dir at all reaches the door — that is the cutover
-// switch, per box, no flag day: drop the bucket var and the box is on the
-// API; put it back and it is off.
+// before fleet identity is even consulted, so every platform box keeps
+// exactly today's store, byte for byte. Only a box that resolves a fleet
+// identity AND has no bucket/dir at all reaches the door. Fleet boxes must
+// not set the bucket var: region-remote-host no longer grants a fleet box
+// any access to the deployment bucket (#1007), so the bucket branch is for
+// platform boxes only.
func openDeployStoreEnv(ctx context.Context, getenv func(string) string) (release.Store, error) {
if b := getenv("CARLOS_DEPLOYMENT_BUCKET"); b != "" {
return release.NewDeploymentS3Store(ctx, b)
diff --git a/internal/host/bootstrap.go b/internal/host/bootstrap.go
index 7920d6a25..e5228f4ce 100644
--- a/internal/host/bootstrap.go
+++ b/internal/host/bootstrap.go
@@ -395,9 +395,10 @@ func (f *repeatableFlag) Set(v string) error {
// bootstrapOffcloud is bootstrap for a box with no EC2 instance profile
// (issue #53 point 4): identical structural work, plus the credential
-// preconditions — a staged 0600 credentials file scoped (at IAM) to the
-// deployment bucket + this host's own region bucket and nothing else, so
-// wrong-region-fails-at-IAM holds off-cloud too. The flag is explicit; no
+// preconditions — a staged 0600 credentials file scoped (at IAM) to this
+// host's own region bucket and nothing else, so wrong-region-fails-at-IAM
+// holds off-cloud too. Releases and heartbeats go through the fleet door,
+// not a deployment-bucket grant (#1007). The flag is explicit; no
// IMDS sniffing (the agent's one IMDS probe is already gated for non-EC2).
//
// Credential shape and mode checks precede bootstrap mutations. A rejected
diff --git a/internal/provision/remote_host_module_test.go b/internal/provision/remote_host_module_test.go
index 1e871e0df..24a8d26bb 100644
--- a/internal/provision/remote_host_module_test.go
+++ b/internal/provision/remote_host_module_test.go
@@ -1,7 +1,10 @@
package provision
import (
+ "os"
+ "path/filepath"
"regexp"
+ "slices"
"strings"
"testing"
)
@@ -9,44 +12,184 @@ import (
// #1007: region-remote-host once granted its off-cloud principal read and
// write on the whole platform deployment bucket, which let a fleet box
// rewrite any instance record. These guards keep the module unable to grant
-// that again. CI has no OpenTofu, so they read the module text; the module's
-// own tofu tests (tests/no_deployment_bucket.tftest.hcl) check the plan.
+// that again. CI has no OpenTofu, so they read the module text, strictly:
+// any shape they do not recognise fails, and the fix is to review the new
+// grant and update the guard. The module's own tofu tests
+// (tests/no_deployment_bucket.tftest.hcl) check the plan.
+
+const remoteHostModule = "infra/modules/region-remote-host"
+
+// Every block the module may declare. A new resource, data source or child
+// module is a possible new grant, so it fails here until reviewed.
+var remoteHostBlocks = []string{
+ `resource "aws_iam_access_key" "host"`,
+ `resource "aws_iam_user" "host"`,
+ `resource "aws_iam_user_policy" "host"`,
+ `resource "aws_s3_bucket" "data"`,
+ `resource "aws_s3_bucket_lifecycle_configuration" "data"`,
+ `resource "aws_s3_bucket_public_access_block" "data"`,
+ `resource "aws_s3_bucket_server_side_encryption_configuration" "data"`,
+ `resource "aws_s3_bucket_versioning" "data"`,
+}
+
+// The only Resource values the host policy may use: its own data bucket,
+// or a sibling's bucket (the arn loop variable) for moves/ staging.
+var remoteHostResources = []string{
+ `["${aws_s3_bucket.data.arn}/*"]`,
+ `[aws_s3_bucket.data.arn]`,
+ `"${arn}/moves/*"`,
+ `arn`,
+}
+
func TestRegionRemoteHostGrantsNoDeploymentBucket(t *testing.T) {
- main := string(groupGuardFile(t, "infra/modules/region-remote-host/main.tf"))
- vars := string(groupGuardFile(t, "infra/modules/region-remote-host/variables.tf"))
- code := stripHCLComments(main)
+ dir := filepath.Join("../..", remoteHostModule)
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ files := map[string]string{}
+ for _, e := range entries {
+ if e.IsDir() {
+ continue
+ }
+ b, err := os.ReadFile(filepath.Join(dir, e.Name()))
+ if err != nil {
+ t.Fatal(err)
+ }
+ files[e.Name()] = string(b)
+ }
+ for _, problem := range remoteHostModuleProblems(files) {
+ t.Error(problem)
+ }
+}
- // One IAM policy, the host's own. Any other way of attaching
- // permissions to the user is a new grant this guard has not read.
- policies := regexp.MustCompile(`(?m)^resource\s+"(aws_iam_[a-z_]*polic[a-z_]*|aws_iam_user_group_membership|aws_iam_group[a-z_]*)"\s+"([^"]+)"`).FindAllStringSubmatch(code, -1)
- if len(policies) != 1 || policies[0][1] != "aws_iam_user_policy" || policies[0][2] != "host" {
- t.Fatalf("region-remote-host must carry exactly one IAM policy, aws_iam_user_policy.host; found %v", policies)
+// Each mutation is a way the grant could come back; the guard must catch
+// every one.
+func TestRegionRemoteHostGuardCatchesRegrants(t *testing.T) {
+ base := map[string]string{}
+ for _, name := range []string{"main.tf", "variables.tf", "outputs.tf", "README.md"} {
+ base[name] = string(groupGuardFile(t, filepath.Join(remoteHostModule, name)))
}
+ if p := remoteHostModuleProblems(base); len(p) != 0 {
+ t.Fatalf("baseline must pass: %v", p)
+ }
+ ownObjects := `Resource = ["${aws_s3_bucket.data.arn}/*"]`
+ condition := `condition = var.deployment_bucket_arn == ""`
+ for _, m := range []struct {
+ name string
+ file string
+ mutate func(string) string
+ }{
+ {"old grant resource", "main.tf", func(s string) string {
+ return s + "\nresource \"aws_iam_user_policy\" \"host_deployment_bucket\" {\n user = aws_iam_user.host.name\n}\n"
+ }},
+ {"indented attachment", "main.tf", func(s string) string {
+ return s + "\n resource \"aws_iam_user_policy_attachment\" \"s3\" {\n user = aws_iam_user.host.name\n}\n"
+ }},
+ {"child module", "main.tf", func(s string) string {
+ return s + "\nmodule \"extra\" {\n source = \"./extra\"\n}\n"
+ }},
+ {"NotResource", "main.tf", func(s string) string {
+ return strings.Replace(s, ownObjects, `NotResource = ["${aws_s3_bucket.data.arn}/*"]`, 1)
+ }},
+ {"NotAction", "main.tf", func(s string) string {
+ return strings.Replace(s, `Action = ["s3:GetObjectVersion"]`, `NotAction = ["s3:GetObjectVersion"]`, 1)
+ }},
+ {"inline wildcard statement", "main.tf", func(s string) string {
+ return strings.Replace(s, "Statement = concat([\n", "Statement = concat([\n { Effect = \"Allow\", Action = [\"s3:*\"], Resource = \"*\" },\n", 1)
+ }},
+ {"deployment bucket resource", "main.tf", func(s string) string {
+ return strings.Replace(s, ownObjects, `Resource = ["${var.deployment_bucket_arn}/*"]`, 1)
+ }},
+ {"variable used", "main.tf", func(s string) string {
+ return s + "\nlocals {\n x = var.deployment_bucket_arn\n}\n"
+ }},
+ {"condition weakened", "variables.tf", func(s string) string {
+ return strings.Replace(s, condition, condition+` || true`, 1)
+ }},
+ {"condition commented out", "variables.tf", func(s string) string {
+ return strings.Replace(s, condition, "# "+condition+"\n condition = true", 1)
+ }},
+ {"new tf file", "extra.tf", func(string) string { return "# nothing yet\n" }},
+ {"tf.json file", "extra.tf.json", func(string) string { return "{}" }},
+ {"resource in variables.tf", "variables.tf", func(s string) string {
+ return s + "\nresource \"aws_iam_user_policy_attachment\" \"s3\" {\n user = \"x\"\n}\n"
+ }},
+ } {
+ files := map[string]string{}
+ for k, v := range base {
+ files[k] = v
+ }
+ mutated := m.mutate(files[m.file])
+ if mutated == files[m.file] {
+ t.Fatalf("%s: mutation did not apply; update the test", m.name)
+ }
+ files[m.file] = mutated
+ if len(remoteHostModuleProblems(files)) == 0 {
+ t.Errorf("%s: guard did not notice", m.name)
+ }
+ }
+}
- // Every Resource names the host's own data bucket, or a sibling
- // staging bucket's moves/ prefix (the arn loop variable).
- resources := regexp.MustCompile(`(?m)^\s*Resource\s*=\s*(.+)$`).FindAllStringSubmatch(code, -1)
- if len(resources) == 0 {
- t.Fatal("no Resource lines found; the policy shape changed, update this guard")
+func remoteHostModuleProblems(files map[string]string) []string {
+ var problems []string
+ var names []string
+ for name := range files {
+ if strings.HasSuffix(name, ".tf") || strings.HasSuffix(name, ".tf.json") {
+ names = append(names, name)
+ }
+ }
+ slices.Sort(names)
+ if !slices.Equal(names, []string{"main.tf", "outputs.tf", "variables.tf"}) {
+ problems = append(problems, "region-remote-host files changed to "+strings.Join(names, ", ")+"; review any new grant, then update this guard")
+ }
+
+ var code strings.Builder
+ for _, name := range names {
+ code.WriteString(stripHCLComments(files[name]))
+ }
+ all := code.String()
+
+ blocks := regexp.MustCompile(`(?m)^\s*(resource|data|module)\s+"[^"]*"(\s+"[^"]*")?`).FindAllString(all, -1)
+ for i := range blocks {
+ blocks[i] = strings.Join(strings.Fields(blocks[i]), " ")
+ }
+ slices.Sort(blocks)
+ if !slices.Equal(blocks, remoteHostBlocks) {
+ problems = append(problems, "region-remote-host declares "+strings.Join(blocks, "; ")+"; want exactly "+strings.Join(remoteHostBlocks, "; ")+" (#1007)")
+ }
+
+ if regexp.MustCompile(`\bNot(Resource|Action|Principal)\b`).MatchString(all) {
+ problems = append(problems, "region-remote-host uses NotResource/NotAction/NotPrincipal, which grants by exclusion (#1007)")
}
- allowed := map[string]bool{
- `["${aws_s3_bucket.data.arn}/*"]`: true,
- `[aws_s3_bucket.data.arn]`: true,
- `"${arn}/moves/*"`: true,
- `arn`: true,
+ resources := regexp.MustCompile(`\bResource\s*=\s*("[^"\n]*"|\[[^\]\n]*\]|[A-Za-z_.]+)`).FindAllStringSubmatch(all, -1)
+ if len(resources) == 0 {
+ problems = append(problems, "no Resource values found; the policy shape changed, update this guard")
}
for _, r := range resources {
- if v := strings.TrimSpace(r[1]); !allowed[v] {
- t.Errorf("region-remote-host grants on %s; it may name only its own data bucket or a sibling's moves/ prefix (#1007)", v)
+ if !slices.Contains(remoteHostResources, r[1]) {
+ problems = append(problems, "region-remote-host grants on "+r[1]+"; it may name only its own data bucket or a sibling's moves/ prefix (#1007)")
}
}
-
- if strings.Contains(code, "var.deployment_bucket_arn") {
- t.Error("main.tf must not use var.deployment_bucket_arn (#1007)")
+ // The variable must refuse every non-empty value: exactly one
+ // condition, and it is the plain equality. Outside its own block,
+ // nothing may read it.
+ start := strings.Index(all, `variable "deployment_bucket_arn" {`)
+ if start < 0 {
+ return append(problems, "variables.tf must keep deployment_bucket_arn so a root that sets it fails the plan (#1007)")
+ }
+ block := all[start:]
+ if end := regexp.MustCompile(`(?m)^}`).FindStringIndex(block); end != nil {
+ block = block[:end[1]]
+ }
+ if strings.Contains(strings.Replace(all, block, "", 1), "deployment_bucket_arn") {
+ problems = append(problems, "region-remote-host code must not use deployment_bucket_arn (#1007)")
}
- if !regexp.MustCompile(`condition\s*=\s*var\.deployment_bucket_arn\s*==\s*""`).MatchString(vars) {
- t.Error(`variables.tf must refuse a non-empty deployment_bucket_arn (condition = var.deployment_bucket_arn == "")`)
+ conditions := regexp.MustCompile(`(?m)^\s*condition\s*=\s*(.*?)\s*$`).FindAllStringSubmatch(block, -1)
+ if len(conditions) != 1 || conditions[0][1] != `var.deployment_bucket_arn == ""` {
+ problems = append(problems, `deployment_bucket_arn must have exactly one validation, condition = var.deployment_bucket_arn == "" (#1007)`)
}
+ return problems
}
func stripHCLComments(s string) string {