| 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 { |