systemd-resolved: serve uplink-names, writing the host names file (issue 960)

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
This commit is contained in:
jochen
2026-11-24 21:19:35 +01:00
parent 03bf70a22b
commit a40d7fb1c4
5 changed files with 394 additions and 5 deletions
@@ -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"])) }),
}
}
@@ -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" {
@@ -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 <file>.new` with the lines on its input, then `sudo -n mv -f <file>.new
// <file>`, 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) {
@@ -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)
+9 -1
View File
@@ -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": {