domains: fresh DNS fixes from Astra R1 (#724)
P1: nameserver addresses come from tenant DNS, so every one passes publicNameserver (global unicast; no private, loopback, link-local, CGNAT/tailnet, NAT64, 6to4 or reserved ranges) before a socket opens. Tests dial through an injected Dial. P2: zones are tried nearest first and a refusing zone passes the question up (a cached CNAME can make the nearest NS set the wrong zone); 1 s per nameserver inside the 3 s lookup, IPv4 first; replies must answer the exact IN A question; CNAME chains must finish without a loop inside 8 hops, and only an out-of-zone target falls back to the cache; the backoff map expires and is capped; StampHealth gives at most 64 randomly ordered names a fresh look per pass, inside 30 s; special-use names (.internal sidecars) are skipped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Destination policy, zone climbing, per-server timeouts, exact reply matching, safe CNAME chains, bounded backoff and per-pass budget.
8 files changed,
+577
−189
docs/superpowers/notes/census-proposal-dns-fresh-lookup-724.md+3 −3internal/domains/export_test.go+12 −0internal/domains/freshdns.go+211 −91internal/domains/freshdns_stamp_test.go+39 −0internal/domains/freshdns_test.go+231 −64internal/domains/reconcile.go+74 −24internal/provision/testdata/plan14-root-reads-chain.tsv+1 −1internal/provision/testdata/plan14-root-reads-dns-fresh-lookup-724.tsv+6 −6
CI failed — run details
diff --git a/docs/superpowers/notes/census-proposal-dns-fresh-lookup-724.md b/docs/superpowers/notes/census-proposal-dns-fresh-lookup-724.md| index 0373ebc0a..361181038 100644 |
| --- a/docs/superpowers/notes/census-proposal-dns-fresh-lookup-724.md |
| +++ b/docs/superpowers/notes/census-proposal-dns-fresh-lookup-724.md |
| @@ -4,8 +4,8 @@ Ruling `census-ruling-dns-fresh-lookup-724`. The independent reviewer approves o |
| | unit | change | read sites | what changed | |
| |---|---|---|---| |
| -| `internal/domains/reconcile.go` `StampHealth` | body | unchanged (21) | DNS loops call freshDNSStatus: a second, uncached lookup for a non-apps-domain name whose cached verdict is "" or "elsewhere"; it may only upgrade to "pointing" (#724) | |
| | `internal/host/agent.go` `domainsTickConfig` | body | unchanged (2) | wires ResolveFresh to a FreshResolver over net.DefaultResolver (#724) | |
| +| `internal/domains/reconcile.go` `StampHealth` | sites | +registry:Alias, +registry:Host, +whole:Route ×3, +whole:RouteAlias ×3 | section 4 now computes every cached verdict first, then freshUpgrade gives up to 64 randomly ordered non-apps-domain names whose verdict is "" or "elsewhere" an uncached lookup (30 s pass budget) that may only upgrade to "pointing", then stamps; the extra sites are the indexed loops over the same rows (#724) | |
| Envelopes re-pinned: `internal/domains`, `internal/host`. |
| @@ -13,13 +13,13 @@ Review: a model from the other family than the author reads the branch's diff ag |
| Recorded dispositions, which each change must still satisfy: |
| -- `internal/domains/reconcile.go` `StampHealth`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route |
| - `internal/host/agent.go` `domainsTickConfig`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input |
| +- `internal/domains/reconcile.go` `StampHealth`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route |
| New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| - new `internal/domains/freshdns.go:FreshResolver.ask`: reads +file:Read; written legacy, accepted-legacy, frozen |
| -Seal: `2774b43ac5970e4340339b859204bce5eb9f83d4c2551f0984e919a2853d0216` → `6d029851d1a1ff285658bf3740def2fe651a8039e3f202bc694b0e973cadb74a`. |
| +Seal: `2774b43ac5970e4340339b859204bce5eb9f83d4c2551f0984e919a2853d0216` → `44917f6a61196f613c10e47a4778fb800d1314f369119bd6e50a79bdea1d4a83`. |
| Overlay: `internal/provision/testdata/plan14-root-reads-dns-fresh-lookup-724.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/internal/domains/export_test.go b/internal/domains/export_test.go| index 13c251e84..6084f6713 100644 |
| --- a/internal/domains/export_test.go |
| +++ b/internal/domains/export_test.go |
| @@ -4,3 +4,15 @@ package domains |
| // row through the edge (rootfs_apex_test.go): package edge imports this one, |
| // so only an external test package can import both. |
| var MintedRoute = mintedRoute |
| + |
| +// SetFreshPassMax shrinks the per-pass fresh-lookup bound for a test and |
| +// returns the restore. |
| +func SetFreshPassMax(n int) (restore func()) { |
| + old := freshPassMax |
| + freshPassMax = n |
| + return func() { freshPassMax = old } |
| +} |
| + |
| +// PublicNameserver is publicNameserver, the fresh lookup's destination |
| +// policy. |
| +var PublicNameserver = publicNameserver |
diff --git a/internal/domains/freshdns.go b/internal/domains/freshdns.go| index b1d43dfd7..96483fb5a 100644 |
| --- a/internal/domains/freshdns.go |
| +++ b/internal/domains/freshdns.go |
| @@ -6,6 +6,7 @@ import ( |
| "fmt" |
| "math/rand/v2" |
| "net" |
| + "net/netip" |
| "strings" |
| "sync" |
| "time" |
| @@ -16,7 +17,7 @@ import ( |
| // FreshResolver answers "what does this hostname resolve to right now" |
| // without any cache in the way (#724). It finds the zone that holds the |
| // name, asks that zone's own nameservers, and trusts only an authoritative |
| -// reply. Config.ResolveFresh is its Resolve. |
| +// reply to the exact question it sent. Config.ResolveFresh is its Resolve. |
| // |
| // Why not just skip the box's cache: systemd-resolved is not the only |
| // cache between us and the customer's zone. The upstream (VPC) resolver |
| @@ -25,16 +26,26 @@ import ( |
| // |
| // The cached resolver (LookupNS, LookupHost) is still used for the names |
| // around the answer that we are not waiting on: the zone's NS set, the |
| -// nameservers' own addresses, and an out-of-zone CNAME target (in practice |
| -// the deployment's own edge name). |
| +// nameservers' own addresses, and a CNAME target outside the zone (in |
| +// practice the deployment's own edge name). |
| +// |
| +// The nameservers are named by tenant DNS, so their addresses are tenant |
| +// input: every one passes publicNameserver before a socket is opened, and |
| +// a private, loopback, link-local or otherwise internal address is never |
| +// dialled. |
| type FreshResolver struct { |
| LookupNS func(ctx context.Context, name string) ([]*net.NS, error) |
| LookupHost func(ctx context.Context, host string) ([]string, error) |
| - // Port is the nameservers' port; "" is 53. A seam for tests. |
| - Port string |
| + // Dial opens the UDP socket to a nameserver that has already passed |
| + // publicNameserver; nil is a net.Dialer. A seam for tests, which point |
| + // a public test address at a loopback server. |
| + Dial func(ctx context.Context, network, address string) (net.Conn, error) |
| // Timeout bounds one whole Resolve; 0 is 3 s, the cached seam's own |
| // budget (internal/host resolveHost). |
| Timeout time.Duration |
| + // AttemptTimeout bounds one nameserver inside it; 0 is 1 s, so a |
| + // silent server leaves time for the next. |
| + AttemptTimeout time.Duration |
| // Backoff is how long a name whose lookup FAILED is answered with the |
| // failure again without asking anyone; 0 is 30 minutes. A dead or lame |
| // nameserver would otherwise cost a full Timeout on every pass. |
| @@ -49,13 +60,37 @@ type FreshResolver struct { |
| // errNoAuthority is a fresh lookup that got no usable authoritative answer. |
| var errNoAuthority = errors.New("fresh dns: no authoritative answer") |
| -// freshMaxServers bounds the nameserver addresses one Resolve tries. |
| -const freshMaxServers = 3 |
| +const ( |
| + // freshMaxServers bounds the nameserver addresses tried per zone. |
| + freshMaxServers = 3 |
| + // freshMaxZones bounds the enclosing zones tried, nearest first. More |
| + // than one, because a cached CNAME at the name can make the nearest NS |
| + // set belong to the CNAME target's zone, which then refuses. |
| + freshMaxZones = 3 |
| + // freshMaxCNAMEs bounds a CNAME chain inside one reply. |
| + freshMaxCNAMEs = 8 |
| + // freshMaxBackoff caps the failure map; past it the oldest go first. |
| + freshMaxBackoff = 4096 |
| +) |
| + |
| +// freshSkipTLDs are special-use top-level names nobody can hold a public |
| +// zone under (RFC 6761, RFC 8375, RFC 9476 and the ICANN .internal |
| +// reservation). The box carries routes under some of them (sidecar |
| +// hosts are <name>.sidecar.internal); asking about them is pure cost. |
| +var freshSkipTLDs = map[string]bool{ |
| + "internal": true, "local": true, "localhost": true, "invalid": true, |
| + "onion": true, "arpa": true, "alt": true, "home": true, "lan": true, |
| +} |
| // Resolve returns host's addresses as its zone's nameservers give them now. |
| // An authoritative "no such name" is a *net.DNSError with IsNotFound, the |
| // same shape the cached resolver gives, so callers classify both alike. |
| func (r *FreshResolver) Resolve(host string) ([]string, error) { |
| + name := strings.ToLower(strings.TrimSuffix(host, ".")) |
| + dot := strings.LastIndex(name, ".") |
| + if dot <= 0 || freshSkipTLDs[name[dot+1:]] { |
| + return nil, fmt.Errorf("%w: %s has no public zone", errNoAuthority, name) |
| + } |
| now := time.Now |
| if r.Now != nil { |
| now = r.Now |
| @@ -64,9 +99,14 @@ func (r *FreshResolver) Resolve(host string) ([]string, error) { |
| if backoff == 0 { |
| backoff = 30 * time.Minute |
| } |
| - name := strings.ToLower(strings.TrimSuffix(host, ".")) |
| r.mu.Lock() |
| - if at, ok := r.failedAt[name]; ok && now().Sub(at) < backoff { |
| + t := now() |
| + for n, at := range r.failedAt { |
| + if t.Sub(at) >= backoff { |
| + delete(r.failedAt, n) |
| + } |
| + } |
| + if at, ok := r.failedAt[name]; ok { |
| r.mu.Unlock() |
| return nil, fmt.Errorf("%w for %s (backing off since %s)", errNoAuthority, name, at.UTC().Format(time.RFC3339)) |
| } |
| @@ -80,109 +120,177 @@ func (r *FreshResolver) Resolve(host string) ([]string, error) { |
| defer cancel() |
| ips, err := r.resolve(ctx, name) |
| - var dnsErr *net.DNSError |
| - failed := err != nil && !(errors.As(err, &dnsErr) && dnsErr.IsNotFound) |
| - r.mu.Lock() |
| - if failed { |
| + if err != nil && !isNotFound(err) { |
| + r.mu.Lock() |
| if r.failedAt == nil { |
| r.failedAt = map[string]time.Time{} |
| } |
| + for len(r.failedAt) >= freshMaxBackoff { |
| + oldest, first := "", true |
| + var oldestAt time.Time |
| + for n, at := range r.failedAt { |
| + if first || at.Before(oldestAt) { |
| + oldest, oldestAt, first = n, at, false |
| + } |
| + } |
| + delete(r.failedAt, oldest) |
| + } |
| r.failedAt[name] = now() |
| - } else { |
| - delete(r.failedAt, name) |
| + r.mu.Unlock() |
| } |
| - r.mu.Unlock() |
| return ips, err |
| } |
| +func isNotFound(err error) bool { |
| + var dnsErr *net.DNSError |
| + return errors.As(err, &dnsErr) && dnsErr.IsNotFound |
| +} |
| + |
| +// resolve walks the enclosing zones of name, nearest first, and asks each |
| +// zone's nameservers until one gives a definitive authoritative answer (the |
| +// addresses, or "no such name"). A zone whose servers all refuse, answer |
| +// without authority, or stay silent passes the question up to the next. |
| +// It stops below the top level: a TLD's servers only refer back down. |
| func (r *FreshResolver) resolve(ctx context.Context, name string) ([]string, error) { |
| - servers, err := r.zoneServers(ctx, name) |
| - if err != nil { |
| - return nil, err |
| - } |
| - port := r.Port |
| - if port == "" { |
| - port = "53" |
| - } |
| - last := errNoAuthority |
| - for _, ip := range servers { |
| - ips, err := r.ask(ctx, net.JoinHostPort(ip, port), name) |
| - if err == nil { |
| - return ips, nil |
| - } |
| - var dnsErr *net.DNSError |
| - if errors.As(err, &dnsErr) && dnsErr.IsNotFound { |
| - return nil, err |
| + last := fmt.Errorf("%w: no zone found for %s", errNoAuthority, name) |
| + zones := 0 |
| + for zone := name; strings.Contains(zone, "."); zone = zone[strings.Index(zone, ".")+1:] { |
| + nss, err := r.LookupNS(ctx, zone) |
| + if err != nil || len(nss) == 0 { |
| + if ctx.Err() != nil { |
| + return nil, last |
| + } |
| + continue |
| } |
| - last = err |
| - if ctx.Err() != nil { |
| + if zones++; zones > freshMaxZones { |
| break |
| } |
| + servers := r.nameserverAddrs(ctx, nss) |
| + if len(servers) == 0 { |
| + last = fmt.Errorf("%w: no public address for any nameserver of %s", errNoAuthority, zone) |
| + continue |
| + } |
| + for _, s := range servers { |
| + ips, err := r.ask(ctx, s, name, zone) |
| + if err == nil || isNotFound(err) { |
| + return ips, err |
| + } |
| + last = err |
| + if ctx.Err() != nil { |
| + return nil, last |
| + } |
| + } |
| } |
| return nil, last |
| } |
| -// zoneServers finds the closest enclosing zone of name that has an NS set |
| -// and returns up to freshMaxServers of its nameservers' addresses. It |
| -// stops below the top level: a TLD's servers only refer back down, and a |
| -// name with no zone under its TLD has nothing fresh to read. |
| -func (r *FreshResolver) zoneServers(ctx context.Context, name string) ([]string, error) { |
| - for zone := name; strings.Contains(zone, "."); zone = zone[strings.Index(zone, ".")+1:] { |
| - nss, err := r.LookupNS(ctx, zone) |
| - if err != nil || len(nss) == 0 { |
| - if ctx.Err() != nil { |
| - return nil, ctx.Err() |
| - } |
| +// nameserverAddrs resolves the NS hosts (in random order) through the |
| +// cached resolver and keeps up to freshMaxServers addresses that pass |
| +// publicNameserver, IPv4 first: a box without a working IPv6 route would |
| +// otherwise spend its attempts on silence. |
| +func (r *FreshResolver) nameserverAddrs(ctx context.Context, nss []*net.NS) []netip.AddrPort { |
| + var v4, v6 []netip.AddrPort |
| + for _, i := range rand.Perm(len(nss)) { |
| + addrs, err := r.LookupHost(ctx, nss[i].Host) |
| + if err != nil { |
| continue |
| } |
| - var out []string |
| - for _, i := range rand.Perm(len(nss)) { |
| - addrs, err := r.LookupHost(ctx, nss[i].Host) |
| - if err != nil { |
| + for _, a := range addrs { |
| + ip, err := netip.ParseAddr(a) |
| + if err != nil || !publicNameserver(ip) { |
| continue |
| } |
| - for _, a := range addrs { |
| - if len(out) < freshMaxServers { |
| - out = append(out, a) |
| - } |
| - } |
| - if len(out) >= freshMaxServers { |
| - break |
| + ap := netip.AddrPortFrom(ip.Unmap(), 53) |
| + if ip.Unmap().Is4() { |
| + v4 = append(v4, ap) |
| + } else { |
| + v6 = append(v6, ap) |
| } |
| } |
| - if len(out) == 0 { |
| - return nil, fmt.Errorf("%w: no address for any nameserver of %s", errNoAuthority, zone) |
| + if len(v4) >= freshMaxServers { |
| + break |
| + } |
| + } |
| + out := append(v4, v6...) |
| + if len(out) > freshMaxServers { |
| + out = out[:freshMaxServers] |
| + } |
| + return out |
| +} |
| + |
| +// nonPublic are ranges netip's predicates do not already cover that no |
| +// public nameserver lives in: shared address space (CGNAT, which also holds |
| +// Tailscale addresses), IETF protocol assignments, benchmarking, the |
| +// reserved class E block, and the IPv6 forms that embed an IPv4 address a |
| +// translator could carry into a private network. |
| +var nonPublic = []netip.Prefix{ |
| + netip.MustParsePrefix("100.64.0.0/10"), |
| + netip.MustParsePrefix("192.0.0.0/24"), |
| + netip.MustParsePrefix("198.18.0.0/15"), |
| + netip.MustParsePrefix("240.0.0.0/4"), |
| + netip.MustParsePrefix("64:ff9b::/96"), |
| + netip.MustParsePrefix("64:ff9b:1::/48"), |
| + netip.MustParsePrefix("2002::/16"), |
| + netip.MustParsePrefix("fec0::/10"), |
| +} |
| + |
| +// publicNameserver is the destination policy: a fresh lookup only ever |
| +// opens a socket to a globally routable unicast address. Tenant DNS names |
| +// the nameservers, so without it a tenant could point the box's queries at |
| +// its own loopback, the VPC, the metadata service or the tailnet. |
| +func publicNameserver(ip netip.Addr) bool { |
| + ip = ip.Unmap() |
| + if !ip.IsValid() || !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || |
| + ip.IsLinkLocalUnicast() || ip.IsUnspecified() || ip.IsMulticast() || ip.Zone() != "" { |
| + return false |
| + } |
| + for _, p := range nonPublic { |
| + if p.Contains(ip) { |
| + return false |
| } |
| - return out, nil |
| } |
| - return nil, fmt.Errorf("%w: no zone found for %s", errNoAuthority, name) |
| + return true |
| } |
| -// ask sends one non-recursive A query for name to server and reads the |
| -// authoritative reply. A CNAME chain in the reply is followed; if it ends |
| -// outside what the server answered, the chain's last name goes to the |
| -// cached LookupHost. |
| -func (r *FreshResolver) ask(ctx context.Context, server, name string) ([]string, error) { |
| - qname, err := dnsmessage.NewName(name + ".") |
| +// ask sends one non-recursive IN A query for name to server and reads the |
| +// authoritative reply to exactly that question. A CNAME chain in the reply |
| +// is followed; if it ends outside zone with no address in the reply, the |
| +// target goes to the cached LookupHost. A chain that loops, runs past |
| +// freshMaxCNAMEs, or ends inside zone with no address is not an answer. |
| +func (r *FreshResolver) ask(ctx context.Context, server netip.AddrPort, name, zone string) ([]string, error) { |
| + if !publicNameserver(server.Addr()) { |
| + return nil, fmt.Errorf("%w: refusing non-public nameserver %s", errNoAuthority, server) |
| + } |
| + attempt := r.AttemptTimeout |
| + if attempt == 0 { |
| + attempt = time.Second |
| + } |
| + actx, cancel := context.WithTimeout(ctx, attempt) |
| + defer cancel() |
| + |
| + fqdn := name + "." |
| + qname, err := dnsmessage.NewName(fqdn) |
| if err != nil { |
| return nil, err |
| } |
| id := uint16(rand.Uint32()) |
| - query := dnsmessage.Message{ |
| - Header: dnsmessage.Header{ID: id}, |
| - Questions: []dnsmessage.Question{{Name: qname, Type: dnsmessage.TypeA, Class: dnsmessage.ClassINET}}, |
| - } |
| + question := dnsmessage.Question{Name: qname, Type: dnsmessage.TypeA, Class: dnsmessage.ClassINET} |
| + query := dnsmessage.Message{Header: dnsmessage.Header{ID: id}, Questions: []dnsmessage.Question{question}} |
| packed, err := query.Pack() |
| if err != nil { |
| return nil, err |
| } |
| - var d net.Dialer |
| - conn, err := d.DialContext(ctx, "udp", server) |
| + dial := r.Dial |
| + if dial == nil { |
| + var d net.Dialer |
| + dial = d.DialContext |
| + } |
| + conn, err := dial(actx, "udp", server.String()) |
| if err != nil { |
| return nil, err |
| } |
| defer conn.Close() |
| - if deadline, ok := ctx.Deadline(); ok { |
| + if deadline, ok := actx.Deadline(); ok { |
| _ = conn.SetDeadline(deadline) |
| } |
| if _, err := conn.Write(packed); err != nil { |
| @@ -195,11 +303,12 @@ func (r *FreshResolver) ask(ctx context.Context, server, name string) ([]string, |
| if err != nil { |
| return nil, err |
| } |
| - if reply.Unpack(buf[:n]) != nil || !reply.Response || reply.ID != id || |
| - len(reply.Questions) != 1 || !strings.EqualFold(reply.Questions[0].Name.String(), name+".") { |
| - continue // not our reply; keep reading until the deadline |
| + if reply.Unpack(buf[:n]) == nil && reply.Response && reply.ID == id && reply.OpCode == 0 && |
| + len(reply.Questions) == 1 && reply.Questions[0].Type == question.Type && |
| + reply.Questions[0].Class == question.Class && strings.EqualFold(reply.Questions[0].Name.String(), fqdn) { |
| + break |
| } |
| - break |
| + // Not the reply to this question; keep reading until the deadline. |
| } |
| if !reply.Authoritative { |
| return nil, fmt.Errorf("%w: %s is not authoritative for %s", errNoAuthority, server, name) |
| @@ -210,39 +319,50 @@ func (r *FreshResolver) ask(ctx context.Context, server, name string) ([]string, |
| switch reply.RCode { |
| case dnsmessage.RCodeSuccess: |
| case dnsmessage.RCodeNameError: |
| - return nil, &net.DNSError{Err: "no such host", Name: name, Server: server, IsNotFound: true} |
| + return nil, &net.DNSError{Err: "no such host", Name: name, Server: server.String(), IsNotFound: true} |
| default: |
| return nil, fmt.Errorf("%w: %s answered %s for %s", errNoAuthority, server, reply.RCode, name) |
| } |
| - // Follow the CNAME chain the server gave, from name, then collect the |
| - // A records of the chain's last name. |
| - current := name + "." |
| - for hops := 0; hops < 8; hops++ { |
| + current := fqdn |
| + seen := map[string]bool{strings.ToLower(current): true} |
| + for hops := 0; ; hops++ { |
| next := "" |
| for _, rr := range reply.Answers { |
| - if c, ok := rr.Body.(*dnsmessage.CNAMEResource); ok && strings.EqualFold(rr.Header.Name.String(), current) { |
| - next = c.CNAME.String() |
| + if c, ok := rr.Body.(*dnsmessage.CNAMEResource); ok && rr.Header.Class == dnsmessage.ClassINET && |
| + strings.EqualFold(rr.Header.Name.String(), current) { |
| + next = strings.ToLower(c.CNAME.String()) |
| break |
| } |
| } |
| if next == "" { |
| break |
| } |
| + if seen[next] || hops >= freshMaxCNAMEs { |
| + return nil, fmt.Errorf("%w: CNAME chain from %s loops or runs too long", errNoAuthority, name) |
| + } |
| + seen[next] = true |
| current = next |
| } |
| var ips []string |
| for _, rr := range reply.Answers { |
| - if a, ok := rr.Body.(*dnsmessage.AResource); ok && strings.EqualFold(rr.Header.Name.String(), current) { |
| - ips = append(ips, net.IP(a.A[:]).String()) |
| + if a, ok := rr.Body.(*dnsmessage.AResource); ok && rr.Header.Class == dnsmessage.ClassINET && |
| + strings.EqualFold(rr.Header.Name.String(), current) { |
| + ips = append(ips, netip.AddrFrom4(a.A).String()) |
| } |
| } |
| if len(ips) > 0 { |
| return ips, nil |
| } |
| - if !strings.EqualFold(current, name+".") { |
| - return r.LookupHost(ctx, strings.TrimSuffix(current, ".")) |
| + target := strings.TrimSuffix(current, ".") |
| + if target == name { |
| + // Authoritative, the name exists, and it has no A record. |
| + return nil, &net.DNSError{Err: "no A record", Name: name, Server: server.String(), IsNotFound: true} |
| + } |
| + if target == zone || strings.HasSuffix(target, "."+zone) { |
| + // In-zone target this server gave no address for: no fallback to |
| + // a cache that may hold an old one. |
| + return nil, fmt.Errorf("%w: %s ends at in-zone %s with no address", errNoAuthority, name, target) |
| } |
| - // Authoritative, the name exists, and it has no A record here. |
| - return nil, &net.DNSError{Err: "no A record", Name: name, Server: server, IsNotFound: true} |
| + return r.LookupHost(ctx, target) |
| } |
diff --git a/internal/domains/freshdns_stamp_test.go b/internal/domains/freshdns_stamp_test.go| index c3313db42..e6100fa41 100644 |
| --- a/internal/domains/freshdns_stamp_test.go |
| +++ b/internal/domains/freshdns_stamp_test.go |
| @@ -177,3 +177,42 @@ func TestStampHealthFreshLookupLeavesResolverFailureAlone(t *testing.T) { |
| t.Fatalf("alias dns_status = %q, want unresolved", got) |
| } |
| } |
| + |
| +// Astra R1 P2-4: abandoned attaches never point here, so the eligible set |
| +// grows without bound. Each pass does at most freshPassMax fresh lookups, |
| +// and the random order works through the whole backlog across passes. |
| +func TestStampHealthFreshLookupsAreBoundedAndFair(t *testing.T) { |
| + defer domains.SetFreshPassMax(2)() |
| + reg := regWith(t, registry.Route{Host: "app.acct.oncarlos.test", Kind: "service", Addr: "10.0.0.1:1", Status: "ready"}) |
| + names := []string{"a.example.com", "b.example.com", "c.example.com", "d.example.com", "e.example.com"} |
| + for _, a := range names { |
| + if err := reg.UpsertAlias(registry.RouteAlias{Alias: a, Host: "app.acct.oncarlos.test", Account: "acct", App: "app"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var calls []string |
| + cfg := freshCfg(func(h string) ([]string, error) { |
| + if h == "app.acct.oncarlos.test" { |
| + return pointingAt(h) |
| + } |
| + return nxdomain(h) |
| + }, nxdomain, &calls) |
| + seen := map[string]bool{} |
| + for pass := 0; pass < 60; pass++ { |
| + calls = nil |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(calls) != 2 { |
| + t.Fatalf("pass %d made %d fresh lookups, want 2", pass, len(calls)) |
| + } |
| + for _, c := range calls { |
| + seen[c] = true |
| + } |
| + } |
| + for _, n := range names { |
| + if !seen[n] { |
| + t.Errorf("%s never got a fresh lookup in 60 passes", n) |
| + } |
| + } |
| +} |
diff --git a/internal/domains/freshdns_test.go b/internal/domains/freshdns_test.go| index 22663a06d..0ab23bae0 100644 |
| --- a/internal/domains/freshdns_test.go |
| +++ b/internal/domains/freshdns_test.go |
| @@ -4,7 +4,9 @@ import ( |
| "context" |
| "errors" |
| "net" |
| + "net/netip" |
| "strings" |
| + "sync" |
| "sync/atomic" |
| "testing" |
| "time" |
| @@ -14,11 +16,10 @@ import ( |
| "github.com/carlosframework/platform/internal/domains" |
| ) |
| -// fakeAuthority is a one-zone authoritative server on loopback. answer |
| -// builds the reply to each query; returning nil drops the query (a dead |
| -// nameserver). |
| +// fakeAuthority is a nameserver on loopback. answer builds the reply to |
| +// each query; returning false drops the query (a silent nameserver). |
| type fakeAuthority struct { |
| - port string |
| + addr string |
| queries atomic.Int32 |
| asked atomic.Value // last question name |
| } |
| @@ -30,8 +31,7 @@ func startAuthority(t *testing.T, answer func(q dnsmessage.Question, reply *dnsm |
| t.Fatal(err) |
| } |
| t.Cleanup(func() { pc.Close() }) |
| - fa := &fakeAuthority{} |
| - _, fa.port, _ = net.SplitHostPort(pc.LocalAddr().String()) |
| + fa := &fakeAuthority{addr: pc.LocalAddr().String()} |
| go func() { |
| buf := make([]byte, 1500) |
| for { |
| @@ -60,12 +60,18 @@ func startAuthority(t *testing.T, answer func(q dnsmessage.Question, reply *dnsm |
| return fa |
| } |
| +func authoritative(rrs ...dnsmessage.Resource) func(dnsmessage.Question, *dnsmessage.Message) bool { |
| + return func(_ dnsmessage.Question, r *dnsmessage.Message) bool { |
| + r.Authoritative = true |
| + r.Answers = rrs |
| + return true |
| + } |
| +} |
| + |
| func aRecord(name, ip string) dnsmessage.Resource { |
| - var a [4]byte |
| - copy(a[:], net.ParseIP(ip).To4()) |
| return dnsmessage.Resource{ |
| Header: dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName(name), Type: dnsmessage.TypeA, Class: dnsmessage.ClassINET, TTL: 300}, |
| - Body: &dnsmessage.AResource{A: a}, |
| + Body: &dnsmessage.AResource{A: netip.MustParseAddr(ip).As4()}, |
| } |
| } |
| @@ -78,45 +84,74 @@ func cnameRecord(name, target string) dnsmessage.Resource { |
| var errNotFound = &net.DNSError{Err: "no such host", IsNotFound: true} |
| -// resolverFor wires a FreshResolver whose only zone is example.com, served |
| -// by fa, with the CACHED half answering the nameserver's and the edge's |
| -// addresses. |
| -func resolverFor(fa *fakeAuthority, now *time.Time) *domains.FreshResolver { |
| +// world is the cached half and the network a FreshResolver sees: which |
| +// names have NS sets, what the nameserver hosts and other names resolve to, |
| +// and which loopback server each public nameserver address reaches. Every |
| +// address Dial is asked for is recorded. |
| +type world struct { |
| + ns map[string][]string // zone -> NS hosts |
| + hosts map[string][]string // name -> addresses (the cache) |
| + routes map[string]*fakeAuthority // "ip:53" -> server |
| + mu sync.Mutex |
| + dialed []string |
| +} |
| + |
| +func (w *world) resolver(now *time.Time) *domains.FreshResolver { |
| return &domains.FreshResolver{ |
| LookupNS: func(_ context.Context, name string) ([]*net.NS, error) { |
| - if name == "example.com" { |
| - return []*net.NS{{Host: "ns1.example.com."}}, nil |
| + hs, ok := w.ns[name] |
| + if !ok { |
| + return nil, errNotFound |
| } |
| - return nil, errNotFound |
| + var out []*net.NS |
| + for _, h := range hs { |
| + out = append(out, &net.NS{Host: h}) |
| + } |
| + return out, nil |
| }, |
| LookupHost: func(_ context.Context, host string) ([]string, error) { |
| - switch strings.TrimSuffix(host, ".") { |
| - case "ns1.example.com": |
| - return []string{"127.0.0.1"}, nil |
| - case "edge.oncarlos.test": |
| - return []string{edgeIP}, nil |
| + if a, ok := w.hosts[strings.TrimSuffix(host, ".")]; ok { |
| + return a, nil |
| } |
| return nil, errNotFound |
| }, |
| - Port: fa.port, |
| - Timeout: 500 * time.Millisecond, |
| - Now: func() time.Time { return *now }, |
| + Dial: func(ctx context.Context, network, address string) (net.Conn, error) { |
| + w.mu.Lock() |
| + w.dialed = append(w.dialed, address) |
| + w.mu.Unlock() |
| + fa, ok := w.routes[address] |
| + if !ok { |
| + return nil, errors.New("no route to " + address) |
| + } |
| + var d net.Dialer |
| + return d.DialContext(ctx, network, fa.addr) |
| + }, |
| + Timeout: 2 * time.Second, |
| + AttemptTimeout: 300 * time.Millisecond, |
| + Now: func() time.Time { return *now }, |
| + } |
| +} |
| + |
| +// oneZone is example.com served by fa at a public test address. |
| +func oneZone(fa *fakeAuthority) *world { |
| + return &world{ |
| + ns: map[string][]string{"example.com": {"ns1.example.com."}}, |
| + hosts: map[string][]string{ |
| + "ns1.example.com": {"192.0.2.53"}, |
| + "edge.oncarlos.test": {edgeIP}, |
| + }, |
| + routes: map[string]*fakeAuthority{"192.0.2.53:53": fa}, |
| } |
| } |
| +func clock() *time.Time { t := time.Unix(1000, 0); return &t } |
| + |
| func TestFreshResolverReadsTheAuthoritativeA(t *testing.T) { |
| - fa := startAuthority(t, func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| - r.Authoritative = true |
| - r.Answers = []dnsmessage.Resource{aRecord(q.Name.String(), edgeIP)} |
| - return true |
| - }) |
| - now := time.Unix(1000, 0) |
| - ips, err := resolverFor(fa, &now).Resolve("shop.example.com") |
| + fa := startAuthority(t, authoritative(aRecord("shop.example.com.", edgeIP))) |
| + ips, err := oneZone(fa).resolver(clock()).Resolve("shop.example.com") |
| if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| t.Fatalf("Resolve = %v, %v; want [%s]", ips, err, edgeIP) |
| } |
| - // The zone was found by walking up from the host, and the host itself |
| - // is what the authority was asked. |
| if got := fa.asked.Load(); got != "shop.example.com." { |
| t.Fatalf("authority asked for %v, want shop.example.com.", got) |
| } |
| @@ -125,26 +160,20 @@ func TestFreshResolverReadsTheAuthoritativeA(t *testing.T) { |
| func TestFreshResolverFollowsAnOutOfZoneCNAME(t *testing.T) { |
| // The usual custom-domain setup: the customer's zone holds only the |
| // CNAME, and the target is ours. |
| - fa := startAuthority(t, func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| - r.Authoritative = true |
| - r.Answers = []dnsmessage.Resource{cnameRecord(q.Name.String(), "edge.oncarlos.test.")} |
| - return true |
| - }) |
| - now := time.Unix(1000, 0) |
| - ips, err := resolverFor(fa, &now).Resolve("shop.example.com") |
| + fa := startAuthority(t, authoritative(cnameRecord("shop.example.com.", "edge.oncarlos.test."))) |
| + ips, err := oneZone(fa).resolver(clock()).Resolve("shop.example.com") |
| if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| t.Fatalf("Resolve = %v, %v; want [%s] via the CNAME target", ips, err, edgeIP) |
| } |
| } |
| func TestFreshResolverReportsAuthoritativeNXDOMAIN(t *testing.T) { |
| - fa := startAuthority(t, func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| + fa := startAuthority(t, func(_ dnsmessage.Question, r *dnsmessage.Message) bool { |
| r.Authoritative = true |
| r.RCode = dnsmessage.RCodeNameError |
| return true |
| }) |
| - now := time.Unix(1000, 0) |
| - _, err := resolverFor(fa, &now).Resolve("shop.example.com") |
| + _, err := oneZone(fa).resolver(clock()).Resolve("shop.example.com") |
| var dnsErr *net.DNSError |
| if !errors.As(err, &dnsErr) || !dnsErr.IsNotFound { |
| t.Fatalf("Resolve error = %v, want a not-found DNSError", err) |
| @@ -152,37 +181,158 @@ func TestFreshResolverReportsAuthoritativeNXDOMAIN(t *testing.T) { |
| } |
| func TestFreshResolverIgnoresNonAuthoritativeAnswers(t *testing.T) { |
| - // A server that is not authoritative for the name (a lame delegation, |
| - // or a resolver squatting on the address) is not the fresh answer we |
| - // went looking for. |
| fa := startAuthority(t, func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| r.Answers = []dnsmessage.Resource{aRecord(q.Name.String(), edgeIP)} |
| return true |
| }) |
| - now := time.Unix(1000, 0) |
| - if ips, err := resolverFor(fa, &now).Resolve("shop.example.com"); err == nil { |
| + if ips, err := oneZone(fa).resolver(clock()).Resolve("shop.example.com"); err == nil { |
| t.Fatalf("Resolve = %v, want an error for a non-authoritative answer", ips) |
| } |
| } |
| func TestFreshResolverRejectsAnswersForOtherNames(t *testing.T) { |
| - fa := startAuthority(t, func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| - r.Authoritative = true |
| - r.Answers = []dnsmessage.Resource{aRecord("other.example.com.", edgeIP)} |
| + fa := startAuthority(t, authoritative(aRecord("other.example.com.", edgeIP))) |
| + if ips, err := oneZone(fa).resolver(clock()).Resolve("shop.example.com"); err == nil { |
| + t.Fatalf("Resolve = %v, want an error: the answer names another host", ips) |
| + } |
| +} |
| + |
| +// Astra R1 P2-5: a reply must answer the exact IN A question sent. |
| +func TestFreshResolverRejectsRepliesToOtherQuestions(t *testing.T) { |
| + cases := map[string]func(*dnsmessage.Message){ |
| + "question type": func(r *dnsmessage.Message) { r.Questions[0].Type = dnsmessage.TypeAAAA }, |
| + "question class": func(r *dnsmessage.Message) { r.Questions[0].Class = dnsmessage.ClassCHAOS }, |
| + "answer class": func(r *dnsmessage.Message) { |
| + r.Answers[0].Header.Class = dnsmessage.ClassCHAOS |
| + }, |
| + } |
| + for name, mangle := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + fa := startAuthority(t, func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| + r.Authoritative = true |
| + r.Answers = []dnsmessage.Resource{aRecord(q.Name.String(), edgeIP)} |
| + mangle(r) |
| + return true |
| + }) |
| + if ips, err := oneZone(fa).resolver(clock()).Resolve("shop.example.com"); err == nil { |
| + t.Fatalf("Resolve = %v, want an error", ips) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Astra R1 P1: nameserver addresses are tenant input. None outside the |
| +// public unicast space is ever dialled. |
| +func TestFreshResolverNeverDialsANonPublicNameserver(t *testing.T) { |
| + for _, addr := range []string{ |
| + "127.0.0.1", "10.0.0.5", "172.16.3.4", "192.168.1.1", "169.254.169.254", |
| + "100.100.1.1", "0.0.0.0", "::1", "fd00:ec2::254", "fe80::1", "::ffff:10.0.0.1", |
| + "64:ff9b::a00:1", "2002:a00:1::1", "240.0.0.1", "198.18.0.1", "192.0.0.8", |
| + } { |
| + t.Run(addr, func(t *testing.T) { |
| + if domains.PublicNameserver(netip.MustParseAddr(addr)) { |
| + t.Fatalf("%s passes the destination policy", addr) |
| + } |
| + w := &world{ |
| + ns: map[string][]string{"example.com": {"ns1.example.com."}}, |
| + hosts: map[string][]string{"ns1.example.com": {addr}}, |
| + } |
| + if _, err := w.resolver(clock()).Resolve("shop.example.com"); err == nil { |
| + t.Fatal("Resolve succeeded") |
| + } |
| + if len(w.dialed) != 0 { |
| + t.Fatalf("dialled %v", w.dialed) |
| + } |
| + }) |
| + } |
| + for _, addr := range []string{"192.0.2.53", "8.8.8.8", "2606:4700::6810:84e5"} { |
| + if !domains.PublicNameserver(netip.MustParseAddr(addr)) { |
| + t.Errorf("%s refused by the destination policy", addr) |
| + } |
| + } |
| +} |
| + |
| +// Astra R1 P2-3: a silent server costs one attempt, not the whole lookup. |
| +func TestFreshResolverMovesPastASilentServer(t *testing.T) { |
| + silent := startAuthority(t, func(dnsmessage.Question, *dnsmessage.Message) bool { return false }) |
| + healthy := startAuthority(t, authoritative(aRecord("shop.example.com.", edgeIP))) |
| + w := &world{ |
| + ns: map[string][]string{"example.com": {"ns1.example.com."}}, |
| + hosts: map[string][]string{"ns1.example.com": {"192.0.2.1", "192.0.2.2"}}, |
| + routes: map[string]*fakeAuthority{"192.0.2.1:53": silent, "192.0.2.2:53": healthy}, |
| + } |
| + ips, err := w.resolver(clock()).Resolve("shop.example.com") |
| + if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| + t.Fatalf("Resolve = %v, %v; want the healthy server's answer", ips, err) |
| + } |
| +} |
| + |
| +// Astra R1 P2-2: a cached CNAME at the name makes the nearest NS set the |
| +// CNAME target's zone. Its refusal must pass the question up to the zone |
| +// that really holds the name. |
| +func TestFreshResolverClimbsPastAWrongZone(t *testing.T) { |
| + wrong := startAuthority(t, func(_ dnsmessage.Question, r *dnsmessage.Message) bool { |
| + r.RCode = dnsmessage.RCodeRefused |
| return true |
| }) |
| - now := time.Unix(1000, 0) |
| - if ips, err := resolverFor(fa, &now).Resolve("shop.example.com"); err == nil { |
| - t.Fatalf("Resolve = %v, want an error: the answer names another host", ips) |
| + right := startAuthority(t, authoritative(aRecord("shop.example.com.", edgeIP))) |
| + w := &world{ |
| + ns: map[string][]string{ |
| + "shop.example.com": {"ns.oldprovider.net."}, |
| + "example.com": {"ns1.example.com."}, |
| + }, |
| + hosts: map[string][]string{ |
| + "ns.oldprovider.net": {"192.0.2.9"}, |
| + "ns1.example.com": {"192.0.2.53"}, |
| + }, |
| + routes: map[string]*fakeAuthority{"192.0.2.9:53": wrong, "192.0.2.53:53": right}, |
| + } |
| + ips, err := w.resolver(clock()).Resolve("shop.example.com") |
| + if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| + t.Fatalf("Resolve = %v, %v; want the enclosing zone's answer", ips, err) |
| + } |
| +} |
| + |
| +// Astra R1 P2-6: only a completed chain is an answer. |
| +func TestFreshResolverRefusesBrokenCNAMEChains(t *testing.T) { |
| + cases := map[string][]dnsmessage.Resource{ |
| + "loop": { |
| + cnameRecord("shop.example.com.", "a.example.com."), |
| + cnameRecord("a.example.com.", "shop.example.com."), |
| + }, |
| + // An in-zone target with no address here: the cache may hold an |
| + // old one for it, so there is no cached fallback. |
| + "in-zone NODATA": {cnameRecord("shop.example.com.", "www.example.com.")}, |
| + } |
| + for name, rrs := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + fa := startAuthority(t, authoritative(rrs...)) |
| + w := oneZone(fa) |
| + w.hosts["www.example.com"] = []string{edgeIP} // stale cache |
| + w.hosts["a.example.com"] = []string{edgeIP} |
| + if ips, err := w.resolver(clock()).Resolve("shop.example.com"); err == nil { |
| + t.Fatalf("Resolve = %v, want an error", ips) |
| + } |
| + }) |
| + } |
| + long := []dnsmessage.Resource{} |
| + prev := "shop.example.com." |
| + for i := 0; i < 12; i++ { |
| + next := "hop" + string(rune('a'+i)) + ".example.com." |
| + long = append(long, cnameRecord(prev, next)) |
| + prev = next |
| + } |
| + long = append(long, aRecord(prev, edgeIP)) |
| + fa := startAuthority(t, authoritative(long...)) |
| + if ips, err := oneZone(fa).resolver(clock()).Resolve("shop.example.com"); err == nil { |
| + t.Fatalf("Resolve over a 12-hop chain = %v, want an error", ips) |
| } |
| } |
| func TestFreshResolverBacksOffAfterAFailure(t *testing.T) { |
| - // A dead nameserver costs one timeout per backoff window, not one per |
| - // pass: every pass would otherwise stall on it. |
| fa := startAuthority(t, func(dnsmessage.Question, *dnsmessage.Message) bool { return false }) |
| - now := time.Unix(1000, 0) |
| - r := resolverFor(fa, &now) |
| + now := clock() |
| + r := oneZone(fa).resolver(now) |
| if _, err := r.Resolve("shop.example.com"); err == nil { |
| t.Fatal("first Resolve against a dead server succeeded") |
| } |
| @@ -190,14 +340,14 @@ func TestFreshResolverBacksOffAfterAFailure(t *testing.T) { |
| if sent == 0 { |
| t.Fatal("no query reached the server") |
| } |
| - now = now.Add(10 * time.Minute) |
| + *now = now.Add(10 * time.Minute) |
| if _, err := r.Resolve("shop.example.com"); err == nil { |
| t.Fatal("Resolve inside the backoff succeeded") |
| } |
| if fa.queries.Load() != sent { |
| t.Fatalf("Resolve inside the backoff queried again (%d -> %d)", sent, fa.queries.Load()) |
| } |
| - now = now.Add(time.Hour) |
| + *now = now.Add(time.Hour) |
| _, _ = r.Resolve("shop.example.com") |
| if fa.queries.Load() == sent { |
| t.Fatal("Resolve after the backoff did not query again") |
| @@ -211,20 +361,37 @@ func TestFreshResolverStopsAtTheTopLevel(t *testing.T) { |
| r := &domains.FreshResolver{ |
| LookupNS: func(_ context.Context, name string) ([]*net.NS, error) { |
| asked = append(asked, name) |
| - if name == "test" { |
| - return []*net.NS{{Host: "tld.test."}}, nil |
| + if name == "org" { |
| + return []*net.NS{{Host: "tld.org."}}, nil |
| } |
| return nil, errNotFound |
| }, |
| LookupHost: func(context.Context, string) ([]string, error) { return nil, errNotFound }, |
| Timeout: 500 * time.Millisecond, |
| } |
| - if _, err := r.Resolve("a.b.nowhere.test"); err == nil { |
| + if _, err := r.Resolve("a.b.nowhere.org"); err == nil { |
| t.Fatal("Resolve with no zone succeeded") |
| } |
| for _, n := range asked { |
| - if n == "test" { |
| + if n == "org" { |
| t.Fatalf("asked the TLD for NS: %v", asked) |
| } |
| } |
| } |
| + |
| +func TestFreshResolverSkipsSpecialUseNames(t *testing.T) { |
| + // The box carries sidecar routes under .internal; nobody can hold a |
| + // public zone there, so they cost no lookup at all. |
| + r := &domains.FreshResolver{ |
| + LookupNS: func(context.Context, string) ([]*net.NS, error) { |
| + t.Fatal("LookupNS called for a special-use name") |
| + return nil, nil |
| + }, |
| + LookupHost: func(context.Context, string) ([]string, error) { return nil, errNotFound }, |
| + } |
| + for _, h := range []string{"bot.app.acct.sidecar.internal", "printer.local", "localhost", "x.invalid"} { |
| + if _, err := r.Resolve(h); err == nil { |
| + t.Fatalf("Resolve(%s) succeeded", h) |
| + } |
| + } |
| +} |
diff --git a/internal/domains/reconcile.go b/internal/domains/reconcile.go| index ad89fa2a8..6256a10fe 100644 |
| --- a/internal/domains/reconcile.go |
| +++ b/internal/domains/reconcile.go |
| @@ -9,6 +9,7 @@ import ( |
| "errors" |
| "fmt" |
| "log" |
| + "math/rand/v2" |
| "net" |
| "os" |
| "path/filepath" |
| @@ -41,7 +42,7 @@ type Config struct { |
| // Resolve is the DNS seam (net resolver in production, a fake in |
| // tests); nil skips DNS stamping entirely. |
| Resolve func(host string) ([]string, error) |
| - // ResolveFresh asks without any cache (#724); see freshDNSStatus. nil |
| + // ResolveFresh asks without any cache (#724); see freshUpgrade. nil |
| // leaves every verdict to Resolve alone. |
| ResolveFresh func(host string) ([]string, error) |
| // AcmeDir is the edge's autocert DirCache directory; "" skips TLS |
| @@ -496,8 +497,24 @@ func StampHealth(ctx context.Context, reg *registry.Registry, cfg Config, routes |
| // gone. A customer who deletes their record must stop reading |
| // "pointing" — refusing that news would be the same lie in the |
| // opposite direction. |
| - for _, rt := range routes { |
| - status := freshDNSStatus(cfg, rt.Host, edge) |
| + routeStatus := make([]string, len(routes)) |
| + for i, rt := range routes { |
| + routeStatus[i] = dnsStatus(cfg.Resolve, rt.Host, edge) |
| + } |
| + aliasStatus := make([]string, len(aliases)) |
| + for i, a := range aliases { |
| + aliasStatus[i] = dnsStatus(cfg.Resolve, a.Alias, edge) |
| + } |
| + var candidates []freshCandidate |
| + for i, rt := range routes { |
| + candidates = append(candidates, freshCandidate{rt.Host, &routeStatus[i]}) |
| + } |
| + for i, a := range aliases { |
| + candidates = append(candidates, freshCandidate{a.Alias, &aliasStatus[i]}) |
| + } |
| + freshUpgrade(cfg, edge, candidates) |
| + for i, rt := range routes { |
| + status := routeStatus[i] |
| if status == unresolvedDNS && rt.DNSStatus != "" { |
| continue |
| } |
| @@ -505,8 +522,8 @@ func StampHealth(ctx context.Context, reg *registry.Registry, cfg Config, routes |
| log.Printf("domains: stamp dns on %s: %v", rt.Host, err) |
| } |
| } |
| - for _, a := range aliases { |
| - status := freshDNSStatus(cfg, a.Alias, edge) |
| + for i, a := range aliases { |
| + status := aliasStatus[i] |
| if status == unresolvedDNS && a.DNSStatus != "" { |
| continue |
| } |
| @@ -570,8 +587,25 @@ func dnsStatus(resolve func(host string) ([]string, error), host string, edge ma |
| return "elsewhere" |
| } |
| -// freshDNSStatus is dnsStatus with a second, uncached look for a customer's |
| -// hostname that does not point here yet (#724). |
| +// freshCandidate is one name section 4 stamps and the verdict the cached |
| +// lookup gave it, which freshUpgrade may raise in place. |
| +type freshCandidate struct { |
| + host string |
| + status *string |
| +} |
| + |
| +// The per-pass bound on fresh lookups (#724). Each costs at most the |
| +// FreshResolver's Timeout, and a deployment can carry any number of names |
| +// that do not point here (abandoned attaches stay that way forever), so |
| +// without a bound the pass would grow with them. Variables so tests can |
| +// shrink them. |
| +var ( |
| + freshPassMax = 64 |
| + freshPassTime = 30 * time.Second |
| +) |
| + |
| +// freshUpgrade gives a customer hostname that does not point here yet a |
| +// second, uncached look (#724). |
| // |
| // The cached answer is the box's resolver's, and that resolver holds a |
| // "no such name" for the zone's SOA minimum: a customer who attaches a |
| @@ -580,34 +614,50 @@ func dnsStatus(resolve func(host string) ([]string, error), host string, edge ma |
| // unpublished all that time. A customer moving a name from another host has |
| // the same wait on the old record's TTL ("elsewhere"). |
| // |
| -// The fresh answer may only UPGRADE the verdict to "pointing". Every other |
| +// The fresh answer may only UPGRADE a verdict to "pointing". Every other |
| // fresh result (no record, another address, a failure) leaves the cached |
| // verdict as it was, so this path can never unpublish anything or turn an |
| // answer into "unresolved". A cached lookup that FAILED is left alone too: |
| // that is our resolver's fault, handled by section 4's hold-last-verdict |
| // rule. Names under the apps domain are the platform's own zone and are |
| // never asked twice. |
| -func freshDNSStatus(cfg Config, host string, edge map[string]bool) string { |
| - status := dnsStatus(cfg.Resolve, host, edge) |
| - if cfg.ResolveFresh == nil || (status != "" && status != "elsewhere") { |
| - return status |
| +// |
| +// Eligible names are visited in a random order and the pass stops after |
| +// freshPassMax lookups or freshPassTime, so a large backlog is worked |
| +// through across passes instead of stretching any one of them. |
| +func freshUpgrade(cfg Config, edge map[string]bool, candidates []freshCandidate) { |
| + if cfg.ResolveFresh == nil { |
| + return |
| } |
| - if apps := strings.ToLower(cfg.AppsDomain); apps != "" { |
| - h := strings.ToLower(strings.TrimSuffix(host, ".")) |
| - if h == apps || strings.HasSuffix(h, "."+apps) { |
| - return status |
| + apps := strings.ToLower(cfg.AppsDomain) |
| + var eligible []freshCandidate |
| + for _, c := range candidates { |
| + if *c.status != "" && *c.status != "elsewhere" { |
| + continue |
| } |
| + h := strings.ToLower(strings.TrimSuffix(c.host, ".")) |
| + if apps != "" && (h == apps || strings.HasSuffix(h, "."+apps)) { |
| + continue |
| + } |
| + eligible = append(eligible, c) |
| } |
| - ips, err := cfg.ResolveFresh(host) |
| - if err != nil { |
| - return status |
| - } |
| - for _, ip := range ips { |
| - if edge[ip] { |
| - return "pointing" |
| + rand.Shuffle(len(eligible), func(i, j int) { eligible[i], eligible[j] = eligible[j], eligible[i] }) |
| + start := time.Now() |
| + for n, c := range eligible { |
| + if n >= freshPassMax || time.Since(start) >= freshPassTime { |
| + return |
| + } |
| + ips, err := cfg.ResolveFresh(c.host) |
| + if err != nil { |
| + continue |
| + } |
| + for _, ip := range ips { |
| + if edge[ip] { |
| + *c.status = "pointing" |
| + break |
| + } |
| } |
| } |
| - return status |
| } |
| // OpsSqid is the built-in ops account's frozen sqid (registry id 1). Every |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 26e838691..1ebac8060 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -134,4 +134,4 @@ plan14-root-reads-managed-fleets-2b1.tsv d467adec3d86ae220afe98269aa226e87adba1b |
| plan14-root-reads-design-console-secrets.tsv ba2d479f7176757f8c8a4e251c498854a2ae092509ff77d9786f79d10c503c19 |
| plan14-root-reads-edge-page-cache-1.tsv 2774b43ac5970e4340339b859204bce5eb9f83d4c2551f0984e919a2853d0216 |
| plan14-root-reads-cli-default-console-carloku.tsv 2774b43ac5970e4340339b859204bce5eb9f83d4c2551f0984e919a2853d0216 |
| -plan14-root-reads-dns-fresh-lookup-724.tsv 6d029851d1a1ff285658bf3740def2fe651a8039e3f202bc694b0e973cadb74a |
| +plan14-root-reads-dns-fresh-lookup-724.tsv 44917f6a61196f613c10e47a4778fb800d1314f369119bd6e50a79bdea1d4a83 |
diff --git a/internal/provision/testdata/plan14-root-reads-dns-fresh-lookup-724.tsv b/internal/provision/testdata/plan14-root-reads-dns-fresh-lookup-724.tsv| index a0199fbd0..32e00286c 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-dns-fresh-lookup-724.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-dns-fresh-lookup-724.tsv |
| @@ -1,11 +1,11 @@ |
| # Census overlay dns-fresh-lookup-724, written by census-propose (#369). census-ruling-dns-fresh-lookup-724, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-dns-fresh-lookup-724.md. |
| -# 2 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 1 body, 1 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| # 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| -@legacy a7e7f45a2e134e460e74edc122b538cdeba410be31ea02c5bed92533978f832e internal/domains/reconcile.go StampHealth legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-dns-fresh-lookup-724;basis=DNS loops call freshDNSStatus: a second, uncached lookup for a non-apps-domain name whose cached verdict is "" or "elsewhere"; it may only upgrade to "pointing" (#724) registry:Alias@3194,registry:Alias@3319,registry:Alias@3409,registry:Alias@3843,registry:Alias@3907,registry:Alias@3995,registry:DNSStatus@2948,registry:DNSStatus@3243,registry:Host@2899,registry:Host@3020,registry:Host@3104,registry:Host@3612,registry:Host@3671,registry:Host@3753,whole:Route@199,whole:Route@236,whole:Route@2856,whole:Route@3566,whole:RouteAlias@3150,whole:RouteAlias@3796,whole:RouteAlias@780 2f3e5a42dce0c5006e98ff8c37ce7ba10bd304b9be9a38d5e039233715b63d10 |
| @legacy 5d3238530e5a92db8e4c656224087ad2a623211170b712dc3a812f55d33f0c52 internal/host/agent.go domainsTickConfig legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-dns-fresh-lookup-724;basis=wires ResolveFresh to a FreshResolver over net.DefaultResolver (#724) data-literal@469,data-literal@510 b5843939ae5cfaf543c55c0806fef21bfb4008c7ebbec67baf22480b9084fc39 |
| -@legacy 88b363b774cbdc2fd722b687c9ceb7acb0e8284d48cf48d60d20cd54fbb53b98 internal/domains/freshdns.go FreshResolver.ask legacy accepted-legacy accepted-legacy;rev3=census-ruling-dns-fresh-lookup-724;basis=new: one UDP DNS query to a zone nameserver; the Read is the socket reply, not a file (#724) file:Read@792 d789fcf6379853ba1e36ebc6cadf896af14af479d53b2683c02dfd019fe9ab6f |
| -internal/domains/reconcile.go StampHealth legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-dns-fresh-lookup-724;basis=DNS loops call freshDNSStatus: a second, uncached lookup for a non-apps-domain name whose cached verdict is "" or "elsewhere"; it may only upgrade to "pointing" (#724) registry:Alias@3194,registry:Alias@3319,registry:Alias@3409,registry:Alias@3843,registry:Alias@3907,registry:Alias@3995,registry:DNSStatus@2948,registry:DNSStatus@3243,registry:Host@2899,registry:Host@3020,registry:Host@3104,registry:Host@3612,registry:Host@3671,registry:Host@3753,whole:Route@199,whole:Route@236,whole:Route@2856,whole:Route@3566,whole:RouteAlias@3150,whole:RouteAlias@3796,whole:RouteAlias@780 2f3e5a42dce0c5006e98ff8c37ce7ba10bd304b9be9a38d5e039233715b63d10 |
| +@legacy 90cc3630ea0c6facb5e3682b51f73d757ead11cce170561755296f6da2a8d7da internal/domains/freshdns.go FreshResolver.ask legacy accepted-legacy accepted-legacy;rev3=census-ruling-dns-fresh-lookup-724;basis=new: one UDP DNS query to a zone nameserver that passed publicNameserver (public unicast only); the Read is the socket reply, not a file (#724) file:Read@1195 b2d3cbe408c1542ff517b243bf777e2b0ab0272f3f4e0bd857e45d37c6009f4b |
| +@legacy 790551ba893a635c8579f6e8ee7fd5b61db9d0e0a05887f1827e53900ee1444e internal/domains/reconcile.go StampHealth legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-dns-fresh-lookup-724;basis=section 4 now computes every cached verdict first, then freshUpgrade gives up to 64 randomly ordered non-apps-domain names whose verdict is "" or "elsewhere" an uncached lookup (30 s pass budget) that may only upgrade to "pointing", then stamps; the extra sites are the indexed loops over the same rows (#724) registry:Alias@3097,registry:Alias@3348,registry:Alias@3864,registry:Alias@3954,registry:Alias@4388,registry:Alias@4452,registry:Alias@4540,registry:DNSStatus@3513,registry:DNSStatus@3788,registry:Host@2955,registry:Host@3234,registry:Host@3585,registry:Host@3669,registry:Host@4157,registry:Host@4216,registry:Host@4298,whole:Route@199,whole:Route@236,whole:Route@2871,whole:Route@2902,whole:Route@3174,whole:Route@3441,whole:Route@4111,whole:RouteAlias@3012,whole:RouteAlias@3043,whole:RouteAlias@3287,whole:RouteAlias@3715,whole:RouteAlias@4341,whole:RouteAlias@780 46715bba1e8b5451f7c5383a425f1b7cace565acaaa9fab4a4405562d7d710f5 |
| internal/host/agent.go domainsTickConfig legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-dns-fresh-lookup-724;basis=wires ResolveFresh to a FreshResolver over net.DefaultResolver (#724) data-literal@469,data-literal@510 b5843939ae5cfaf543c55c0806fef21bfb4008c7ebbec67baf22480b9084fc39 |
| -internal/domains/freshdns.go FreshResolver.ask legacy accepted-legacy accepted-legacy;rev3=census-ruling-dns-fresh-lookup-724;basis=new: one UDP DNS query to a zone nameserver; the Read is the socket reply, not a file (#724) file:Read@792 d789fcf6379853ba1e36ebc6cadf896af14af479d53b2683c02dfd019fe9ab6f |
| -@coverage internal/domains 010df09d6fdcd1e83569ba2dcb0e74f4f92e9e38eeb32b8531a7187ecafcb6ec |
| +internal/domains/freshdns.go FreshResolver.ask legacy accepted-legacy accepted-legacy;rev3=census-ruling-dns-fresh-lookup-724;basis=new: one UDP DNS query to a zone nameserver that passed publicNameserver (public unicast only); the Read is the socket reply, not a file (#724) file:Read@1195 b2d3cbe408c1542ff517b243bf777e2b0ab0272f3f4e0bd857e45d37c6009f4b |
| +internal/domains/reconcile.go StampHealth legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-dns-fresh-lookup-724;basis=section 4 now computes every cached verdict first, then freshUpgrade gives up to 64 randomly ordered non-apps-domain names whose verdict is "" or "elsewhere" an uncached lookup (30 s pass budget) that may only upgrade to "pointing", then stamps; the extra sites are the indexed loops over the same rows (#724) registry:Alias@3097,registry:Alias@3348,registry:Alias@3864,registry:Alias@3954,registry:Alias@4388,registry:Alias@4452,registry:Alias@4540,registry:DNSStatus@3513,registry:DNSStatus@3788,registry:Host@2955,registry:Host@3234,registry:Host@3585,registry:Host@3669,registry:Host@4157,registry:Host@4216,registry:Host@4298,whole:Route@199,whole:Route@236,whole:Route@2871,whole:Route@2902,whole:Route@3174,whole:Route@3441,whole:Route@4111,whole:RouteAlias@3012,whole:RouteAlias@3043,whole:RouteAlias@3287,whole:RouteAlias@3715,whole:RouteAlias@4341,whole:RouteAlias@780 46715bba1e8b5451f7c5383a425f1b7cace565acaaa9fab4a4405562d7d710f5 |
| +@coverage internal/domains f3bd9a67d2a297169e1be17811cf2e948e446fe16caf940604baf8c0058596be |
| @coverage internal/host 2ebf59ee154f59349da7887e5675ab5bd0d732ae8748685d8d2f5ecb4e9d7cdf |