diff --git a/internal/apply/apply.go b/internal/apply/apply.go index f6efe674..cdd9862f 100644 --- a/internal/apply/apply.go +++ b/internal/apply/apply.go @@ -794,6 +794,10 @@ func applyScoped( in.agentHomes = rootNeverHomes(d) in.dirsBefore = map[string]bool{} in.files = declaredFiles(d.Resources) + in.placed = placedPaths(d.Resources) + if scope != nil { + in.placed = placedPaths(d.Resources, scope.Others) + } for _, resource := range d.Resources { in.declares[resource.Identity()] = declaredDigest(resource) if dir, ok := resource.(*declaration.Directory); ok { @@ -1603,7 +1607,7 @@ func applyOne(ctx context.Context, sys system.System, r declaration.Resource, ru } switch res := r.(type) { case *declaration.Directory: - return applyDirectory(res, previous, in.dirsBefore[filepath.Clean(res.Path)]) + return applyDirectory(res, previous, in.dirsBefore[filepath.Clean(res.Path)], in.placed) case *declaration.File: return applyFile(res, previous, unseal, keepFound) case *declaration.Service: @@ -1705,7 +1709,11 @@ func modeOf(spec string, fallback os.FileMode) (os.FileMode, error) { // directory is the mesh's when its record says the mesh applied it at this path before (a record from before // this rule counts, which is every directory on a running machine), when this apply made it, or when it // already has the declared owner and mode, so a person who sets them by hand at the machine hands it over. -func applyDirectory(r *declaration.Directory, previous store.Applied, wasBefore bool) (Outcome, error) { +// +// **A directory whose owner changes gives its contents the new owner too** (H-A-545 (2), H-A-550): what its previous +// owner held below it, but for the paths placed names (every path the declaration places) and what lies below them +// (giveContents). +func applyDirectory(r *declaration.Directory, previous store.Applied, wasBefore bool, placed map[string]bool) (Outcome, error) { out := begin(r) mode, err := dirModeOf(r.Mode, 0o755) if err != nil { @@ -1776,7 +1784,7 @@ func applyDirectory(r *declaration.Directory, previous store.Applied, wasBefore // Outside every home, made and given its mode and owner only through a descriptor opened from /, following // no link another account could have made (novox/hq issue 358, mesh_dirs.go). if meshDirsByDescriptor && homeAbove(r.Path) == "" { - return applyMeshDirectory(r, out, mode, existed) + return applyMeshDirectory(r, out, mode, existed, placed) } if !existed { if err := makeDirs(r.Path, mode, r.Owner); err != nil { @@ -1810,6 +1818,11 @@ func applyDirectory(r *declaration.Directory, previous store.Applied, wasBefore if err := own(r.Path, r.Owner); err != nil { return out, err } + if existed { + if err := giveContentsTo(r, before, placed); err != nil { + return out, err + } + } } out.Action = "unchanged" @@ -2802,6 +2815,9 @@ type inputs struct { // dirsBefore is every declared directory that was on the machine when this apply began (novox/hq issue // 339): one the apply itself made — a file's parent — is the mesh's, one that was there may not be. dirsBefore map[string]bool + // placed is every path the declaration and the other modules' compositions place (Scope.Others): a directory whose + // owner changes leaves them to their own resource when it gives its contents the new owner (H-A-550). + placed map[string]bool // held is the root of every library whose disk or mount is not there, with its name: no container that mounts // it is created (novox/hq ADR 0328 §9). held map[string]string diff --git a/internal/apply/contents_owner.go b/internal/apply/contents_owner.go new file mode 100644 index 00000000..58fe7a42 --- /dev/null +++ b/internal/apply/contents_owner.go @@ -0,0 +1,97 @@ +package apply + +// A directory whose owner changes gives its contents the new owner too (design 47 H2, H-A-545 (2), H-A-550): a module +// moved to an account of its own (runs-as) keeps reading what it wrote as the account it ran as before, and nobody +// changes an owner by hand. +// +// Only what the directory's previous owner held, and only what no resource of the declaration places: a path the +// declaration places (a directory or a file of its own, gitea's data below its state) keeps its declared owner, and +// nothing below it is touched; an entry another account owns is left, and nothing below it is walked. No link is +// followed (a link is owned as a link, Lchown), and the walk stays on the directory's file system. + +import ( + "fmt" + "io/fs" + "os" + "path/filepath" + + "git.novox.be/novox/mesh-sdk/go/declaration" +) + +// giveContents gives every entry below dir that from (uid, gid) owns to the new owner to (uid, gid), but for the paths +// placed names (cleaned paths the declaration places) and what lies below them, an entry from does not own and what lies +// below it, and what lies on another file system. Answers how many entries changed hands. +func giveContents(dir string, from, to [2]int, placed map[string]bool) (int, error) { + root := filepath.Clean(dir) + device, err := deviceOf(root) + if err != nil { + return 0, fmt.Errorf("the file system of %s cannot be read: %w", root, err) + } + given := 0 + err = filepath.WalkDir(root, func(path string, e fs.DirEntry, err error) error { + if err != nil { + return err + } + if path == root { + return nil + } + skip := func() error { + if e.IsDir() { + return filepath.SkipDir + } + return nil + } + if placed[filepath.Clean(path)] { + return skip() + } + info, err := os.Lstat(path) + if err != nil { + return err + } + uid, gid, ok := statOwner(info) + if !ok || uid != from[0] || gid != from[1] { + return skip() + } + if e.IsDir() { + if d, derr := deviceOf(path); derr != nil || d != device { + return filepath.SkipDir + } + } + if err := lchownContent(path, to[0], to[1]); err != nil { + return fmt.Errorf("cannot give %s to the directory's new owner: %w", path, err) + } + given++ + return nil + }) + return given, err +} + +// lchownContent owns one entry as itself, a link as a link; a variable so a test sees what was given without being root. +var lchownContent = os.Lchown + +// placedPaths is every path the resources place, cleaned: what giveContents leaves to its own resource. +func placedPaths(resources ...[]declaration.Resource) map[string]bool { + out := map[string]bool{} + for _, list := range resources { + for _, r := range list { + if t := r.Target(); t != "" { + out[filepath.Clean(t)] = true + } + } + } + return out +} + +// giveContentsTo gives the contents of the directory r, found as before, to r's declared owner (giveContents). +func giveContentsTo(r *declaration.Directory, before os.FileInfo, placed map[string]bool) error { + fromUID, fromGID, ok := statOwner(before) + if !ok || r.Owner == "" { + return nil + } + uid, gid, err := idsOf(r.Owner) + if err != nil { + return fmt.Errorf("%s should belong to %q: %w", r.Path, r.Owner, err) + } + _, err = giveContents(r.Path, [2]int{fromUID, fromGID}, [2]int{uid, gid}, placed) + return err +} diff --git a/internal/apply/contents_owner_test.go b/internal/apply/contents_owner_test.go new file mode 100644 index 00000000..5b31526c --- /dev/null +++ b/internal/apply/contents_owner_test.go @@ -0,0 +1,95 @@ +package apply + +import ( + "os" + "path/filepath" + "sort" + "strings" + "testing" + + "git.novox.be/novox/mesh-sdk/go/declaration" +) + +// A directory whose owner changes gives its contents the new owner (H-A-545 (2), H-A-550): what its previous owner +// held, never a path the declaration places (a declared child with the same previous owner keeps its owner, and what +// lies below it), never what another account owns, never through a link, never on another file system. +func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) { + me, myGroup := os.Getuid(), os.Getgid() + to := [2]int{me + 4242, myGroup + 4242} + cases := []struct { + name string + from [2]int + placed func(root string) []string + other string // a directory the stand-in deviceOf says is on another file system + want []string + }{ + {name: "what the previous owner wrote is given", from: [2]int{me, myGroup}, + want: []string{"data", "data/repo", "kept", "kept/webhook.secret", "link", "token"}}, + {name: "a declared child with the same previous owner keeps its owner, and what lies below it", + from: [2]int{me, myGroup}, placed: func(root string) []string { return []string{filepath.Join(root, "data")} }, + want: []string{"kept", "kept/webhook.secret", "link", "token"}}, + {name: "what another account owns is left", from: [2]int{me + 1, myGroup}}, + {name: "another file system is not crossed", from: [2]int{me, myGroup}, other: "kept", + want: []string{"data", "data/repo", "link", "token"}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + outside := t.TempDir() + if err := os.WriteFile(filepath.Join(outside, "elsewhere"), []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + root := t.TempDir() + for _, d := range []string{"data", "kept"} { + if err := os.Mkdir(filepath.Join(root, d), 0o700); err != nil { + t.Fatal(err) + } + } + for _, f := range []string{"data/repo", "kept/webhook.secret", "token"} { + if err := os.WriteFile(filepath.Join(root, f), []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + } + // A link to a directory outside: owned as a link, and never followed. + if err := os.Symlink(outside, filepath.Join(root, "link")); err != nil { + t.Fatal(err) + } + var given []string + wasChown, wasDevice := lchownContent, deviceOf + t.Cleanup(func() { lchownContent, deviceOf = wasChown, wasDevice }) + lchownContent = func(path string, uid, gid int) error { + if uid != to[0] || gid != to[1] { + t.Errorf("%s given to %d:%d, want %d:%d", path, uid, gid, to[0], to[1]) + } + rel, _ := filepath.Rel(root, path) + given = append(given, rel) + return nil + } + deviceOf = func(path string) (uint64, error) { + if c.other != "" && filepath.Clean(path) == filepath.Join(root, c.other) { + return 2, nil + } + return 1, nil + } + placed := map[string]bool{} + if c.placed != nil { + for _, p := range c.placed(root) { + placed[filepath.Clean(p)] = true + } + } + n, err := giveContents(root, c.from, to, placed) + if err != nil { + t.Fatal(err) + } + sort.Strings(given) + if n != len(c.want) || strings.Join(given, ",") != strings.Join(c.want, ",") { + t.Fatalf("gave %d: %v, want %v", n, given, c.want) + } + }) + } + // The placed paths are every resource's target, cleaned. + got := placedPaths([]declaration.Resource{&declaration.Directory{Path: "/var/lib/gitea/data/"}}, + []declaration.Resource{&declaration.File{Path: "/var/lib/gitea/server.env"}}) + if !got["/var/lib/gitea/data"] || !got["/var/lib/gitea/server.env"] || len(got) != 2 { + t.Fatalf("placed %v", got) + } +} diff --git a/internal/apply/converge_dirs.go b/internal/apply/converge_dirs.go index c210a09f..2ba31001 100644 --- a/internal/apply/converge_dirs.go +++ b/internal/apply/converge_dirs.go @@ -19,6 +19,7 @@ func ConvergeDirectories(d *declaration.Declaration, known store.State) []string return nil } var lines []string + placed := placedPaths(d.Resources) for _, r := range d.Resources { dir, ok := r.(*declaration.Directory) if !ok { @@ -36,7 +37,7 @@ func ConvergeDirectories(d *declaration.Declaration, known store.State) []string lines = append(lines, fmt.Sprintf("%s (%s) cannot be judged at this start: %v", dir.Path, dir.ID, err)) continue } - out, err := applyDirectory(dir, rec, true) + out, err := applyDirectory(dir, rec, true, placed) switch { case err != nil: lines = append(lines, fmt.Sprintf("%s (%s) is %s and cannot be set right at this start: %v", dir.Path, dir.ID, drift, err)) diff --git a/internal/apply/mesh_dirs_apply_linux.go b/internal/apply/mesh_dirs_apply_linux.go index 5e62b607..a564ae41 100644 --- a/internal/apply/mesh_dirs_apply_linux.go +++ b/internal/apply/mesh_dirs_apply_linux.go @@ -36,7 +36,10 @@ func openMeshDir(path string, mode os.FileMode, made func(dir string, fd int) er // (novox/hq issue 358): opened by openMeshDir, made there when missing, judged a directory by fstat on it, changed // with fchmod and fchown on it, and read back from it. The parents it makes inside the owner's home are the owner's, // as makeDirs gives them (novox/hq ADR 0182). -func applyMeshDirectory(r *declaration.Directory, out Outcome, mode os.FileMode, existed bool) (Outcome, error) { +// +// Its owner changed, it gives its contents the new owner too, but for what placed names (giveContents; H-A-545 (2), +// H-A-550). +func applyMeshDirectory(r *declaration.Directory, out Outcome, mode os.FileMode, existed bool, placed map[string]bool) (Outcome, error) { uid, gid, chown := 0, 0, r.Owner != "" var err error if chown { @@ -92,6 +95,11 @@ func applyMeshDirectory(r *declaration.Directory, out Outcome, mode os.FileMode, if err := unix.Fchmod(fd, unixDirMode(mode)); err != nil { return out, &os.PathError{Op: "chmod", Path: r.Path, Err: err} } + if existed && !created { + if _, err := giveContents(walk.At, [2]int{beforeUID, beforeGID}, [2]int{uid, gid}, placed); err != nil { + return out, err + } + } } // Read back, from the descriptor that was changed. diff --git a/internal/apply/mesh_dirs_test.go b/internal/apply/mesh_dirs_test.go index 0cfdbfab..d909bddb 100644 --- a/internal/apply/mesh_dirs_test.go +++ b/internal/apply/mesh_dirs_test.go @@ -28,7 +28,7 @@ func testALinkOnlyRootCouldMakeIsFollowed(t *testing.T) { base, r, previous := aMeshDirectory(t) target := swapParentForLink(t, base, to(base)) - out, err := applyDirectory(r, previous, true) + out, err := applyDirectory(r, previous, true, nil) if err != nil { t.Fatalf("a directory behind a root-only link was refused: %v", err) } @@ -48,7 +48,7 @@ func testALinkAnotherAccountOwnsIsRefused(t *testing.T) { base, r, previous := aMeshDirectory(t) target := swapParentForLink(t, base, filepath.Join(base, "elsewhere")) - _, err := applyDirectory(r, previous, true) + _, err := applyDirectory(r, previous, true, nil) if err == nil || !strings.Contains(err.Error(), "mallory") { t.Fatalf("a link another account owns was not refused naming it: %v", err) } @@ -68,7 +68,7 @@ func testAMissingDirectoryIsMadeBehindARootOnlyLink(t *testing.T) { t.Fatal(err) } r := &declaration.Directory{ID: "mod.state", Path: filepath.Join(base, "link", "a", "b"), Mode: "0750"} - out, err := applyDirectory(r, store.Applied{}, false) + out, err := applyDirectory(r, store.Applied{}, false, nil) if err != nil { t.Fatal(err) } diff --git a/internal/apply/mesh_tree_found_test.go b/internal/apply/mesh_tree_found_test.go index 247d3ead..cee31e7c 100644 --- a/internal/apply/mesh_tree_found_test.go +++ b/internal/apply/mesh_tree_found_test.go @@ -115,7 +115,7 @@ func testALinkInTheMeshsTreeLeadingOutOfItIsNotTheTree(t *testing.T) { t.Fatal(err) } r := &declaration.Directory{ID: "postgres.data", Path: filepath.Join(meshDataRoot, "postgres", "data"), Mode: "0750"} - out, err := applyDirectory(r, store.Applied{}, true) + out, err := applyDirectory(r, store.Applied{}, true, nil) if err != nil { t.Fatal(err) } diff --git a/internal/apply/replay358_test.go b/internal/apply/replay358_test.go index a9ba1c73..29ff9e0d 100644 --- a/internal/apply/replay358_test.go +++ b/internal/apply/replay358_test.go @@ -23,7 +23,7 @@ func aMeshDirectory(t *testing.T) (base string, r *declaration.Directory, previo t.Helper() base = t.TempDir() r = &declaration.Directory{ID: "mod.state", Path: filepath.Join(base, "parent", "state"), Mode: "0700"} - out, err := applyDirectory(r, store.Applied{}, false) + out, err := applyDirectory(r, store.Applied{}, false, nil) if err != nil { t.Fatalf("the first apply: %v", err) } @@ -69,7 +69,7 @@ func TestAParentSwappedForALinkLeavesItsTargetUntouched(t *testing.T) { base, r, previous := aMeshDirectory(t) target := swapParentForLink(t, base, filepath.Join(base, "elsewhere")) - _, err := applyDirectory(r, previous, true) + _, err := applyDirectory(r, previous, true, nil) var refusal *PlacementRefusedError if !errors.As(err, &refusal) { t.Fatalf("the directory reached through a link was not refused: %v", err)