carlos / platform Public

domains: uncached DNS look for un-pointing custom domains

A customer who attached a hostname and then added the record (the order
attach prints) waited out their zone's negative-cache TTL before the
alias was published and a cert ordered: the box's caching resolver held
the earlier NXDOMAIN. Seen at 38 minutes on the flagship.

StampHealth now gives a name outside the apps domain whose cached
verdict is "" or "elsewhere" a second look through FreshResolver: it
verifies the zone by an authoritative SOA from the server it is about to
ask, asks that zone's own nameservers (public addresses only), trusts
only an authoritative reply to the exact IN A question, and follows an
out-of-zone CNAME through the cached resolver. The fresh answer can only
upgrade a verdict to "pointing". At most 64 names / 30 s per pass, 4 s
per lookup, 30-minute backoff after a failure; special-use names
(.internal sidecars) are never asked.

Astra: R1 NOT READY, R2 READY AFTER FIXES, fix check confirmed; census
approved on #280. Fixes #724.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from dns-fresh-lookup-724 into main.
claude agent, operated by paul@keymail.dev f3a9531e870d7ba9de82d46fd47f5816b27184d1 parent de380c2
10 files changed, +1,387 −4
  • docs/superpowers/notes/census-proposal-dns-fresh-lookup-724.md +25 −0
  • internal/domains/export_test.go +12 −0
  • internal/domains/freshdns.go +447 −0
  • internal/domains/freshdns_stamp_test.go +250 −0
  • internal/domains/freshdns_test.go +530 −0
  • internal/domains/reconcile.go +98 −4
  • internal/host/agent.go +8 −0
  • internal/host/host_test.go +5 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-dns-fresh-lookup-724.tsv +11 −0

