Merge pull request 'The node-engine gives a directory's contents its new owner (design 47 H2, H-A-545, H-A-550, H-A-554, H-A-556)' (#256) from fix/gitea-runs-as into main

This commit was merged in pull request #256.
This commit is contained in:
2026-11-23 11:31:54 +00:00
10 changed files with 328 additions and 15 deletions
+22 -4
View File
@@ -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 {
@@ -1807,7 +1815,14 @@ func applyDirectory(r *declaration.Directory, previous store.Applied, wasBefore
return out, err
}
if !ownedAlready {
if err := own(r.Path, r.Owner); 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 {
if err := giveContentsTo(r, before, placed); err != nil {
return out, err
}
}
if err := ownDirectory(r.Path, r.Owner); err != nil {
return out, err
}
}
@@ -2802,6 +2817,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
+117
View File
@@ -0,0 +1,117 @@
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 (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"git.novox.be/novox/mesh-sdk/go/declaration"
)
// 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)
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 {
if errors.Is(err, fs.ErrNotExist) {
return 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 errors.Is(err, fs.ErrNotExist) {
return skip()
}
if err != nil {
return err
}
uid, gid, ok := statOwner(info)
if !ok || uid != from[0] {
return skip()
}
if e.IsDir() {
if d, derr := deviceOf(path); derr != nil || d != device {
return filepath.SkipDir
}
}
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++
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), 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 == "" {
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
}
// ownDirectory gives a directory changed by path its owner (own); a variable so a test sees it without being root.
var ownDirectory = own
+155
View File
@@ -0,0 +1,155 @@
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
// 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
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},
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 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"}},
}
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 })
wantGroup := to[1]
if c.group != 0 {
wantGroup = c.group
}
lchownContent = func(path string, uid, gid int) error {
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)
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)
}
}
// 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)
}
}
}
+2 -1
View File
@@ -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))
+15 -2
View File
@@ -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
@@ -36,7 +39,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 {
@@ -85,7 +91,14 @@ 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.
+3 -3
View File
@@ -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)
}
+1 -1
View File
@@ -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)
}
+2 -2
View File
@@ -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)
+8 -2
View File
@@ -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).
+3
View File
@@ -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)
}