From a40d7fb1c4bff3d4e1571732fd2227c29d964213 Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 21:19:35 +0100 Subject: [PATCH 01/12] systemd-resolved: serve uplink-names, writing the host names file (issue 960) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The verb checks each host name (root, wildcard, trailing dot, a label over 63 bytes, the mesh's own domain or under it, more than 8), writes /var/lib/node-resolver/uplink-names whole through sudo -n install then sudo -n mv -f, and answers the names with the link carrying the default route (the lowest-metric kernel default route that is neither routed nor the private network's interface) and when they were set. Builds: design 08 sign-in-page §2, §5, §6 --- .../cmd/resolver-tools/main.go | 6 + .../cmd/resolver-tools/manifest_test.go | 2 +- .../cmd/resolver-tools/resolver.go | 238 +++++++++++++++++- .../cmd/resolver-tools/resolver_test.go | 143 ++++++++++- modules/systemd-resolved/module.json | 10 +- 5 files changed, 394 insertions(+), 5 deletions(-) diff --git a/modules/systemd-resolved/cmd/resolver-tools/main.go b/modules/systemd-resolved/cmd/resolver-tools/main.go index f569654b1..089f3f40d 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/main.go +++ b/modules/systemd-resolved/cmd/resolver-tools/main.go @@ -93,5 +93,11 @@ func tools(r *Resolver, history string) []stdio.Tool { "when the link has none. (a)", map[string]any{"link": str("the network link, by name")}, func(a map[string]any) (any, error) { return r.Unroute(ctx, arg(a, "link")) }), + verb("uplink-names", "Give this machine's own resolver the network manager's own check's host names, so a "+ + "working network it tests resolves through the network it tests: at most 8, each a host name of "+ + "letters, digits, hyphens and dots; an empty list takes them away. Refused, naming the name and why: "+ + "not a host name, the root, the mesh's own domain or under it, or more than 8. (a)", + map[string]any{"names": str("the host names, separated by spaces or commas; empty clears them")}, + func(a map[string]any) (any, error) { return r.SetUplinkNames(ctx, Split(a["names"])) }), } } diff --git a/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go b/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go index c1ec63d42..446319888 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go @@ -100,7 +100,7 @@ func TestTheManifestSaysWhatTheGuardKeeps(t *testing.T) { if !guard || !service { t.Errorf("the guard (root, long-running, its health said) %v; resolved (running, restarted on its drop-in) %v", guard, service) } - if len(m.Claims) != 1 || m.Claims[0].Name != Seat || strings.Join(m.Claims[0].Serves, " ") != "routes route unroute" { + if len(m.Claims) != 1 || m.Claims[0].Name != Seat || strings.Join(m.Claims[0].Serves, " ") != "routes route unroute uplink-names" { t.Errorf("the claim is %+v", m.Claims) } if len(m.Provides) != 1 || m.Provides[0].Name != "split-dns" || m.Provides[0].Reach != "machine" { diff --git a/modules/systemd-resolved/cmd/resolver-tools/resolver.go b/modules/systemd-resolved/cmd/resolver-tools/resolver.go index e77cc62e2..19fcddff4 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/resolver.go +++ b/modules/systemd-resolved/cmd/resolver-tools/resolver.go @@ -14,6 +14,7 @@ package main import ( "bytes" "context" + "encoding/json" "errors" "fmt" "net" @@ -91,13 +92,26 @@ type Resolver struct { Answers func(ctx context.Context, server string) bool // AnswerWithinFile holds how long one of them is given to answer (the config value answer-within). AnswerWithinFile string + // PrivateInterfaceFile holds the private network's own interface name, rendered beside SuffixFile + // (design 08 sign-in-page §7, DQ-1): never the private network's interface is the uplink's link. + PrivateInterfaceFile string + // UplinkNamesFile is where the uplink's holder's names are kept, one a line (design 08 sign-in-page §6). + UplinkNamesFile string + // UplinkNamesAppliedFile is what the guard last gave the link carrying the default route (§8). + UplinkNamesAppliedFile string + // WriteUplinkNames writes UplinkNamesFile whole, as root (§6); stood in for in tests. + WriteUplinkNames func(ctx context.Context, content []byte) error + // Now is the clock the uplink-names verb stamps its answer with; stood in for in tests. + Now func() time.Time } // ThisResolver is the machine's. func ThisResolver() *Resolver { r := &Resolver{Change: execRunner, Read: readRunner, NetDir: "/sys/class/net", SuffixFile: SuffixPath, - AnswerWithinFile: AnswerWithinPath} + AnswerWithinFile: AnswerWithinPath, PrivateInterfaceFile: PrivateInterfacePath, + UplinkNamesFile: UplinkNamesPath, UplinkNamesAppliedFile: UplinkNamesAppliedPath, Now: time.Now} r.Answers = r.asks + r.WriteUplinkNames = r.writeUplinkNamesFile return r } @@ -144,6 +158,25 @@ func (r *Resolver) asks(ctx context.Context, server string) bool { // SuffixPath is the file the mesh renders the mesh's own domain into (the manifest's fact `suffix`). const SuffixPath = "/etc/node-resolver/suffix" +// PrivateInterfacePath is the file the mesh renders the private network's own interface name into, +// beside SuffixPath (the manifest's fact `private-interface`; design 08 sign-in-page §7, DQ-1). +const PrivateInterfacePath = "/etc/node-resolver/private-interface" + +// UplinkNamesPath is where `uplink-names` keeps the host names, one a line, whole (design 08 sign-in-page +// §6): root's, mode 0644, written through `sudo -n install` then `sudo -n mv -f`. +const UplinkNamesPath = "/var/lib/node-resolver/uplink-names" + +// UplinkNamesAppliedPath is what the guard last gave the link carrying the default route (§8): the list, +// the link, when, and resolved's refusal or empty. +const UplinkNamesAppliedPath = "/var/lib/node-resolver/uplink-names.applied" + +// privateInterface is the private network's own interface name, as the mesh rendered it; empty before it +// has (DQ-1). +func (r *Resolver) privateInterface() string { + raw, _ := os.ReadFile(r.PrivateInterfaceFile) + return strings.TrimSpace(string(raw)) +} + // Scope is one place resolved sends names: the machine's global servers (the mesh's resolvers), or a link. type Scope struct { Link string `json:"link,omitempty"` @@ -364,6 +397,209 @@ func Servers(given []string) ([]string, error) { return out, nil } +// hostNameLabel matches one label of a host name: letters, digits and hyphens. +var hostNameLabel = regexp.MustCompile(`^[a-z0-9-]+$`) + +// HostNames checks the names given to `uplink-names` (design 08 sign-in-page §2): 0 to 8 host names, each +// 1 to 253 bytes of letters, digits, hyphens and dots, lower-cased. Refused, naming the name and the +// reason: a name that is not a host name (a wildcard, a trailing dot, a label over 63 bytes), the root, +// the mesh's own domain or a name under it (ADR 0247 §12's rule for `route`, for the same reason), or more +// than 8 names. +func (r *Resolver) HostNames(given []string) ([]string, error) { + suffix := r.suffix() + out := make([]string, 0, len(given)) + for _, n := range given { + n = strings.ToLower(strings.TrimSpace(n)) + if n == "" || n == "." { + return nil, errors.New("the root is not a host name: only the mesh's resolvers answer every name") + } + if strings.Contains(n, "*") { + return nil, fmt.Errorf("%q is not a host name: a wildcard", n) + } + if strings.HasSuffix(n, ".") { + return nil, fmt.Errorf("%q is not a host name: a trailing dot", n) + } + if len(n) > 253 { + return nil, fmt.Errorf("%q is not a host name: over 253 bytes", n) + } + for _, label := range strings.Split(n, ".") { + if len(label) > 63 { + return nil, fmt.Errorf("%q is not a host name: a label over 63 bytes", n) + } + if !hostNameLabel.MatchString(label) { + return nil, fmt.Errorf("%q is not a host name", n) + } + } + if n == suffix || strings.HasSuffix(n, "."+suffix) { + return nil, fmt.Errorf("%q is the mesh's own domain: the mesh's names are answered by the mesh's resolvers alone", n) + } + out = append(out, n) + } + if len(out) > 8 { + return nil, fmt.Errorf("%d names; at most 8", len(out)) + } + return out, nil +} + +// writeUplinkNamesFile writes UplinkNamesFile whole (design 08 sign-in-page §6): `sudo -n install -m 0644 +// -o root -g root /dev/stdin .new` with the lines on its input, then `sudo -n mv -f .new +// `, so a reader never sees it half-written. As root (the guard never calls this; only the verb, +// over the bus, does), both run unescalated. +func (r *Resolver) writeUplinkNamesFile(ctx context.Context, content []byte) error { + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + newPath := r.UplinkNamesFile + ".new" + program, args := escalated(os.Getuid(), "install", []string{"-m", "0644", "-o", "root", "-g", "root", "/dev/stdin", newPath}) + cmd := exec.CommandContext(ctx, program, args...) + cmd.Stdin = bytes.NewReader(content) + var stderr bytes.Buffer + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + if said := strings.TrimSpace(stderr.String()); said != "" { + return fmt.Errorf("install: %s", said) + } + return fmt.Errorf("install failed: %w", err) + } + _, err := r.Change(ctx, "mv", "-f", newPath, r.UplinkNamesFile) + return err +} + +// UplinkNames is `uplink-names`'s answer (design 08 sign-in-page §2): the names now given, the link they +// are answered over now (empty when no link carries a default route), and when the list was set. +type UplinkNames struct { + Names []string `json:"names"` + Link string `json:"link"` + SetAt time.Time `json:"set_at"` +} + +// SetUplinkNames writes the host names the uplink's holder gives for its network's own check, through +// UplinkNamesFile (§6), and answers them with the link carrying the default route now (§2, DQ-2): empty +// when there is no such link. +func (r *Resolver) SetUplinkNames(ctx context.Context, given []string) (*UplinkNames, error) { + names, err := r.HostNames(given) + if err != nil { + return nil, err + } + content := []byte(strings.Join(names, "\n")) + if len(names) > 0 { + content = append(content, '\n') + } + if err := r.WriteUplinkNames(ctx, content); err != nil { + return nil, err + } + link := "" + if routes, rerr := r.Routes(ctx); rerr == nil { + link, _ = r.DefaultRouteLink(ctx, routes) + } + return &UplinkNames{Names: names, Link: link, SetAt: r.Now()}, nil +} + +// ReadUplinkNames reads the host names `uplink-names` last wrote, one a line; empty before it has. +func ReadUplinkNames(path string) []string { + raw, err := os.ReadFile(path) + if err != nil { + return []string{} + } + out := []string{} + for _, line := range strings.Split(string(raw), "\n") { + if line = strings.TrimSpace(line); line != "" { + out = append(out, line) + } + } + return out +} + +// UplinkApplied is what the guard last gave the link carrying the default route (design 08 sign-in-page +// §8): the list, the link, when, and resolved's refusal or empty. +type UplinkApplied struct { + Names []string `json:"names"` + Link string `json:"link"` + At time.Time `json:"at"` + Refused string `json:"refused,omitempty"` +} + +// ReadUplinkApplied reads what the guard applied last; the zero value before its first round, or after a +// restart with nothing written yet. +func ReadUplinkApplied(path string) UplinkApplied { + raw, err := os.ReadFile(path) + if err != nil { + return UplinkApplied{} + } + var a UplinkApplied + if json.Unmarshal(raw, &a) != nil { + return UplinkApplied{} + } + return a +} + +// kernelDefaultRoute is one of the kernel's default routes: its link and metric (the lowest wins). +type kernelDefaultRoute struct { + link string + metric int +} + +// kernelDefaultRoutes reads the kernel's default routes for one family ("-4" or "-6"); a route the kernel +// names no metric for gets 0, its own highest priority. +func (r *Resolver) kernelDefaultRoutes(ctx context.Context, family string) ([]kernelDefaultRoute, error) { + out, err := r.Read(ctx, "ip", family, "route", "show", "default") + if err != nil { + return nil, fmt.Errorf("the kernel's default routes: %w", err) + } + var routes []kernelDefaultRoute + for _, line := range strings.Split(out, "\n") { + fields := strings.Fields(line) + if len(fields) == 0 || fields[0] != "default" { + continue + } + var kr kernelDefaultRoute + for i := 0; i+1 < len(fields); i++ { + switch fields[i] { + case "dev": + kr.link = fields[i+1] + case "metric": + if n, err := strconv.Atoi(fields[i+1]); err == nil { + kr.metric = n + } + } + } + if kr.link != "" { + routes = append(routes, kr) + } + } + return routes, nil +} + +// DefaultRouteLink is the link that carries the default route now (design 08 sign-in-page §7, §9; DQ-1, +// DQ-2): among the kernel's IPv4 default routes, or the IPv6 ones when there is no IPv4 one, the one with +// the lowest metric whose link is neither one `route` routed (a VPN's, read from resolved) nor the private +// network's own interface; empty when there is no such link. +func (r *Resolver) DefaultRouteLink(ctx context.Context, routes *Routes) (string, error) { + private := r.privateInterface() + routed := map[string]bool{} + for _, l := range routes.Links { + routed[l.Link] = l.routed + } + candidates, err := r.kernelDefaultRoutes(ctx, "-4") + if err != nil { + return "", err + } + if len(candidates) == 0 { + if candidates, err = r.kernelDefaultRoutes(ctx, "-6"); err != nil { + return "", err + } + } + best, bestMetric := "", 0 + for _, c := range candidates { + if c.link == private || routed[c.link] { + continue + } + if best == "" || c.metric < bestMetric { + best, bestMetric = c.link, c.metric + } + } + return best, nil +} + // Route sends these domains, and every name under them, to these servers over this link — and only them. // Whatever the link was given before is replaced. resolved forgets it when the link goes. func (r *Resolver) Route(ctx context.Context, link string, domains, servers []string) (*Routed, error) { diff --git a/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go b/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go index 79a29f933..acb722f93 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go @@ -2,6 +2,7 @@ package main import ( "context" + "fmt" "net" "os" "path/filepath" @@ -10,13 +11,21 @@ import ( "time" ) -// fakeResolved answers resolvectl as systemd-resolved would, and records what was asked of it. +// fakeResolved answers resolvectl, and `ip route show default`, as the machine would, and records what was +// asked of it. type fakeResolved struct { dns, domain, defaults string + ip string changed [][]string } func (f *fakeResolved) read(_ context.Context, name string, args ...string) (string, error) { + if name == "ip" { + if len(args) > 0 && args[0] == "-6" { + return "", nil + } + return f.ip, nil + } switch args[0] { case "dns": return f.dns, nil @@ -46,7 +55,14 @@ func aMachine(t *testing.T, f *fakeResolved, links ...string) *Resolver { if err := os.WriteFile(suffix, []byte("internal\n"), 0o644); err != nil { t.Fatal(err) } - return &Resolver{Change: f.change, Read: f.read, NetDir: filepath.Join(dir, "net"), SuffixFile: suffix} + return &Resolver{Change: f.change, Read: f.read, NetDir: filepath.Join(dir, "net"), SuffixFile: suffix, + PrivateInterfaceFile: filepath.Join(dir, "private-interface"), + UplinkNamesFile: filepath.Join(dir, "uplink-names"), + UplinkNamesAppliedFile: filepath.Join(dir, "uplink-names.applied"), + Now: func() time.Time { return time.Date(2026, 11, 24, 12, 0, 0, 0, time.UTC) }, + WriteUplinkNames: func(_ context.Context, content []byte) error { + return os.WriteFile(filepath.Join(dir, "uplink-names"), content, 0o644) + }} } // A route sends the domains to the servers over the link, and only them: the link is first told it is @@ -173,6 +189,129 @@ func TestChangesAreEscalatedOnlyWhenNotRoot(t *testing.T) { } } +// Given names, uplink-names writes the file one a line and answers them (design 08 sign-in-page §2, §6; +// R-1). +func TestUplinkNamesWritesTheFileAndAnswersThem(t *testing.T) { + f := &fakeResolved{} + r := aMachine(t, f, "tun0") + got, err := r.SetUplinkNames(context.Background(), []string{"Check.Example", "check2.example"}) + if err != nil { + t.Fatal(err) + } + if strings.Join(got.Names, " ") != "check.example check2.example" { + t.Errorf("the answer names %v", got.Names) + } + if got.SetAt.IsZero() { + t.Error("set_at was not stamped") + } + raw, err := os.ReadFile(r.UplinkNamesFile) + if err != nil { + t.Fatal(err) + } + if string(raw) != "check.example\ncheck2.example\n" { + t.Errorf("the file holds %q", raw) + } +} + +// An empty list empties the file (design 08 sign-in-page §2; R-2). +func TestAnEmptyListEmptiesTheUplinkNamesFile(t *testing.T) { + f := &fakeResolved{} + r := aMachine(t, f, "tun0") + if _, err := r.SetUplinkNames(context.Background(), []string{"check.example"}); err != nil { + t.Fatal(err) + } + got, err := r.SetUplinkNames(context.Background(), nil) + if err != nil { + t.Fatal(err) + } + if len(got.Names) != 0 { + t.Errorf("the answer names %v, not empty", got.Names) + } + raw, err := os.ReadFile(r.UplinkNamesFile) + if err != nil { + t.Fatal(err) + } + if string(raw) != "" { + t.Errorf("the file holds %q, not emptied", raw) + } +} + +// Each refusal of §2 is answered naming the name and the reason, and writes nothing (design 08 +// sign-in-page §2; acceptance test 4; R-3). +func TestEachRefusalOfUplinkNamesIsNamedAndWritesNothing(t *testing.T) { + for name, c := range map[string]struct{ given, says string }{ + "the root": {".", "root"}, + "empty string": {"", "root"}, + "a wildcard": {"*.example", "wildcard"}, + "a trailing dot": {"check.example.", "trailing dot"}, + "a label over 63": {strings.Repeat("a", 64) + ".example", "label over 63 bytes"}, + "the mesh's domain": {"internal", "mesh's own domain"}, + "under it": {"check.internal", "mesh's own domain"}, + "not a host name": {"a b/c", "not a host name"}, + } { + f := &fakeResolved{} + r := aMachine(t, f, "tun0") + _, err := r.SetUplinkNames(context.Background(), []string{c.given}) + if err == nil || !strings.Contains(err.Error(), c.says) { + t.Errorf("%s: %v", name, err) + } + if _, statErr := os.Stat(r.UplinkNamesFile); statErr == nil { + t.Errorf("%s: the file was written: %s", name, contentOf(t, r.UplinkNamesFile)) + } + } + f := &fakeResolved{} + r := aMachine(t, f, "tun0") + nine := make([]string, 9) + for i := range nine { + nine[i] = fmt.Sprintf("check%d.example", i) + } + _, err := r.SetUplinkNames(context.Background(), nine) + if err == nil || !strings.Contains(err.Error(), "at most 8") { + t.Errorf("more than 8 names: %v", err) + } + if _, statErr := os.Stat(r.UplinkNamesFile); statErr == nil { + t.Error("more than 8 names: the file was written") + } +} + +// The link carrying the default route is the lowest-metric one that is neither routed (a VPN's) nor the +// private network's; none when there is none (design 08 sign-in-page §7, §9; DQ-1, DQ-2). +func TestDefaultRouteLinkIsTheLowestMetricOneThatIsNeitherRoutedNorPrivate(t *testing.T) { + f := &fakeResolved{} + r := aMachine(t, f, "tun0", "wlan0", "mesh0") + if err := os.WriteFile(r.PrivateInterfaceFile, []byte("mesh0\n"), 0o644); err != nil { + t.Fatal(err) + } + f.ip = "default via 10.0.0.1 dev wlan0 metric 600\ndefault via 10.1.0.1 dev mesh0 metric 50\n" + f.dns = "Link 7 (tun0): 10.9.0.1\n" + f.domain = "Link 7 (tun0): ~corp.example\n" + routes, err := r.Routes(context.Background()) + if err != nil { + t.Fatal(err) + } + link, err := r.DefaultRouteLink(context.Background(), routes) + if err != nil { + t.Fatal(err) + } + if link != "wlan0" { + t.Errorf("the link is %q, not wlan0 (mesh0 is the private interface)", link) + } + // A link `route` routed is also never chosen. + f.ip = "default via 10.0.0.1 dev tun0 metric 10\ndefault via 10.2.0.1 dev wlan0 metric 600\n" + link, err = r.DefaultRouteLink(context.Background(), routes) + if err != nil { + t.Fatal(err) + } + if link != "wlan0" { + t.Errorf("the link is %q, not wlan0 (tun0 is routed)", link) + } + // None when there is none. + f.ip = "default via 10.0.0.1 dev tun0 metric 10\ndefault via 10.1.0.1 dev mesh0 metric 50\n" + if link, err = r.DefaultRouteLink(context.Background(), routes); err != nil || link != "" { + t.Errorf("the link is %q, want none", link) + } +} + // One of the mesh's resolvers answers when it says anything, a name not found included; one that is silent // does not, and the guard does not wait on it past the config value answer-within, read from the file the // mesh renders, or a second before it has. (1981/AC3) diff --git a/modules/systemd-resolved/module.json b/modules/systemd-resolved/module.json index 22a27ed7a..a0eb879f4 100644 --- a/modules/systemd-resolved/module.json +++ b/modules/systemd-resolved/module.json @@ -28,7 +28,8 @@ "serves": [ "routes", "route", - "unroute" + "unroute", + "uplink-names" ] } ], @@ -102,6 +103,13 @@ "health": { "kind": "unit" } + }, + { + "id": "uplink-names", + "type": "directory", + "path": "/var/lib/node-resolver", + "mode": "0755", + "unknown": "program" } ], "build": { From b694c5e2a5899e17dc8311d42c6bb35eb484d1dc Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 21:23:06 +0100 Subject: [PATCH 02/12] systemd-resolved: the guard applies the uplink's names every round (issue 960) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each round it finds the link carrying the default route (the lowest-metric kernel default route that is neither one route routed nor the private network's interface), gives it the names from uplink-names's file plus its own search and routing domains, and takes them off the link they were on before when that differs. What it applied is kept in uplink-names.applied, read at its own start so a restart never infers which link to take them off, and a resolved refusal is journalled once per change, not every round. The guard's own names are left out of whether a link is judged `route` routed, so the fallback still gives a link holding only them its default route back while the mesh's resolvers are silent (ADR 0688 stands). Builds: design 08 sign-in-page §7, §8 --- .../cmd/resolver-tools/guard.go | 108 +++++++++++++++ .../cmd/resolver-tools/guard_test.go | 127 +++++++++++++++++- .../cmd/resolver-tools/main.go | 3 + .../cmd/resolver-tools/resolver.go | 25 +++- 4 files changed, 260 insertions(+), 3 deletions(-) diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard.go b/modules/systemd-resolved/cmd/resolver-tools/guard.go index 0e39cd0d4..5d244d9d7 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard.go @@ -94,6 +94,11 @@ type Guard struct { // silent is whether none of the mesh's resolvers answered at the last look, so each turn is said once. // Only the routes' loop reads and writes it. silent bool + + // applied is what the guard last gave the link carrying the default route (design 08 sign-in-page §8): + // read at start from UplinkNamesAppliedFile, so a restart takes the names off the link it names, + // never inferring which. Only the uplink names' round reads and writes it. + applied UplinkApplied } // NewGuard is the machine's. @@ -335,6 +340,7 @@ func (g *Guard) Run(ctx context.Context) { g.Tick() case <-routes.C: g.KeepRoutes(ctx) + g.KeepUplinkNames(ctx) } } } @@ -367,6 +373,108 @@ func (g *Guard) KeepRoutes(ctx context.Context) { } } +// sameNames is whether two name lists are the same, in the same order (the file holds them one a line, in +// the order given). +func sameNames(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// rawDomainsOf is one link's domains as resolved holds them now, `~` kept, so its routing domains and its +// plain search domains are told apart. +func (g *Guard) rawDomainsOf(ctx context.Context, link string) ([]string, error) { + out, err := g.Resolver.Read(ctx, "resolvectl", "domain") + if err != nil { + return nil, err + } + _, links := perScope(out) + return links[link], nil +} + +// setLinkUplinkNames sets one link's domains to its own, apart from the names the guard applied there +// last, plus `~` per name now given (design 08 sign-in-page §7): every search domain and routing +// domain the link already has, apart from the guard's own, stays. An empty names takes them off. +func (g *Guard) setLinkUplinkNames(ctx context.Context, link string, names []string) error { + raw, err := g.rawDomainsOf(ctx, link) + if err != nil { + return err + } + marked := map[string]bool{} + for _, n := range g.applied.Names { + marked["~"+n] = true + } + base := withoutMarked(raw, marked) + full := append([]string{}, base...) + for _, n := range names { + full = append(full, "~"+n) + } + _, err = g.Resolver.Change(ctx, "resolvectl", append([]string{"domain", link}, full...)...) + return err +} + +// KeepUplinkNames gives the names in the file to the link carrying the default route, every round (design +// 08 sign-in-page §7, §8): it never sets a link's servers, its default route for names, its addresses or +// its routes. A round in which they are already in place changes nothing. +func (g *Guard) KeepUplinkNames(ctx context.Context) { + given := ReadUplinkNames(g.Resolver.UplinkNamesFile) + routes, err := g.Resolver.Routes(ctx) + if err != nil { + return + } + link, err := g.Resolver.DefaultRouteLink(ctx, routes) + if err != nil { + g.Log("the kernel's default routes: %v", err) + return + } + if link == g.applied.Link && sameNames(given, g.applied.Names) && g.applied.Refused == "" { + return + } + if g.applied.Link != "" && g.applied.Link != link { + if err := g.setLinkUplinkNames(ctx, g.applied.Link, nil); err != nil { + g.Log("taking the uplink's names off %s failed: %v", g.applied.Link, err) + } + } + refused := "" + if link != "" { + if err := g.setLinkUplinkNames(ctx, link, given); err != nil { + refused = err.Error() + } + } + if link != g.applied.Link { + g.Log("the uplink's names are now answered over %q, were %q", link, g.applied.Link) + } else if !sameNames(given, g.applied.Names) { + g.Log("the uplink's names change on %s", link) + } + if refused != g.applied.Refused { + if refused != "" { + g.Log("resolved refuses the uplink's names: %s", refused) + } else { + g.Log("resolved accepts the uplink's names again") + } + } + g.applied = UplinkApplied{Names: given, Link: link, At: g.Now(), Refused: refused} + g.writeApplied() +} + +// writeApplied writes what the guard applied last, whole (beside, renamed over), design 08 sign-in-page §8. +func (g *Guard) writeApplied() { + raw, err := json.MarshalIndent(g.applied, "", " ") + if err != nil { + return + } + tmp := g.Resolver.UplinkNamesAppliedFile + ".tmp" + if os.WriteFile(tmp, raw, 0o644) == nil { + _ = os.Rename(tmp, g.Resolver.UplinkNamesAppliedFile) + } +} + // Request is one call over the socket: a verb and its arguments, one JSON line. type Request struct { Verb string `json:"verb"` diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go index b82e0d4ef..ca6a0ec94 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go @@ -4,6 +4,8 @@ import ( "bufio" "context" "encoding/json" + "errors" + "fmt" "net" "os" "path/filepath" @@ -20,6 +22,13 @@ const vpnFile = "# Dynamic resolv.conf(5) file for glibc resolver(3) generated b // aGuardedMachine is a guard over a temporary /etc and /run, with a clock the test moves. func aGuardedMachine(t *testing.T) (*Guard, *time.Time, *fakeResolved) { + t.Helper() + g, now, f, _ := aGuardedMachineWithLinks(t, "tun0") + return g, now, f +} + +// aGuardedMachineWithLinks is the same, over the links named, and answers the resolver too. +func aGuardedMachineWithLinks(t *testing.T, links ...string) (*Guard, *time.Time, *fakeResolved, *Resolver) { t.Helper() dir := t.TempDir() for _, d := range []string{"etc/node-resolver", "run"} { @@ -31,10 +40,11 @@ func aGuardedMachine(t *testing.T) (*Guard, *time.Time, *fakeResolved) { write(t, filepath.Join(dir, "etc/resolv.conf"), meshFile) now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) f := &fakeResolved{} + r := aMachine(t, f, links...) g := &Guard{Path: filepath.Join(dir, "etc/resolv.conf"), KeptPath: filepath.Join(dir, "etc/node-resolver/resolv.conf"), Dir: filepath.Join(dir, "run"), Hold: Hold, Now: func() time.Time { return now }, - Resolver: aMachine(t, f, "tun0"), Log: t.Logf, wake: make(chan struct{}, 1)} - return g, &now, f + Resolver: r, Log: t.Logf, wake: make(chan struct{}, 1)} + return g, &now, f, r } func write(t *testing.T, path, content string) { @@ -286,6 +296,119 @@ func TestTheNetworksServersAnswerWhileTheMeshsResolversAreSilent(t *testing.T) { step(g, routed, "Link 2 (wlan0): yes\nLink 7 (tun0): no\n", "resolvectl default-route wlan0 false") } +// The uplink's names are answered over the link carrying the default route, and move with the route: the +// old link loses them and keeps its own search domain (design 08 sign-in-page §7, §9; R-4, R-5). +func TestUplinkNamesMoveWithTheDefaultRoute(t *testing.T) { + g, _, f, r := aGuardedMachineWithLinks(t, "wlan0", "wlan1") + f.dns = "Link 2 (wlan0): 192.168.1.1\n" + f.domain = "Link 2 (wlan0): lan\n" + f.ip = "default via 10.0.0.1 dev wlan0 metric 100\n" + if err := os.WriteFile(r.UplinkNamesFile, []byte("check.example\n"), 0o644); err != nil { + t.Fatal(err) + } + g.KeepUplinkNames(context.Background()) + if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan ~check.example" { + t.Fatalf("wlan0 was given %v", f.changed) + } + if g.applied.Link != "wlan0" || strings.Join(g.applied.Names, ",") != "check.example" { + t.Fatalf("applied is %+v", g.applied) + } + applied := contentOf(t, r.UplinkNamesAppliedFile) + if !strings.Contains(applied, "wlan0") || !strings.Contains(applied, "check.example") { + t.Errorf("uplink-names.applied does not say so: %s", applied) + } + // The route moves to wlan1: wlan0, as resolved now holds it, keeps "lan" and the uplink's name. + f.domain = "Link 2 (wlan0): lan ~check.example\nLink 3 (wlan1):\n" + f.ip = "default via 10.1.0.1 dev wlan1 metric 50\n" + f.changed = nil + g.KeepUplinkNames(context.Background()) + if len(f.changed) != 2 { + t.Fatalf("moving the route changed %v", f.changed) + } + if strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan" { + t.Errorf("wlan0 lost the uplink's name but not its own: %v", f.changed[0]) + } + if strings.Join(f.changed[1], " ") != "resolvectl domain wlan1 ~check.example" { + t.Errorf("wlan1 was not given the uplink's name: %v", f.changed[1]) + } + if g.applied.Link != "wlan1" { + t.Errorf("applied is now %+v", g.applied) + } +} + +// A guard restarted with an applied file takes the uplink's names off the link it names, never inferring +// which (design 08 sign-in-page §8, §9; R-6). +func TestARestartedGuardTakesTheUplinkNamesOffTheLinkItNames(t *testing.T) { + g, _, f, r := aGuardedMachineWithLinks(t, "wlan0", "wlan1") + f.dns = "Link 2 (wlan0): 192.168.1.1\n" + f.domain = "Link 2 (wlan0): lan ~check.example\nLink 3 (wlan1):\n" + f.ip = "default via 10.1.0.1 dev wlan1 metric 50\n" // the route has already moved to wlan1 + applied := UplinkApplied{Names: []string{"check.example"}, Link: "wlan0", At: time.Now()} + raw, _ := json.Marshal(applied) + if err := os.WriteFile(r.UplinkNamesAppliedFile, raw, 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(r.UplinkNamesFile, []byte("check.example\n"), 0o644); err != nil { + t.Fatal(err) + } + g.applied = ReadUplinkApplied(r.UplinkNamesAppliedFile) // what the guard does at its start + g.KeepUplinkNames(context.Background()) + if len(f.changed) != 2 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan" || + strings.Join(f.changed[1], " ") != "resolvectl domain wlan1 ~check.example" { + t.Errorf("the restarted guard did %v", f.changed) + } +} + +// A link holding only the uplink's names is still given its default route back while the mesh's resolvers +// are silent: the guard's own names are left out of whether it is judged `route` routed (design 08 +// sign-in-page §7, §9; DMC-2; issue 1981's AC1; R-7). +func TestALinkOfOnlyUplinkNamesStillGetsItsDefaultRouteBack(t *testing.T) { + g, _, f, r := aGuardedMachineWithLinks(t, "tun0") + g.Resolver.Answers = func(context.Context, string) bool { return false } // the mesh is silent + f.dns = "Global: 10.42.0.1\nLink 7 (tun0): 10.9.0.1\n" + f.domain = "Global: ~.\nLink 7 (tun0): ~check.example\n" // only the uplink's name, no search domain + f.defaults = "Link 7 (tun0): no\n" + applied := UplinkApplied{Names: []string{"check.example"}, Link: "tun0", At: time.Now()} + raw, _ := json.Marshal(applied) + if err := os.WriteFile(r.UplinkNamesAppliedFile, raw, 0o644); err != nil { + t.Fatal(err) + } + g.KeepRoutes(context.Background()) + if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl default-route tun0 true" { + t.Errorf("the fallback did %v, want tun0 given its default route back", f.changed) + } +} + +// A refusal by resolved is journalled once per change, never every round (design 08 sign-in-page §8; R-8). +func TestARefusalByResolvedIsJournalledOncePerChange(t *testing.T) { + g, _, f, r := aGuardedMachineWithLinks(t, "wlan0") + f.dns = "Link 2 (wlan0): 192.168.1.1\n" + f.ip = "default via 10.0.0.1 dev wlan0 metric 100\n" + if err := os.WriteFile(r.UplinkNamesFile, []byte("check.example\n"), 0o644); err != nil { + t.Fatal(err) + } + refuse := true + g.Resolver.Change = func(ctx context.Context, name string, args ...string) (string, error) { + if refuse && len(args) > 0 && args[0] == "domain" { + return "", errors.New("refused: not a domain mesh owns") + } + return f.change(ctx, name, args...) + } + var said []string + g.Log = func(format string, a ...any) { said = append(said, fmt.Sprintf(format, a...)) } + g.KeepUplinkNames(context.Background()) + g.KeepUplinkNames(context.Background()) // the file and the link are unchanged: no new refusal to say + count := 0 + for _, s := range said { + if strings.Contains(s, "refuses") { + count++ + } + } + if count != 1 { + t.Errorf("the refusal was journalled %d times, want once: %v", count, said) + } +} + // A network joined while the mesh's resolvers are silent keeps its default route, and loses it once one answers. // (1981/AC2) func TestANetworkJoinedWhileTheMeshIsSilentKeepsItsDefaultRoute(t *testing.T) { diff --git a/modules/systemd-resolved/cmd/resolver-tools/main.go b/modules/systemd-resolved/cmd/resolver-tools/main.go index 089f3f40d..b48a37a50 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/main.go +++ b/modules/systemd-resolved/cmd/resolver-tools/main.go @@ -47,6 +47,9 @@ func guard() error { return err } g.writeHistory() + // Read what it applied last, so a restart takes the uplink's names off the link it names, never + // inferring which (design 08 sign-in-page §8). + g.applied = ReadUplinkApplied(g.Resolver.UplinkNamesAppliedFile) go g.Run(ctx) return g.Serve(ctx, Socket) } diff --git a/modules/systemd-resolved/cmd/resolver-tools/resolver.go b/modules/systemd-resolved/cmd/resolver-tools/resolver.go index 19fcddff4..13c0fb00c 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/resolver.go +++ b/modules/systemd-resolved/cmd/resolver-tools/resolver.go @@ -258,8 +258,20 @@ func (r *Resolver) Routes(ctx context.Context) (*Routes, error) { } } sort.Strings(names) + // The guard's own uplink names (design 08 sign-in-page §7, DMC-2) are left out of whether a link is + // judged `route` routed: a link holding only those names is still the fallback's to give a default + // route back while the mesh's resolvers are silent, never one the fallback takes for a VPN's. + applied := ReadUplinkApplied(r.UplinkNamesAppliedFile) + marked := map[string]bool{} + for _, n := range applied.Names { + marked["~"+n] = true + } for _, name := range names { - s := Scope{Link: name, Servers: lServers[name], Domains: orEmpty(unrouted(lDomains[name])), routed: onlyRouting(lDomains[name])} + judge := lDomains[name] + if name == applied.Link && len(marked) > 0 { + judge = withoutMarked(judge, marked) + } + s := Scope{Link: name, Servers: lServers[name], Domains: orEmpty(unrouted(lDomains[name])), routed: onlyRouting(judge)} if d, ok := lDefault[name]; ok && len(d) > 0 { yes := d[0] == "yes" s.DefaultRoute = &yes @@ -269,6 +281,17 @@ func (r *Resolver) Routes(ctx context.Context) (*Routes, error) { return out, nil } +// withoutMarked is domains without those marked (design 08 sign-in-page DMC-2). +func withoutMarked(domains []string, marked map[string]bool) []string { + out := make([]string, 0, len(domains)) + for _, d := range domains { + if !marked[d] { + out = append(out, d) + } + } + return out +} + func orEmpty(s []string) []string { if s == nil { return []string{} From 9f5614b35ea9d3fa1f80ff2f50dd3908ac78c68b Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 21:26:30 +0100 Subject: [PATCH 03/12] systemd-resolved: routes answers the uplink's names and the mesh's fallback (issue 960) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit routes (bus and the machine socket) gains uplink_names {names, link, refused}, the applied list's names resolved holds on that link now, never the file's, and mesh_resolvers {silent, since} from the guard's fallback state. The guard writes that state at each of ADR 0688's two turns, and once more at its own first round, since it goes at every boot. Builds: design 08 sign-in-page §2, §8, §9 --- .../cmd/resolver-tools/guard.go | 64 +++++++++++++++-- .../cmd/resolver-tools/guard_test.go | 68 +++++++++++++++++++ .../cmd/resolver-tools/main.go | 3 +- .../cmd/resolver-tools/resolver.go | 36 +++++++++- .../cmd/resolver-tools/resolver_test.go | 1 + 5 files changed, 165 insertions(+), 7 deletions(-) diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard.go b/modules/systemd-resolved/cmd/resolver-tools/guard.go index 5d244d9d7..7fb736a67 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard.go @@ -46,6 +46,9 @@ const ( Socket = RunDir + "/verbs.sock" History = RunDir + "/history.json" Displaced = RunDir + "/displaced" + // Fallback is `routes`'s state for ADR 0688's fallback (design 08 sign-in-page §8, S-N5, R2-2): + // whether the mesh's resolvers are silent, and since when. + Fallback = RunDir + "/fallback.json" ) // Timing. @@ -94,6 +97,11 @@ type Guard struct { // silent is whether none of the mesh's resolvers answered at the last look, so each turn is said once. // Only the routes' loop reads and writes it. silent bool + // silentSince is when silent last changed, for Fallback's `since` (design 08 sign-in-page §8, S-N5). + silentSince time.Time + // fallbackWritten is whether Fallback has been written since this guard started; its first round + // writes it once more regardless of a turn, since it goes at every boot (§8). + fallbackWritten bool // applied is what the guard last gave the link carrying the default route (design 08 sign-in-page §8): // read at start from UplinkNamesAppliedFile, so a restart takes the names off the link it names, @@ -355,24 +363,69 @@ func (g *Guard) KeepRoutes(ctx context.Context) { return } if !g.Resolver.TheMeshAnswers(ctx, routes.Mesh.Servers) { - if !g.silent { + if turn := !g.silent; turn || !g.fallbackWritten { + if turn { + g.silentSince = g.Now() + } g.silent = true - g.Log("none of the mesh's resolvers answers; a network's own servers answer every name until one does") + g.writeFallback() + if turn { + g.Log("none of the mesh's resolvers answers; a network's own servers answer every name until one does") + } } if changed, err := g.Resolver.ADefaultRouteAgain(ctx, routes); err == nil && len(changed) > 0 { g.Log("%s answers every name again, while the mesh's resolvers are silent", strings.Join(changed, ", ")) } return } - if g.silent { + if turn := g.silent; turn || !g.fallbackWritten { + if turn { + g.silentSince = g.Now() + } g.silent = false - g.Log("one of the mesh's resolvers answers again") + g.writeFallback() + if turn { + g.Log("one of the mesh's resolvers answers again") + } } if changed, err := g.Resolver.OnlyTheMeshIsADefaultRoute(ctx); err == nil && len(changed) > 0 { g.Log("%s had servers answering every name; now only their own domains", strings.Join(changed, ", ")) } } +// Fallback is `routes`'s state for ADR 0688's fallback (design 08 sign-in-page §8). +type FallbackState struct { + Silent bool `json:"silent"` + Since time.Time `json:"since"` +} + +// writeFallback writes Resolver.FallbackFile whole, at each of the fallback's two turns, and once more at +// the guard's first round, since it goes at every boot (design 08 sign-in-page §8). +func (g *Guard) writeFallback() { + g.fallbackWritten = true + raw, err := json.MarshalIndent(FallbackState{Silent: g.silent, Since: g.silentSince}, "", " ") + if err != nil { + return + } + tmp := g.Resolver.FallbackFile + ".tmp" + if os.WriteFile(tmp, raw, 0o644) == nil { + _ = os.Rename(tmp, g.Resolver.FallbackFile) + } +} + +// ReadFallback reads what the guard last said of ADR 0688's fallback; the zero value before it has run. +func ReadFallback(path string) FallbackState { + raw, err := os.ReadFile(path) + if err != nil { + return FallbackState{} + } + var s FallbackState + if json.Unmarshal(raw, &s) != nil { + return FallbackState{} + } + return s +} + // sameNames is whether two name lists are the same, in the same order (the file holds them one a line, in // the order given). func sameNames(a, b []string) bool { @@ -499,7 +552,8 @@ func (g *Guard) Answer(ctx context.Context, req Request) Reply { case "routes": var routes *Routes if routes, err = g.Resolver.Routes(ctx); err == nil { - result = map[string]any{"mesh": routes.Mesh, "links": routes.Links} + result = map[string]any{"mesh": routes.Mesh, "links": routes.Links, + "uplink_names": g.Resolver.UplinkNamesAnswer(routes), "mesh_resolvers": g.Resolver.MeshResolversAnswer()} } case "route": var routed *Routed diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go index ca6a0ec94..2acfa29aa 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go @@ -41,6 +41,7 @@ func aGuardedMachineWithLinks(t *testing.T, links ...string) (*Guard, *time.Time now := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC) f := &fakeResolved{} r := aMachine(t, f, links...) + r.FallbackFile = filepath.Join(dir, "run", "fallback.json") g := &Guard{Path: filepath.Join(dir, "etc/resolv.conf"), KeptPath: filepath.Join(dir, "etc/node-resolver/resolv.conf"), Dir: filepath.Join(dir, "run"), Hold: Hold, Now: func() time.Time { return now }, Resolver: r, Log: t.Logf, wake: make(chan struct{}, 1)} @@ -409,6 +410,73 @@ func TestARefusalByResolvedIsJournalledOncePerChange(t *testing.T) { } } +// The guard writes Resolver.FallbackFile at each of ADR 0688's two turns, and once more at its own first +// round, since it goes at every boot (design 08 sign-in-page §8; S-N5, R2-2; R-9). +func TestTheGuardWritesTheFallbackFileAtEachTurnAndItsFirstRound(t *testing.T) { + g, now, f := aGuardedMachine(t) + meshAnswers := true + g.Resolver.Answers = func(context.Context, string) bool { return meshAnswers } + f.dns = "Global: 10.42.0.1\n" + f.domain = "Global: ~.\n" + // The first round, the mesh answering, writes the file although nothing changed. + g.KeepRoutes(context.Background()) + first := ReadFallback(g.Resolver.FallbackFile) + if first.Silent { + t.Fatalf("the first round says %+v, want not silent", first) + } + // A second round with nothing changed does not move `since`. + *now = now.Add(time.Second) + g.KeepRoutes(context.Background()) + if again := ReadFallback(g.Resolver.FallbackFile); !again.Since.Equal(first.Since) { + t.Errorf("an unchanged round moved since: %v, was %v", again.Since, first.Since) + } + // The mesh goes silent: the turn is written with the new since. + *now = now.Add(time.Second) + meshAnswers = false + g.KeepRoutes(context.Background()) + silentState := ReadFallback(g.Resolver.FallbackFile) + if !silentState.Silent || !silentState.Since.Equal(*now) { + t.Errorf("the silent turn is %+v, want silent since %v", silentState, *now) + } + // It answers again: the other turn. + *now = now.Add(time.Second) + meshAnswers = true + g.KeepRoutes(context.Background()) + answering := ReadFallback(g.Resolver.FallbackFile) + if answering.Silent || !answering.Since.Equal(*now) { + t.Errorf("the answering turn is %+v, want not silent since %v", answering, *now) + } +} + +// routes answers uplink_names with the applied list's names resolved holds on that link now, resolved's +// refusal, and mesh_resolvers from the fallback file (design 08 sign-in-page §2, §9; R-9). +func TestRoutesAnswersUplinkNamesAndMeshResolvers(t *testing.T) { + f := &fakeResolved{dns: "Link 2 (wlan0): 192.168.1.1\n", domain: "Link 2 (wlan0): lan ~check.example\n"} + r := aMachine(t, f, "wlan0") + applied := UplinkApplied{Names: []string{"check.example", "not-held.example"}, Link: "wlan0", Refused: "refused once"} + raw, _ := json.Marshal(applied) + if err := os.WriteFile(r.UplinkNamesAppliedFile, raw, 0o644); err != nil { + t.Fatal(err) + } + since := time.Date(2026, 11, 24, 10, 0, 0, 0, time.UTC) + fb, _ := json.Marshal(FallbackState{Silent: true, Since: since}) + if err := os.WriteFile(r.FallbackFile, fb, 0o644); err != nil { + t.Fatal(err) + } + routes, err := r.Routes(context.Background()) + if err != nil { + t.Fatal(err) + } + un := r.UplinkNamesAnswer(routes) + if names, _ := un["names"].([]string); strings.Join(names, ",") != "check.example" || un["link"] != "wlan0" || un["refused"] != "refused once" { + t.Errorf("uplink_names is %+v", un) + } + mr := r.MeshResolversAnswer() + if mr["silent"] != true || !mr["since"].(time.Time).Equal(since) { + t.Errorf("mesh_resolvers is %+v", mr) + } +} + // A network joined while the mesh's resolvers are silent keeps its default route, and loses it once one answers. // (1981/AC2) func TestANetworkJoinedWhileTheMeshIsSilentKeepsItsDefaultRoute(t *testing.T) { diff --git a/modules/systemd-resolved/cmd/resolver-tools/main.go b/modules/systemd-resolved/cmd/resolver-tools/main.go index b48a37a50..440625dea 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/main.go +++ b/modules/systemd-resolved/cmd/resolver-tools/main.go @@ -81,7 +81,8 @@ func tools(r *Resolver, history string) []stdio.Tool { if err != nil { return nil, err } - return map[string]any{"mesh": routes.Mesh, "links": routes.Links, "outside_writes": ReadHistory(history)}, nil + return map[string]any{"mesh": routes.Mesh, "links": routes.Links, "outside_writes": ReadHistory(history), + "uplink_names": r.UplinkNamesAnswer(routes), "mesh_resolvers": r.MeshResolversAnswer()}, nil }), verb("route", "Send these domains, and every name under them, to these servers over this link, and only "+ "them: the link never answers other names, and the mesh's own domain is refused. Replaces whatever the "+ diff --git a/modules/systemd-resolved/cmd/resolver-tools/resolver.go b/modules/systemd-resolved/cmd/resolver-tools/resolver.go index 13c0fb00c..2d6b8c851 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/resolver.go +++ b/modules/systemd-resolved/cmd/resolver-tools/resolver.go @@ -99,6 +99,9 @@ type Resolver struct { UplinkNamesFile string // UplinkNamesAppliedFile is what the guard last gave the link carrying the default route (§8). UplinkNamesAppliedFile string + // FallbackFile is `routes`'s state for ADR 0688's fallback (§8): whether the mesh's resolvers are + // silent, and since when. + FallbackFile string // WriteUplinkNames writes UplinkNamesFile whole, as root (§6); stood in for in tests. WriteUplinkNames func(ctx context.Context, content []byte) error // Now is the clock the uplink-names verb stamps its answer with; stood in for in tests. @@ -109,7 +112,8 @@ type Resolver struct { func ThisResolver() *Resolver { r := &Resolver{Change: execRunner, Read: readRunner, NetDir: "/sys/class/net", SuffixFile: SuffixPath, AnswerWithinFile: AnswerWithinPath, PrivateInterfaceFile: PrivateInterfacePath, - UplinkNamesFile: UplinkNamesPath, UplinkNamesAppliedFile: UplinkNamesAppliedPath, Now: time.Now} + UplinkNamesFile: UplinkNamesPath, UplinkNamesAppliedFile: UplinkNamesAppliedPath, FallbackFile: Fallback, + Now: time.Now} r.Answers = r.asks r.WriteUplinkNames = r.writeUplinkNamesFile return r @@ -281,6 +285,36 @@ func (r *Resolver) Routes(ctx context.Context) (*Routes, error) { return out, nil } +// UplinkNamesAnswer is `routes`'s `uplink_names` field (design 08 sign-in-page §2, §9; DQ-3): the applied +// list's names that resolved holds on that link now, never the file's, the link, and resolved's refusal or +// empty. +func (r *Resolver) UplinkNamesAnswer(routes *Routes) map[string]any { + applied := ReadUplinkApplied(r.UplinkNamesAppliedFile) + held := []string{} + for _, l := range routes.Links { + if l.Link != applied.Link { + continue + } + has := map[string]bool{} + for _, d := range l.Domains { + has[d] = true + } + for _, n := range applied.Names { + if has[n] { + held = append(held, n) + } + } + } + return map[string]any{"names": held, "link": applied.Link, "refused": applied.Refused} +} + +// MeshResolversAnswer is `routes`'s `mesh_resolvers` field (design 08 sign-in-page §9; S-N5): whether the +// mesh's resolvers are silent now, by ADR 0688's guard, and since when. +func (r *Resolver) MeshResolversAnswer() map[string]any { + s := ReadFallback(r.FallbackFile) + return map[string]any{"silent": s.Silent, "since": s.Since} +} + // withoutMarked is domains without those marked (design 08 sign-in-page DMC-2). func withoutMarked(domains []string, marked map[string]bool) []string { out := make([]string, 0, len(domains)) diff --git a/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go b/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go index acb722f93..caceb0cd8 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go @@ -59,6 +59,7 @@ func aMachine(t *testing.T, f *fakeResolved, links ...string) *Resolver { PrivateInterfaceFile: filepath.Join(dir, "private-interface"), UplinkNamesFile: filepath.Join(dir, "uplink-names"), UplinkNamesAppliedFile: filepath.Join(dir, "uplink-names.applied"), + FallbackFile: filepath.Join(dir, "fallback.json"), Now: func() time.Time { return time.Date(2026, 11, 24, 12, 0, 0, 0, time.UTC) }, WriteUplinkNames: func(_ context.Context, content []byte) error { return os.WriteFile(filepath.Join(dir, "uplink-names"), content, 0o644) From 0c2a95aacd6de2def6dba79cfb399105de33f27f Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 21:33:25 +0100 Subject: [PATCH 04/12] systemd-resolved: README names uplink-names, its files and the guard's new duty (issue 960) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Says the verb and its answer, the two new files (uplink-names, its applied record) and fallback.json, the guard's round over the default- route link, the sudo -n install / mv -f commands, and that uplink-names only sets how resolved answers those names over a link, never the link itself. Builds: design 08 sign-in-page §10 --- modules/systemd-resolved/README.md | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/modules/systemd-resolved/README.md b/modules/systemd-resolved/README.md index 17c752a8f..dfaaf9c3a 100644 --- a/modules/systemd-resolved/README.md +++ b/modules/systemd-resolved/README.md @@ -20,6 +20,10 @@ itself (NetworkManager's VPNs, WireGuard set up by networkd, Tailscale) needs no | `/etc/node-resolver/suffix` | the mesh's own domain, which a route may never take | | `/etc/systemd/resolved.conf.d/50-mesh.conf` | every mesh resolver as the default route for names (`DNS=`, `Domains=~.`), no public fallback, the stub on loopback and on the private address, no cache, no LLMNR or mDNS | | `/etc/node-resolver/answer-within` | the config value `answer-within`: how long the guard gives each of the mesh's resolvers to answer before it takes them for silent (issue 1981) | +| `/etc/node-resolver/private-interface` | the private network's own interface name, so the guard never gives the uplink's names to it (design 08 sign-in-page §7, DQ-1) | +| `/var/lib/node-resolver/uplink-names` | the host names `uplink-names` gave, one a line, root's, written through `sudo -n install` then `sudo -n mv -f` (§6); stays until an empty list or a person's cleanup, even once the module leaves | +| `/var/lib/node-resolver/uplink-names.applied` | the guard's own record of what it last gave the link carrying the default route: the names, the link, when, and resolved's refusal or empty (§8); read at the guard's start, so a restart takes the names off the link it names, never inferring which | +| `/run/node-resolver/fallback.json` | whether the mesh's resolvers are silent now, by ADR 0688's guard, and since when; `routes`' `mesh_resolvers` field reads it; gone at the next boot, and the guard's first round writes it again | **On the private address, so containers reach it.** A container copies its machine's resolver file and cannot reach the machine's loopback, so the file names the address the machine has on the private @@ -61,6 +65,20 @@ One long-running process, as root: `resolver-tools guard`. its journal, and the node's network check still says the mesh's names do not resolve. - **What it says elsewhere** — the `routes` verb's `outside_writes`, from `/run/node-resolver/history.json` — is when, the writer's name and what became of each write. It never includes a server or a domain. +- **It gives the uplink's holder's check names to the link carrying the default route.** Every round it + reads `/var/lib/node-resolver/uplink-names` and finds the link that carries the default route: among the + kernel's IPv4 default routes, or the IPv6 ones when there is none, the one with the lowest metric whose + link is neither one `route` routed (a VPN's) nor the private network's own interface (its own fact, + `/etc/node-resolver/private-interface`); none when there is no such link. It gives that link its own + domains plus one routing-only domain `~` per name, keeping every search domain and routing domain it + already has, and takes the names off the link they were on before, when that differs: never a link's + servers, its default route for names (that stays the fallback's alone), its addresses or its routes. It + never counts its own names when it judges whether a link is `route` routed, so a link holding only them + still has its default route given back by the fallback while the mesh's resolvers are silent. What it + gave is kept in `/var/lib/node-resolver/uplink-names.applied`, read at the guard's own start, so a + restart never infers which link to take them off; a refusal by resolved is journalled once per change, + never every round. `uplink-names` only sets how resolved answers those names over a link — never the + link itself, which the network manager chooses. ## Its verbs @@ -68,14 +86,16 @@ On the mesh, through the node's runtime as the operator account (writes escalate | verb | does | |---|---| -| `/node-resolver.routes` (r) | the mesh's resolvers, each link given servers of its own with its routed domains and whether it is a default route, and the resolver file's outside writes | +| `/node-resolver.routes` (r) | the mesh's resolvers, each link given servers of its own with its routed domains and whether it is a default route, and the resolver file's outside writes. Also `uplink_names {names, link, refused}` (the applied list's names resolved holds on that link now, never the file's) and `mesh_resolvers {silent, since}` (ADR 0688's fallback). The machine's own socket answers the same | | `/node-resolver.route` (a) | `{link, domains, servers}`: these domains, and every name under them, to these servers over this link, and only them. The mesh's own domain and the root are refused | | `/node-resolver.unroute` (a) | `{link}`: that link's domains go to the mesh's resolvers again | +| `/node-resolver.uplink-names` (a) | `{names}`: at most 8 host names (letters, digits, hyphens and dots, lower-cased); an empty list takes them away. Writes `/var/lib/node-resolver/uplink-names` whole, through `sudo -n install -m 0644 -o root -g root /dev/stdin uplink-names.new` then `sudo -n mv -f uplink-names.new uplink-names`. Answers `{names, link, set_at}`: the names now given, the link they are answered over now (empty when no link carries a default route), and when. Refused, naming the name and why: not a host name (a wildcard, a trailing dot, a label over 63 bytes), the root, the mesh's own domain or under it, or more than 8 names | **On the machine, to its own root processes**, over `/run/node-resolver/verbs.sock` (mode 0600). The path is the seat's, so a caller does not need to know which holder answers. The protocol is one JSON line -`{"verb": …, "args": {…}}` and one JSON line back, `{"result": …}` or `{"error": "…"}`. The verbs are the -same three, plus: +`{"verb": …, "args": {…}}` and one JSON line back, `{"result": …}` or `{"error": "…"}`. The verbs are +`routes`, `route` and `unroute` (`uplink-names` is the bus's alone, never the machine's: its caller is +always on the bus), plus: - `displaced`: the write standing now, with what it held, or null; - `route` with `takes` (the write's `id`) and `by` (the module's name): route, then take that write, so From 691ad760d33c762ddfdc2f6dfb3d00f12775e9f6 Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 21:34:42 +0100 Subject: [PATCH 05/12] systemd-resolved: test that a changed list replaces the old one on the link (issue 960) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit R2's acceptance criteria name this case directly: the file's list changes while the default-route link stays the same, and the guard gives the new names to that same link without moving them first. Builds: design 08 sign-in-page §7, §9 --- .../cmd/resolver-tools/guard_test.go | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go index 2acfa29aa..c0e637059 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go @@ -337,6 +337,34 @@ func TestUplinkNamesMoveWithTheDefaultRoute(t *testing.T) { } } +// A changed list replaces the old one on the link, the route itself staying put (design 08 sign-in-page §9). +func TestAChangedListReplacesTheOldOneOnTheLink(t *testing.T) { + g, _, f, r := aGuardedMachineWithLinks(t, "wlan0") + f.dns = "Link 2 (wlan0): 192.168.1.1\n" + f.domain = "Link 2 (wlan0): lan\n" + f.ip = "default via 10.0.0.1 dev wlan0 metric 100\n" + if err := os.WriteFile(r.UplinkNamesFile, []byte("check.example\n"), 0o644); err != nil { + t.Fatal(err) + } + g.KeepUplinkNames(context.Background()) + if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan ~check.example" { + t.Fatalf("the first list was given as %v", f.changed) + } + // resolved now holds it; the file's list changes, the link stays the same. + f.domain = "Link 2 (wlan0): lan ~check.example\n" + f.changed = nil + if err := os.WriteFile(r.UplinkNamesFile, []byte("other.example\n"), 0o644); err != nil { + t.Fatal(err) + } + g.KeepUplinkNames(context.Background()) + if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan ~other.example" { + t.Errorf("the changed list was given as %v, want the old name replaced on the same link", f.changed) + } + if g.applied.Link != "wlan0" || strings.Join(g.applied.Names, ",") != "other.example" { + t.Errorf("applied is %+v", g.applied) + } +} + // A guard restarted with an applied file takes the uplink's names off the link it names, never inferring // which (design 08 sign-in-page §8, §9; R-6). func TestARestartedGuardTakesTheUplinkNamesOffTheLinkItNames(t *testing.T) { From ae7d0f874bf0aee4bf9493520f90f2d10fc19bc9 Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 21:36:32 +0100 Subject: [PATCH 06/12] systemd-resolved: declare the private-interface fact, the literal mesh0 (lead answer L-2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The fact itself was missing from the manifest (R2's own gap): the guard and the uplink-names verb's DefaultRouteLink already read /etc/node-resolver/private-interface, but nothing rendered it. Its template is the literal "mesh0" per L-2, quick not thorough: the live interface, named the same way already by netcheck's TunnelInterface and networkmanager's unmanaged-devices. One value every module reads instead is L-2's finding, carried outside this milestone. Builds: design 08 sign-in-page §7, DQ-1 --- modules/systemd-resolved/README.md | 2 +- modules/systemd-resolved/cmd/resolver-tools/manifest_test.go | 5 +++++ modules/systemd-resolved/cmd/resolver-tools/resolver.go | 5 ++++- modules/systemd-resolved/module.json | 4 ++++ 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/modules/systemd-resolved/README.md b/modules/systemd-resolved/README.md index dfaaf9c3a..3952968ed 100644 --- a/modules/systemd-resolved/README.md +++ b/modules/systemd-resolved/README.md @@ -20,7 +20,7 @@ itself (NetworkManager's VPNs, WireGuard set up by networkd, Tailscale) needs no | `/etc/node-resolver/suffix` | the mesh's own domain, which a route may never take | | `/etc/systemd/resolved.conf.d/50-mesh.conf` | every mesh resolver as the default route for names (`DNS=`, `Domains=~.`), no public fallback, the stub on loopback and on the private address, no cache, no LLMNR or mDNS | | `/etc/node-resolver/answer-within` | the config value `answer-within`: how long the guard gives each of the mesh's resolvers to answer before it takes them for silent (issue 1981) | -| `/etc/node-resolver/private-interface` | the private network's own interface name, so the guard never gives the uplink's names to it (design 08 sign-in-page §7, DQ-1) | +| `/etc/node-resolver/private-interface` | the private network's own interface name, so the guard never gives the uplink's names to it (design 08 sign-in-page §7, DQ-1); the literal `mesh0` (lead answer L-2), as netcheck and networkmanager already name it | | `/var/lib/node-resolver/uplink-names` | the host names `uplink-names` gave, one a line, root's, written through `sudo -n install` then `sudo -n mv -f` (§6); stays until an empty list or a person's cleanup, even once the module leaves | | `/var/lib/node-resolver/uplink-names.applied` | the guard's own record of what it last gave the link carrying the default route: the names, the link, when, and resolved's refusal or empty (§8); read at the guard's start, so a restart takes the names off the link it names, never inferring which | | `/run/node-resolver/fallback.json` | whether the mesh's resolvers are silent now, by ADR 0688's guard, and since when; `routes`' `mesh_resolvers` field reads it; gone at the next boot, and the guard's first round writes it again | diff --git a/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go b/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go index 446319888..7d04d7847 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go @@ -53,6 +53,11 @@ func TestTheManifestSaysWhatTheGuardKeeps(t *testing.T) { if m.Facts["resolvers"].Path != ResolvConf || m.Facts["kept"].Path != KeptPath || m.Facts["suffix"].Path != SuffixPath { t.Errorf("the rendered paths are not the ones the guard reads: %+v", m.Facts) } + // design 08 sign-in-page §7, DQ-1; lead answer L-2: the literal interface name, as netcheck and + // networkmanager already name it. + if m.Facts["private-interface"].Path != PrivateInterfacePath || m.Facts["private-interface"].Template != "mesh0\n" { + t.Errorf("the private interface fact is %+v", m.Facts["private-interface"]) + } if m.Facts["resolvers"].Template != m.Facts["kept"].Template { t.Error("the resolver file and the copy the guard puts back are not one template") } diff --git a/modules/systemd-resolved/cmd/resolver-tools/resolver.go b/modules/systemd-resolved/cmd/resolver-tools/resolver.go index 2d6b8c851..3079dd114 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/resolver.go +++ b/modules/systemd-resolved/cmd/resolver-tools/resolver.go @@ -163,7 +163,10 @@ func (r *Resolver) asks(ctx context.Context, server string) bool { const SuffixPath = "/etc/node-resolver/suffix" // PrivateInterfacePath is the file the mesh renders the private network's own interface name into, -// beside SuffixPath (the manifest's fact `private-interface`; design 08 sign-in-page §7, DQ-1). +// beside SuffixPath (the manifest's fact `private-interface`; design 08 sign-in-page §7, DQ-1). The fact's +// template is the literal `mesh0` (lead answer L-2): the live interface, named the same way already by +// netcheck's `TunnelInterface` and networkmanager's `unmanaged-devices`; one value every module reads +// instead is the thorough fix, carried as a finding outside this milestone. const PrivateInterfacePath = "/etc/node-resolver/private-interface" // UplinkNamesPath is where `uplink-names` keeps the host names, one a line, whole (design 08 sign-in-page diff --git a/modules/systemd-resolved/module.json b/modules/systemd-resolved/module.json index a0eb879f4..e569346a5 100644 --- a/modules/systemd-resolved/module.json +++ b/modules/systemd-resolved/module.json @@ -67,6 +67,10 @@ "suffix": { "path": "/etc/node-resolver/suffix", "template": "{{.Suffix}}\n" + }, + "private-interface": { + "path": "/etc/node-resolver/private-interface", + "template": "mesh0\n" } }, "resources": [ From 717f8ec2e5a38a5c07fea1835f2c312febf6192f Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 22:00:15 +0100 Subject: [PATCH 07/12] systemd-resolved: answer with the generated contract's own types (review r1 C-6, C-8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C-6: import noderesolver (mesh-networking's seat definition) at the zero version; routes, route, unroute and uplink-names answer with its RoutesAnswer, RouteAnswer, UnrouteAnswer and UplinkNamesAnswer, never a map or a parallel struct, and uplink-names' input names is a JSON array (arrayArg), never a comma- or space-split string. C-8: the names file write's 15 s is the stated constant WriteUplinkNamesBound, not an inline literal. Builds: design 08 sign-in-page §2, §5, §6, §9, DQ-12, C-6, C-8 --- .../cmd/resolver-tools/guard.go | 5 +- .../cmd/resolver-tools/guard_test.go | 8 +- .../cmd/resolver-tools/main.go | 27 +++- .../cmd/resolver-tools/resolver.go | 119 +++++++++++++----- .../cmd/resolver-tools/resolver_test.go | 2 +- modules/systemd-resolved/go.mod | 5 +- 6 files changed, 121 insertions(+), 45 deletions(-) diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard.go b/modules/systemd-resolved/cmd/resolver-tools/guard.go index 7fb736a67..3761e12e2 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard.go @@ -552,8 +552,9 @@ func (g *Guard) Answer(ctx context.Context, req Request) Reply { case "routes": var routes *Routes if routes, err = g.Resolver.Routes(ctx); err == nil { - result = map[string]any{"mesh": routes.Mesh, "links": routes.Links, - "uplink_names": g.Resolver.UplinkNamesAnswer(routes), "mesh_resolvers": g.Resolver.MeshResolversAnswer()} + // The machine's socket answers routes the same as the bus's (§5, DQ-5), with no outside_writes + // of its own list: a module on the machine reads displaced over its own verb. + result = g.Resolver.RoutesAnswer(routes, nil) } case "route": var routed *Routed diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go index c0e637059..7bd693572 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go @@ -495,12 +495,12 @@ func TestRoutesAnswersUplinkNamesAndMeshResolvers(t *testing.T) { if err != nil { t.Fatal(err) } - un := r.UplinkNamesAnswer(routes) - if names, _ := un["names"].([]string); strings.Join(names, ",") != "check.example" || un["link"] != "wlan0" || un["refused"] != "refused once" { + un := r.UplinkNamesField(routes) + if strings.Join(un.Names, ",") != "check.example" || un.Link != "wlan0" || un.Refused != "refused once" { t.Errorf("uplink_names is %+v", un) } - mr := r.MeshResolversAnswer() - if mr["silent"] != true || !mr["since"].(time.Time).Equal(since) { + mr := r.MeshResolversField() + if !mr.Silent || mr.Since != since.UTC().Format(time.RFC3339) { t.Errorf("mesh_resolvers is %+v", mr) } } diff --git a/modules/systemd-resolved/cmd/resolver-tools/main.go b/modules/systemd-resolved/cmd/resolver-tools/main.go index 440625dea..f77f3d373 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/main.go +++ b/modules/systemd-resolved/cmd/resolver-tools/main.go @@ -63,6 +63,25 @@ func arg(a map[string]any, k string) string { return v } +// stringArray declares an input as an array of strings, as the seat's definition says `names` is (design 08 +// sign-in-page C-6, DQ-12): never a string a caller must separate by hand. +func stringArray(description string) map[string]any { + return map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": description} +} + +// arrayArg reads an argument declared with stringArray: a JSON array of strings, empty for anything else +// (never comma- or space-split, unlike Split). +func arrayArg(a map[string]any, k string) []string { + list, _ := a[k].([]any) + out := make([]string, 0, len(list)) + for _, v := range list { + if s, ok := v.(string); ok { + out = append(out, s) + } + } + return out +} + // verb is one of the seat's verbs: listed as `.`, so the runtime serves it on the seat's // subject, as /node-resolver.. func verb(name, description string, input map[string]any, run func(a map[string]any) (any, error)) stdio.Tool { @@ -81,8 +100,8 @@ func tools(r *Resolver, history string) []stdio.Tool { if err != nil { return nil, err } - return map[string]any{"mesh": routes.Mesh, "links": routes.Links, "outside_writes": ReadHistory(history), - "uplink_names": r.UplinkNamesAnswer(routes), "mesh_resolvers": r.MeshResolversAnswer()}, nil + answer := r.RoutesAnswer(routes, ReadHistory(history)) + return &answer, nil }), verb("route", "Send these domains, and every name under them, to these servers over this link, and only "+ "them: the link never answers other names, and the mesh's own domain is refused. Replaces whatever the "+ @@ -101,7 +120,7 @@ func tools(r *Resolver, history string) []stdio.Tool { "working network it tests resolves through the network it tests: at most 8, each a host name of "+ "letters, digits, hyphens and dots; an empty list takes them away. Refused, naming the name and why: "+ "not a host name, the root, the mesh's own domain or under it, or more than 8. (a)", - map[string]any{"names": str("the host names, separated by spaces or commas; empty clears them")}, - func(a map[string]any) (any, error) { return r.SetUplinkNames(ctx, Split(a["names"])) }), + map[string]any{"names": stringArray("the host names, at most 8; an empty array clears them")}, + func(a map[string]any) (any, error) { return r.SetUplinkNames(ctx, arrayArg(a, "names")) }), } } diff --git a/modules/systemd-resolved/cmd/resolver-tools/resolver.go b/modules/systemd-resolved/cmd/resolver-tools/resolver.go index 3079dd114..982bd2c8e 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/resolver.go +++ b/modules/systemd-resolved/cmd/resolver-tools/resolver.go @@ -27,8 +27,27 @@ import ( "strconv" "strings" "time" + + noderesolver "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver" ) +// rfc3339 is a time as the generated contract's answers hold one, RFC 3339, empty for the zero time +// (design 08 sign-in-page C-6, DQ-12). +func rfc3339(t time.Time) string { + if t.IsZero() { + return "" + } + return t.UTC().Format(time.RFC3339) +} + +// rfc3339Ptr is the same for a time that may not have happened yet. +func rfc3339Ptr(t *time.Time) string { + if t == nil { + return "" + } + return rfc3339(*t) +} + // Runner runs one command — as root when it changes something — and answers what it printed. type Runner func(ctx context.Context, name string, args ...string) (string, error) @@ -288,10 +307,10 @@ func (r *Resolver) Routes(ctx context.Context) (*Routes, error) { return out, nil } -// UplinkNamesAnswer is `routes`'s `uplink_names` field (design 08 sign-in-page §2, §9; DQ-3): the applied -// list's names that resolved holds on that link now, never the file's, the link, and resolved's refusal or -// empty. -func (r *Resolver) UplinkNamesAnswer(routes *Routes) map[string]any { +// UplinkNamesField is `routes`'s `uplink_names` field, the generated contract's own type (design 08 +// sign-in-page §2, §9, C-6; DQ-3, DQ-12): the applied list's names that resolved holds on that link now, +// never the file's, the link, and resolved's refusal or empty. +func (r *Resolver) UplinkNamesField(routes *Routes) noderesolver.UplinkNames { applied := ReadUplinkApplied(r.UplinkNamesAppliedFile) held := []string{} for _, l := range routes.Links { @@ -308,14 +327,58 @@ func (r *Resolver) UplinkNamesAnswer(routes *Routes) map[string]any { } } } - return map[string]any{"names": held, "link": applied.Link, "refused": applied.Refused} + return noderesolver.UplinkNames{Names: held, Link: applied.Link, Refused: applied.Refused} } -// MeshResolversAnswer is `routes`'s `mesh_resolvers` field (design 08 sign-in-page §9; S-N5): whether the -// mesh's resolvers are silent now, by ADR 0688's guard, and since when. -func (r *Resolver) MeshResolversAnswer() map[string]any { +// MeshResolversField is `routes`'s `mesh_resolvers` field, the generated contract's own type (design 08 +// sign-in-page §9, C-6; S-N5, DQ-12): whether the mesh's resolvers are silent now, by ADR 0688's guard, and +// since when. +func (r *Resolver) MeshResolversField() noderesolver.MeshResolvers { s := ReadFallback(r.FallbackFile) - return map[string]any{"silent": s.Silent, "since": s.Since} + return noderesolver.MeshResolvers{Silent: s.Silent, Since: rfc3339(s.Since)} +} + +// ScopeField is one scope as the generated contract answers it (design 08 sign-in-page C-6, DQ-12). +func ScopeField(s Scope) noderesolver.Scope { + return noderesolver.Scope{Link: s.Link, Servers: orEmpty(s.Servers), Domains: orEmpty(s.Domains), + DefaultRoute: s.DefaultRoute != nil && *s.DefaultRoute} +} + +// ScopeFields is every scope as the generated contract answers them. +func ScopeFields(ss []Scope) []noderesolver.Scope { + out := make([]noderesolver.Scope, len(ss)) + for i, s := range ss { + out[i] = ScopeField(s) + } + return out +} + +// OutsideWriteField is one outside write as the generated contract answers it. +func OutsideWriteField(d Displacement) noderesolver.OutsideWrite { + return noderesolver.OutsideWrite{ID: d.ID, At: rfc3339(d.At), Writer: d.Writer, TakenBy: d.TakenBy, + TakenAt: rfc3339Ptr(d.TakenAt), Ended: rfc3339Ptr(d.Ended), How: d.How} +} + +// OutsideWriteFields is every outside write as the generated contract answers them. +func OutsideWriteFields(ds []Displacement) []noderesolver.OutsideWrite { + out := make([]noderesolver.OutsideWrite, len(ds)) + for i, d := range ds { + out[i] = OutsideWriteField(d) + } + return out +} + +// RoutesAnswer is `routes`'s whole answer, the generated contract's own type (design 08 sign-in-page §2, +// §5, §9, C-6; DQ-12): what this machine's own resolver sends where, the resolver file's outside writes, +// and the uplink's names and the mesh's fallback. +func (r *Resolver) RoutesAnswer(routes *Routes, outside []Displacement) noderesolver.RoutesAnswer { + return noderesolver.RoutesAnswer{ + Mesh: ScopeField(routes.Mesh), + Links: ScopeFields(routes.Links), + OutsideWrites: OutsideWriteFields(outside), + UplinkNames: r.UplinkNamesField(routes), + MeshResolvers: r.MeshResolversField(), + } } // withoutMarked is domains without those marked (design 08 sign-in-page DMC-2). @@ -337,12 +400,8 @@ func orEmpty(s []string) []string { } // Routed is what a route did. -type Routed struct { - Link string `json:"link"` - Servers []string `json:"servers"` - Domains []string `json:"domains"` - Said string `json:"said"` -} +// Routed is `route`'s answer, the generated contract's own type (design 08 sign-in-page C-6, DQ-12). +type Routed = noderesolver.RouteAnswer var ( linkName = regexp.MustCompile(`^[A-Za-z0-9_.:@-]{1,15}$`) @@ -501,12 +560,17 @@ func (r *Resolver) HostNames(given []string) ([]string, error) { return out, nil } +// WriteUplinkNamesBound is how long the names file's write (install, then mv) is given before it is +// abandoned (design 08 sign-in-page §6, C-8): a stated constant, since nothing here says it is a setting +// the machine differs on. +const WriteUplinkNamesBound = 15 * time.Second + // writeUplinkNamesFile writes UplinkNamesFile whole (design 08 sign-in-page §6): `sudo -n install -m 0644 // -o root -g root /dev/stdin .new` with the lines on its input, then `sudo -n mv -f .new // `, so a reader never sees it half-written. As root (the guard never calls this; only the verb, // over the bus, does), both run unescalated. func (r *Resolver) writeUplinkNamesFile(ctx context.Context, content []byte) error { - ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + ctx, cancel := context.WithTimeout(ctx, WriteUplinkNamesBound) defer cancel() newPath := r.UplinkNamesFile + ".new" program, args := escalated(os.Getuid(), "install", []string{"-m", "0644", "-o", "root", "-g", "root", "/dev/stdin", newPath}) @@ -524,18 +588,10 @@ func (r *Resolver) writeUplinkNamesFile(ctx context.Context, content []byte) err return err } -// UplinkNames is `uplink-names`'s answer (design 08 sign-in-page §2): the names now given, the link they -// are answered over now (empty when no link carries a default route), and when the list was set. -type UplinkNames struct { - Names []string `json:"names"` - Link string `json:"link"` - SetAt time.Time `json:"set_at"` -} - // SetUplinkNames writes the host names the uplink's holder gives for its network's own check, through -// UplinkNamesFile (§6), and answers them with the link carrying the default route now (§2, DQ-2): empty -// when there is no such link. -func (r *Resolver) SetUplinkNames(ctx context.Context, given []string) (*UplinkNames, error) { +// UplinkNamesFile (§6), and answers them with the generated contract's own type (C-6, DQ-12): the link +// carrying the default route now (§2, DQ-2), empty when there is no such link, and when the list was set. +func (r *Resolver) SetUplinkNames(ctx context.Context, given []string) (*noderesolver.UplinkNamesAnswer, error) { names, err := r.HostNames(given) if err != nil { return nil, err @@ -551,7 +607,7 @@ func (r *Resolver) SetUplinkNames(ctx context.Context, given []string) (*UplinkN if routes, rerr := r.Routes(ctx); rerr == nil { link, _ = r.DefaultRouteLink(ctx, routes) } - return &UplinkNames{Names: names, Link: link, SetAt: r.Now()}, nil + return &noderesolver.UplinkNamesAnswer{Names: names, Link: link, SetAt: rfc3339(r.Now())}, nil } // ReadUplinkNames reads the host names `uplink-names` last wrote, one a line; empty before it has. @@ -694,11 +750,8 @@ func (r *Resolver) Route(ctx context.Context, link string, domains, servers []st Said: fmt.Sprintf("%d domains go to %d servers over %s; every other name to the mesh's resolvers", len(ds), len(ss), link)}, nil } -// Unrouted is what taking a route away did. -type Unrouted struct { - Link string `json:"link"` - Said string `json:"said"` -} +// Unrouted is `unroute`'s answer, the generated contract's own type (design 08 sign-in-page C-6, DQ-12). +type Unrouted = noderesolver.UnrouteAnswer // Unroute takes one link's route away. A link that has gone has nothing to take away. func (r *Resolver) Unroute(ctx context.Context, link string) (*Unrouted, error) { diff --git a/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go b/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go index caceb0cd8..f49345a3c 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go @@ -202,7 +202,7 @@ func TestUplinkNamesWritesTheFileAndAnswersThem(t *testing.T) { if strings.Join(got.Names, " ") != "check.example check2.example" { t.Errorf("the answer names %v", got.Names) } - if got.SetAt.IsZero() { + if got.SetAt == "" { t.Error("set_at was not stamped") } raw, err := os.ReadFile(r.UplinkNamesFile) diff --git a/modules/systemd-resolved/go.mod b/modules/systemd-resolved/go.mod index 0a105d761..bb58d1e11 100644 --- a/modules/systemd-resolved/go.mod +++ b/modules/systemd-resolved/go.mod @@ -2,7 +2,10 @@ module systemd-resolved go 1.26.0 -require git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 +require ( + git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver v0.0.0-00010101000000-000000000000 + git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 +) require ( github.com/klauspost/compress v1.20.1 // indirect From bd6dcdcd0c232fcaa3ebc41c752c8002935d5b53 Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 22:01:01 +0100 Subject: [PATCH 08/12] systemd-resolved: judge "in place" from what resolved holds now (review r1 C-4, note c) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit C-4: the guard reads the link's domains fresh with rawDomainsOf before skipping a round, never trusting its own applied record alone, so a network manager that rewrites the link's domains, or a restarted resolved, is found and the names are set again. note (c): fallback.json's since is the time of the guard's first round, never the zero time; it moved only on a real turn before, so the first round's write carried a zero since. Builds: design 08 sign-in-page §7, §8, C-4 --- .../cmd/resolver-tools/guard.go | 47 ++++++++++++---- .../cmd/resolver-tools/guard_test.go | 54 +++++++++++++++++-- 2 files changed, 89 insertions(+), 12 deletions(-) diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard.go b/modules/systemd-resolved/cmd/resolver-tools/guard.go index 3761e12e2..1511b19cf 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard.go @@ -364,9 +364,9 @@ func (g *Guard) KeepRoutes(ctx context.Context) { } if !g.Resolver.TheMeshAnswers(ctx, routes.Mesh.Servers) { if turn := !g.silent; turn || !g.fallbackWritten { - if turn { - g.silentSince = g.Now() - } + // since is this round's time whether it is a real turn or the guard's first round + // establishing where things stand (design 08 sign-in-page §8, note (c)): never the zero time. + g.silentSince = g.Now() g.silent = true g.writeFallback() if turn { @@ -379,9 +379,7 @@ func (g *Guard) KeepRoutes(ctx context.Context) { return } if turn := g.silent; turn || !g.fallbackWritten { - if turn { - g.silentSince = g.Now() - } + g.silentSince = g.Now() g.silent = false g.writeFallback() if turn { @@ -472,6 +470,32 @@ func (g *Guard) setLinkUplinkNames(ctx context.Context, link string, names []str return err } +// uplinkNamesHeld is whether resolved holds every name on the link now, read fresh with rawDomainsOf +// (design 08 sign-in-page §7, C-4): never the guard's own applied record alone, so a network manager that +// rewrites the link's domains, or a restarted resolved, is found and the names are set again. +func (g *Guard) uplinkNamesHeld(ctx context.Context, link string, names []string) bool { + if len(names) == 0 { + return true + } + if link == "" { + return false + } + raw, err := g.rawDomainsOf(ctx, link) + if err != nil { + return false + } + has := map[string]bool{} + for _, d := range raw { + has[d] = true + } + for _, n := range names { + if !has["~"+n] { + return false + } + } + return true +} + // KeepUplinkNames gives the names in the file to the link carrying the default route, every round (design // 08 sign-in-page §7, §8): it never sets a link's servers, its default route for names, its addresses or // its routes. A round in which they are already in place changes nothing. @@ -486,9 +510,11 @@ func (g *Guard) KeepUplinkNames(ctx context.Context) { g.Log("the kernel's default routes: %v", err) return } - if link == g.applied.Link && sameNames(given, g.applied.Names) && g.applied.Refused == "" { + held := g.uplinkNamesHeld(ctx, link, given) + if link == g.applied.Link && g.applied.Refused == "" && held { return } + missing := link == g.applied.Link && sameNames(given, g.applied.Names) && !held if g.applied.Link != "" && g.applied.Link != link { if err := g.setLinkUplinkNames(ctx, g.applied.Link, nil); err != nil { g.Log("taking the uplink's names off %s failed: %v", g.applied.Link, err) @@ -500,9 +526,12 @@ func (g *Guard) KeepUplinkNames(ctx context.Context) { refused = err.Error() } } - if link != g.applied.Link { + switch { + case link != g.applied.Link: g.Log("the uplink's names are now answered over %q, were %q", link, g.applied.Link) - } else if !sameNames(given, g.applied.Names) { + case missing: + g.Log("the uplink's names were missing from %s, as resolved holds it now; set again", link) + case !sameNames(given, g.applied.Names): g.Log("the uplink's names change on %s", link) } if refused != g.applied.Refused { diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go index 7bd693572..fb9723ff4 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go @@ -365,6 +365,53 @@ func TestAChangedListReplacesTheOldOneOnTheLink(t *testing.T) { } } +// A network manager that rewrites the link's domains (a DHCP renewal, say) loses the uplink's names; the +// guard judges "in place" from what resolved holds now, never its own record alone, and sets them again +// (design 08 sign-in-page §7; C-4). +func TestANetworkManagerRewriteOfTheLinksDomainsIsSetAgain(t *testing.T) { + g, _, f, r := aGuardedMachineWithLinks(t, "wlan0") + f.dns = "Link 2 (wlan0): 192.168.1.1\n" + f.domain = "Link 2 (wlan0): lan\n" + f.ip = "default via 10.0.0.1 dev wlan0 metric 100\n" + if err := os.WriteFile(r.UplinkNamesFile, []byte("check.example\n"), 0o644); err != nil { + t.Fatal(err) + } + g.KeepUplinkNames(context.Background()) + if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan ~check.example" { + t.Fatalf("the first round gave %v", f.changed) + } + // The network manager rewrites the link's domains: the uplink's name is gone, the applied record is not. + f.domain = "Link 2 (wlan0): lan\n" + f.changed = nil + g.KeepUplinkNames(context.Background()) + if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 lan ~check.example" { + t.Errorf("a rewrite that lost the uplink's name was not set again: %v", f.changed) + } +} + +// resolved itself restarts, forgetting every link's domains; the guard's next round, judging from what +// resolved holds now, sets the uplink's names again (design 08 sign-in-page §7; C-4). +func TestAResolvedRestartLosingTheLinksDomainsIsSetAgain(t *testing.T) { + g, _, f, r := aGuardedMachineWithLinks(t, "wlan0") + f.dns = "Link 2 (wlan0): 192.168.1.1\n" + f.domain = "Link 2 (wlan0): lan\n" + f.ip = "default via 10.0.0.1 dev wlan0 metric 100\n" + if err := os.WriteFile(r.UplinkNamesFile, []byte("check.example\n"), 0o644); err != nil { + t.Fatal(err) + } + g.KeepUplinkNames(context.Background()) + if len(f.changed) != 1 { + t.Fatalf("the first round gave %v", f.changed) + } + // resolved restarts: every link's domains are gone, the guard's applied record is not. + f.domain = "Link 2 (wlan0):\n" + f.changed = nil + g.KeepUplinkNames(context.Background()) + if len(f.changed) != 1 || strings.Join(f.changed[0], " ") != "resolvectl domain wlan0 ~check.example" { + t.Errorf("a restarted resolved was not given the uplink's names again: %v", f.changed) + } +} + // A guard restarted with an applied file takes the uplink's names off the link it names, never inferring // which (design 08 sign-in-page §8, §9; R-6). func TestARestartedGuardTakesTheUplinkNamesOffTheLinkItNames(t *testing.T) { @@ -446,11 +493,12 @@ func TestTheGuardWritesTheFallbackFileAtEachTurnAndItsFirstRound(t *testing.T) { g.Resolver.Answers = func(context.Context, string) bool { return meshAnswers } f.dns = "Global: 10.42.0.1\n" f.domain = "Global: ~.\n" - // The first round, the mesh answering, writes the file although nothing changed. + // The first round, the mesh answering, writes the file although nothing changed: since is the first + // round's time, never the zero time (design 08 sign-in-page note (c)). g.KeepRoutes(context.Background()) first := ReadFallback(g.Resolver.FallbackFile) - if first.Silent { - t.Fatalf("the first round says %+v, want not silent", first) + if first.Silent || !first.Since.Equal(*now) { + t.Fatalf("the first round says %+v, want not silent since %v", first, *now) } // A second round with nothing changed does not move `since`. *now = now.Add(time.Second) From a74afe71f30f42ab2110c3405345bb8275eac7cc Mon Sep 17 00:00:00 2001 From: jochen Date: Tue, 24 Nov 2026 22:01:21 +0100 Subject: [PATCH 09/12] systemd-resolved: an unknown path in its directory is left and journalled once (review r1 C-7) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The checks/owned check refuses a directory without unknown (ADR 0422 §8). /var/lib/node-resolver stays, its value "module" (lead answer L-1), not "program": no other program writes there. The guard looks for a path it does not know every round and, finding one, leaves it exactly as it is and says so to the journal once, never every round. Builds: design 08 sign-in-page §6, C-7 --- modules/systemd-resolved/README.md | 6 ++-- .../cmd/resolver-tools/guard.go | 31 +++++++++++++++++++ .../cmd/resolver-tools/guard_test.go | 27 ++++++++++++++++ .../cmd/resolver-tools/manifest_test.go | 11 +++++++ modules/systemd-resolved/module.json | 2 +- 5 files changed, 74 insertions(+), 3 deletions(-) diff --git a/modules/systemd-resolved/README.md b/modules/systemd-resolved/README.md index 3952968ed..09d510275 100644 --- a/modules/systemd-resolved/README.md +++ b/modules/systemd-resolved/README.md @@ -79,6 +79,8 @@ One long-running process, as root: `resolver-tools guard`. restart never infers which link to take them off; a refusal by resolved is journalled once per change, never every round. `uplink-names` only sets how resolved answers those names over a link — never the link itself, which the network manager chooses. +- **A path in its directory this module does not know** — `/var/lib/node-resolver` declares `unknown: + module` — is left exactly as it is, and said to the journal once, never every round (ADR 0422 §8). ## Its verbs @@ -86,10 +88,10 @@ On the mesh, through the node's runtime as the operator account (writes escalate | verb | does | |---|---| -| `/node-resolver.routes` (r) | the mesh's resolvers, each link given servers of its own with its routed domains and whether it is a default route, and the resolver file's outside writes. Also `uplink_names {names, link, refused}` (the applied list's names resolved holds on that link now, never the file's) and `mesh_resolvers {silent, since}` (ADR 0688's fallback). The machine's own socket answers the same | +| `/node-resolver.routes` (r) | the generated contract's `RoutesAnswer`: the mesh's resolvers, each link given servers of its own with its routed domains and whether it is a default route, and the resolver file's outside writes. Also `uplink_names {names, link, refused}` (the applied list's names resolved holds on that link now, never the file's) and `mesh_resolvers {silent, since}` (ADR 0688's fallback). The machine's own socket answers the same, without `outside_writes` (its own `displaced` verb gives the write standing now) | | `/node-resolver.route` (a) | `{link, domains, servers}`: these domains, and every name under them, to these servers over this link, and only them. The mesh's own domain and the root are refused | | `/node-resolver.unroute` (a) | `{link}`: that link's domains go to the mesh's resolvers again | -| `/node-resolver.uplink-names` (a) | `{names}`: at most 8 host names (letters, digits, hyphens and dots, lower-cased); an empty list takes them away. Writes `/var/lib/node-resolver/uplink-names` whole, through `sudo -n install -m 0644 -o root -g root /dev/stdin uplink-names.new` then `sudo -n mv -f uplink-names.new uplink-names`. Answers `{names, link, set_at}`: the names now given, the link they are answered over now (empty when no link carries a default route), and when. Refused, naming the name and why: not a host name (a wildcard, a trailing dot, a label over 63 bytes), the root, the mesh's own domain or under it, or more than 8 names | +| `/node-resolver.uplink-names` (a) | `{names}`, an array of at most 8 host names (letters, digits, hyphens and dots, lower-cased), as the generated contract's `UplinkNamesInput` says; an empty array takes them away. Writes `/var/lib/node-resolver/uplink-names` whole, through `sudo -n install -m 0644 -o root -g root /dev/stdin uplink-names.new` then `sudo -n mv -f uplink-names.new uplink-names`, within 15 s. Answers the contract's `UplinkNamesAnswer` `{names, link, set_at}`: the names now given, the link they are answered over now (empty when no link carries a default route), and when. Refused, naming the name and why: not a host name (a wildcard, a trailing dot, a label over 63 bytes), the root, the mesh's own domain or under it, or more than 8 names | **On the machine, to its own root processes**, over `/run/node-resolver/verbs.sock` (mode 0600). The path is the seat's, so a caller does not need to know which holder answers. The protocol is one JSON line diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard.go b/modules/systemd-resolved/cmd/resolver-tools/guard.go index 1511b19cf..4f54d14fa 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard.go @@ -107,6 +107,10 @@ type Guard struct { // read at start from UplinkNamesAppliedFile, so a restart takes the names off the link it names, // never inferring which. Only the uplink names' round reads and writes it. applied UplinkApplied + + // unknownSaid is every path in the uplink-names directory this module does not know, already said to + // the journal (design 08 sign-in-page C-7): said once, never every round. + unknownSaid map[string]bool } // NewGuard is the machine's. @@ -349,6 +353,7 @@ func (g *Guard) Run(ctx context.Context) { case <-routes.C: g.KeepRoutes(ctx) g.KeepUplinkNames(ctx) + g.checkUnknownPaths() } } } @@ -557,6 +562,32 @@ func (g *Guard) writeApplied() { } } +// checkUnknownPaths looks at the uplink-names directory for a path this module does not know (design 08 +// sign-in-page C-7; ADR 0422 §8, lead answer L-1): it leaves it exactly as it is, and says so to the +// journal once, never every round. +func (g *Guard) checkUnknownPaths() { + dir := filepath.Dir(g.Resolver.UplinkNamesFile) + entries, err := os.ReadDir(dir) + if err != nil { + return + } + known := map[string]bool{ + filepath.Base(g.Resolver.UplinkNamesFile): true, + filepath.Base(g.Resolver.UplinkNamesAppliedFile): true, + } + for _, e := range entries { + name := e.Name() + if known[name] || strings.HasSuffix(name, ".tmp") || g.unknownSaid[name] { + continue + } + if g.unknownSaid == nil { + g.unknownSaid = map[string]bool{} + } + g.unknownSaid[name] = true + g.Log("%s in %s is not this module's; left as it is", name, dir) + } +} + // Request is one call over the socket: a verb and its arguments, one JSON line. type Request struct { Verb string `json:"verb"` diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go index fb9723ff4..f1b1a7070 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go @@ -337,6 +337,33 @@ func TestUplinkNamesMoveWithTheDefaultRoute(t *testing.T) { } } +// A path in the uplink-names directory this module does not know is left exactly as it is, and said to +// the journal once, never every round (design 08 sign-in-page C-7; ADR 0422 §8, lead answer L-1). +func TestAnUnknownPathIsLeftAndJournalledOnce(t *testing.T) { + g, _, _, r := aGuardedMachineWithLinks(t, "wlan0") + dir := filepath.Dir(r.UplinkNamesFile) + stray := filepath.Join(dir, "a-program-left-this") + if err := os.WriteFile(stray, []byte("not this module's"), 0o644); err != nil { + t.Fatal(err) + } + var said []string + g.Log = func(format string, a ...any) { said = append(said, fmt.Sprintf(format, a...)) } + g.checkUnknownPaths() + g.checkUnknownPaths() + count := 0 + for _, s := range said { + if strings.Contains(s, "a-program-left-this") { + count++ + } + } + if count != 1 { + t.Errorf("said %d times, want once: %v", count, said) + } + if got := contentOf(t, stray); got != "not this module's" { + t.Errorf("the unknown path was changed: %q", got) + } +} + // A changed list replaces the old one on the link, the route itself staying put (design 08 sign-in-page §9). func TestAChangedListReplacesTheOldOneOnTheLink(t *testing.T) { g, _, f, r := aGuardedMachineWithLinks(t, "wlan0") diff --git a/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go b/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go index 7d04d7847..193e3a51c 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go @@ -58,6 +58,17 @@ func TestTheManifestSaysWhatTheGuardKeeps(t *testing.T) { if m.Facts["private-interface"].Path != PrivateInterfacePath || m.Facts["private-interface"].Template != "mesh0\n" { t.Errorf("the private interface fact is %+v", m.Facts["private-interface"]) } + // design 08 sign-in-page C-7; ADR 0422 §8, lead answer L-1: a directory needs `unknown`, and this + // one's is "module" (the guard leaves a path it does not know as it is), never "program". + uplinkDir := false + for _, r := range m.Resources { + if r["type"] == "directory" && r["path"] == "/var/lib/node-resolver" { + uplinkDir = r["unknown"] == "module" + } + } + if !uplinkDir { + t.Error("/var/lib/node-resolver's directory resource does not say unknown: module") + } if m.Facts["resolvers"].Template != m.Facts["kept"].Template { t.Error("the resolver file and the copy the guard puts back are not one template") } diff --git a/modules/systemd-resolved/module.json b/modules/systemd-resolved/module.json index e569346a5..4f0a7c73a 100644 --- a/modules/systemd-resolved/module.json +++ b/modules/systemd-resolved/module.json @@ -113,7 +113,7 @@ "type": "directory", "path": "/var/lib/node-resolver", "mode": "0755", - "unknown": "program" + "unknown": "module" } ], "build": { From 8f86aedeae12c6bb7e30591f3a8c772c9984fb3f Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 01:17:26 +0100 Subject: [PATCH 10/12] systemd-resolved: checkUnknownPaths knows exactly its own files (review r2 (4)) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It treated the verb's own uplink-names.new as unknown and accepted any bare *.tmp; it now knows exactly uplink-names, uplink-names.new, uplink-names.applied and uplink-names.applied.tmp, as §6 and §8 name them, and nothing else. Builds: design 08 sign-in-page §6, §8, C-7 --- .../cmd/resolver-tools/guard.go | 11 +++++++--- .../cmd/resolver-tools/guard_test.go | 22 +++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard.go b/modules/systemd-resolved/cmd/resolver-tools/guard.go index 4f54d14fa..4552d03d1 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard.go @@ -571,13 +571,18 @@ func (g *Guard) checkUnknownPaths() { if err != nil { return } + // Exactly what this module writes there (review r2 (4)): the names file and the one §6 writes it + // beside (uplink-names, uplink-names.new), the applied record and the one it is written beside (§8: + // uplink-names.applied, uplink-names.applied.tmp). Nothing else, a bare *.tmp included. known := map[string]bool{ - filepath.Base(g.Resolver.UplinkNamesFile): true, - filepath.Base(g.Resolver.UplinkNamesAppliedFile): true, + filepath.Base(g.Resolver.UplinkNamesFile): true, + filepath.Base(g.Resolver.UplinkNamesFile) + ".new": true, + filepath.Base(g.Resolver.UplinkNamesAppliedFile): true, + filepath.Base(g.Resolver.UplinkNamesAppliedFile) + ".tmp": true, } for _, e := range entries { name := e.Name() - if known[name] || strings.HasSuffix(name, ".tmp") || g.unknownSaid[name] { + if known[name] || g.unknownSaid[name] { continue } if g.unknownSaid == nil { diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go index f1b1a7070..6271f4b6d 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go @@ -364,6 +364,28 @@ func TestAnUnknownPathIsLeftAndJournalledOnce(t *testing.T) { } } +// The verb's own uplink-names.new and the guard's own uplink-names.applied.tmp are this module's, never +// said as unknown (design 08 sign-in-page §6, §8; review r2 (4)). +func TestItsOwnTemporaryFilesAreNeverSaidUnknown(t *testing.T) { + g, _, _, r := aGuardedMachineWithLinks(t, "wlan0") + // A directory of its own: /var/lib/node-resolver holds nothing but this module's files, unlike the + // fixture's shared one, which also keeps net/ and suffix for the Resolver's other paths. + dir := t.TempDir() + r.UplinkNamesFile = filepath.Join(dir, "uplink-names") + r.UplinkNamesAppliedFile = filepath.Join(dir, "uplink-names.applied") + for _, name := range []string{r.UplinkNamesFile + ".new", r.UplinkNamesAppliedFile + ".tmp"} { + if err := os.WriteFile(name, []byte(""), 0o644); err != nil { + t.Fatal(err) + } + } + var said []string + g.Log = func(format string, a ...any) { said = append(said, fmt.Sprintf(format, a...)) } + g.checkUnknownPaths() + if len(said) != 0 { + t.Errorf("said %v, want nothing for this module's own files", said) + } +} + // A changed list replaces the old one on the link, the route itself staying put (design 08 sign-in-page §9). func TestAChangedListReplacesTheOldOneOnTheLink(t *testing.T) { g, _, f, r := aGuardedMachineWithLinks(t, "wlan0") From d85938066966a59dfa421ec8452713ccacdf3a1b Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 01:17:55 +0100 Subject: [PATCH 11/12] systemd-resolved: the machine's socket answers routes with outside_writes too (review r2 (5)) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It answered an empty outside_writes while the bus answered the kept history; the socket now reads the guard's own history (its own history file, the same the bus's tools() reads in production), so both answer the same (§5, DQ-5). Builds: design 08 sign-in-page §5, §9, DQ-5 --- .../cmd/resolver-tools/guard.go | 8 ++++--- .../cmd/resolver-tools/guard_test.go | 21 +++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard.go b/modules/systemd-resolved/cmd/resolver-tools/guard.go index 4552d03d1..fbbf6dcd7 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard.go @@ -617,9 +617,11 @@ func (g *Guard) Answer(ctx context.Context, req Request) Reply { case "routes": var routes *Routes if routes, err = g.Resolver.Routes(ctx); err == nil { - // The machine's socket answers routes the same as the bus's (§5, DQ-5), with no outside_writes - // of its own list: a module on the machine reads displaced over its own verb. - result = g.Resolver.RoutesAnswer(routes, nil) + // The machine's socket answers routes the same as the bus's (§5, DQ-5, review r2 (5)): + // outside_writes is the guard's own history too, from the same file the bus's tools() reads + // (History, RunDir/history.json); g.Dir is that directory (RunDir in production, a test's own + // in a test), so both read one history. + result = g.Resolver.RoutesAnswer(routes, ReadHistory(filepath.Join(g.Dir, "history.json"))) } case "route": var routed *Routed diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go index 6271f4b6d..1337fc2ce 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go @@ -12,6 +12,8 @@ import ( "strings" "testing" "time" + + noderesolver "git.novox.be/novox/mesh-networking/modules/mesh-connectivity-contracts/go/seats/noderesolver" ) const meshFile = "# Managed by the mesh\nnameserver 10.42.0.2\noptions timeout:3 attempts:2 edns0\n" @@ -188,6 +190,25 @@ func TestNothingIsGuardedBeforeTheFileIsRendered(t *testing.T) { } } +// The machine's socket answers routes with outside_writes too, the guard's own history, the same the bus +// reads (design 08 sign-in-page §5; DQ-5, review r2 (5)). +func TestTheSocketsRoutesAnswersOutsideWritesFromTheGuardsOwnHistory(t *testing.T) { + g, _, _ := aGuardedMachine(t) + write(t, g.Path, vpnFile) + g.Tick() + reply := g.Answer(context.Background(), Request{Verb: "routes"}) + if reply.Error != "" { + t.Fatal(reply.Error) + } + answer, ok := reply.Result.(noderesolver.RoutesAnswer) + if !ok { + t.Fatalf("the result is %T, not a RoutesAnswer", reply.Result) + } + if len(answer.OutsideWrites) != 1 || answer.OutsideWrites[0].Writer != "FortiClient" { + t.Errorf("outside_writes is %+v, want the one the guard just kept", answer.OutsideWrites) + } +} + // The socket: a module routes and takes the write standing now in one call, and the module's file is // back; a bad request and an unknown verb are answered, not dropped; the socket is root's alone. func TestTheVerbsOnTheMachine(t *testing.T) { From ac50980ba1c9b69217b794b860b6fddf18c28bc5 Mon Sep 17 00:00:00 2001 From: jochen Date: Wed, 25 Nov 2026 01:18:09 +0100 Subject: [PATCH 12/12] systemd-resolved: the names file write refuses naming its bound on the deadline (review r2 (3)) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Past WriteUplinkNamesBound (15 s) the refusal read the bare signal the deadline killed the process with ("install failed: signal: killed"); it now names the bound and says the file was left as it was, for either step (install or mv). Builds: design 08 sign-in-page §6, C-8 --- .../cmd/resolver-tools/resolver.go | 14 ++++++++++++-- .../cmd/resolver-tools/resolver_test.go | 12 ++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/modules/systemd-resolved/cmd/resolver-tools/resolver.go b/modules/systemd-resolved/cmd/resolver-tools/resolver.go index 982bd2c8e..47bfb061a 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/resolver.go +++ b/modules/systemd-resolved/cmd/resolver-tools/resolver.go @@ -579,13 +579,23 @@ func (r *Resolver) writeUplinkNamesFile(ctx context.Context, content []byte) err var stderr bytes.Buffer cmd.Stderr = &stderr if err := cmd.Run(); err != nil { + // Past the bound, name it and say the file was left as it was (review r2 (3)), never the bare + // signal the deadline killed the process with. + if ctx.Err() == context.DeadlineExceeded { + return fmt.Errorf("the names file's write did not finish within %s; it was left as it was", WriteUplinkNamesBound) + } if said := strings.TrimSpace(stderr.String()); said != "" { return fmt.Errorf("install: %s", said) } return fmt.Errorf("install failed: %w", err) } - _, err := r.Change(ctx, "mv", "-f", newPath, r.UplinkNamesFile) - return err + if _, err := r.Change(ctx, "mv", "-f", newPath, r.UplinkNamesFile); err != nil { + if ctx.Err() == context.DeadlineExceeded { + return fmt.Errorf("the names file's write did not finish within %s; it was left as it was", WriteUplinkNamesBound) + } + return err + } + return nil } // SetUplinkNames writes the host names the uplink's holder gives for its network's own check, through diff --git a/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go b/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go index f49345a3c..967da14d2 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/resolver_test.go @@ -192,6 +192,18 @@ func TestChangesAreEscalatedOnlyWhenNotRoot(t *testing.T) { // Given names, uplink-names writes the file one a line and answers them (design 08 sign-in-page §2, §6; // R-1). +// Past the names file write's bound, the refusal names it and says the file was left as it was, never the +// bare signal the deadline killed the process with (design 08 sign-in-page §6; C-8, review r2 (3)). +func TestTheWriteRefusesNamingTheBoundOnTheDeadline(t *testing.T) { + r := aMachine(t, &fakeResolved{}, "tun0") + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Minute)) + defer cancel() + err := r.writeUplinkNamesFile(ctx, []byte("check.example\n")) + if err == nil || !strings.Contains(err.Error(), WriteUplinkNamesBound.String()) || !strings.Contains(err.Error(), "left as it was") { + t.Errorf("the refusal is %v, want it to name %s and say the file was left as it was", err, WriteUplinkNamesBound) + } +} + func TestUplinkNamesWritesTheFileAndAnswersThem(t *testing.T) { f := &fakeResolved{} r := aMachine(t, f, "tun0")