CI passed — 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
new file mode 100644
index 000000000..9654cd12b
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-dns-fresh-lookup-724.md
@@ -0,0 +1,25 @@
+# Census approval: dns-fresh-lookup-724
+
+Ruling `census-ruling-dns-fresh-lookup-724`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/host/agent.go` `domainsTickConfig` | body | unchanged (2) | wires ResolveFresh to a FreshResolver over net.DefaultResolver (LookupNS, LookupHost, LookupCNAME) (#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 names that could have a public zone (not under the apps domain, not special-use like .internal) and 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`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `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.exchange`: reads +file:Read; written legacy, accepted-legacy, frozen
+
+Seal: `f05716181a82721b38cba9b2d89c47925dc2ca426e5c4876ebf1df7b45895ee3` → `7ac2bde8301c37c7546e9aa19d375f1468fc8061876a618fa8f93dd4543c5652`.
+
+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
new file mode 100644
index 000000000..b05641a30
--- /dev/null
+++ b/internal/domains/freshdns.go
@@ -0,0 +1,447 @@
+package domains
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "math/rand/v2"
+ "net"
+ "net/netip"
+ "strings"
+ "sync"
+ "time"
+
+ "golang.org/x/net/dns/dnsmessage"
+)
+
+// 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 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
+// behind it may hold a "no such name" for the same SOA minimum. Asking the
+// zone's own nameservers is the one answer no cache can hold back.
+//
+// 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 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)
+ // LookupCNAME is the cached resolver's canonical name, used only to
+ // skip a level that is an alias; nil skips that shortcut (verifyZone
+ // still refuses a wrong zone).
+ LookupCNAME func(ctx context.Context, host string) (string, error)
+ // 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 4 s: two silent servers at
+ // AttemptTimeout each, then a verified zone's two queries.
+ 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.
+ Backoff time.Duration
+ // Now is the clock seam; nil is time.Now.
+ Now func() time.Time
+
+ mu sync.Mutex
+ failedAt map[string]time.Time
+}
+
+// errNoAuthority is a fresh lookup that got no usable authoritative answer.
+var errNoAuthority = errors.New("fresh dns: no authoritative answer")
+
+const (
+ // freshMaxServers bounds the nameserver addresses tried per zone, so a
+ // zone of silent servers leaves time for the next zone up.
+ freshMaxServers = 2
+ // 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,
+}
+
+// freshPublicName reports whether name (lower case, no trailing dot) could
+// live in a public zone at all: more than one label, and not under a
+// special-use top-level name. Resolve refuses the rest, and freshUpgrade
+// leaves them out before they can take a share of a pass's budget.
+func freshPublicName(name string) bool {
+ dot := strings.LastIndex(name, ".")
+ return dot > 0 && !freshSkipTLDs[name[dot+1:]]
+}
+
+// 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, "."))
+ if !freshPublicName(name) {
+ return nil, fmt.Errorf("%w: %s has no public zone", errNoAuthority, name)
+ }
+ now := time.Now
+ if r.Now != nil {
+ now = r.Now
+ }
+ backoff := r.Backoff
+ if backoff == 0 {
+ backoff = 30 * time.Minute
+ }
+ r.mu.Lock()
+ 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))
+ }
+ r.mu.Unlock()
+
+ timeout := r.Timeout
+ if timeout == 0 {
+ timeout = 4 * time.Second
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), timeout)
+ defer cancel()
+ ips, err := r.resolve(ctx, name)
+
+ 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()
+ 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"). It stops below the top level: a TLD's
+// servers only refer back down.
+//
+// A zone is only used once it is VERIFIED: the server about to be asked
+// answers, with authority, an SOA record owned by exactly that name. The
+// cached LookupNS cannot be trusted to name the zone on its own, because an
+// NS query follows a CNAME and Go drops the owner of the records it returns:
+// a cached "shop.example.com CNAME old-provider.net" hands back
+// old-provider.net's servers as if they were shop.example.com's. Verifying
+// at the server keeps every fresh answer, and the in-zone test on a CNAME
+// target, tied to the zone that really holds the name. A level the cached
+// resolver already knows to be an alias is skipped without asking anyone,
+// since a CNAME cannot sit at a zone apex.
+func (r *FreshResolver) resolve(ctx context.Context, name string) ([]string, error) {
+ 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:] {
+ if r.aliased(ctx, zone) {
+ continue
+ }
+ nss, err := r.LookupNS(ctx, zone)
+ if err != nil || len(nss) == 0 {
+ if ctx.Err() != nil {
+ return nil, last
+ }
+ continue
+ }
+ 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 {
+ if err := r.verifyZone(ctx, s, zone); err != nil {
+ last = err
+ if ctx.Err() != nil {
+ return nil, last
+ }
+ continue
+ }
+ 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
+}
+
+// aliased reports whether the cached resolver says zone is a CNAME to some
+// other name. Only a definite answer counts; a failed lookup is not one.
+func (r *FreshResolver) aliased(ctx context.Context, zone string) bool {
+ if r.LookupCNAME == nil {
+ return false
+ }
+ canon, err := r.LookupCNAME(ctx, zone)
+ if err != nil || canon == "" {
+ return false
+ }
+ return !strings.EqualFold(strings.TrimSuffix(canon, "."), zone)
+}
+
+// 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
+ }
+ for _, a := range addrs {
+ ip, err := netip.ParseAddr(a)
+ if err != nil || !publicNameserver(ip) {
+ continue
+ }
+ ap := netip.AddrPortFrom(ip.Unmap(), 53)
+ if ip.Unmap().Is4() {
+ v4 = append(v4, ap)
+ } else {
+ v6 = append(v6, ap)
+ }
+ }
+ 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 true
+}
+
+// exchange sends one non-recursive IN query of type qtype for name to
+// server and returns the reply to exactly that question, which must carry
+// authority and not be truncated. The RCODE is the caller's to read.
+func (r *FreshResolver) exchange(ctx context.Context, server netip.AddrPort, name string, qtype dnsmessage.Type) (*dnsmessage.Message, 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())
+ question := dnsmessage.Question{Name: qname, Type: qtype, 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
+ }
+ 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 := actx.Deadline(); ok {
+ _ = conn.SetDeadline(deadline)
+ }
+ if _, err := conn.Write(packed); err != nil {
+ return nil, err
+ }
+ buf := make([]byte, 1500)
+ var reply dnsmessage.Message
+ for {
+ n, err := conn.Read(buf)
+ if err != nil {
+ return nil, err
+ }
+ 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
+ }
+ // 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)
+ }
+ if reply.Truncated {
+ return nil, fmt.Errorf("%w: truncated reply from %s", errNoAuthority, server)
+ }
+ return &reply, nil
+}
+
+// verifyZone checks that server holds zone: an authoritative answer with an
+// IN SOA record owned by exactly zone. A server for some other zone (the
+// CNAME target's, say) refuses, answers without authority, or puts its own
+// apex's SOA in the authority section, and fails this.
+func (r *FreshResolver) verifyZone(ctx context.Context, server netip.AddrPort, zone string) error {
+ reply, err := r.exchange(ctx, server, zone, dnsmessage.TypeSOA)
+ if err != nil {
+ return err
+ }
+ if reply.RCode == dnsmessage.RCodeSuccess {
+ for _, rr := range reply.Answers {
+ if _, ok := rr.Body.(*dnsmessage.SOAResource); ok && rr.Header.Class == dnsmessage.ClassINET &&
+ strings.EqualFold(rr.Header.Name.String(), zone+".") {
+ return nil
+ }
+ }
+ }
+ return fmt.Errorf("%w: %s does not hold zone %s", errNoAuthority, server, zone)
+}
+
+// ask sends one non-recursive IN A query for name to server, which
+// verifyZone has shown holds zone, and reads the answer. 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) {
+ reply, err := r.exchange(ctx, server, name, dnsmessage.TypeA)
+ if err != nil {
+ return nil, err
+ }
+ fqdn := name + "."
+ switch reply.RCode {
+ case dnsmessage.RCodeSuccess:
+ case dnsmessage.RCodeNameError:
+ 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)
+ }
+
+ 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 && 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 && 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
+ }
+ 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)
+ }
+ return r.LookupHost(ctx, target)
+}
diff --git a/internal/domains/freshdns_stamp_test.go b/internal/domains/freshdns_stamp_test.go
new file mode 100644
index 000000000..bc663c777
--- /dev/null
+++ b/internal/domains/freshdns_stamp_test.go
@@ -0,0 +1,250 @@
+package domains_test
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// #724: a customer attaches a hostname and THEN adds the record, as the
+// attach output tells them to. The box's caching resolver has already
+// answered NXDOMAIN for the name and holds that for the zone's SOA minimum,
+// so every pass inside that window reads "" and the alias stays unpublished.
+// ResolveFresh asks without the cache and may only UPGRADE a verdict to
+// "pointing"; it never makes a verdict worse.
+
+const edgeIP = "203.0.113.7"
+
+func freshCfg(cached, fresh func(string) ([]string, error), calls *[]string) domains.Config {
+ return domains.Config{
+ AppsDomain: "oncarlos.test",
+ EdgeIPs: func() []string { return []string{edgeIP} },
+ Resolve: cached,
+ ResolveFresh: func(host string) ([]string, error) {
+ *calls = append(*calls, host)
+ return fresh(host)
+ },
+ Now: func() time.Time { return time.Unix(5000, 0) },
+ }
+}
+
+func nxdomain(string) ([]string, error) {
+ return nil, &net.DNSError{Err: "no such host", IsNotFound: true}
+}
+
+func pointingAt(string) ([]string, error) { return []string{edgeIP}, nil }
+
+func aliasStatus(t *testing.T, reg *registry.Registry, alias string) string {
+ t.Helper()
+ aliases, err := reg.ListAliases()
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, a := range aliases {
+ if a.Alias == alias {
+ return a.DNSStatus
+ }
+ }
+ t.Fatalf("alias %s not found", alias)
+ return ""
+}
+
+func regWithAlias(t *testing.T, alias string) *registry.Registry {
+ t.Helper()
+ reg := regWith(t, registry.Route{Host: "app.acct.oncarlos.test", Kind: "service", Addr: "10.0.0.1:1", Status: "ready"})
+ if err := reg.UpsertAlias(registry.RouteAlias{Alias: alias, Host: "app.acct.oncarlos.test", Account: "acct", App: "app"}); err != nil {
+ t.Fatal(err)
+ }
+ return reg
+}
+
+func TestStampHealthFreshLookupBeatsCachedNXDOMAIN(t *testing.T) {
+ reg := regWithAlias(t, "shop.example.com")
+ var calls []string
+ cfg := freshCfg(func(h string) ([]string, error) {
+ if h == "shop.example.com" {
+ return nxdomain(h)
+ }
+ return pointingAt(h)
+ }, pointingAt, &calls)
+ if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil {
+ t.Fatal(err)
+ }
+ if got := aliasStatus(t, reg, "shop.example.com"); got != "pointing" {
+ t.Fatalf("alias dns_status = %q, want pointing: the uncached answer says the record is live", got)
+ }
+}
+
+func TestStampHealthFreshLookupBeatsCachedElsewhere(t *testing.T) {
+ // The customer moved the name from another host: the cache still holds
+ // the old record until its TTL runs out.
+ reg := regWithAlias(t, "shop.example.com")
+ var calls []string
+ cfg := freshCfg(func(h string) ([]string, error) {
+ if h == "shop.example.com" {
+ return []string{"198.51.100.9"}, nil
+ }
+ return pointingAt(h)
+ }, pointingAt, &calls)
+ if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil {
+ t.Fatal(err)
+ }
+ if got := aliasStatus(t, reg, "shop.example.com"); got != "pointing" {
+ t.Fatalf("alias dns_status = %q, want pointing", got)
+ }
+}
+
+func TestStampHealthFreshLookupNeverDowngrades(t *testing.T) {
+ cases := map[string]func(string) ([]string, error){
+ "fresh NXDOMAIN": nxdomain,
+ "fresh failure": func(string) ([]string, error) { return nil, errors.New("timeout") },
+ "fresh elsewhere": func(string) ([]string, error) { return []string{"198.51.100.9"}, nil },
+ }
+ for name, fresh := range cases {
+ t.Run(name, func(t *testing.T) {
+ reg := regWithAlias(t, "shop.example.com")
+ var calls []string
+ cfg := freshCfg(func(h string) ([]string, error) {
+ if h == "shop.example.com" {
+ return nxdomain(h)
+ }
+ return pointingAt(h)
+ }, fresh, &calls)
+ if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil {
+ t.Fatal(err)
+ }
+ if got := aliasStatus(t, reg, "shop.example.com"); got != "" {
+ t.Fatalf("alias dns_status = %q, want \"\" (the cached verdict stands)", got)
+ }
+ })
+ }
+}
+
+func TestStampHealthFreshLookupOnlyWhereItCanHelp(t *testing.T) {
+ reg := regWith(t,
+ registry.Route{Host: "app.acct.oncarlos.test", Kind: "service", Addr: "10.0.0.1:1", Status: "ready"},
+ registry.Route{Host: "gone.acct.oncarlos.test", Kind: "service", Addr: "10.0.0.1:2", Status: "ready"},
+ )
+ for _, a := range []string{"live.example.com", "new.example.com"} {
+ 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) {
+ switch h {
+ case "new.example.com", "gone.acct.oncarlos.test":
+ return nxdomain(h)
+ }
+ return pointingAt(h)
+ }, pointingAt, &calls)
+ if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil {
+ t.Fatal(err)
+ }
+ // Already pointing: no second lookup. Under the apps domain: the
+ // platform's own zone, not a customer's, so nothing to bypass.
+ if len(calls) != 1 || calls[0] != "new.example.com" {
+ t.Fatalf("fresh lookups = %v, want only [new.example.com]", calls)
+ }
+ if got := mustGet(t, reg, "gone.acct.oncarlos.test"); got.DNSStatus != "" {
+ t.Fatalf("apps-domain route = %q, want \"\"", got.DNSStatus)
+ }
+}
+
+func TestStampHealthFreshLookupLeavesResolverFailureAlone(t *testing.T) {
+ // Our resolver failing is not a customer verdict to second-guess: the
+ // existing hold-last-verdict rule applies untouched.
+ reg := regWithAlias(t, "shop.example.com")
+ var calls []string
+ cfg := freshCfg(func(h string) ([]string, error) {
+ if h == "shop.example.com" {
+ return nil, errors.New("SERVFAIL")
+ }
+ return pointingAt(h)
+ }, pointingAt, &calls)
+ if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil {
+ t.Fatal(err)
+ }
+ if len(calls) != 0 {
+ t.Fatalf("fresh lookups = %v, want none on a resolver failure", calls)
+ }
+ if got := aliasStatus(t, reg, "shop.example.com"); got != "unresolved" {
+ 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)
+ }
+ }
+}
+
+// Astra R2 P2-3: names that can never get a fresh lookup (sidecar hosts
+// under .internal) take no share of the budget, so a customer alias is
+// asked every pass however many of them there are.
+func TestStampHealthSpecialUseNamesTakeNoBudget(t *testing.T) {
+ defer domains.SetFreshPassMax(1)()
+ routes := []registry.Route{{Host: "app.acct.oncarlos.test", Kind: "service", Addr: "10.0.0.1:1", Status: "ready"}}
+ for i := 0; i < 80; i++ {
+ routes = append(routes, registry.Route{Host: fmt.Sprintf("bot%d.app.acct.sidecar.internal", i), Kind: "service", Addr: "10.0.0.1:1", Status: "ready"})
+ }
+ reg := regWith(t, routes...)
+ if err := reg.UpsertAlias(registry.RouteAlias{Alias: "shop.example.com", 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)
+ for pass := 0; pass < 5; pass++ {
+ calls = nil
+ if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil {
+ t.Fatal(err)
+ }
+ if len(calls) != 1 || calls[0] != "shop.example.com" {
+ t.Fatalf("pass %d fresh lookups = %v, want [shop.example.com]", pass, calls)
+ }
+ }
+}
diff --git a/internal/domains/freshdns_test.go b/internal/domains/freshdns_test.go
new file mode 100644
index 000000000..7d6fd2cd9
--- /dev/null
+++ b/internal/domains/freshdns_test.go
@@ -0,0 +1,530 @@
+package domains_test
+
+import (
+ "context"
+ "errors"
+ "net"
+ "net/netip"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "golang.org/x/net/dns/dnsmessage"
+
+ "github.com/carlosframework/platform/internal/domains"
+)
+
+// fakeAuthority is a nameserver on loopback for zone. It answers SOA
+// queries itself, as a real server for zone would: the apex's SOA with
+// authority, an authoritative NODATA inside the zone, REFUSED outside it.
+// An empty zone hands SOA queries to answer too. answer builds the reply
+// to every other query; returning false drops the
+// query. A nil answer is a silent server that drops everything.
+type fakeAuthority struct {
+ addr string
+ queries atomic.Int32
+ asked atomic.Value // last A question name
+}
+
+func soaRecord(zone string) dnsmessage.Resource {
+ return dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName(zone + "."), Type: dnsmessage.TypeSOA, Class: dnsmessage.ClassINET, TTL: 300},
+ Body: &dnsmessage.SOAResource{NS: dnsmessage.MustNewName("ns1." + zone + "."), MBox: dnsmessage.MustNewName("hostmaster." + zone + "."),
+ Serial: 1, Refresh: 3600, Retry: 600, Expire: 86400, MinTTL: 1800},
+ }
+}
+
+func startAuthority(t *testing.T, zone string, answer func(q dnsmessage.Question, reply *dnsmessage.Message) bool) *fakeAuthority {
+ t.Helper()
+ pc, err := net.ListenPacket("udp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { pc.Close() })
+ fa := &fakeAuthority{addr: pc.LocalAddr().String()}
+ go func() {
+ buf := make([]byte, 1500)
+ for {
+ n, from, err := pc.ReadFrom(buf)
+ if err != nil {
+ return
+ }
+ var q dnsmessage.Message
+ if q.Unpack(buf[:n]) != nil || len(q.Questions) != 1 {
+ continue
+ }
+ fa.queries.Add(1)
+ if answer == nil {
+ continue
+ }
+ qq := q.Questions[0]
+ reply := dnsmessage.Message{Header: dnsmessage.Header{ID: q.ID, Response: true}, Questions: q.Questions}
+ if qq.Type == dnsmessage.TypeSOA && zone != "" {
+ qn := strings.TrimSuffix(qq.Name.String(), ".")
+ switch {
+ case qn == zone:
+ reply.Authoritative = true
+ reply.Answers = []dnsmessage.Resource{soaRecord(zone)}
+ case strings.HasSuffix(qn, "."+zone):
+ reply.Authoritative = true
+ reply.Authorities = []dnsmessage.Resource{soaRecord(zone)}
+ default:
+ reply.RCode = dnsmessage.RCodeRefused
+ }
+ } else {
+ fa.asked.Store(qq.Name.String())
+ if !answer(qq, &reply) {
+ continue
+ }
+ }
+ out, err := reply.Pack()
+ if err != nil {
+ t.Errorf("pack reply: %v", err)
+ return
+ }
+ pc.WriteTo(out, from)
+ }
+ }()
+ 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 {
+ return dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName(name), Type: dnsmessage.TypeA, Class: dnsmessage.ClassINET, TTL: 300},
+ Body: &dnsmessage.AResource{A: netip.MustParseAddr(ip).As4()},
+ }
+}
+
+func cnameRecord(name, target string) dnsmessage.Resource {
+ return dnsmessage.Resource{
+ Header: dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName(name), Type: dnsmessage.TypeCNAME, Class: dnsmessage.ClassINET, TTL: 300},
+ Body: &dnsmessage.CNAMEResource{CNAME: dnsmessage.MustNewName(target)},
+ }
+}
+
+var errNotFound = &net.DNSError{Err: "no such host", IsNotFound: true}
+
+// 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
+ cnames map[string]string // name -> cached canonical name
+ 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) {
+ hs, ok := w.ns[name]
+ if !ok {
+ 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) {
+ if a, ok := w.hosts[strings.TrimSuffix(host, ".")]; ok {
+ return a, nil
+ }
+ return nil, errNotFound
+ },
+ LookupCNAME: func(_ context.Context, host string) (string, error) {
+ if c, ok := w.cnames[host]; ok {
+ return c, nil
+ }
+ return "", errNotFound
+ },
+ 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, "example.com", 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)
+ }
+ if got := fa.asked.Load(); got != "shop.example.com." {
+ t.Fatalf("authority asked for %v, want shop.example.com.", got)
+ }
+}
+
+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, "example.com", 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, "example.com", func(_ dnsmessage.Question, r *dnsmessage.Message) bool {
+ r.Authoritative = true
+ r.RCode = dnsmessage.RCodeNameError
+ return true
+ })
+ _, 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)
+ }
+}
+
+func TestFreshResolverIgnoresNonAuthoritativeAnswers(t *testing.T) {
+ fa := startAuthority(t, "example.com", func(q dnsmessage.Question, r *dnsmessage.Message) bool {
+ r.Answers = []dnsmessage.Resource{aRecord(q.Name.String(), edgeIP)}
+ return true
+ })
+ 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, "example.com", 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, "example.com", 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, "example.com", nil)
+ healthy := startAuthority(t, "example.com", 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, "oldprovider.net", func(_ dnsmessage.Question, r *dnsmessage.Message) bool {
+ r.RCode = dnsmessage.RCodeRefused
+ return true
+ })
+ right := startAuthority(t, "example.com", 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, "example.com", 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, "example.com", 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) {
+ fa := startAuthority(t, "example.com", nil)
+ 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")
+ }
+ sent := fa.queries.Load()
+ if sent == 0 {
+ t.Fatal("no query reached the server")
+ }
+ *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)
+ _, _ = r.Resolve("shop.example.com")
+ if fa.queries.Load() == sent {
+ t.Fatal("Resolve after the backoff did not query again")
+ }
+}
+
+func TestFreshResolverStopsAtTheTopLevel(t *testing.T) {
+ // No zone found below the TLD: an error, and the TLD's own servers are
+ // never asked (they would only refer us back down).
+ var asked []string
+ r := &domains.FreshResolver{
+ LookupNS: func(_ context.Context, name string) ([]*net.NS, error) {
+ asked = append(asked, name)
+ 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.org"); err == nil {
+ t.Fatal("Resolve with no zone succeeded")
+ }
+ for _, n := range asked {
+ 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)
+ }
+ }
+}
+
+// Astra R2 P2-1: a cached CNAME at the name hands LookupNS the target's
+// servers. A server that is not the name's authority must never supply the
+// answer, even when it marks its reply authoritative.
+func TestFreshResolverNeverTrustsAWrongZoneServer(t *testing.T) {
+ wrong := startAuthority(t, "oldprovider.net", authoritative(aRecord("shop.example.com.", edgeIP)))
+ right := startAuthority(t, "example.com", func(_ dnsmessage.Question, r *dnsmessage.Message) bool {
+ r.Authoritative = true
+ r.RCode = dnsmessage.RCodeNameError
+ return true
+ })
+ 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 !isNotFoundErr(err) {
+ t.Fatalf("Resolve = %v, %v; want the real zone's NXDOMAIN, not the wrong zone's address", ips, err)
+ }
+}
+
+// A level the cache already knows to be an alias is not a zone: its
+// (silent, here) servers are never dialled, so they cannot use up the time.
+func TestFreshResolverSkipsAnAliasedLevel(t *testing.T) {
+ silent := startAuthority(t, "oldprovider.net", nil)
+ right := startAuthority(t, "example.com", 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", "192.0.2.10"},
+ "ns1.example.com": {"192.0.2.53"},
+ },
+ routes: map[string]*fakeAuthority{"192.0.2.9:53": silent, "192.0.2.10:53": silent, "192.0.2.53:53": right},
+ cnames: map[string]string{"shop.example.com": "old-provider.net."},
+ }
+ ips, err := w.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)
+ }
+ for _, d := range w.dialed {
+ if d != "192.0.2.53:53" {
+ t.Fatalf("dialled %v, want only the real zone's server", w.dialed)
+ }
+ }
+}
+
+// Astra R2 P2-2: with a cached "shop.example.com CNAME example.com",
+// LookupNS(shop.example.com) returns example.com's own servers. The zone
+// must still come out as example.com, so an in-zone target with no
+// address is refused rather than filled in from a stale cache.
+func TestFreshResolverInZoneTestUsesTheVerifiedZone(t *testing.T) {
+ fa := startAuthority(t, "example.com", authoritative(cnameRecord("shop.example.com.", "www.example.com.")))
+ w := oneZone(fa)
+ w.ns["shop.example.com"] = []string{"ns1.example.com."}
+ w.hosts["www.example.com"] = []string{edgeIP} // stale cache
+ if ips, err := w.resolver(clock()).Resolve("shop.example.com"); err == nil {
+ t.Fatalf("Resolve = %v, want an error: the in-zone target has no address", ips)
+ }
+}
+
+func isNotFoundErr(err error) bool {
+ var dnsErr *net.DNSError
+ return errors.As(err, &dnsErr) && dnsErr.IsNotFound
+}
+
+// A sloppy server puts its own apex's SOA in the answer section whatever
+// name it is asked about. Only an SOA owned by the asked name verifies a
+// zone, or shop.example.com would pass as a zone and www.example.com would
+// look out-of-zone, open to the stale cache.
+func TestFreshResolverVerifiesTheSOAOwner(t *testing.T) {
+ fa := startAuthority(t, "", func(q dnsmessage.Question, r *dnsmessage.Message) bool {
+ r.Authoritative = true
+ if q.Type == dnsmessage.TypeSOA {
+ r.Answers = []dnsmessage.Resource{soaRecord("example.com")}
+ return true
+ }
+ r.Answers = []dnsmessage.Resource{cnameRecord("shop.example.com.", "www.example.com.")}
+ return true
+ })
+ w := oneZone(fa)
+ w.ns["shop.example.com"] = []string{"ns1.example.com."}
+ w.hosts["www.example.com"] = []string{edgeIP} // stale cache
+ if ips, err := w.resolver(clock()).Resolve("shop.example.com"); err == nil {
+ t.Fatalf("Resolve = %v, want an error", ips)
+ }
+}
diff --git a/internal/domains/reconcile.go b/internal/domains/reconcile.go
index dc3a64c61..61f120601 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,6 +42,9 @@ 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 freshUpgrade. nil
+ // leaves every verdict to Resolve alone.
+ ResolveFresh func(host string) ([]string, error)
// AcmeDir is the edge's autocert DirCache directory; "" skips TLS
// stamping entirely.
AcmeDir string
@@ -493,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 := dnsStatus(cfg.Resolve, 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
}
@@ -502,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 := dnsStatus(cfg.Resolve, a.Alias, edge)
+ for i, a := range aliases {
+ status := aliasStatus[i]
if status == unresolvedDNS && a.DNSStatus != "" {
continue
}
@@ -567,6 +587,80 @@ func dnsStatus(resolve func(host string) ([]string, error), host string, edge ma
return "elsewhere"
}
+// 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
+// hostname and then adds the record (the order attach prints) is read as
+// "" for 30 minutes to a day after the record went live, and the alias stays
+// 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 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 names
+// with no possible public zone (sidecar hosts under .internal) have nothing
+// to ask; neither is eligible, so neither takes a share of the budget.
+//
+// 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
+ }
+ 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 !freshPublicName(h) || (apps != "" && (h == apps || strings.HasSuffix(h, "."+apps))) {
+ continue
+ }
+ eligible = append(eligible, c)
+ }
+ 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
+ }
+ }
+ }
+}
+
// OpsSqid is the built-in ops account's frozen sqid (registry id 1). Every
// deployment has it, console or not.
var OpsSqid = Sqid(1)
diff --git a/internal/host/agent.go b/internal/host/agent.go
index bb418a720..9b1effa73 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -3795,6 +3795,14 @@ func domainsTickConfig(getenv func(string) string, publicIP string) (domains.Con
AcmeDir: filepath.Join(dd, "acme"),
Now: time.Now,
Resolve: resolveHost,
+ // #724: the uncached second look, for a customer hostname the
+ // cached answer says does not point here yet. The cached resolver
+ // still finds the zone's nameservers and our own CNAME target.
+ ResolveFresh: (&domains.FreshResolver{
+ LookupNS: net.DefaultResolver.LookupNS,
+ LookupHost: net.DefaultResolver.LookupHost,
+ LookupCNAME: net.DefaultResolver.LookupCNAME,
+ }).Resolve,
}
// EdgeIPs is deliberately left nil here — a Config out of this function
// alone stamps nothing. domainsLoop installs the fold once it has a
diff --git a/internal/host/host_test.go b/internal/host/host_test.go
index 4e09236fd..c52acf253 100644
--- a/internal/host/host_test.go
+++ b/internal/host/host_test.go
@@ -770,6 +770,11 @@ func TestDomainsTickConfig(t *testing.T) {
if got.Resolve == nil || got.Now == nil {
t.Error("Resolve/Now seams not populated on a configured deployment")
}
+ // #724: the uncached second look for a customer's hostname is wired in
+ // production, not only in the domains tests.
+ if got.ResolveFresh == nil {
+ t.Error("ResolveFresh not populated on a configured deployment")
+ }
// No explicit edge IPs: the box's own public IP (IMDS) is the default.
got, envIPs, _ = domainsTickConfig(env(map[string]string{"PLATFORM_APPS_DOMAIN": "oncarlos.test"}), "9.9.9.9")
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 4d4ba08c2..4c12aba2c 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -135,3 +135,4 @@ plan14-root-reads-design-console-secrets.tsv ba2d479f7176757f8c8a4e251c498854a2a
plan14-root-reads-edge-page-cache-1.tsv 2774b43ac5970e4340339b859204bce5eb9f83d4c2551f0984e919a2853d0216
plan14-root-reads-cli-default-console-carloku.tsv 2774b43ac5970e4340339b859204bce5eb9f83d4c2551f0984e919a2853d0216
plan14-root-reads-gvisor-demos.tsv f05716181a82721b38cba9b2d89c47925dc2ca426e5c4876ebf1df7b45895ee3
+plan14-root-reads-dns-fresh-lookup-724.tsv 7ac2bde8301c37c7546e9aa19d375f1468fc8061876a618fa8f93dd4543c5652
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
new file mode 100644
index 000000000..9af254375
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-dns-fresh-lookup-724.tsv
@@ -0,0 +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.
+# 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 fb048df97af767c79c1bd5495c5338df8716ecbacef15197f6588dc84e595482 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 (LookupNS, LookupHost, LookupCNAME) (#724) data-literal@469,data-literal@510 015ea39a31e76d50ee6f573cec2f2cbf915c729accfd017ec99fd8b7299ac2e5
+@legacy 5d4d1b5fe6d590e9dad9840c14878453d4dc94daf08f726c398b518a1df6c650 internal/domains/freshdns.go FreshResolver.exchange legacy accepted-legacy accepted-legacy;rev3=census-ruling-dns-fresh-lookup-724;basis=new: one non-recursive IN query over UDP to a nameserver that passed publicNameserver (public unicast only), 1 s per attempt; the Read is the socket reply, not a file (#724) file:Read@1217 42780e6af3180514c8d83fefff0aa84069a8e4db9ec49ee8bfa404edce0ee21b
+@legacy cbfa6a628884ab6c9f95a5e174caa9a44fa526bde29a4f36bfd0686514b8b913 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 names that could have a public zone (not under the apps domain, not special-use like .internal) and 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 (LookupNS, LookupHost, LookupCNAME) (#724) data-literal@469,data-literal@510 015ea39a31e76d50ee6f573cec2f2cbf915c729accfd017ec99fd8b7299ac2e5
+internal/domains/freshdns.go FreshResolver.exchange legacy accepted-legacy accepted-legacy;rev3=census-ruling-dns-fresh-lookup-724;basis=new: one non-recursive IN query over UDP to a nameserver that passed publicNameserver (public unicast only), 1 s per attempt; the Read is the socket reply, not a file (#724) file:Read@1217 42780e6af3180514c8d83fefff0aa84069a8e4db9ec49ee8bfa404edce0ee21b
+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 names that could have a public zone (not under the apps domain, not special-use like .internal) and 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 8c13a19a1f3c0ce734679577bf1d8aeb9e62b07877dff9c5d3bd04104f51aa94
+@coverage internal/host a0ff080e9c6ef84efc193f1b6f3ec1e840696392a8ca30ce544bbe7c058368f4