From d16c4cd0034f56f4fc63e628f32028ec255c8a76 Mon Sep 17 00:00:00 2001 From: jochen Date: Mon, 23 Nov 2026 12:07:40 +0100 Subject: [PATCH 1/3] A directory whose owner changes gives its contents the new owner A module moved to an account of its own (runs-as) has files below its directories that it wrote as the account it ran as before (gitea's webhook secret, 0600, as the operator's account); the node-engine changed only the directory's owner, so the new account could not read them. Now applyDirectory and applyMeshDirectory give the new owner to what the previous owner held below the directory, but never a path the declaration or another module's composition places (and what lies below it), never an entry another account owns, never through a link (Lchown) and never on another file system. Builds: design 47 H2 H-A-545 (2), H-A-550 --- internal/apply/apply.go | 22 +++++- internal/apply/contents_owner.go | 97 +++++++++++++++++++++++++ internal/apply/contents_owner_test.go | 95 ++++++++++++++++++++++++ internal/apply/converge_dirs.go | 3 +- internal/apply/mesh_dirs_apply_linux.go | 10 ++- internal/apply/mesh_dirs_test.go | 6 +- internal/apply/mesh_tree_found_test.go | 2 +- internal/apply/replay358_test.go | 4 +- 8 files changed, 228 insertions(+), 11 deletions(-) create mode 100644 internal/apply/contents_owner.go create mode 100644 internal/apply/contents_owner_test.go 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) From 684931e0992b5daf7bd10312c5f08bd6bc4f3ede Mon Sep 17 00:00:00 2001 From: jochen Date: Mon, 23 Nov 2026 12:25:59 +0100 Subject: [PATCH 2/3] Give a directory's contents before the directory, matched by user Review round 1: the contents are now given before the directory's own owner changes, so a walk that fails leaves the directory as it was and the next apply walks again; an entry gone meanwhile is nothing to give. An entry is matched by its user alone: one of another user is left with everything below it, and one given the new user gets the new group only where its group was the previous group. A test now applies a directory whose owner changed, with stand-ins for the chowns, and shows the contents given first and a placed child left. Builds: design 47 H2 H-A-550, H-A-554 (2) --- internal/apply/apply.go | 8 +-- internal/apply/contents_owner.go | 32 +++++++++--- internal/apply/contents_owner_test.go | 66 +++++++++++++++++++++++-- internal/apply/mesh_dirs_apply_linux.go | 17 ++++--- 4 files changed, 105 insertions(+), 18 deletions(-) diff --git a/internal/apply/apply.go b/internal/apply/apply.go index cdd9862f..78610f25 100644 --- a/internal/apply/apply.go +++ b/internal/apply/apply.go @@ -1815,14 +1815,16 @@ func applyDirectory(r *declaration.Directory, previous store.Applied, wasBefore return out, err } if !ownedAlready { - if err := own(r.Path, r.Owner); err != nil { - return out, err - } + // The contents first (H-A-554 (2)): a walk that fails leaves the directory's owner as it was, so the next apply + // walks again. if existed { if err := giveContentsTo(r, before, placed); err != nil { return out, err } } + if err := ownDirectory(r.Path, r.Owner); err != nil { + return out, err + } } out.Action = "unchanged" diff --git a/internal/apply/contents_owner.go b/internal/apply/contents_owner.go index 58fe7a42..b99682c1 100644 --- a/internal/apply/contents_owner.go +++ b/internal/apply/contents_owner.go @@ -10,6 +10,7 @@ package apply // followed (a link is owned as a link, Lchown), and the walk stays on the directory's file system. import ( + "errors" "fmt" "io/fs" "os" @@ -18,9 +19,11 @@ import ( "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. +// giveContents gives every entry below dir whose user is from's (uid) to the new user to's, and the new group to's only +// where the entry's group was from's (H-A-554 (2)); but for the paths placed names (cleaned paths the declaration places) +// and what lies below them, an entry of another user and what lies below it, and what lies on another file system. An +// entry gone while the walk runs is nothing to give. Answers how many entries changed hands. Called before the directory's +// own owner changes (H-A-554 (2)), so a walk that failed is walked again at the next apply. func giveContents(dir string, from, to [2]int, placed map[string]bool) (int, error) { root := filepath.Clean(dir) device, err := deviceOf(root) @@ -30,6 +33,9 @@ func giveContents(dir string, from, to [2]int, placed map[string]bool) (int, err given := 0 err = filepath.WalkDir(root, func(path string, e fs.DirEntry, err error) error { if err != nil { + if errors.Is(err, fs.ErrNotExist) { + return nil + } return err } if path == root { @@ -45,11 +51,14 @@ func giveContents(dir string, from, to [2]int, placed map[string]bool) (int, err return skip() } info, err := os.Lstat(path) + if errors.Is(err, fs.ErrNotExist) { + return skip() + } if err != nil { return err } uid, gid, ok := statOwner(info) - if !ok || uid != from[0] || gid != from[1] { + if !ok || uid != from[0] { return skip() } if e.IsDir() { @@ -57,7 +66,14 @@ func giveContents(dir string, from, to [2]int, placed map[string]bool) (int, err return filepath.SkipDir } } - if err := lchownContent(path, to[0], to[1]); err != nil { + group := gid + if gid == from[1] { + group = to[1] + } + if err := lchownContent(path, to[0], group); err != nil { + if errors.Is(err, fs.ErrNotExist) { + return skip() + } return fmt.Errorf("cannot give %s to the directory's new owner: %w", path, err) } given++ @@ -82,7 +98,8 @@ func placedPaths(resources ...[]declaration.Resource) map[string]bool { return out } -// giveContentsTo gives the contents of the directory r, found as before, to r's declared owner (giveContents). +// giveContentsTo gives the contents of the directory r, found as before, to r's declared owner (giveContents), before the +// directory's own owner changes. func giveContentsTo(r *declaration.Directory, before os.FileInfo, placed map[string]bool) error { fromUID, fromGID, ok := statOwner(before) if !ok || r.Owner == "" { @@ -95,3 +112,6 @@ func giveContentsTo(r *declaration.Directory, before os.FileInfo, placed map[str _, err = giveContents(r.Path, [2]int{fromUID, fromGID}, [2]int{uid, gid}, placed) return err } + +// ownDirectory gives a directory changed by path its owner (own); a variable so a test sees it without being root. +var ownDirectory = own diff --git a/internal/apply/contents_owner_test.go b/internal/apply/contents_owner_test.go index 5b31526c..4526c562 100644 --- a/internal/apply/contents_owner_test.go +++ b/internal/apply/contents_owner_test.go @@ -1,13 +1,16 @@ package apply import ( + "fmt" "os" "path/filepath" "sort" "strings" + "syscall" "testing" "git.novox.be/novox/mesh-sdk/go/declaration" + "github.com/novox/mesh-host/internal/store" ) // A directory whose owner changes gives its contents the new owner (H-A-545 (2), H-A-550): what its previous owner @@ -21,6 +24,7 @@ func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) { from [2]int placed func(root string) []string other string // a directory the stand-in deviceOf says is on another file system + group int // the group an entry keeps, when not to's want []string }{ {name: "what the previous owner wrote is given", from: [2]int{me, myGroup}, @@ -28,7 +32,9 @@ func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) { {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: "what another user owns is left", from: [2]int{me + 1, myGroup}}, + {name: "the new user is given, the group only where it was the previous group", from: [2]int{me, myGroup + 1}, + group: myGroup, want: []string{"data", "data/repo", "kept", "kept/webhook.secret", "link", "token"}}, {name: "another file system is not crossed", from: [2]int{me, myGroup}, other: "kept", want: []string{"data", "data/repo", "link", "token"}}, } @@ -56,9 +62,13 @@ func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) { var given []string wasChown, wasDevice := lchownContent, deviceOf t.Cleanup(func() { lchownContent, deviceOf = wasChown, wasDevice }) + wantGroup := to[1] + if c.group != 0 { + wantGroup = c.group + } 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]) + if uid != to[0] || gid != wantGroup { + t.Errorf("%s given to %d:%d, want %d:%d", path, uid, gid, to[0], wantGroup) } rel, _ := filepath.Rel(root, path) given = append(given, rel) @@ -93,3 +103,53 @@ func TestADirectoryGivesItsContentsTheNewOwner(t *testing.T) { t.Fatalf("placed %v", got) } } + +// Through the apply (review r1 of fix/gitea-runs-as): a directory found with another owner than declared gives its +// contents the new owner first, then itself; a placed child with the same previous owner keeps its owner; and a walk that +// fails leaves the directory's owner as it was. +func TestADirectoryWhoseOwnerChangedGivesItsContentsFirst(t *testing.T) { + me, myGroup := os.Getuid(), os.Getgid() + root := t.TempDir() + dir := filepath.Join(root, "state") + for _, d := range []string{dir, filepath.Join(dir, "data")} { + if err := os.Mkdir(d, 0o700); err != nil { + t.Fatal(err) + } + } + for _, f := range []string{"webhook.secret", "data/repo"} { + if err := os.WriteFile(filepath.Join(dir, f), []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + } + owner := fmt.Sprintf("%d:%d", me+4242, myGroup+4242) + r := &declaration.Directory{ID: "gitea.state", Path: dir, Mode: "0700", Owner: owner} + placed := map[string]bool{filepath.Join(dir, "data"): true} + for _, fails := range []bool{true, false} { + var order []string + wasContent, wasOwn, wasF := lchownContent, ownDirectory, fchownDirectory + lchownContent = func(path string, uid, gid int) error { + if fails { + return syscall.EPERM + } + rel, _ := filepath.Rel(dir, path) + order = append(order, rel) + return nil + } + ownDirectory = func(path, o string) error { order = append(order, "."); return nil } + fchownDirectory = func(fd, uid, gid int) error { order = append(order, "."); return nil } + _, err := applyDirectory(r, store.Applied{Target: dir}, true, placed) + lchownContent, ownDirectory, fchownDirectory = wasContent, wasOwn, wasF + if fails { + if err == nil || len(order) != 0 { + t.Fatalf("a failing walk answered %v and changed %v; want an error and the directory's owner left", err, order) + } + continue + } + if err != nil { + t.Fatal(err) + } + if strings.Join(order, ",") != "webhook.secret,." { + t.Fatalf("changed %v, want the contents but the placed data, then the directory", order) + } + } +} diff --git a/internal/apply/mesh_dirs_apply_linux.go b/internal/apply/mesh_dirs_apply_linux.go index a564ae41..5408fea1 100644 --- a/internal/apply/mesh_dirs_apply_linux.go +++ b/internal/apply/mesh_dirs_apply_linux.go @@ -17,6 +17,9 @@ import ( "git.novox.be/novox/mesh-sdk/go/declaration" ) +// fchownDirectory gives a mesh directory its owner through its descriptor; a variable so a test sees it without being root. +var fchownDirectory = unix.Fchown + // meshDirsByDescriptor says this system can open a directory component by component without following a link. const meshDirsByDescriptor = true @@ -88,18 +91,20 @@ func applyMeshDirectory(r *declaration.Directory, out Outcome, mode os.FileMode, } ownedAlready := !chown || (beforeUID == uid && beforeGID == gid) if !ownedAlready { - if err := unix.Fchown(fd, uid, gid); err != nil { + // The contents first (H-A-554 (2)): a walk that fails leaves the directory's owner as it was, so the next apply + // walks again. + if existed && !created { + if _, err := giveContents(walk.At, [2]int{beforeUID, beforeGID}, [2]int{uid, gid}, placed); err != nil { + return out, err + } + } + if err := fchownDirectory(fd, uid, gid); err != nil { return out, fmt.Errorf("cannot give %s to %q: %w", r.Path, r.Owner, &os.PathError{Op: "chown", Path: r.Path, Err: err}) } // A chown may take the setgid bit: the mode is set again after it. 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. From 70d410934f0b01f5b35c7cebdc0435adf2a480be Mon Sep 17 00:00:00 2001 From: jochen Date: Mon, 23 Nov 2026 12:25:59 +0100 Subject: [PATCH 3/3] The node-engine states it gives a directory's contents their new owner readsNow states the reader capability directory-contents-owner, which mesh-sdk's ManifestNeeds names for every manifest declaring runs-as, so the module graph orders a move to an account of its own after this engine runs on its node. Builds: design 47 H2 H-A-554 (1), H-A-556 --- internal/link/have_test.go | 10 ++++++++-- internal/link/record.go | 3 +++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/internal/link/have_test.go b/internal/link/have_test.go index ea8a0c2b..508cfad9 100644 --- a/internal/link/have_test.go +++ b/internal/link/have_test.go @@ -382,6 +382,10 @@ func testTheNodeKeyCarriesTheNodesFacts(t *testing.T) { if !slices.Contains(got.Record.ManifestReads, nodeengine.ManifestReadWordWantVersion) || slices.Contains(got.Record.Capabilities, "want-parts") { t.Errorf("the record states reads %v and capabilities %v, want the word want:version and no want-parts", got.Record.ManifestReads, got.Record.Capabilities) } + // And that it gives a directory's contents the directory's new owner (H-A-556). + if !slices.Contains(got.Record.ManifestReads, catalogue.ReadDirectoryContentsOwner) { + t.Errorf("the record states reads %v, want %s", got.Record.ManifestReads, catalogue.ReadDirectoryContentsOwner) + } // Among them, that it fills a seat's reach from the seat holder's listen (ADR 0632 §1). // And the words and forms it builds (design 42 zfs-owns-zfs §4, answer A-13). for _, read := range []string{catalogue.ReadForm + catalogue.ReferenceFormSeatReach, "word:resources.if-config", @@ -1056,9 +1060,11 @@ func slicesIndex(rs []ResourceHealth, id string) int { return -1 } -// statedReads is the contract's reads with the word that the engine reads a want by its version (design 47 H §772). +// statedReads is the contract's reads with the word that the engine reads a want by its version (design 47 H §772) and +// that it gives a directory's contents its new owner (H-A-556). func statedReads() []string { - return slices.Sorted(slices.Values(append(catalogue.ManifestReads(), nodeengine.ManifestReadWordWantVersion))) + return slices.Sorted(slices.Values(append(catalogue.ManifestReads(), nodeengine.ManifestReadWordWantVersion, + catalogue.ReadDirectoryContentsOwner))) } // TestHave runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget). diff --git a/internal/link/record.go b/internal/link/record.go index 1db4748c..8cc45ee6 100644 --- a/internal/link/record.go +++ b/internal/link/record.go @@ -58,6 +58,9 @@ func readsNow() []string { } out := make([]string, 0, len(set)) set[nodeengine.ManifestReadWordWantVersion] = true + // And that it gives a directory's contents the directory's new owner (internal/apply giveContents; H-A-556): a module + // declaring runs-as needs it, so its move waits for this engine on its node. + set[catalogue.ReadDirectoryContentsOwner] = true for r := range set { out = append(out, r) }