//go:build linux package layout import ( "errors" "os" "path/filepath" "strconv" "strings" "syscall" "testing" "time" "github.com/carlosframework/platform/internal/instancefs" "github.com/carlosframework/platform/internal/registry" ) func TestPreflightRefusesAConfigEnvOwnedByAnotherRoute(t *testing.T) { p, _ := PlanFor("/data", "/run/carlos", "x.example.com", ModeNested) routes := []registry.Route{{Host: "x.example.com"}, {Host: "x.example.com.config"}} err := Preflight(p, routes) if err == nil || !strings.Contains(err.Error(), "x.example.com.config") { t.Fatalf("ambiguous config-env accepted: %v", err) } if err := Preflight(p, []registry.Route{{Host: "x.example.com"}}); err != nil { t.Fatalf("unambiguous plan refused: %v", err) } // Reverting applies the same table: a flat destination another route owns is a refusal. r, _ := PlanFor("/data", "/run/carlos", "x.example.com", ModeFlat) if err := Preflight(r, routes); err == nil { t.Fatal("revert onto another route's file accepted") } // The other direction of the same rule: a host named .config // has an env file that is also 's rendered bundle. c, _ := PlanFor("/data", "/run/carlos", "x.example.com.config", ModeNested) if err := Preflight(c, routes); err == nil || !strings.Contains(err.Error(), "x.example.com") { t.Fatalf("an env file that is another route's bundle accepted: %v", err) } } // The same collision through the sidecar env: a route named -sidecar // owns -sidecar.env as its instance env, and h's plan would move it as // h's sidecar env. func TestPreflightRefusesASidecarEnvOwnedByAnotherRoute(t *testing.T) { routes := []registry.Route{{Host: "x.example.com"}, {Host: "x.example.com-sidecar"}} p, _ := PlanFor("/data", "/run/carlos", "x.example.com", ModeNested) err := Preflight(p, routes) if err == nil || !strings.Contains(err.Error(), "x.example.com-sidecar.env") || !strings.Contains(err.Error(), "x.example.com-sidecar (its instance env)") { t.Fatalf("ambiguous sidecar env accepted: %v", err) } if err := Preflight(p, []registry.Route{{Host: "x.example.com"}}); err != nil { t.Fatalf("unambiguous plan refused: %v", err) } r, _ := PlanFor("/data", "/run/carlos", "x.example.com", ModeFlat) if err := Preflight(r, routes); err == nil { t.Fatal("revert onto another route's sidecar env accepted") } // The other direction: the host named -sidecar has an env file // that is also 's sidecar env. c, _ := PlanFor("/data", "/run/carlos", "x.example.com-sidecar", ModeNested) if err := Preflight(c, routes); err == nil || !strings.Contains(err.Error(), "x.example.com (its sidecar env)") { t.Fatalf("an env file that is another route's sidecar env accepted: %v", err) } } // A nested socket's control twin must fit a unix socket address. The // socket dir here is long enough that the nested address overflows it. func TestPreflightRefusesANestedSocketTooLongForItsControlTwin(t *testing.T) { long := "/" + strings.Repeat("s", 60) host := strings.Repeat("h", 30) + ".example.com" p, _ := PlanFor("/data", long, host, ModeNested) want := len(p.To.Socket) + len(".control") err := Preflight(p, []registry.Route{{Host: host}}) if err == nil || !strings.Contains(err.Error(), "107") || !strings.Contains(err.Error(), strconv.Itoa(want)) { t.Fatalf("overlong socket accepted or not measured: %v (want %d named)", err, want) } // Reverting to flat does not create the nested address, so it is not // measured. r, _ := PlanFor("/data", long, host, ModeFlat) if err := Preflight(r, []registry.Route{{Host: host}}); err != nil { t.Fatalf("revert refused over a nested length: %v", err) } } func TestDestinationCheckRefusesTwoDatabasesAndMovesEnvAside(t *testing.T) { dd := t.TempDir() p, _ := PlanFor(dd, filepath.Join(dd, "run"), "h.example.com", ModeNested) if err := os.MkdirAll(rawInstanceDir(dd, "h.example.com"), 0o700); err != nil { t.Fatal(err) } if err := os.WriteFile(p.Artifacts[0].Dst, []byte("x"), 0o600); err != nil { t.Fatal(err) } if _, err := DestinationCheck(p, time.Now); err == nil || !strings.Contains(err.Error(), "two databases") { t.Fatalf("two databases not refused: %v", err) } os.Remove(p.Artifacts[0].Dst) if err := os.WriteFile(p.Artifacts[3].Dst, []byte("fresh env minted by an older binary"), 0o600); err != nil { t.Fatal(err) } aside, err := DestinationCheck(p, func() time.Time { return time.Unix(1700000000, 0) }) if err != nil { t.Fatal(err) } if len(aside) != 1 || !strings.HasSuffix(aside[0], ".env.aside-1700000000") { t.Fatalf("aside = %v", aside) } if _, err := os.Stat(p.Artifacts[3].Dst); !os.IsNotExist(err) { t.Error("env destination still occupied") } if b, err := os.ReadFile(aside[0]); err != nil || string(b) != "fresh env minted by an older binary" { t.Errorf("aside copy: %q %v", b, err) } } func artifactNamed(t *testing.T, p *Plan, name string) Artifact { t.Helper() for _, a := range p.Artifacts { if a.Name == name { return a } } t.Fatalf("no artifact %q", name) return Artifact{} } // A litestream shadow already at the destination is a second replication // state for one database: refused like a second database. A quarantine // already there is moved aside like an env file, and the rendered bundle // is cleared so the source takes its name. func TestDestinationCheckShadowRefusesCorruptAsideConfigCleared(t *testing.T) { dd := t.TempDir() host := "h.example.com" p, _ := PlanFor(dd, filepath.Join(dd, "run"), host, ModeNested) if err := os.MkdirAll(rawInstanceDir(dd, host), 0o700); err != nil { t.Fatal(err) } shadow := artifactNamed(t, p, "litestream-shadow").Dst if err := os.Mkdir(shadow, 0o700); err != nil { t.Fatal(err) } if _, err := DestinationCheck(p, time.Now); err == nil || !strings.Contains(err.Error(), "two replication states") { t.Fatalf("destination shadow not refused: %v", err) } os.Remove(shadow) corrupt := artifactNamed(t, p, "corrupt").Dst config := artifactNamed(t, p, "config-env").Dst for _, f := range []string{corrupt, config} { if err := os.WriteFile(f, []byte("old"), 0o600); err != nil { t.Fatal(err) } } aside, err := DestinationCheck(p, func() time.Time { return time.Unix(1700000000, 0) }) if err != nil { t.Fatal(err) } // The kept copy lives under the pass's own aside directory, outside // the instance tree (review F3). if len(aside) != 1 || aside[0] != filepath.Join(dd, "layout", "aside", host, filepath.Base(corrupt)+".aside-1700000000") { t.Fatalf("aside = %v", aside) } for _, f := range []string{corrupt, config} { if _, err := os.Lstat(f); !errors.Is(err, os.ErrNotExist) { t.Errorf("%s still occupied", f) } } } // The reverse direction checks the flat side the same way. func TestDestinationCheckRefusesADatabaseAtTheFlatPathOnRevert(t *testing.T) { dd := t.TempDir() p, _ := PlanFor(dd, filepath.Join(dd, "run"), "h.example.com", ModeFlat) if err := os.WriteFile(filepath.Join(dd, "h.example.com.db-wal"), []byte("w"), 0o600); err != nil { t.Fatal(err) } if _, err := DestinationCheck(p, time.Now); err == nil || !strings.Contains(err.Error(), "two databases") { t.Fatalf("a flat wal on revert not refused: %v", err) } } func TestEnsureDirsCreatesTheRawDirectoriesWithTheRightModes(t *testing.T) { dd, rd := t.TempDir(), t.TempDir() if err := EnsureDirs(dd, rd, "h.example.com", -1); err != nil { t.Fatal(err) } fi, err := os.Lstat(rawInstanceDir(dd, "h.example.com")) if err != nil || !fi.IsDir() || fi.Mode().Perm() != 0o700 { t.Errorf("data dir: %v %v", fi, err) } fi, err = os.Lstat(rawRunDir(rd, "h.example.com")) if err != nil || !fi.IsDir() || fi.Mode().Perm() != 0o750 { t.Errorf("run dir: %v %v", fi, err) } // Idempotent: the pass calls it on every move. if err := EnsureDirs(dd, rd, "h.example.com", -1); err != nil { t.Fatalf("second call: %v", err) } } func TestEnsureDirsRefusesASymlinkAtTheInstanceDirectory(t *testing.T) { dd, rd, elsewhere := t.TempDir(), t.TempDir(), t.TempDir() host := "h.example.com" raw := rawInstanceDir(dd, host) if err := os.MkdirAll(filepath.Dir(raw), 0o700); err != nil { t.Fatal(err) } if err := os.Symlink(elsewhere, raw); err != nil { t.Fatal(err) } if err := EnsureDirs(dd, rd, host, -1); !errors.Is(err, instancefs.ErrSymlink) { t.Fatalf("err = %v, want ErrSymlink", err) } } // supplementaryGroup is a group the test runner is in other than its // effective one, so a directory can be given a group that inheritance // alone explains. The runner is not assumed to be root. func supplementaryGroup(t *testing.T) int { t.Helper() groups, err := os.Getgroups() if err != nil { t.Fatal(err) } probe := t.TempDir() for _, g := range groups { // A group the runner is listed in can still be unusable: inside a // user namespace an unmapped gid is refused with EINVAL. if g != os.Getegid() && os.Chown(probe, -1, g) == nil { return g } } t.Skip("the test runner is in no usable supplementary group, so a setgid parent with a group other than its own cannot be built") return -1 } func gidOf(t *testing.T, path string) int { t.Helper() fi, err := os.Lstat(path) if err != nil { t.Fatal(err) } return int(fi.Sys().(*syscall.Stat_t).Gid) } // runParentFixture makes /.instances with group gid and mode, the way // tmpfiles leaves it on a box, and the data parent 0700. func runParentFixture(t *testing.T, dd, rd string, gid int, mode os.FileMode) string { t.Helper() host := "h.example.com" parent := filepath.Dir(rawRunDir(rd, host)) if err := os.Mkdir(parent, 0o700); err != nil { t.Fatal(err) } if err := os.Chown(parent, -1, gid); err != nil { t.Fatal(err) } if err := os.Chmod(parent, mode); err != nil { t.Fatal(err) } if err := os.Mkdir(filepath.Dir(rawInstanceDir(dd, host)), 0o700); err != nil { t.Fatal(err) } return parent } // The pass runs as carlos, which is not in carlos-sockets, so it can // neither chown into that group nor chmod a directory of it without the // kernel clearing setgid. The instance's run directory gets the group and // setgid by inheritance alone, and the tmpfiles-owned parents are never // touched. The parent's mode here is deliberately not the 2750 tmpfiles // gives it, so any chmod of it shows. func TestEnsureDirsInheritsTheSocketsGroupAndLeavesTheParentsAlone(t *testing.T) { g := supplementaryGroup(t) dd, rd := t.TempDir(), t.TempDir() host := "h.example.com" runParent := runParentFixture(t, dd, rd, g, 0o770|os.ModeSetgid) dataParent := filepath.Dir(rawInstanceDir(dd, host)) if err := os.Chmod(dataParent, 0o710); err != nil { t.Fatal(err) } before := map[string]os.FileMode{} for _, d := range []string{runParent, dataParent} { fi, err := os.Lstat(d) if err != nil { t.Fatal(err) } before[d] = fi.Mode() } for i := 0; i < 2; i++ { if err := EnsureDirs(dd, rd, host, g); err != nil { t.Fatalf("call %d: %v", i+1, err) } } run := rawRunDir(rd, host) fi, err := os.Lstat(run) if err != nil || !fi.IsDir() || fi.Mode().Perm() != 0o750 || fi.Mode()&os.ModeSetgid == 0 { t.Fatalf("run dir: %v %v, want a 2750 directory", fi, err) } if got := gidOf(t, run); got != g { t.Errorf("run dir group = %d, want the inherited %d", got, g) } for d, mode := range before { fi, err := os.Lstat(d) if err != nil { t.Fatal(err) } if fi.Mode() != mode { t.Errorf("%s mode changed from %v to %v; the pass must never chmod a tmpfiles-owned parent", d, mode, fi.Mode()) } } if got := gidOf(t, runParent); got != g { t.Errorf("run parent group changed to %d", got) } } // A run parent that has lost setgid, or carries the wrong group, would // hand every new instance directory the wrong group. The pass refuses, // names the parent, repairs nothing and creates nothing. func TestEnsureDirsRefusesARunParentWithoutSetgidOrTheSocketsGroup(t *testing.T) { g := supplementaryGroup(t) for _, tc := range []struct { name string gid int mode os.FileMode }{ {"no setgid", g, 0o750}, {"wrong group", os.Getegid(), 0o750 | os.ModeSetgid}, } { t.Run(tc.name, func(t *testing.T) { dd, rd := t.TempDir(), t.TempDir() host := "h.example.com" parent := runParentFixture(t, dd, rd, tc.gid, tc.mode) err := EnsureDirs(dd, rd, host, g) if err == nil || !strings.Contains(err.Error(), parent) || !strings.Contains(err.Error(), "tmpfiles should restore it") { t.Fatalf("err = %v, want a refusal naming %s", err, parent) } for _, d := range []string{rawInstanceDir(dd, host), rawRunDir(rd, host)} { if _, err := os.Lstat(d); !errors.Is(err, os.ErrNotExist) { t.Errorf("%s was created by a refused call", d) } } fi, _ := os.Lstat(parent) if fi.Mode() != os.ModeDir|tc.mode || gidOf(t, parent) != tc.gid { t.Errorf("parent repaired to %v group %d", fi.Mode(), gidOf(t, parent)) } }) } } // An instance directory already there with the wrong group, without the // setgid its parent has, or with the wrong mode is refused as it stands: // changing it is exactly the chmod or chown the pass cannot do safely. func TestEnsureDirsRefusesAnExistingInstanceDirectoryItCannotVouchFor(t *testing.T) { g := supplementaryGroup(t) host := "h.example.com" for _, tc := range []struct { name string setup func(t *testing.T, dd, rd string) string }{ {"run dir with the wrong group", func(t *testing.T, dd, rd string) string { d := rawRunDir(rd, host) if err := os.Mkdir(d, 0o750); err != nil { t.Fatal(err) } if err := os.Chown(d, -1, os.Getegid()); err != nil { t.Fatal(err) } if err := os.Chmod(d, 0o750|os.ModeSetgid); err != nil { t.Fatal(err) } return d }}, {"run dir without setgid", func(t *testing.T, dd, rd string) string { d := rawRunDir(rd, host) if err := os.Mkdir(d, 0o750); err != nil { t.Fatal(err) } if err := os.Chmod(d, 0o750); err != nil { t.Fatal(err) } return d }}, {"data dir opened up", func(t *testing.T, dd, rd string) string { d := rawInstanceDir(dd, host) if err := os.Mkdir(d, 0o700); err != nil { t.Fatal(err) } if err := os.Chmod(d, 0o755); err != nil { t.Fatal(err) } return d }}, } { t.Run(tc.name, func(t *testing.T) { dd, rd := t.TempDir(), t.TempDir() runParentFixture(t, dd, rd, g, 0o750|os.ModeSetgid) d := tc.setup(t, dd, rd) before, err := os.Lstat(d) if err != nil { t.Fatal(err) } gid := gidOf(t, d) if err := EnsureDirs(dd, rd, host, g); err == nil || !strings.Contains(err.Error(), d) { t.Fatalf("err = %v, want a refusal naming %s", err, d) } after, _ := os.Lstat(d) if after.Mode() != before.Mode() || gidOf(t, d) != gid { t.Errorf("%s changed from %v group %d to %v group %d", d, before.Mode(), gid, after.Mode(), gidOf(t, d)) } }) } } // Review F1, amended by the landing follow-up: a flat tenant can make a // sibling's future directory ahead of the pass and hard-link the box's // credentials into it. The entry is quarantined into the host's aside // directory, outside every namespace, and the migration goes on: a // refusal would have let one tenant hold a sibling down with a touch. // The link itself moves as an entry, so the credentials file keeps its // own name and the quarantined name is harmless where it now sits. func TestDestinationCheckQuarantinesEntriesThePlanDoesNotName(t *testing.T) { dd := t.TempDir() host := "h.example.com" p, _ := PlanFor(dd, filepath.Join(dd, "run"), host, ModeNested) raw := rawInstanceDir(dd, host) if err := os.MkdirAll(raw, 0o700); err != nil { t.Fatal(err) } secret := filepath.Join(dd, "litestream.env") if err := os.WriteFile(secret, []byte("AWS_SECRET_ACCESS_KEY=x\n"), 0o600); err != nil { t.Fatal(err) } if err := os.Link(secret, filepath.Join(raw, "creds")); err != nil { t.Skipf("hard links unavailable here: %v", err) } if err := os.Mkdir(filepath.Join(raw, "stash"), 0o700); err != nil { t.Fatal(err) } if err := os.Symlink(secret, filepath.Join(raw, "link")); err != nil { t.Fatal(err) } aside, err := DestinationCheck(p, time.Now) if err != nil { t.Fatalf("planted entries not quarantined: %v", err) } if len(aside) != 3 { t.Fatalf("aside = %v, want the three planted entries", aside) } for _, a := range aside { if !strings.HasPrefix(a, filepath.Join(dd, "layout", "aside", host)+"/") || !strings.Contains(filepath.Base(a), ".q-") { t.Errorf("quarantined to %s, want under layout/aside/%s with a .q- suffix", a, host) } } entries, err := os.ReadDir(raw) if err != nil || len(entries) != 0 { t.Errorf("instance directory still holds %v (%v)", entries, err) } // The credentials file is untouched and still has its own name. if fi, err := os.Lstat(secret); err != nil { t.Errorf("litestream.env: %v", err) } else if n, _ := linkCount(fi); n != 2 { t.Errorf("litestream.env has %d names; the quarantined link should still be one of them", n) } // The revert direction's destination is the flat directory, where the // rule cannot apply; nothing there is touched for being unplanned. rev, _ := PlanFor(dd, filepath.Join(dd, "run"), host, ModeFlat) if moved, err := DestinationCheck(rev, time.Now); err != nil || len(moved) != 0 { t.Fatalf("revert touched the flat directory's other files: %v %v", moved, err) } } // A planted entry at a PLANNED name is handled by that name's rule, and // the aside copy ends up outside the instance tree (review F3), where no // instance namespace reaches: a tenant must not read what a previous // owner of its hostname, or a sibling, left at that name. func TestDestinationCheckKeepsAsidesOutsideTheInstanceTree(t *testing.T) { dd := t.TempDir() host := "h.example.com" p, _ := PlanFor(dd, filepath.Join(dd, "run"), host, ModeNested) if err := os.MkdirAll(rawInstanceDir(dd, host), 0o700); err != nil { t.Fatal(err) } env := artifactNamed(t, p, "env").Dst if err := os.WriteFile(env, []byte("CARLOS_ADMIN_TOKEN=previous-owner\n"), 0o600); err != nil { t.Fatal(err) } aside, err := DestinationCheck(p, func() time.Time { return time.Unix(1700000000, 0) }) if err != nil { t.Fatal(err) } want := filepath.Join(dd, "layout", "aside", host, host+".env.aside-1700000000") if len(aside) != 1 || aside[0] != want { t.Fatalf("aside = %v, want %s", aside, want) } if b, err := os.ReadFile(want); err != nil || string(b) != "CARLOS_ADMIN_TOKEN=previous-owner\n" { t.Errorf("aside copy: %q %v", b, err) } entries, err := os.ReadDir(rawInstanceDir(dd, host)) if err != nil || len(entries) != 0 { t.Errorf("instance directory still holds %v (%v); the aside must live outside it", entries, err) } // The aside directory is not a journal: JournalHosts lists hosts from // *.json only, so the layout directory's new child does not read as a // fenced host. if hosts, err := JournalHosts(dd); err != nil || len(hosts) != 0 { t.Errorf("JournalHosts = %v %v with only an aside directory present", hosts, err) } } // LinkCheck refuses a file with a second name, a hard link inside the // shadow directory included, and a symlink inside it; a file with one // name passes. func TestLinkCheckRefusesASecondNameAndWalksTheShadow(t *testing.T) { dd := t.TempDir() host := "h.example.com" p, _ := PlanFor(dd, filepath.Join(dd, "run"), host, ModeNested) db := artifactNamed(t, p, "db") shadow := artifactNamed(t, p, "litestream-shadow") if err := os.WriteFile(db.Src, []byte("db"), 0o600); err != nil { t.Fatal(err) } if err := os.MkdirAll(filepath.Join(shadow.Src, "generations"), 0o700); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(shadow.Src, "generations", "g"), []byte("g"), 0o600); err != nil { t.Fatal(err) } for i := range p.Artifacts { p.Artifacts[i].Present = p.Artifacts[i].Name == "db" || p.Artifacts[i].Name == "litestream-shadow" } src := func(a Artifact) string { return a.Src } if err := LinkCheck(p, src); err != nil { t.Fatalf("clean plan refused: %v", err) } other := filepath.Join(dd, "sibling.db") if err := os.WriteFile(other, []byte("sibling"), 0o600); err != nil { t.Fatal(err) } planted := filepath.Join(shadow.Src, "generations", "sibling") if err := os.Link(other, planted); err != nil { t.Skipf("hard links unavailable here: %v", err) } if err := LinkCheck(p, src); err == nil || !strings.Contains(err.Error(), "2 names") { t.Fatalf("hard link in the shadow not refused: %v", err) } os.Remove(planted) if err := os.Symlink(other, planted); err != nil { t.Fatal(err) } if err := LinkCheck(p, src); err == nil || !strings.Contains(err.Error(), "not a regular file") { t.Fatalf("symlink in the shadow not refused: %v", err) } os.Remove(planted) if err := os.Link(db.Src, filepath.Join(dd, "second-name.db")); err != nil { t.Fatal(err) } if err := LinkCheck(p, src); err == nil || !strings.Contains(err.Error(), "2 names") { t.Fatalf("database with two names not refused: %v", err) } }