diff --git a/modules/systemd-resolved/README.md b/modules/systemd-resolved/README.md index 17c752a8f..09d510275 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); 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 | **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,22 @@ 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. +- **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 @@ -68,14 +88,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 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}`, 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 -`{"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 diff --git a/modules/systemd-resolved/cmd/resolver-tools/guard.go b/modules/systemd-resolved/cmd/resolver-tools/guard.go index 0e39cd0d4..fbbf6dcd7 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,20 @@ 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, + // 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. @@ -335,6 +352,8 @@ func (g *Guard) Run(ctx context.Context) { g.Tick() case <-routes.C: g.KeepRoutes(ctx) + g.KeepUplinkNames(ctx) + g.checkUnknownPaths() } } } @@ -349,24 +368,231 @@ 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 { + // 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.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 { + 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 { + 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 +} + +// 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. +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 + } + 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) + } + } + refused := "" + if link != "" { + if err := g.setLinkUplinkNames(ctx, link, given); err != nil { + refused = err.Error() + } + } + switch { + case link != g.applied.Link: + g.Log("the uplink's names are now answered over %q, were %q", link, g.applied.Link) + 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 { + 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) + } +} + +// 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 + } + // 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.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] || 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"` @@ -391,7 +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 { - result = map[string]any{"mesh": routes.Mesh, "links": routes.Links} + // 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 b82e0d4ef..1337fc2ce 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/guard_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/guard_test.go @@ -4,12 +4,16 @@ import ( "bufio" "context" "encoding/json" + "errors" + "fmt" "net" "os" "path/filepath" "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" @@ -20,6 +24,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 +42,12 @@ 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...) + 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: 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) { @@ -177,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) { @@ -286,6 +318,311 @@ 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 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) + } +} + +// 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") + 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 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) { + 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) + } +} + +// 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: 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 || !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) + 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.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.MeshResolversField() + if !mr.Silent || mr.Since != since.UTC().Format(time.RFC3339) { + 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 f569654b1..f77f3d373 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) } @@ -60,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 { @@ -78,7 +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)}, 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 "+ @@ -93,5 +116,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": 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/manifest_test.go b/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go index c1ec63d42..193e3a51c 100644 --- a/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go +++ b/modules/systemd-resolved/cmd/resolver-tools/manifest_test.go @@ -53,6 +53,22 @@ 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"]) + } + // 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") } @@ -100,7 +116,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..47bfb061a 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" @@ -26,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) @@ -91,13 +111,30 @@ 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 + // 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. + 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, FallbackFile: Fallback, + Now: time.Now} r.Answers = r.asks + r.WriteUplinkNames = r.writeUplinkNamesFile return r } @@ -144,6 +181,28 @@ 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). 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 +// §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"` @@ -225,8 +284,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 @@ -236,6 +307,91 @@ func (r *Resolver) Routes(ctx context.Context) (*Routes, error) { return out, nil } +// 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 { + 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 noderesolver.UplinkNames{Names: held, Link: applied.Link, Refused: applied.Refused} +} + +// 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 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). +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{} @@ -244,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}$`) @@ -364,6 +516,216 @@ 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 +} + +// 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, WriteUplinkNamesBound) + 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 { + // 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) + } + 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 +// 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 + } + 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 &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. +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) { @@ -398,11 +760,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 79a29f933..967da14d2 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,15 @@ 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"), + 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) + }} } // A route sends the domains to the servers over the link, and only them: the link is first told it is @@ -173,6 +190,141 @@ 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") + 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 == "" { + 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/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 diff --git a/modules/systemd-resolved/module.json b/modules/systemd-resolved/module.json index 22a27ed7a..4f0a7c73a 100644 --- a/modules/systemd-resolved/module.json +++ b/modules/systemd-resolved/module.json @@ -28,7 +28,8 @@ "serves": [ "routes", "route", - "unroute" + "unroute", + "uplink-names" ] } ], @@ -66,6 +67,10 @@ "suffix": { "path": "/etc/node-resolver/suffix", "template": "{{.Suffix}}\n" + }, + "private-interface": { + "path": "/etc/node-resolver/private-interface", + "template": "mesh0\n" } }, "resources": [ @@ -102,6 +107,13 @@ "health": { "kind": "unit" } + }, + { + "id": "uplink-names", + "type": "directory", + "path": "/var/lib/node-resolver", + "mode": "0755", + "unknown": "module" } ], "build": {