carlos / platform Public

Allow HA departure settings in root-owned host.env

Allow fixed box identity maps and retain the termination queue key. Validate and single-quote only the binding JSON so shell and systemd readers preserve it, while keeping owner-only directory checks and 0600 files.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev f7116c2282a9643777522308cc80637ef5e67f70 parent 45a9897
3 files changed, +97 −7
  • internal/hostenv/hostenv.go +35 −6
  • internal/hostenv/write_linux_test.go +61 −0
  • internal/provision/testdata/plan14-root-reads-region-ha-p1b3b-t.tsv +1 −1
diff --git a/internal/hostenv/hostenv.go b/internal/hostenv/hostenv.go
index 77512fc30..5e12092b9 100644
--- a/internal/hostenv/hostenv.go
+++ b/internal/hostenv/hostenv.go
@@ -15,8 +15,11 @@ import (
"bufio"
"bytes"
"context"
+ "encoding/json"
+
"errors"
"fmt"
+ "github.com/carlosframework/platform/internal/controlname"
"regexp"
"slices"
"sort"
@@ -80,6 +83,7 @@ var Optional = []string{
"CARLOS_EDGE_GZIP",
"CARLOS_EDGE_PROTECT",
"CARLOS_EDGE_RECORDS",
+ "CARLOS_HA_FIXED_BOX_IDENTITIES",
"CARLOS_HIBERNATE_IDLE",
"CARLOS_HIBERNATE_PREFIX",
"CARLOS_HOST_CLAIM_RETIRED_LOCATIONS",
@@ -168,9 +172,11 @@ var (
)
var (
- scopeName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)
- keyName = regexp.MustCompile(`^[A-Z][A-Z0-9_]*$`)
- safeValue = regexp.MustCompile(`^[A-Za-z0-9_./:,@+=%-]*$`)
+ scopeName = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)
+ keyName = regexp.MustCompile(`^[A-Z][A-Z0-9_]*$`)
+ bindingValue = regexp.MustCompile(`^[a-z0-9{}":, -]*$`)
+ bindingIID = regexp.MustCompile(`^i-[0-9a-f]{8}([0-9a-f]{9})?$`)
+ safeValue = regexp.MustCompile(`^[A-Za-z0-9_./:,@+=%-]*$`)
)
// Prefix is the parameter path of one scope: a region's placement code or
@@ -233,7 +239,8 @@ func Missing(env map[string]string) []string {
const renderedHeader = "# Written by carlos system host-env write from the deployment's parameters. Do not edit by hand."
// Render is host.env's bytes: one KEY=value line per variable, sorted.
-// Values are written bare, so the file means the same to systemd's
+// Values use bare safe characters, except the quoted fixed-identity map.
+// The file means the same to systemd's
// EnvironmentFile and to a shell that sources it. A value outside the safe
// set (letters, digits and _ . / : , @ + = % -) is refused rather than
// quoted; the error names the variables, never their values, which may be
@@ -242,7 +249,7 @@ func Render(env map[string]string) ([]byte, error) {
keys := make([]string, 0, len(env))
var bad []string
for k, v := range env {
- if !ValidKey(k) || !safeValue.MatchString(v) {
+ if _, ok := renderValue(k, v); !ValidKey(k) || !ok {
bad = append(bad, k)
continue
}
@@ -256,11 +263,33 @@ func Render(env map[string]string) ([]byte, error) {
var b bytes.Buffer
b.WriteString(renderedHeader + "\n")
for _, k := range keys {
- b.WriteString(k + "=" + env[k] + "\n")
+ value, _ := renderValue(k, env[k])
+ b.WriteString(k + "=" + value + "\n")
}
return b.Bytes(), nil
}
+// The binding map alone uses single quotes, preserving its JSON quotes for
+// both shell and systemd readers. Refuse shell syntax and multiline values.
+func renderValue(key, value string) (string, bool) {
+ if key != "CARLOS_HA_FIXED_BOX_IDENTITIES" || value == "" {
+ return value, safeValue.MatchString(value)
+ }
+ if !bindingValue.MatchString(value) {
+ return "", false
+ }
+ var bindings map[string]string
+ if json.Unmarshal([]byte(value), &bindings) != nil || bindings == nil {
+ return "", false
+ }
+ for ref, iid := range bindings {
+ if !controlname.ValidLabel(ref) || !bindingIID.MatchString(iid) {
+ return "", false
+ }
+ }
+ return "'" + value + "'", true
+}
+
// Parse reads an existing host.env: KEY=value lines, with blank lines,
// comments and a leading "export " ignored, and one layer of matching
// quotes removed from a value. A variable set twice, or a line that is
diff --git a/internal/hostenv/write_linux_test.go b/internal/hostenv/write_linux_test.go
index 4aed0f6a0..16fbbad29 100644
--- a/internal/hostenv/write_linux_test.go
+++ b/internal/hostenv/write_linux_test.go
@@ -4,8 +4,10 @@ package hostenv
import (
"os"
+ "os/exec"
"path/filepath"
"strings"
+ "syscall"
"testing"
)
@@ -114,3 +116,62 @@ func safeDir(t *testing.T) string {
}
return dir
}
+
+func TestDepartureHostEnvKeys(t *testing.T) {
+ env := today()
+ env["CARLOS_HA_FIXED_BOX_IDENTITIES"] = `{"peer":"i-1123456789abcdef0", "other":"i-2123456789abcdef0"}`
+ env["CARLOS_TERMINATION_QUEUE_URL"] = "https://sqs.eu-west-1.amazonaws.com/123456789012/terminations"
+ p := &fakeParams{vals: map[string]string{}}
+ if _, err := Seed(t.Context(), p, "example", "ie", env); err != nil {
+ t.Fatal(err)
+ }
+ body, err := Fetch(t.Context(), p, "example", "ie")
+ if err != nil {
+ t.Fatal(err)
+ }
+ root := withHostEnvRoot(t)
+ if err = writeHostEnv(root, body); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(root, "etc", "carlos", "host.env")
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := Parse(data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, key := range []string{"CARLOS_HA_FIXED_BOX_IDENTITIES", "CARLOS_TERMINATION_QUEUE_URL"} {
+ if !Allowed(key) || got[key] != env[key] {
+ t.Fatalf("key=%s got=%q", key, got[key])
+ }
+ }
+ cmd := exec.Command("bash", "--noprofile", "--norc", "-c", `. "$1"; printf '%s' "$CARLOS_HA_FIXED_BOX_IDENTITIES"`, "host-env", path)
+ output, err := cmd.Output()
+ if err != nil || string(output) != env["CARLOS_HA_FIXED_BOX_IDENTITIES"] {
+ t.Fatalf("shell parse: %q %v", output, err)
+ }
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Mode().Perm() != 0600 {
+ t.Fatalf("mode=%v", info.Mode())
+ }
+ stat, ok := info.Sys().(*syscall.Stat_t)
+ if !ok || int(stat.Uid) != os.Geteuid() {
+ t.Fatalf("owner=%v", info.Sys())
+ }
+}
+
+func TestDepartureHostEnvRejectsUnsafeBindings(t *testing.T) {
+ for _, raw := range []string{`null`, `[]`, `{"peer":"$(id)"}`, `{"peer":"i-1123456789abcdef0'"}`, "{\n\"peer\":\"i-1123456789abcdef0\"}", `{"peer/other":"i-1123456789abcdef0"}`, `{"peer":"wrong"}`} {
+ if _, err := Render(map[string]string{"CARLOS_HA_FIXED_BOX_IDENTITIES": raw}); err == nil {
+ t.Errorf("accepted %q", raw)
+ }
+ }
+ if _, err := Render(map[string]string{"CARLOS_HIBERNATE_PREFIX": `{"peer":"i-1123456789abcdef0"}`}); err == nil {
+ t.Fatal("JSON exception escaped its key")
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-p1b3b-t.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-p1b3b-t.tsv
index b2442203b..31809281f 100644
--- a/internal/provision/testdata/plan14-root-reads-region-ha-p1b3b-t.tsv
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-p1b3b-t.tsv
@@ -220,7 +220,7 @@ internal/schedule/runner.go Runner.fire hint E2 accepted-legacy;rev3=census-ruli
@coverage internal/edge 4c522d8c7a17a7508be62e248126a9f66978dd09bdb096678dacf9c9bdffb1a2
@coverage internal/hadeparture 96414c792279b1616004f4d5a3ec00b5eb9f7da3a71888c5a70f85f6649ab0e4
@coverage internal/host fb3d5907fa60faaf9d54d591ce025a1b62200ee235209e2deb858cf26334a42f
-@coverage internal/hostenv 73e273b78febb9102acb9baf06b441e5001b70f5c96b38fefc64bb50c6e726a7
+@coverage internal/hostenv d5e9735d49727a6e7ab2b0e1886dae1c170d4033dc46cb314ab9569a7a964587
@coverage internal/hostfiles 21a32d89c6143031af13cb18bc1a2227353ed8595ab23bde7abd1e9d2df92eaf
@coverage internal/lease 46a3a2a7f3215d5f717bd23655bdaec7b78307f58dad0decb8a5fecbe06912f5
@coverage internal/metrics f6382028853ea94ef1f962546281cfd1d0351dd597193f73f593d70623f695d0