Merge branch 'no-negative-prime-724' into main
domains: never prime negative DNS caches for new custom hostnames (#724) The DNS health stamp takes the fresh, authoritative look first for names not yet pointing, so no box of ours plants a "no such name" entry in the resolver caches before the customer adds their record; the cert issuer then sees a clean miss after publication on every box, the home box included. FreshResolver walks top-down from the ICANN registrable domain following referrals, every zone verified by its own SOA, with no cached query below the registrable domain. Published names keep the cached-first path plus an upgrade re-check that reaches every zone main reached. Two-strike rule before any cached fallback; NODATA handled with an AAAA follow-up; backoff cleared on publication and reclaimed for removed names. Built by Claude Opus 5.5 and Claude Fable 5.2; reviewed by Astra (five rounds) and Fable 5.2 (two rounds); census approved by Astra on #280.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
10 files changed,
+3,116
−287
docs/superpowers/notes/census-proposal-no-negative-prime-724.md+25 −0internal/domains/export_test.go+35 −0internal/domains/freshdns.go+639 −116internal/domains/freshdns_stamp_test.go+946 −6internal/domains/freshdns_test.go+1,230 −103internal/domains/reconcile.go+209 −52internal/host/agent.go+16 −8internal/host/host_test.go+2 −2internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-no-negative-prime-724.tsv+13 −0
CI passed — run details
diff --git a/docs/superpowers/notes/census-proposal-no-negative-prime-724.md b/docs/superpowers/notes/census-proposal-no-negative-prime-724.md| new file mode 100644 |
| index 000000000..3a8fbc395 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-no-negative-prime-724.md |
| @@ -0,0 +1,25 @@ |
| +# Census approval: no-negative-prime-724 |
| + |
| +Ruling `census-ruling-no-negative-prime-724`. The independent reviewer approves or rejects every change below, 3 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) | builds the one FreshResolver per config as a local and wires five of its methods into domains.Config: Resolve (ResolveFresh), ResolveUpgrade (new: for names already "pointing" only, asks the name's nearest zones first, climbing its levels below the registrable domain through cached NS sets, at most three levels that have one, and then the same top-down walk), Forget (FreshForget, clears that resolver's in-memory backoff and strike for a host), Strike (new FreshStrike, the in-memory two-strike rule for a new name's fresh failure) and Retain (new FreshRetain, drops that resolver's in-memory backoff and strike entries for names not in the pass's route and alias hostnames; it only deletes map entries, sends and reads nothing); drops LookupCNAME from the resolver; comment updated to say which cached lookups each path makes; reads nothing new, no file, path, env var or command input added (#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;rev3=census-ruling-dns-fresh-lookup-724;basis=wires ResolveFresh to a FreshResolver over net.DefaultResolver (LookupNS, LookupHost, LookupCNAME) (#724) |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/domains/freshdns.go:FreshResolver.query`: reads +file:Read; written legacy, accepted-legacy, frozen |
| +- quiet `internal/domains/freshdns.go:FreshResolver.exchange`: reads nothing now; retired while it reads nothing (or its row keeps no sites) |
| +- reads `internal/domains/reconcile.go:StampHealth`: -registry:Alias, +registry:DNSCheckedAt ×2, +registry:DNSStatus ×2, -registry:Host, -whole:Route, -whole:RouteAlias; keeps legacy, task accepted-legacy |
| + |
| +Seal: `8924fafc5b6083858a72f45c764081abe3bcad6a6de71901470586c076c64bb6` → `ab10145ee873e26b87a653f728cd0c9737592fefe94b659ac5988201c195cb7a`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-no-negative-prime-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 6084f6713..6564a249f 100644 |
| --- a/internal/domains/export_test.go |
| +++ b/internal/domains/export_test.go |
| @@ -1,5 +1,7 @@ |
| package domains |
| +import "time" |
| + |
| // MintedRoute is mintedRoute, for the external tests that drive a minted |
| // row through the edge (rootfs_apex_test.go): package edge imports this one, |
| // so only an external test package can import both. |
| @@ -16,3 +18,36 @@ func SetFreshPassMax(n int) (restore func()) { |
| // PublicNameserver is publicNameserver, the fresh lookup's destination |
| // policy. |
| var PublicNameserver = publicNameserver |
| + |
| +// RegistrableDomain is registrableDomain, where the fresh walk starts. |
| +var RegistrableDomain = registrableDomain |
| + |
| +// ErrFreshNoData and ErrFreshBackingOff are the fresh lookup's "exists, no |
| +// A record" and "answered from the backoff". |
| +var ( |
| + ErrFreshNoData = errNoData |
| + ErrFreshBackingOff = errBackingOff |
| +) |
| + |
| +// SetFreshPassTime changes the per-pass fresh time budget for a test and |
| +// returns the restore. |
| +func SetFreshPassTime(d time.Duration) (restore func()) { |
| + old := freshPassTime |
| + freshPassTime = d |
| + return func() { freshPassTime = old } |
| +} |
| + |
| +// FreshStrikeState is r's two-strike entry for name: 0 none, 1 a pending |
| +// first strike, 2 a second strike taken. |
| +func FreshStrikeState(r *FreshResolver, name string) int { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + return r.struck[name] |
| +} |
| + |
| +// FreshMaxBackoff and FreshMaxNSHosts are the resolver's map and |
| +// nameserver-host bounds. |
| +const ( |
| + FreshMaxBackoff = freshMaxBackoff |
| + FreshMaxNSHosts = freshMaxNSHosts |
| +) |
diff --git a/internal/domains/freshdns.go b/internal/domains/freshdns.go| index b05641a30..cae8eeb3f 100644 |
| --- a/internal/domains/freshdns.go |
| +++ b/internal/domains/freshdns.go |
| @@ -12,22 +12,30 @@ import ( |
| "time" |
| "golang.org/x/net/dns/dnsmessage" |
| + "golang.org/x/net/publicsuffix" |
| ) |
| // 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. |
| +// name by asking authoritative servers top-down from the name's registrable |
| +// domain, asks that zone's own nameservers, and trusts only an |
| +// authoritative reply to the exact question it sent. Config.ResolveFresh is |
| +// its Resolve, Config.ResolveUpgrade its ResolveUpgrade, Config.FreshForget |
| +// its Forget, Config.FreshStrike its Strike and Config.FreshRetain its |
| +// Retain. |
| // |
| // 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 cached resolver is still used, only for names that exist whatever |
| +// the customer has done yet: the registrable domain's NS set (LookupNS), |
| +// nameserver host addresses and a CNAME target outside the zone (in |
| +// practice the deployment's own edge name) (LookupHost). For a new name |
| +// (Resolve) it is never asked about the name or any label between it and |
| +// the registrable domain; see resolve. A published name (ResolveUpgrade) |
| +// exists, so that look may ask it about those too. |
| // |
| // The nameservers are named by tenant DNS, so their addresses are tenant |
| // input: every one passes publicNameserver before a socket is opened, and |
| @@ -36,45 +44,82 @@ import ( |
| 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 bounds one whole Resolve, cached discovery included, and is |
| + // the deadline every exchange runs under; 0 is 4 s. That is enough for |
| + // a silent server at AttemptTimeout and a verified answer from the |
| + // next, or for a few referrals at ordinary latency; a slow, deep |
| + // delegation runs out of it and fails (closed, into the backoff). |
| Timeout time.Duration |
| - // AttemptTimeout bounds one nameserver inside it; 0 is 1 s, so a |
| - // silent server leaves time for the next. |
| + // AttemptTimeout bounds one exchange with 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. |
| + // nameserver would otherwise cost a full Timeout on every pass. Forget |
| + // ends it early. |
| Backoff time.Duration |
| // Now is the clock seam; nil is time.Now. |
| Now func() time.Time |
| mu sync.Mutex |
| failedAt map[string]time.Time |
| + struck map[string]int // strikePending or strikeTaken, by name; see Strike |
| } |
| +// A name's state in the two-strike map: its fresh-first look has failed |
| +// once and the second attempt is still owed (strikePending), or it has |
| +// failed twice in a row and taken the cached look (strikeTaken). |
| +const ( |
| + strikePending = 1 |
| + strikeTaken = 2 |
| +) |
| + |
| // errNoAuthority is a fresh lookup that got no usable authoritative answer. |
| var errNoAuthority = errors.New("fresh dns: no authoritative answer") |
| +// errBackingOff is a Resolve answered from the failure backoff: nothing was |
| +// sent, so section 4 does not count it against its per-pass budget. |
| +var errBackingOff = errors.New("fresh dns: backing off") |
| + |
| +// errNoData is an authoritative "the name exists but has no address |
| +// record": NODATA for A and then for AAAA, each from the verified server |
| +// with the zone's SOA in the authority section (noData). A TXT record at |
| +// the name, a child such as _acme-challenge making it an empty |
| +// non-terminal, or a zone that denies with NODATA instead of "no such name" |
| +// all look like this before the customer adds the record. It is definitive, |
| +// so it never enters the backoff, and section 4 stamps it "" like "no such |
| +// name" without asking the cache: a cached query would plant a per-type |
| +// negative entry for the SOA minimum (RFC 2308), which is #724 again. |
| +var errNoData = errors.New("fresh dns: name exists with no address record") |
| + |
| +// definitive reports a fresh result that settles the question: addresses, |
| +// "no such name", or "exists with no address record". |
| +func definitive(err error) bool { |
| + return err == nil || isNotFound(err) || errors.Is(err, errNoData) |
| +} |
| + |
| const ( |
| // freshMaxServers bounds the nameserver addresses tried per zone, so a |
| - // zone of silent servers leaves time for the next zone up. |
| + // zone of silent servers leaves time for the referral below it. |
| 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 bounds the referrals (and co-hosted child zones, see |
| + // zoneHint) followed below the registrable domain: up to four zones in |
| + // all. Deeper delegation fails the top-down walk. A published name's |
| + // upgrade look has asked up to freshMaxZones of its nearest zones |
| + // before that (nearest); a new name falls to the rules in section 4. |
| freshMaxZones = 3 |
| // freshMaxCNAMEs bounds a CNAME chain inside one reply. |
| freshMaxCNAMEs = 8 |
| - // freshMaxBackoff caps the failure map; past it the oldest go first. |
| + // freshMaxNSHosts bounds the nameserver hosts looked up through the |
| + // cache per zone, so a zone listing dozens of hosts cannot spend the |
| + // Timeout on cached lookups. |
| + freshMaxNSHosts = 4 |
| + // freshMaxBackoff caps the failure map (past it the oldest go first) |
| + // and the strike map (see Strike for what goes first there). |
| freshMaxBackoff = 4096 |
| ) |
| @@ -89,17 +134,38 @@ var freshSkipTLDs = map[string]bool{ |
| // 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 |
| +// special-use top-level name. Resolve refuses the rest, and dnsVerdicts |
| // 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. |
| +// Resolve returns host's addresses as its zone's nameservers give them now, |
| +// found top-down from the registrable domain (resolve). An authoritative |
| +// "no such name" is a *net.DNSError with IsNotFound, the same shape the |
| +// cached resolver gives, so callers classify both alike; a name with no |
| +// address record of either family is errNoData. |
| func (r *FreshResolver) Resolve(host string) ([]string, error) { |
| + return r.lookup(host, false) |
| +} |
| + |
| +// ResolveUpgrade is the fresh look for a name that is already published, |
| +// so exists. It asks the name's nearest zones FIRST, found by climbing |
| +// from the name through cached NS sets (nearest), and walks top-down from |
| +// the registrable domain only when that gives no definitive answer. Nearest-first because it is the lookup |
| +// main did, so it succeeds wherever main's did, with the whole Timeout to |
| +// do it in: run second, a deep delegation with slow servers left it no time |
| +// and the name backed off for the whole Backoff. Priming is no concern for |
| +// a name that exists, so on this path the cache may also be asked for any |
| +// nameserver host's address (serverAddrs). Section 4 uses it ONLY for names |
| +// whose previous stamp is "pointing"; a new name must never take it, since |
| +// it asks the cache about the name's own levels. |
| +func (r *FreshResolver) ResolveUpgrade(host string) ([]string, error) { |
| + return r.lookup(host, true) |
| +} |
| + |
| +func (r *FreshResolver) lookup(host string, near bool) ([]string, error) { |
| name := strings.ToLower(strings.TrimSuffix(host, ".")) |
| if !freshPublicName(name) { |
| return nil, fmt.Errorf("%w: %s has no public zone", errNoAuthority, name) |
| @@ -121,7 +187,7 @@ func (r *FreshResolver) Resolve(host string) ([]string, error) { |
| } |
| 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)) |
| + return nil, fmt.Errorf("%w: %w for %s since %s", errNoAuthority, errBackingOff, name, at.UTC().Format(time.RFC3339)) |
| } |
| r.mu.Unlock() |
| @@ -131,9 +197,22 @@ func (r *FreshResolver) Resolve(host string) ([]string, error) { |
| } |
| ctx, cancel := context.WithTimeout(context.Background(), timeout) |
| defer cancel() |
| - ips, err := r.resolve(ctx, name) |
| + var ips []string |
| + var err error |
| + if near { |
| + ips, err = r.nearest(ctx, name) |
| + if !definitive(err) && ctx.Err() == nil { |
| + ips, err = r.resolve(ctx, name, true) |
| + } |
| + } else { |
| + ips, err = r.resolve(ctx, name, false) |
| + } |
| - if err != nil && !isNotFound(err) { |
| + if definitive(err) { |
| + r.mu.Lock() |
| + delete(r.struck, name) |
| + r.mu.Unlock() |
| + } else { |
| r.mu.Lock() |
| if r.failedAt == nil { |
| r.failedAt = map[string]time.Time{} |
| @@ -154,96 +233,374 @@ func (r *FreshResolver) Resolve(host string) ([]string, error) { |
| return ips, err |
| } |
| +// Forget ends host's failure backoff and its strike, so the next Resolve |
| +// asks again. Section 4 calls it when a name it looked at fresh before |
| +// publication is published by any path: a failure recorded while the name |
| +// was unpublished must never stop the look that keeps it published (Astra |
| +// R2 on #724). |
| +func (r *FreshResolver) Forget(host string) { |
| + name := strings.ToLower(strings.TrimSuffix(host, ".")) |
| + r.mu.Lock() |
| + delete(r.failedAt, name) |
| + delete(r.struck, name) |
| + r.mu.Unlock() |
| +} |
| + |
| +// Retain forgets the failure backoff and the strike of every name that is |
| +// not in hosts. Section 4 hands it the deployment's hostnames once per |
| +// pass, so a name that failed once and was then removed gives its place in |
| +// the strike map back; left there, such pending strikes would fill the map |
| +// and send every later failure straight to the cached look (see Strike). A |
| +// name still in hosts keeps both, a pending first strike included. |
| +func (r *FreshResolver) Retain(hosts []string) { |
| + keep := make(map[string]bool, len(hosts)) |
| + for _, h := range hosts { |
| + keep[strings.ToLower(strings.TrimSuffix(h, "."))] = true |
| + } |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + for n := range r.failedAt { |
| + if !keep[n] { |
| + delete(r.failedAt, n) |
| + } |
| + } |
| + for n := range r.struck { |
| + if !keep[n] { |
| + delete(r.struck, n) |
| + } |
| + } |
| +} |
| + |
| +// Strike is section 4's two-strike rule for a NEW name whose fresh look |
| +// failed (Fable R3 on #724). The first failure in a row is forgiven: its |
| +// backoff is cleared so the next pass asks fresh again, and Strike reports |
| +// false (section 4 then asks nobody else). The second in a row reports true |
| +// and keeps the backoff (section 4 then takes the cached look). A |
| +// definitive fresh answer, or Forget, resets the count. |
| +// |
| +// The map holds at most freshMaxBackoff names. A pending first strike is |
| +// never evicted before its second attempt: forgetting it would hold the |
| +// name a second time and defer its cached look again. When the map is |
| +// full, a name that has already taken its second strike makes room (the |
| +// worst it loses is one held pass after its backoff); when every entry is |
| +// still pending, the new failure is not recorded and counts as the second |
| +// strike, so the name takes the cached look now instead of being held. |
| +// Retain keeps that last case rare: only names the deployment still carries |
| +// hold a place. |
| +func (r *FreshResolver) Strike(host string) (second bool) { |
| + name := strings.ToLower(strings.TrimSuffix(host, ".")) |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + if r.struck[name] != 0 { |
| + r.struck[name] = strikeTaken |
| + return true |
| + } |
| + if r.struck == nil { |
| + r.struck = map[string]int{} |
| + } |
| + if len(r.struck) >= freshMaxBackoff { |
| + taken := "" |
| + for n, s := range r.struck { |
| + if s == strikeTaken { |
| + taken = n |
| + break |
| + } |
| + } |
| + if taken == "" { |
| + return true |
| + } |
| + delete(r.struck, taken) |
| + } |
| + r.struck[name] = strikePending |
| + delete(r.failedAt, name) |
| + return false |
| +} |
| + |
| 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 |
| +// registrableDomain is name's ICANN registrable domain: the one label of |
| +// name below its ICANN public suffix (example.com for shop.eu.example.com, |
| +// github.io for shop.api.eu.github.io, shop.co.uk for itself). Private |
| +// public-suffix entries (eu.github.io's own rules) and wildcard rules are |
| +// climbed past until an ICANN entry is found: a private or wildcard |
| +// boundary does not prove the label below it exists, while a customer must |
| +// have registered the ICANN registrable domain for the name to resolve at |
| +// all. With no ICANN entry (an unlisted TLD) it is the last two labels. |
| +// false when name is itself a public suffix. |
| +func registrableDomain(name string) (string, bool) { |
| + suffix := "" |
| + for x := name; ; { |
| + ps, icann := publicsuffix.PublicSuffix(x) |
| + if icann { |
| + suffix = ps |
| + break |
| } |
| - if zones++; zones > freshMaxZones { |
| + i := strings.Index(ps, ".") |
| + if i < 0 { |
| 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 |
| + x = ps[i+1:] |
| + } |
| + if suffix == "" { |
| + labels := strings.Split(name, ".") |
| + return strings.Join(labels[len(labels)-2:], "."), true |
| + } |
| + rest, ok := strings.CutSuffix(name, "."+suffix) |
| + if !ok { |
| + return "", false |
| + } |
| + return rest[strings.LastIndex(rest, ".")+1:] + "." + suffix, true |
| +} |
| + |
| +// resolve finds the zone that holds name and asks it, top-down from the |
| +// registrable domain, without the cached resolver ever hearing about the |
| +// name or any label between it and the registrable domain: |
| +// |
| +// 1. zone = registrableDomain(name). Its NS set comes from the cached |
| +// LookupNS: the domain is registered, so the answer is positive and |
| +// primes nothing. This is the ONLY cached NS (or any) query on the |
| +// name's path. |
| +// 2. Each of up to freshMaxServers public addresses of the zone's servers |
| +// is verified to hold zone (verifyZone: an authoritative SOA owned by |
| +// exactly zone) and then asked for name (ask). |
| +// 3. A definitive answer (addresses, an authoritative not-found, or an |
| +// authoritative NODATA for A and AAAA carrying zone's SOA) ends the |
| +// lookup. A REFERRAL (no authority, NS records whose owner is |
| +// strictly below zone and at or above name) is followed: the owner |
| +// becomes zone, its servers come from the referral (glue only for |
| +// nameservers inside the child zone, the cached LookupHost for the |
| +// rest), and step 2 runs again, verifying the child before trusting |
| +// it. A HINT (an authoritative empty reply under the SOA of such a |
| +// child: the server holds the child zone too, see zoneHint) is |
| +// followed the same way with the servers already in hand, the hinting |
| +// one first; the cache is asked nothing. At most freshMaxZones |
| +// referrals and hints together. Anything else from a server (an |
| +// error, a referral or hint off the path, an unverified zone) moves on |
| +// to the next server, and when none is left the lookup fails. |
| +// |
| +// Why: the cached resolver (systemd-resolved, then the VPC resolver) caches |
| +// a "no such name" for a NAME, whatever type was asked (RFC 2308 section |
| +// 5), for the zone's SOA minimum, and a resolver doing NXDOMAIN cuts (RFC |
| +// 8020) denies every name below it too. A customer attaches a hostname |
| +// before adding its record, so a cached query for the name, or for a label |
| +// on the way to it that does not exist (eu.example.com), would plant |
| +// exactly that negative entry, and the cert issuer reading the same caches |
| +// would wait it out. Discovering the zone from authoritative servers |
| +// needs no such query. The remaining ways a name gets a cached query are |
| +// outside this function: section 4's cached look after a second fresh |
| +// failure in a row and for names past the per-pass budget. |
| +// |
| +// upgrade is ResolveUpgrade's walk for a published name: the same walk, |
| +// except that serverAddrs may ask the cache for any nameserver host. |
| +// |
| +// Cost, worst case, all inside Timeout (each exchange also inside |
| +// AttemptTimeout). A zone is asked through up to freshMaxServers servers, |
| +// and a server costs at most three exchanges: SOA, A, and AAAA after a |
| +// NODATA. A zone that hands the walk on does so with its last server's A |
| +// reply, so it costs at most 3 + 2 = 5 (the first server answers NODATA |
| +// and then fails the AAAA exchange, the second refers); the zone the walk |
| +// ends in costs at most 3 + 3 = 6. With 1 + freshMaxZones zones that is |
| +// 3*5 + 6 = 21 authoritative exchanges. A hint costs what a referral does. |
| +// Cached: one LookupNS; LookupHost for at most freshMaxNSHosts nameserver |
| +// hosts per zone, 16 in all (fewer once freshMaxServers IPv4 addresses are |
| +// found; none for a zone reached by a hint); and one LookupHost per reply |
| +// that ends in an out-of-zone CNAME target, which a failed lookup repeats |
| +// on the next server: one in each zone that hands on, two in the last, 5 |
| +// in all. 22 cached calls. The two maxima need different replies from the |
| +// same servers, so no one lookup reaches both. |
| +// |
| +// ResolveUpgrade adds nearest's share before the walk: up to freshMaxZones |
| +// zones at 6 exchanges each, 18, so 39 exchanges; and one LookupNS per |
| +// level of the name below the registrable domain (L of them, the name |
| +// included; only levels WITH an NS set are capped), plus for each of those |
| +// zones 4 nameserver hosts and 2 CNAME targets, 18, so 40 + L cached calls. |
| +// |
| +// Verification is what makes a referral or an NS set safe to follow: a |
| +// server only answers once it has shown, with authority, an SOA owned by |
| +// exactly the zone it was found for, so a lame or hostile server for some |
| +// other zone cannot supply the answer, and the in-zone test on a CNAME |
| +// target is tied to the zone that really holds the name. |
| +func (r *FreshResolver) resolve(ctx context.Context, name string, upgrade bool) ([]string, error) { |
| + zone, ok := registrableDomain(name) |
| + if !ok { |
| + return nil, fmt.Errorf("%w: %s is a public suffix", errNoAuthority, name) |
| + } |
| + nss, err := r.LookupNS(ctx, zone) |
| + if err != nil || len(nss) == 0 { |
| + return nil, fmt.Errorf("%w: no NS set for %s", errNoAuthority, zone) |
| + } |
| + hosts := make([]string, len(nss)) |
| + for i, ns := range nss { |
| + hosts[i] = ns.Host |
| + } |
| + registrable := zone |
| + servers := r.serverAddrs(ctx, name, registrable, zone, hosts, nil, upgrade) |
| + for referrals := 0; ; referrals++ { |
| + ips, ref, err := r.askZone(ctx, servers, name, zone) |
| + if ref == nil { |
| + return ips, err |
| } |
| - for _, s := range servers { |
| - if err := r.verifyZone(ctx, s, zone); err != nil { |
| - last = err |
| - if ctx.Err() != nil { |
| - return nil, last |
| + if referrals >= freshMaxZones { |
| + return nil, fmt.Errorf("%w: delegation to %s is more than %d levels below the registrable domain", errNoAuthority, name, freshMaxZones) |
| + } |
| + if ref.hint { |
| + // The same servers, the one that named the child first. No |
| + // cached query: nothing new was learned about where to ask. |
| + for i, s := range servers { |
| + if s == ref.from { |
| + servers[0], servers[i] = servers[i], servers[0] |
| } |
| - continue |
| } |
| - ips, err := r.ask(ctx, s, name, zone) |
| - if err == nil || isNotFound(err) { |
| + } else { |
| + servers = r.serverAddrs(ctx, name, registrable, ref.zone, ref.hosts, ref.glue, upgrade) |
| + } |
| + zone = ref.zone |
| + } |
| +} |
| + |
| +// nearest is ResolveUpgrade's first look for a published name. It climbs |
| +// the name's levels asking the cached LookupNS at each, as main's lookup |
| +// did: the immediate parent, the name itself (a delegated sub-zone, which |
| +// the parent only refers to), then each ancestor above the parent. A level |
| +// with no NS set is no zone: it is skipped and costs nothing more. A level |
| +// with one is verified and asked like any zone, and up to freshMaxZones of |
| +// those are tried, all inside the same Timeout. So a name with labels that |
| +// are not zones between it and its zone (shop.eu.a.b.c.d.example.com |
| +// served by a.b.c.d.example.com) is found however deep that zone is |
| +// delegated, which the top-down walk alone cannot do past freshMaxZones |
| +// referrals. |
| +// |
| +// The climb stops below the registrable domain, which is left to the |
| +// top-down walk that follows and starts there: a name directly under it |
| +// tries only itself here, and an apex nothing at all (its parent would be |
| +// the TLD, whose servers are never asked). The climb asks the cache about |
| +// the name's own levels, which is why only a name that already exists ever |
| +// comes here. |
| +func (r *FreshResolver) nearest(ctx context.Context, name string) ([]string, error) { |
| + registrable, ok := registrableDomain(name) |
| + var last error = fmt.Errorf("%w: no zone near %s", errNoAuthority, name) |
| + if !ok || name == registrable { |
| + return nil, last |
| + } |
| + parent := func(n string) string { return n[strings.Index(n, ".")+1:] } |
| + levels := []string{name} |
| + if up := parent(name); up != registrable { |
| + levels = []string{up, name} |
| + for up = parent(up); up != registrable && strings.Contains(up, "."); up = parent(up) { |
| + levels = append(levels, up) |
| + } |
| + } |
| + zones := 0 |
| + for _, zone := range levels { |
| + nss, err := r.LookupNS(ctx, zone) |
| + if err == nil && len(nss) > 0 { |
| + hosts := make([]string, len(nss)) |
| + for i, ns := range nss { |
| + hosts[i] = ns.Host |
| + } |
| + ips, ref, err := r.askZone(ctx, r.serverAddrs(ctx, name, registrable, zone, hosts, nil, true), name, zone) |
| + if ref == nil && definitive(err) { |
| return ips, err |
| } |
| - last = err |
| - if ctx.Err() != nil { |
| - return nil, last |
| + if err != nil { |
| + last = err |
| + } |
| + if zones++; zones >= freshMaxZones { |
| + break |
| } |
| } |
| + if ctx.Err() != nil { |
| + break |
| + } |
| } |
| 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 |
| +// askZone asks servers, which the caller found for zone, about name, one |
| +// at a time: each is verified to hold zone first. It returns the first |
| +// definitive answer, valid referral or valid hint, else the last failure. |
| +func (r *FreshResolver) askZone(ctx context.Context, servers []netip.AddrPort, name, zone string) ([]string, *referral, error) { |
| + var last error = fmt.Errorf("%w: no public address for any nameserver of %s", errNoAuthority, zone) |
| + for _, s := range servers { |
| + if last = r.verifyZone(ctx, s, zone); last == nil { |
| + ips, ref, err := r.ask(ctx, s, name, zone) |
| + if ref != nil || definitive(err) { |
| + return ips, ref, err |
| + } |
| + last = err |
| + } |
| + if ctx.Err() != nil { |
| + break |
| + } |
| } |
| - return !strings.EqualFold(strings.TrimSuffix(canon, "."), zone) |
| + return nil, nil, last |
| } |
| -// 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 { |
| +// referral is a server's "ask the child zone": the child's apex, its NS |
| +// hosts, and glue addresses for the hosts inside it. A hint is the other |
| +// way a server names a child zone (zoneHint): it has no hosts or glue, only |
| +// the server it came from, which is where the child is looked for first. |
| +type referral struct { |
| + zone string |
| + hosts []string |
| + glue map[string][]netip.Addr |
| + hint bool |
| + from netip.AddrPort |
| +} |
| + |
| +// serverAddrs resolves zone's NS hosts (in random order) 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. At most freshMaxNSHosts hosts go to the cached LookupHost. |
| +// |
| +// For a NEW name (upgrade false) two kinds of host never reach the cache. |
| +// A host inside a referred zone (glue non-nil) is taken from glue only: |
| +// the cache would be asked about a name below the registrable domain. And |
| +// a host that is name itself or one of its levels below registrable (a |
| +// stale NS entry naming eu.example.com, or the name) is not looked up at |
| +// all, at the registrable domain or on a referral: that label may not |
| +// exist, and the lookup would plant its negative (Astra R3 on #724). |
| +// |
| +// For a published name (upgrade true) neither rule applies: the name |
| +// exists, so there is nothing to prime, and a zone whose only nameserver |
| +// host sits on the name's path (example.com served by eu.example.com, for |
| +// shop.eu.example.com) must still be reachable or the name would be |
| +// unpublished. Glue is used where the referral carries it, the cache for |
| +// every other host. |
| +func (r *FreshResolver) serverAddrs(ctx context.Context, name, registrable, zone string, hosts []string, glue map[string][]netip.Addr, upgrade bool) []netip.AddrPort { |
| + onPath := func(host string) bool { |
| + return host == name || (strings.HasSuffix(name, "."+host) && strings.HasSuffix(host, "."+registrable)) |
| + } |
| var v4, v6 []netip.AddrPort |
| - for _, i := range rand.Perm(len(nss)) { |
| - addrs, err := r.LookupHost(ctx, nss[i].Host) |
| - if err != nil { |
| + lookups := 0 |
| + for _, i := range rand.Perm(len(hosts)) { |
| + host := strings.ToLower(strings.TrimSuffix(hosts[i], ".")) |
| + var addrs []netip.Addr |
| + inChild := glue != nil && (host == zone || strings.HasSuffix(host, "."+zone)) |
| + if inChild && (!upgrade || len(glue[host]) > 0) { |
| + addrs = glue[host] |
| + } else if !upgrade && onPath(host) { |
| continue |
| + } else { |
| + if lookups >= freshMaxNSHosts { |
| + continue |
| + } |
| + lookups++ |
| + found, err := r.LookupHost(ctx, host) |
| + if err != nil { |
| + continue |
| + } |
| + for _, a := range found { |
| + if ip, err := netip.ParseAddr(a); err == nil { |
| + addrs = append(addrs, ip) |
| + } |
| + } |
| } |
| - for _, a := range addrs { |
| - ip, err := netip.ParseAddr(a) |
| - if err != nil || !publicNameserver(ip) { |
| + for _, ip := range addrs { |
| + if !publicNameserver(ip) { |
| continue |
| } |
| ap := netip.AddrPortFrom(ip.Unmap(), 53) |
| @@ -298,10 +655,25 @@ func publicNameserver(ip netip.Addr) bool { |
| 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. |
| +// exchange is query for a reply that 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) { |
| + reply, err := r.query(ctx, server, name, qtype) |
| + if err != nil { |
| + return nil, err |
| + } |
| + 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 |
| +} |
| + |
| +// query sends one non-recursive IN query of type qtype for name to server |
| +// and returns the reply to exactly that question, whatever its flags. |
| +func (r *FreshResolver) query(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) |
| } |
| @@ -354,12 +726,6 @@ func (r *FreshResolver) exchange(ctx context.Context, server netip.AddrPort, nam |
| } |
| // 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 |
| } |
| @@ -384,23 +750,169 @@ func (r *FreshResolver) verifyZone(ctx context.Context, server netip.AddrPort, z |
| } |
| // 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) |
| +// verifyZone has shown holds zone, and reads the answer. A truncated reply |
| +// is a failure for this server. A reply without authority is only usable |
| +// as a referral down the name's path (see referralFrom). A CNAME chain in |
| +// an authoritative 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. A NODATA for the name itself sends one AAAA query to |
| +// the same server, and an empty reply under a child zone's SOA comes back |
| +// as a hint (see answer). |
| +func (r *FreshResolver) ask(ctx context.Context, server netip.AddrPort, name, zone string) ([]string, *referral, error) { |
| + reply, err := r.query(ctx, server, name, dnsmessage.TypeA) |
| + if err != nil { |
| + return nil, nil, err |
| + } |
| + if reply.Truncated { |
| + return nil, nil, fmt.Errorf("%w: truncated reply from %s", errNoAuthority, server) |
| + } |
| + if !reply.Authoritative { |
| + ref, err := referralFrom(reply, name, zone) |
| + if err != nil { |
| + return nil, nil, fmt.Errorf("%w (from %s)", err, server) |
| + } |
| + return nil, ref, nil |
| + } |
| + return r.answer(ctx, reply, server, name, zone) |
| +} |
| + |
| +// referralFrom reads a non-authoritative reply as a delegation. It must |
| +// carry no answer and only NS records, all owned by one child zone that is |
| +// strictly below zone and at or above name: a referral sideways, upward or |
| +// to itself (a loop) is refused. Glue is kept only for NS hosts inside the |
| +// child. |
| +func referralFrom(reply *dnsmessage.Message, name, zone string) (*referral, error) { |
| + if reply.RCode != dnsmessage.RCodeSuccess || len(reply.Answers) != 0 { |
| + return nil, fmt.Errorf("%w: no authority for %s", errNoAuthority, name) |
| + } |
| + ref := &referral{glue: map[string][]netip.Addr{}} |
| + for _, rr := range reply.Authorities { |
| + ns, ok := rr.Body.(*dnsmessage.NSResource) |
| + if !ok || rr.Header.Class != dnsmessage.ClassINET { |
| + continue |
| + } |
| + owner := strings.ToLower(strings.TrimSuffix(rr.Header.Name.String(), ".")) |
| + if ref.zone == "" { |
| + ref.zone = owner |
| + } else if owner != ref.zone { |
| + return nil, fmt.Errorf("%w: referral for %s names more than one zone", errNoAuthority, name) |
| + } |
| + ref.hosts = append(ref.hosts, strings.ToLower(strings.TrimSuffix(ns.NS.String(), "."))) |
| + } |
| + if ref.zone == "" { |
| + return nil, fmt.Errorf("%w: no authority and no referral for %s", errNoAuthority, name) |
| + } |
| + if !strings.HasSuffix(ref.zone, "."+zone) || (ref.zone != name && !strings.HasSuffix(name, "."+ref.zone)) { |
| + return nil, fmt.Errorf("%w: referral to %s is not between %s and %s", errNoAuthority, ref.zone, zone, name) |
| + } |
| + for _, rr := range reply.Additionals { |
| + if rr.Header.Class != dnsmessage.ClassINET { |
| + continue |
| + } |
| + owner := strings.ToLower(strings.TrimSuffix(rr.Header.Name.String(), ".")) |
| + if owner != ref.zone && !strings.HasSuffix(owner, "."+ref.zone) { |
| + continue |
| + } |
| + switch b := rr.Body.(type) { |
| + case *dnsmessage.AResource: |
| + ref.glue[owner] = append(ref.glue[owner], netip.AddrFrom4(b.A)) |
| + case *dnsmessage.AAAAResource: |
| + ref.glue[owner] = append(ref.glue[owner], netip.AddrFrom16(b.AAAA)) |
| + } |
| + } |
| + return ref, nil |
| +} |
| + |
| +// noData reports whether reply, which the caller has checked carries |
| +// authority, is a NODATA from zone: success, no answer, and an IN SOA owned |
| +// by exactly zone in the authority section (RFC 2308 section 2.2). Without |
| +// that SOA an empty reply proves nothing about the name (a referral-shaped |
| +// reply, or a server answering for some other zone, looks the same), so it |
| +// is a failure, not a verdict. |
| +func noData(reply *dnsmessage.Message, zone string) bool { |
| + if reply.RCode != dnsmessage.RCodeSuccess || len(reply.Answers) != 0 { |
| + return false |
| + } |
| + for _, rr := range reply.Authorities { |
| + if _, ok := rr.Body.(*dnsmessage.SOAResource); ok && rr.Header.Class == dnsmessage.ClassINET && |
| + strings.EqualFold(rr.Header.Name.String(), zone+".") { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// zoneHint reads reply, an authoritative reply to name's A query from a |
| +// server verified for zone, as a DISCOVERY HINT: success, no answer, and in |
| +// the authority section one IN SOA whose owner is strictly below zone and |
| +// at or above name. A server that holds both a zone and a child delegated |
| +// from it (example.com and eu.example.com) answers for a name in the child |
| +// from the child, with the child's SOA, and never refers. noData rightly |
| +// refuses that reply as proof of anything: the SOA is not the verified |
| +// zone's. But it names the one place the answer can be, so the caller |
| +// verifies that child like any referred zone (its own SOA, with authority, |
| +// from this server or the zone's others) and asks again under it. The |
| +// reply itself is never trusted: an owner off the name's path is no hint, |
| +// and a child that does not verify is a failure. "" when reply is no hint. |
| +func zoneHint(reply *dnsmessage.Message, name, zone string) string { |
| + if reply.RCode != dnsmessage.RCodeSuccess || len(reply.Answers) != 0 { |
| + return "" |
| + } |
| + child := "" |
| + for _, rr := range reply.Authorities { |
| + if _, ok := rr.Body.(*dnsmessage.SOAResource); !ok || rr.Header.Class != dnsmessage.ClassINET { |
| + continue |
| + } |
| + owner := strings.ToLower(strings.TrimSuffix(rr.Header.Name.String(), ".")) |
| + if child != "" && owner != child { |
| + return "" |
| + } |
| + child = owner |
| + } |
| + if !strings.HasSuffix(child, "."+zone) || (child != name && !strings.HasSuffix(name, "."+child)) { |
| + return "" |
| + } |
| + return child |
| +} |
| + |
| +// answerAAAA runs after server's NODATA for name's A record: one AAAA |
| +// query to the same verified server. Addresses owned by name are the |
| +// answer (section 4 classifies them with the usual any-edge rule); a |
| +// second NODATA is errNoData; anything else is a failure. |
| +func (r *FreshResolver) answerAAAA(ctx context.Context, server netip.AddrPort, name, zone string) ([]string, error) { |
| + reply, err := r.exchange(ctx, server, name, dnsmessage.TypeAAAA) |
| if err != nil { |
| return nil, err |
| } |
| + var ips []string |
| + if reply.RCode == dnsmessage.RCodeSuccess { |
| + for _, rr := range reply.Answers { |
| + if a, ok := rr.Body.(*dnsmessage.AAAAResource); ok && rr.Header.Class == dnsmessage.ClassINET && |
| + strings.EqualFold(rr.Header.Name.String(), name+".") { |
| + ips = append(ips, netip.AddrFrom16(a.AAAA).String()) |
| + } |
| + } |
| + } |
| + if len(ips) > 0 { |
| + return ips, nil |
| + } |
| + if noData(reply, zone) { |
| + return nil, fmt.Errorf("%w: %s (from %s)", errNoData, name, server) |
| + } |
| + return nil, fmt.Errorf("%w: %s gave no usable AAAA answer for %s", errNoAuthority, server, name) |
| +} |
| + |
| +// answer reads an authoritative reply to name's A query from server: the |
| +// addresses, a hint to a co-hosted child zone (zoneHint), or an error. |
| +func (r *FreshResolver) answer(ctx context.Context, reply *dnsmessage.Message, server netip.AddrPort, name, zone string) ([]string, *referral, error) { |
| 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} |
| + return nil, 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) |
| + return nil, nil, fmt.Errorf("%w: %s answered %s for %s", errNoAuthority, server, reply.RCode, name) |
| } |
| current := fqdn |
| @@ -418,7 +930,7 @@ func (r *FreshResolver) ask(ctx context.Context, server netip.AddrPort, name, zo |
| break |
| } |
| if seen[next] || hops >= freshMaxCNAMEs { |
| - return nil, fmt.Errorf("%w: CNAME chain from %s loops or runs too long", errNoAuthority, name) |
| + return nil, nil, fmt.Errorf("%w: CNAME chain from %s loops or runs too long", errNoAuthority, name) |
| } |
| seen[next] = true |
| current = next |
| @@ -431,17 +943,28 @@ func (r *FreshResolver) ask(ctx context.Context, server netip.AddrPort, name, zo |
| } |
| } |
| if len(ips) > 0 { |
| - return ips, nil |
| + return ips, nil, 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} |
| + // No A record and no CNAME for the name. Only a NODATA carrying the |
| + // verified zone's SOA says the name exists without one; then the |
| + // same server is asked for AAAA. Under a child zone's SOA the |
| + // reply decides nothing, but says where to look. |
| + if noData(reply, zone) { |
| + ips, err := r.answerAAAA(ctx, server, name, zone) |
| + return ips, nil, err |
| + } |
| + if child := zoneHint(reply, name, zone); child != "" { |
| + return nil, &referral{zone: child, hint: true, from: server}, nil |
| + } |
| + return nil, nil, fmt.Errorf("%w: %s gave no answer and no SOA of %s for %s", errNoAuthority, server, zone, name) |
| } |
| 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 nil, nil, fmt.Errorf("%w: %s ends at in-zone %s with no address", errNoAuthority, name, target) |
| } |
| - return r.LookupHost(ctx, target) |
| + ips, err := r.LookupHost(ctx, target) |
| + return ips, nil, err |
| } |
diff --git a/internal/domains/freshdns_stamp_test.go b/internal/domains/freshdns_stamp_test.go| index bc663c777..78b4fe1dc 100644 |
| --- a/internal/domains/freshdns_stamp_test.go |
| +++ b/internal/domains/freshdns_stamp_test.go |
| @@ -5,9 +5,12 @@ import ( |
| "errors" |
| "fmt" |
| "net" |
| + "sync/atomic" |
| "testing" |
| "time" |
| + "golang.org/x/net/dns/dnsmessage" |
| + |
| "github.com/carlosframework/platform/internal/domains" |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| @@ -16,8 +19,10 @@ import ( |
| // 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. |
| +// ResolveFresh asks without the cache. For a name that was not "pointing" |
| +// before the pass it decides the verdict, so the cache is never asked about |
| +// a name that may not exist yet; for a name that was "pointing" it may only |
| +// UPGRADE the cached verdict back to "pointing", never make it worse. |
| const edgeIP = "203.0.113.7" |
| @@ -100,6 +105,9 @@ func TestStampHealthFreshLookupBeatsCachedElsewhere(t *testing.T) { |
| } |
| } |
| +// A name that was "pointing" keeps the cached-first path: the fresh answer |
| +// may only raise the cached verdict back to "pointing", never lower it. |
| +// This is the invariant that stops the fresh path unpublishing a name. |
| func TestStampHealthFreshLookupNeverDowngrades(t *testing.T) { |
| cases := map[string]func(string) ([]string, error){ |
| "fresh NXDOMAIN": nxdomain, |
| @@ -109,6 +117,7 @@ func TestStampHealthFreshLookupNeverDowngrades(t *testing.T) { |
| for name, fresh := range cases { |
| t.Run(name, func(t *testing.T) { |
| reg := regWithAlias(t, "shop.example.com") |
| + stampAlias(t, reg, "shop.example.com", "pointing") |
| var calls []string |
| cfg := freshCfg(func(h string) ([]string, error) { |
| if h == "shop.example.com" { |
| @@ -136,6 +145,7 @@ func TestStampHealthFreshLookupOnlyWhereItCanHelp(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| + stampAlias(t, reg, "live.example.com", "pointing") |
| var calls []string |
| cfg := freshCfg(func(h string) ([]string, error) { |
| switch h { |
| @@ -158,9 +168,10 @@ func TestStampHealthFreshLookupOnlyWhereItCanHelp(t *testing.T) { |
| } |
| func TestStampHealthFreshLookupLeavesResolverFailureAlone(t *testing.T) { |
| - // Our resolver failing is not a customer verdict to second-guess: the |
| - // existing hold-last-verdict rule applies untouched. |
| + // Our resolver failing on a published name is not a customer verdict to |
| + // second-guess: the existing hold-last-verdict rule applies untouched. |
| reg := regWithAlias(t, "shop.example.com") |
| + stampAlias(t, reg, "shop.example.com", "pointing") |
| var calls []string |
| cfg := freshCfg(func(h string) ([]string, error) { |
| if h == "shop.example.com" { |
| @@ -174,8 +185,8 @@ func TestStampHealthFreshLookupLeavesResolverFailureAlone(t *testing.T) { |
| 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) |
| + if got := aliasStatus(t, reg, "shop.example.com"); got != "pointing" { |
| + t.Fatalf("alias dns_status = %q, want pointing held", got) |
| } |
| } |
| @@ -248,3 +259,932 @@ func TestStampHealthSpecialUseNamesTakeNoBudget(t *testing.T) { |
| } |
| } |
| } |
| + |
| +func stampAlias(t *testing.T, reg *registry.Registry, alias, status string) { |
| + t.Helper() |
| + if err := reg.SetAliasDNSStatus(alias, status, 4000); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// counted wraps a cached resolver and records every name it is asked about. |
| +func counted(resolve func(string) ([]string, error), asked map[string]int) func(string) ([]string, error) { |
| + return func(h string) ([]string, error) { |
| + asked[h]++ |
| + return resolve(h) |
| + } |
| +} |
| + |
| +// #724 follow-up: a name that was not "pointing" before this pass is looked |
| +// at fresh FIRST, so the box's cached resolver never hears about it while |
| +// the record may not exist yet. A cached query would plant a "no such name" |
| +// in systemd-resolved and the VPC resolver for the SOA minimum, and the |
| +// cert issuer reads those caches. |
| +func TestStampHealthNewNameIsLookedAtFreshFirst(t *testing.T) { |
| + cases := []struct { |
| + name string |
| + fresh func(string) ([]string, error) |
| + want string |
| + }{ |
| + {"record absent", nxdomain, ""}, |
| + {"record pointing", pointingAt, "pointing"}, |
| + {"record elsewhere", func(string) ([]string, error) { return []string{"198.51.100.9"}, nil }, "elsewhere"}, |
| + } |
| + for _, tc := range cases { |
| + t.Run(tc.name, func(t *testing.T) { |
| + reg := regWithAlias(t, "shop.example.com") |
| + asked := map[string]int{} |
| + var calls []string |
| + // The cached resolver would say not-found, the primed answer. |
| + cfg := freshCfg(counted(func(h string) ([]string, error) { |
| + if h == "shop.example.com" { |
| + return nxdomain(h) |
| + } |
| + return pointingAt(h) |
| + }, asked), tc.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 != tc.want { |
| + t.Fatalf("alias dns_status = %q, want %q", got, tc.want) |
| + } |
| + if asked["shop.example.com"] != 0 { |
| + t.Fatalf("cached resolver asked about shop.example.com %d times, want 0", asked["shop.example.com"]) |
| + } |
| + if len(calls) != 1 || calls[0] != "shop.example.com" { |
| + t.Fatalf("fresh lookups = %v, want [shop.example.com]", calls) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Routes are stamped the same way as aliases: a custom-domain route that |
| +// was not pointing is looked at fresh first. |
| +func TestStampHealthNewRouteIsLookedAtFreshFirst(t *testing.T) { |
| + reg := regWith(t, registry.Route{Host: "shop.example.com", Kind: "service", Addr: "10.0.0.1:1", Status: "ready"}) |
| + asked := map[string]int{} |
| + var calls []string |
| + cfg := freshCfg(counted(nxdomain, asked), pointingAt, &calls) |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := mustGet(t, reg, "shop.example.com").DNSStatus; got != "pointing" { |
| + t.Fatalf("route dns_status = %q, want pointing", got) |
| + } |
| + if asked["shop.example.com"] != 0 { |
| + t.Fatalf("cached resolver asked about shop.example.com %d times, want 0", asked["shop.example.com"]) |
| + } |
| +} |
| + |
| +// A fresh lookup that FAILS (no authority, backoff, timeout) decides |
| +// nothing: the cached path stamps exactly as it did before #724. |
| +func TestStampHealthFreshErrorFallsBackToCached(t *testing.T) { |
| + failing := func(string) ([]string, error) { return nil, errors.New("fresh dns: no authoritative answer") } |
| + cases := []struct { |
| + name string |
| + cached func(string) ([]string, error) |
| + want string |
| + }{ |
| + {"cached pointing", pointingAt, "pointing"}, |
| + {"cached not-found", nxdomain, ""}, |
| + {"cached elsewhere", func(string) ([]string, error) { return []string{"198.51.100.9"}, nil }, "elsewhere"}, |
| + {"cached failure", func(string) ([]string, error) { return nil, errors.New("SERVFAIL") }, "unresolved"}, |
| + } |
| + for _, tc := range cases { |
| + t.Run(tc.name, func(t *testing.T) { |
| + reg := regWithAlias(t, "shop.example.com") |
| + asked := map[string]int{} |
| + var calls []string |
| + cfg := freshCfg(counted(func(h string) ([]string, error) { |
| + if h == "shop.example.com" { |
| + return tc.cached(h) |
| + } |
| + return pointingAt(h) |
| + }, asked), failing, &calls) |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if asked["shop.example.com"] != 1 { |
| + t.Fatalf("cached resolver asked about shop.example.com %d times, want 1", asked["shop.example.com"]) |
| + } |
| + if len(calls) != 1 { |
| + t.Fatalf("fresh lookups = %v, want exactly one (no second try in the upgrade)", calls) |
| + } |
| + if got := aliasStatus(t, reg, "shop.example.com"); got != tc.want { |
| + t.Fatalf("alias dns_status = %q, want %q", got, tc.want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A name that was "pointing" is decided by the cached path, as before: a |
| +// positive cache entry is cheap and cannot be a primed miss. The upgrade |
| +// still re-raises a cached "" when the fresh look says pointing. |
| +func TestStampHealthPointingNameStaysCachedFirst(t *testing.T) { |
| + t.Run("cached pointing", func(t *testing.T) { |
| + reg := regWithAlias(t, "shop.example.com") |
| + stampAlias(t, reg, "shop.example.com", "pointing") |
| + asked := map[string]int{} |
| + var calls []string |
| + cfg := freshCfg(counted(pointingAt, asked), nxdomain, &calls) |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if asked["shop.example.com"] != 1 || len(calls) != 0 { |
| + t.Fatalf("cached asked %d, fresh %v; want cached once and no fresh look", asked["shop.example.com"], calls) |
| + } |
| + if got := aliasStatus(t, reg, "shop.example.com"); got != "pointing" { |
| + t.Fatalf("alias dns_status = %q, want pointing", got) |
| + } |
| + }) |
| + t.Run("cached not-found, fresh pointing", func(t *testing.T) { |
| + reg := regWithAlias(t, "shop.example.com") |
| + stampAlias(t, reg, "shop.example.com", "pointing") |
| + asked := map[string]int{} |
| + var calls []string |
| + cfg := freshCfg(counted(func(h string) ([]string, error) { |
| + if h == "shop.example.com" { |
| + return nxdomain(h) |
| + } |
| + return pointingAt(h) |
| + }, asked), pointingAt, &calls) |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if asked["shop.example.com"] != 1 { |
| + t.Fatalf("cached resolver asked about shop.example.com %d times, want 1 (cached first)", asked["shop.example.com"]) |
| + } |
| + if got := aliasStatus(t, reg, "shop.example.com"); got != "pointing" { |
| + t.Fatalf("alias dns_status = %q, want pointing re-raised", got) |
| + } |
| + }) |
| +} |
| + |
| +// Names past the per-pass fresh budget are stamped by the cached path, as |
| +// before. |
| +func TestStampHealthFreshFirstRespectsTheBudget(t *testing.T) { |
| + defer domains.SetFreshPassMax(1)() |
| + reg := regWithAlias(t, "a.example.com") |
| + if err := reg.UpsertAlias(registry.RouteAlias{Alias: "b.example.com", Host: "app.acct.oncarlos.test", Account: "acct", App: "app"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + asked := map[string]int{} |
| + var calls []string |
| + cfg := freshCfg(counted(pointingAt, asked), func(string) ([]string, error) { return []string{"198.51.100.9"}, nil }, &calls) |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(calls) != 1 { |
| + t.Fatalf("fresh lookups = %v, want 1 (the budget)", calls) |
| + } |
| + freshName := calls[0] |
| + other := "a.example.com" |
| + if freshName == other { |
| + other = "b.example.com" |
| + } |
| + if asked[freshName] != 0 || asked[other] != 1 { |
| + t.Fatalf("cached asked %v; want none for %s and once for %s", asked, freshName, other) |
| + } |
| + if got := aliasStatus(t, reg, freshName); got != "elsewhere" { |
| + t.Fatalf("%s = %q, want elsewhere (fresh)", freshName, got) |
| + } |
| + if got := aliasStatus(t, reg, other); got != "pointing" { |
| + t.Fatalf("%s = %q, want pointing (cached)", other, got) |
| + } |
| +} |
| + |
| +// Apps-domain names (the platform's own zone) and names with no public |
| +// zone are never eligible: cached only, no fresh call. |
| +func TestStampHealthIneligibleNamesStayCached(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: "bot.app.acct.sidecar.internal", Kind: "service", Addr: "10.0.0.1:2", Status: "ready"}, |
| + ) |
| + asked := map[string]int{} |
| + var calls []string |
| + cfg := freshCfg(counted(pointingAt, asked), 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", calls) |
| + } |
| + for _, h := range []string{"app.acct.oncarlos.test", "bot.app.acct.sidecar.internal"} { |
| + if asked[h] != 1 { |
| + t.Fatalf("cached resolver asked about %s %d times, want 1", h, asked[h]) |
| + } |
| + } |
| +} |
| + |
| +// Astra R1 P1 on #724 follow-up: new names must not spend the fresh budget |
| +// a published name needs. A "pointing" alias whose cache has gone stale |
| +// (NXDOMAIN) but whose record still points here is re-checked before any |
| +// fresh-first name, so it stays published; new names past the budget get |
| +// the cached look. |
| +func TestStampHealthUpgradesBeforeFreshFirst(t *testing.T) { |
| + defer domains.SetFreshPassMax(2)() |
| + newNames := []string{"a.example.com", "b.example.com", "c.example.com", "d.example.com", "e.example.com"} |
| + for pass := 0; pass < 20; pass++ { |
| + reg := regWithAlias(t, "live.example.com") |
| + stampAlias(t, reg, "live.example.com", "pointing") |
| + for _, n := range newNames { |
| + if err := reg.UpsertAlias(registry.RouteAlias{Alias: n, Host: "app.acct.oncarlos.test", Account: "acct", App: "app"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + asked := map[string]int{} |
| + var calls []string |
| + cfg := freshCfg(counted(func(h string) ([]string, error) { |
| + if h == "live.example.com" { |
| + return nxdomain(h) |
| + } |
| + return pointingAt(h) |
| + }, asked), func(h string) ([]string, error) { |
| + if h == "live.example.com" { |
| + return pointingAt(h) |
| + } |
| + return []string{"198.51.100.9"}, nil |
| + }, &calls) |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := aliasStatus(t, reg, "live.example.com"); got != "pointing" { |
| + t.Fatalf("pass %d: published alias = %q, want pointing (fresh calls %v)", pass, got, calls) |
| + } |
| + if len(calls) != 2 || calls[0] != "live.example.com" { |
| + t.Fatalf("pass %d: fresh lookups = %v, want live.example.com then one new name", pass, calls) |
| + } |
| + for _, n := range newNames { |
| + want, cached := "pointing", 1 |
| + if n == calls[1] { |
| + want, cached = "elsewhere", 0 |
| + } |
| + if got := aliasStatus(t, reg, n); got != want || asked[n] != cached { |
| + t.Fatalf("pass %d: %s = %q with %d cached queries, want %q with %d", pass, n, got, asked[n], want, cached) |
| + } |
| + } |
| + } |
| +} |
| + |
| +// realFresh is one FreshResolver kept across passes, as in production, |
| +// for example.com served by a fake authority whose A answers can be |
| +// switched off (silent) and on (pointing here). cached is what the box's |
| +// cached resolver says about shop.example.com. |
| +type realFresh struct { |
| + fa *fakeAuthority |
| + live *atomic.Bool |
| + cached *func(string) ([]string, error) |
| + asked map[string]int // cached-resolver queries by name |
| + now *time.Time |
| + cfg domains.Config |
| +} |
| + |
| +func newRealFresh(t *testing.T) *realFresh { |
| + t.Helper() |
| + live := &atomic.Bool{} |
| + fa := startAuthority(t, "example.com", func(_ dnsmessage.Question, r *dnsmessage.Message) bool { |
| + if !live.Load() { |
| + return false |
| + } |
| + r.Authoritative = true |
| + r.Answers = []dnsmessage.Resource{aRecord("shop.example.com.", edgeIP)} |
| + return true |
| + }) |
| + rf := &realFresh{fa: fa, live: live, now: clock(), asked: map[string]int{}} |
| + cached := nxdomain |
| + rf.cached = &cached |
| + fresh := oneZone(fa).resolver(rf.now) |
| + rf.cfg = domains.Config{ |
| + AppsDomain: "oncarlos.test", |
| + EdgeIPs: func() []string { return []string{edgeIP} }, |
| + Resolve: func(h string) ([]string, error) { |
| + rf.asked[h]++ |
| + if h == "shop.example.com" { |
| + return (*rf.cached)(h) |
| + } |
| + return pointingAt(h) |
| + }, |
| + // Wired exactly as domainsTickConfig wires production. |
| + ResolveFresh: fresh.Resolve, |
| + ResolveUpgrade: fresh.ResolveUpgrade, |
| + FreshForget: fresh.Forget, |
| + FreshStrike: fresh.Strike, |
| + FreshRetain: fresh.Retain, |
| + Now: func() time.Time { return *rf.now }, |
| + } |
| + return rf |
| +} |
| + |
| +func (rf *realFresh) pass(t *testing.T, reg *registry.Registry, live bool, cached func(string) ([]string, error)) { |
| + t.Helper() |
| + rf.live.Store(live) |
| + *rf.cached = cached |
| + if err := domains.StampHealth(context.Background(), reg, rf.cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// INVARIANT GUARD (Astra R2 P1-1 on #724): a fresh failure recorded while |
| +// a name was unpublished never suppresses a look after it is published. |
| +// Passes A1 and A2: the new name's fresh look fails twice (silent zone, |
| +// backoff recorded on the second) and the cache says pointing, so it is |
| +// published. Pass B, inside the backoff: the cache has gone negative while |
| +// the record still points here. The upgrade look must really be sent, and |
| +// the name stays published. |
| +func TestStampHealthPublicationClearsAnOnboardingBackoff(t *testing.T) { |
| + rf := newRealFresh(t) |
| + reg := regWithAlias(t, "shop.example.com") |
| + rf.pass(t, reg, false, pointingAt) |
| + rf.pass(t, reg, false, pointingAt) |
| + if got := aliasStatus(t, reg, "shop.example.com"); got != "pointing" { |
| + t.Fatalf("pass A: alias = %q, want pointing from the cached fallback", got) |
| + } |
| + sent := rf.fa.queries.Load() |
| + *rf.now = rf.now.Add(10 * time.Minute) |
| + rf.pass(t, reg, true, nxdomain) |
| + if rf.fa.queries.Load() == sent { |
| + t.Fatal("pass B: the upgrade look was suppressed by the onboarding failure's backoff") |
| + } |
| + if got := aliasStatus(t, reg, "shop.example.com"); got != "pointing" { |
| + t.Fatalf("pass B: alias = %q, want pointing (unpublished by a stale backoff)", got) |
| + } |
| +} |
| + |
| +// Control: a failure incurred while the name is published still backs off. |
| +// The published name's upgrade look fails (pass A, cache negative: the |
| +// record was really removed, so it stamps ""); inside the backoff no look |
| +// is sent, however the authority answers now. |
| +func TestStampHealthPublishedFailureStillBacksOff(t *testing.T) { |
| + rf := newRealFresh(t) |
| + reg := regWithAlias(t, "shop.example.com") |
| + stampAlias(t, reg, "shop.example.com", "pointing") |
| + rf.pass(t, reg, false, nxdomain) |
| + if got := aliasStatus(t, reg, "shop.example.com"); got != "" { |
| + t.Fatalf("pass A: alias = %q, want \"\" (cached removal stands)", got) |
| + } |
| + sent := rf.fa.queries.Load() |
| + if sent == 0 { |
| + t.Fatal("pass A sent no fresh look") |
| + } |
| + *rf.now = rf.now.Add(10 * time.Minute) |
| + rf.pass(t, reg, true, nxdomain) |
| + if rf.fa.queries.Load() != sent { |
| + t.Fatalf("pass B asked inside the backoff (%d -> %d)", sent, rf.fa.queries.Load()) |
| + } |
| +} |
| + |
| +// INVARIANT GUARD (Fable R3 P2-1 on #724): two strikes before the cache. |
| +// A new name's first fresh failure asks nobody else and leaves the stamp |
| +// alone; the next pass asks fresh again. Only a second failure in a row |
| +// takes the cached look, and then the backoff holds (no exchange on the |
| +// pass after, and no Forget for a name that stays ""). |
| +func TestStampHealthNewNameTwoStrikes(t *testing.T) { |
| + t.Run("fails, fails", func(t *testing.T) { |
| + rf := newRealFresh(t) |
| + reg := regWithAlias(t, "shop.example.com") |
| + rf.pass(t, reg, false, nxdomain) |
| + if rf.asked["shop.example.com"] != 0 { |
| + t.Fatal("pass A: first fresh failure asked the cache") |
| + } |
| + if a := aliasRow(t, reg, "shop.example.com"); a.DNSStatus != "" || a.DNSCheckedAt != 0 { |
| + t.Fatalf("pass A: stamp %q at %d, want untouched", a.DNSStatus, a.DNSCheckedAt) |
| + } |
| + sent := rf.fa.queries.Load() |
| + rf.pass(t, reg, false, nxdomain) |
| + if rf.fa.queries.Load() == sent { |
| + t.Fatal("pass B: no fresh retry after the first failure") |
| + } |
| + if rf.asked["shop.example.com"] != 1 { |
| + t.Fatalf("pass B: cached asked %d times, want 1 (second strike)", rf.asked["shop.example.com"]) |
| + } |
| + if a := aliasRow(t, reg, "shop.example.com"); a.DNSStatus != "" || a.DNSCheckedAt == 0 { |
| + t.Fatalf("pass B: stamp %q at %d, want the cached \"\" stamped", a.DNSStatus, a.DNSCheckedAt) |
| + } |
| + sent = rf.fa.queries.Load() |
| + rf.pass(t, reg, true, nxdomain) |
| + if rf.fa.queries.Load() != sent { |
| + t.Fatal("pass C: asked inside the backoff (Forget called for a name that stayed \"\")") |
| + } |
| + }) |
| + t.Run("fails, then answers", func(t *testing.T) { |
| + rf := newRealFresh(t) |
| + reg := regWithAlias(t, "shop.example.com") |
| + rf.pass(t, reg, false, nxdomain) |
| + rf.pass(t, reg, true, nxdomain) |
| + if got := aliasStatus(t, reg, "shop.example.com"); got != "pointing" { |
| + t.Fatalf("pass B: alias = %q, want pointing", got) |
| + } |
| + if rf.asked["shop.example.com"] != 0 { |
| + t.Fatalf("cached asked %d times, want 0", rf.asked["shop.example.com"]) |
| + } |
| + }) |
| +} |
| + |
| +func aliasRow(t *testing.T, reg *registry.Registry, alias string) registry.RouteAlias { |
| + t.Helper() |
| + aliases, err := reg.ListAliases() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, a := range aliases { |
| + if a.Alias == alias { |
| + return a |
| + } |
| + } |
| + t.Fatalf("alias %s not found", alias) |
| + return registry.RouteAlias{} |
| +} |
| + |
| +// deepCfg is production wiring over deepWorld, with a cached resolver that |
| +// says NXDOMAIN for name and counts its queries. |
| +func deepCfg(t *testing.T, name string, asked map[string]int) (domains.Config, *world) { |
| + t.Helper() |
| + w, _ := deepWorld(t) |
| + fresh := w.resolver(clock()) |
| + return domains.Config{ |
| + AppsDomain: "oncarlos.test", |
| + EdgeIPs: func() []string { return []string{edgeIP} }, |
| + Resolve: counted(func(h string) ([]string, error) { |
| + if h == name { |
| + return nxdomain(h) |
| + } |
| + return pointingAt(h) |
| + }, asked), |
| + ResolveFresh: fresh.Resolve, |
| + ResolveUpgrade: fresh.ResolveUpgrade, |
| + FreshForget: fresh.Forget, |
| + FreshStrike: fresh.Strike, |
| + FreshRetain: fresh.Retain, |
| + Now: func() time.Time { return time.Unix(5000, 0) }, |
| + }, w |
| +} |
| + |
| +// INVARIANT GUARD (Astra R3 P1 on #724, and P1 on 259abef0): a published |
| +// name under a delegation deeper than the top-down walk follows stays |
| +// published: its upgrade look asks the nearest zones, climbing past a |
| +// label that is no zone (deepGapName) as main did. The same name as a NEW |
| +// candidate never takes that look: nothing below the registrable domain |
| +// reaches the cache. |
| +func TestStampHealthDeepDelegation(t *testing.T) { |
| + for _, name := range []string{deepName, deepGapName} { |
| + t.Run("published "+name, func(t *testing.T) { |
| + asked := map[string]int{} |
| + cfg, _ := deepCfg(t, name, asked) |
| + reg := regWithAlias(t, name) |
| + stampAlias(t, reg, name, "pointing") |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := aliasStatus(t, reg, name); got != "pointing" { |
| + t.Fatalf("published alias = %q, want pointing", got) |
| + } |
| + }) |
| + t.Run("new "+name, func(t *testing.T) { |
| + asked := map[string]int{} |
| + cfg, w := deepCfg(t, name, asked) |
| + reg := regWithAlias(t, name) |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + noCachedBelow(t, w, name, "example.com") |
| + if asked[name] != 0 { |
| + t.Fatalf("cached resolver asked about %s on the first failure", name) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// worldCfg is production wiring over w's resolver, with a cached resolver |
| +// that says NXDOMAIN for name and counts its queries in asked. |
| +func worldCfg(w *world, name string, asked map[string]int, edges ...string) (domains.Config, *domains.FreshResolver) { |
| + fresh := w.resolver(clock()) |
| + return domains.Config{ |
| + AppsDomain: "oncarlos.test", |
| + EdgeIPs: func() []string { return append([]string{edgeIP}, edges...) }, |
| + Resolve: counted(func(h string) ([]string, error) { |
| + if h == name { |
| + return nxdomain(h) |
| + } |
| + return pointingAt(h) |
| + }, asked), |
| + ResolveFresh: fresh.Resolve, |
| + ResolveUpgrade: fresh.ResolveUpgrade, |
| + FreshForget: fresh.Forget, |
| + FreshStrike: fresh.Strike, |
| + FreshRetain: fresh.Retain, |
| + Now: func() time.Time { return time.Unix(5000, 0) }, |
| + }, fresh |
| +} |
| + |
| +// INVARIANT GUARD (item 1 of the last round on #724): an authoritative |
| +// NODATA never sends a new name to the cache. A name with only an AAAA |
| +// record pointing at an IPv6 edge is "pointing" from the same server's AAAA |
| +// answer; a name that exists with no address record (a TXT there before |
| +// the CNAME, an _acme-challenge child) is stamped "". Zero cached queries |
| +// for the name either way: the cache would keep a per-type negative. |
| +func TestStampHealthNoDataNeverAsksTheCache(t *testing.T) { |
| + const edge6 = "2001:db8::7" |
| + for name, tc := range map[string]struct { |
| + aaaa func(dnsmessage.Question, *dnsmessage.Message) bool |
| + want string |
| + }{ |
| + "AAAA only, pointing at an IPv6 edge": {authoritative(aaaaRecord("shop.example.com.", edge6)), "pointing"}, |
| + "AAAA only, elsewhere": {authoritative(aaaaRecord("shop.example.com.", "2001:db8::99")), "elsewhere"}, |
| + "TXT only": {nodata("example.com"), ""}, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + w := oneZone(startAuthority(t, "example.com", byType(nodata("example.com"), tc.aaaa))) |
| + asked := map[string]int{} |
| + cfg, _ := worldCfg(w, "shop.example.com", asked, edge6) |
| + reg := regWithAlias(t, "shop.example.com") |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if a := aliasRow(t, reg, "shop.example.com"); a.DNSStatus != tc.want || a.DNSCheckedAt == 0 { |
| + t.Fatalf("alias stamp = %q at %d, want %q stamped this pass", a.DNSStatus, a.DNSCheckedAt, tc.want) |
| + } |
| + if asked["shop.example.com"] != 0 { |
| + t.Fatalf("cached resolver asked about shop.example.com %d times, want 0", asked["shop.example.com"]) |
| + } |
| + noCachedBelow(t, w, "shop.example.com", "example.com") |
| + }) |
| + } |
| +} |
| + |
| +// INVARIANT GUARD (Astra P1 of the last round on #724): example.com's only |
| +// nameserver host is eu.example.com, on the path of shop.eu.example.com. |
| +// Published, the name stays "pointing" while the cache says NXDOMAIN: its |
| +// upgrade look may ask the cache for that host. As a NEW candidate the |
| +// same name still sends no cached query below the registrable domain. |
| +func TestStampHealthOnPathOnlyNameserver(t *testing.T) { |
| + const name = "shop.eu.example.com" |
| + t.Run("published", func(t *testing.T) { |
| + cfg, _ := worldCfg(onPathWorld(t), name, map[string]int{}) |
| + reg := regWithAlias(t, name) |
| + stampAlias(t, reg, name, "pointing") |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got := aliasStatus(t, reg, name); got != "pointing" { |
| + t.Fatalf("published alias = %q, want pointing", got) |
| + } |
| + }) |
| + t.Run("new", func(t *testing.T) { |
| + w := onPathWorld(t) |
| + asked := map[string]int{} |
| + cfg, _ := worldCfg(w, name, asked) |
| + reg := regWithAlias(t, name) |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + noCachedBelow(t, w, name, "example.com") |
| + if asked[name] != 0 { |
| + t.Fatalf("cached resolver asked about %s %d times, want 0", name, asked[name]) |
| + } |
| + }) |
| +} |
| + |
| +// INVARIANT GUARD (strike map overflow, last round on #724): a new name's |
| +// first fresh failure is held; then the two-strike map overflows with |
| +// other names' failures; the name's second failure, on the next pass, |
| +// still takes the cached look instead of being held again. |
| +func TestStampHealthStrikeSurvivesAFullMap(t *testing.T) { |
| + w := oneZone(startAuthority(t, "example.com", nil)) |
| + asked := map[string]int{} |
| + cfg, fresh := worldCfg(w, "shop.example.com", asked) |
| + reg := regWithAlias(t, "shop.example.com") |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if asked["shop.example.com"] != 0 || aliasRow(t, reg, "shop.example.com").DNSCheckedAt != 0 { |
| + t.Fatal("pass A: the first fresh failure was not held") |
| + } |
| + for i := 0; i < 2*domains.FreshMaxBackoff; i++ { |
| + fresh.Strike(fmt.Sprintf("n%d.example.net", i)) |
| + } |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if asked["shop.example.com"] != 1 || aliasRow(t, reg, "shop.example.com").DNSCheckedAt == 0 { |
| + t.Fatalf("pass B: cached asked %d times, want 1: the pending strike was forgotten and the name held again", asked["shop.example.com"]) |
| + } |
| +} |
| + |
| +// Fable P3 of the last round: a hostname carried by two rows (a route and |
| +// an alias) is decided once per pass. Decided twice, the second row's |
| +// fresh failure would be the second strike inside the same pass and take |
| +// the cached look the first had just held. |
| +func TestStampHealthDecidesAHostOncePerPass(t *testing.T) { |
| + const name = "shop.example.com" |
| + fa := startAuthority(t, "example.com", nil) |
| + w := oneZone(fa) |
| + asked := map[string]int{} |
| + cfg, _ := worldCfg(w, name, asked) |
| + reg := regWith(t, |
| + registry.Route{Host: "app.acct.oncarlos.test", Kind: "service", Addr: "10.0.0.1:1", Status: "ready"}, |
| + registry.Route{Host: name, Kind: "service", Addr: "10.0.0.1:2", Status: "ready"}, |
| + ) |
| + if err := reg.UpsertAlias(registry.RouteAlias{Alias: name, Host: "app.acct.oncarlos.test", Account: "acct", App: "app"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if asked[name] != 0 { |
| + t.Fatalf("pass A: cached asked about %s %d times, want 0 (one held first strike)", name, asked[name]) |
| + } |
| + if rt, a := mustGet(t, reg, name), aliasRow(t, reg, name); rt.DNSCheckedAt != 0 || a.DNSCheckedAt != 0 { |
| + t.Fatalf("pass A: route checked at %d, alias at %d; want both held", rt.DNSCheckedAt, a.DNSCheckedAt) |
| + } |
| + sent := fa.queries.Load() |
| + // Pass B: the second strike. One fresh look, one cached look, and the |
| + // verdict on both rows. |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if fa.queries.Load() == sent || asked[name] != 1 { |
| + t.Fatalf("pass B: %d more fresh queries and %d cached; want a fresh retry and exactly one cached look", fa.queries.Load()-sent, asked[name]) |
| + } |
| + if rt, a := mustGet(t, reg, name), aliasRow(t, reg, name); rt.DNSCheckedAt == 0 || a.DNSCheckedAt == 0 { |
| + t.Fatalf("pass B: route checked at %d, alias at %d; want both stamped", rt.DNSCheckedAt, a.DNSCheckedAt) |
| + } |
| +} |
| + |
| +// Fable R3 P2-2: never-checked names get the fresh budget before standing |
| +// non-pointing ones, and a lookup answered from the backoff costs none. |
| +func TestStampHealthFreshBudgetOrder(t *testing.T) { |
| + defer domains.SetFreshPassMax(1)() |
| + t.Run("never checked first", func(t *testing.T) { |
| + for trial := 0; trial < 10; trial++ { |
| + reg := regWithAlias(t, "old.example.com") |
| + if err := reg.SetAliasDNSStatus("old.example.com", "elsewhere", 100); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.UpsertAlias(registry.RouteAlias{Alias: "new.example.com", Host: "app.acct.oncarlos.test", Account: "acct", App: "app"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + var calls []string |
| + cfg := freshCfg(pointingAt, nxdomain, &calls) |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(calls) != 1 || calls[0] != "new.example.com" { |
| + t.Fatalf("fresh lookups = %v, want [new.example.com]", calls) |
| + } |
| + } |
| + }) |
| + // Distinct from never-checked-first: both names have been checked, and |
| + // the one checked longest ago gets the budget. |
| + t.Run("oldest check first", func(t *testing.T) { |
| + for trial := 0; trial < 10; trial++ { |
| + reg := regWithAlias(t, "recent.example.com") |
| + if err := reg.UpsertAlias(registry.RouteAlias{Alias: "stale.example.com", Host: "app.acct.oncarlos.test", Account: "acct", App: "app"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for alias, at := range map[string]int64{"recent.example.com": 300, "stale.example.com": 200} { |
| + if err := reg.SetAliasDNSStatus(alias, "elsewhere", at); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var calls []string |
| + cfg := freshCfg(pointingAt, nxdomain, &calls) |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(calls) != 1 || calls[0] != "stale.example.com" { |
| + t.Fatalf("fresh lookups = %v, want [stale.example.com]", calls) |
| + } |
| + } |
| + }) |
| + t.Run("backoff hits are free", func(t *testing.T) { |
| + reg := regWithAlias(t, "a.example.com") |
| + if err := reg.UpsertAlias(registry.RouteAlias{Alias: "b.example.com", Host: "app.acct.oncarlos.test", Account: "acct", App: "app"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + for alias, at := range map[string]int64{"a.example.com": 100, "b.example.com": 200} { |
| + if err := reg.SetAliasDNSStatus(alias, "elsewhere", at); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var calls []string |
| + cfg := freshCfg(pointingAt, func(h string) ([]string, error) { |
| + if h == "a.example.com" { |
| + return nil, fmt.Errorf("%w", domains.ErrFreshBackingOff) |
| + } |
| + return nxdomain(h) |
| + }, &calls) |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(calls) != 2 { |
| + t.Fatalf("fresh lookups = %v, want both: the backoff hit cost nothing", calls) |
| + } |
| + }) |
| +} |
| + |
| +// Fable R3 P2-3: past the budget, a published name keeps its cached |
| +// verdict (no upgrade look), by count and by time. |
| +func TestStampHealthPublishedNamePastTheBudget(t *testing.T) { |
| + setup := func(t *testing.T) (*registry.Registry, domains.Config, *[]string) { |
| + reg := regWithAlias(t, "a.example.com") |
| + if err := reg.UpsertAlias(registry.RouteAlias{Alias: "b.example.com", Host: "app.acct.oncarlos.test", Account: "acct", App: "app"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + stampAlias(t, reg, "a.example.com", "pointing") |
| + stampAlias(t, reg, "b.example.com", "pointing") |
| + var calls []string |
| + cfg := freshCfg(func(h string) ([]string, error) { |
| + if h == "app.acct.oncarlos.test" { |
| + return pointingAt(h) |
| + } |
| + return nxdomain(h) |
| + }, pointingAt, &calls) |
| + return reg, cfg, &calls |
| + } |
| + t.Run("count", func(t *testing.T) { |
| + defer domains.SetFreshPassMax(1)() |
| + reg, cfg, calls := setup(t) |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(*calls) != 1 { |
| + t.Fatalf("fresh lookups = %v, want 1", *calls) |
| + } |
| + other := "a.example.com" |
| + if (*calls)[0] == other { |
| + other = "b.example.com" |
| + } |
| + if aliasStatus(t, reg, (*calls)[0]) != "pointing" || aliasStatus(t, reg, other) != "" { |
| + t.Fatalf("looked-at name raised and the other on its cached \"\" expected") |
| + } |
| + }) |
| + t.Run("time", func(t *testing.T) { |
| + defer domains.SetFreshPassTime(0)() |
| + reg, cfg, calls := setup(t) |
| + 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 with no time budget", *calls) |
| + } |
| + if aliasStatus(t, reg, "a.example.com") != "" || aliasStatus(t, reg, "b.example.com") != "" { |
| + t.Fatal("past the time budget a published name keeps its cached verdict") |
| + } |
| + }) |
| +} |
| + |
| +// INVARIANT GUARD (Astra P1 on 259abef0): one server holds example.com and |
| +// the delegated eu.example.com, and shop.eu.example.com has only a TXT |
| +// record. The server answers from the child, under the child's SOA; the |
| +// child is verified and asked, and the name is stamped "" on the first |
| +// pass. Across two passes the cache hears nothing about the name: read as |
| +// a failure instead, the second pass would take the cached look and plant |
| +// the negative entry #724 is about. |
| +func TestStampHealthCoHostedChildZoneNeverAsksTheCache(t *testing.T) { |
| + const name = "shop.eu.example.com" |
| + w := oneZone(startAuthority(t, "", cohost(nodata("eu.example.com"), "example.com", "eu.example.com"))) |
| + asked := map[string]int{} |
| + cfg, _ := worldCfg(w, name, asked) |
| + reg := regWithAlias(t, name) |
| + for pass := 1; pass <= 2; pass++ { |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if a := aliasRow(t, reg, name); a.DNSStatus != "" || a.DNSCheckedAt == 0 { |
| + t.Fatalf("pass %d: alias stamp = %q at %d, want \"\" stamped", pass, a.DNSStatus, a.DNSCheckedAt) |
| + } |
| + if asked[name] != 0 { |
| + t.Fatalf("pass %d: cached resolver asked about %s %d times, want 0", pass, name, asked[name]) |
| + } |
| + noCachedBelow(t, w, name, "example.com") |
| + } |
| +} |
| + |
| +// INVARIANT GUARD (Astra P2 on 259abef0): names that failed once and were |
| +// then removed do not keep their places in the strike map. Here the map is |
| +// full of such pending strikes; the pass hands the resolver its hostnames, |
| +// they are dropped, and a new name's first failure is held as usual. Left |
| +// there, they would make it count as the second strike and take the cached |
| +// look at once. |
| +func TestStampHealthRemovedNamesGiveTheirStrikesBack(t *testing.T) { |
| + const name = "shop.example.com" |
| + w := oneZone(startAuthority(t, "example.com", nil)) |
| + asked := map[string]int{} |
| + cfg, fresh := worldCfg(w, name, asked) |
| + reg := regWithAlias(t, name) |
| + for i := 0; i < domains.FreshMaxBackoff; i++ { |
| + fresh.Strike(fmt.Sprintf("gone%d.example.net", i)) |
| + } |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if asked[name] != 0 || aliasRow(t, reg, name).DNSCheckedAt != 0 { |
| + t.Fatalf("pass A: cached asked %d times; want the first failure held, the removed names' strikes reclaimed", asked[name]) |
| + } |
| + if got := domains.FreshStrikeState(fresh, "gone7.example.net"); got != 0 { |
| + t.Fatalf("removed name's strike state = %d, want 0", got) |
| + } |
| + // The name is still carried, so its pending strike survives the next |
| + // pass's Retain: the second failure takes the cached look. |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if asked[name] != 1 { |
| + t.Fatalf("pass B: cached asked %d times, want 1 (second strike)", asked[name]) |
| + } |
| +} |
| + |
| +// twoRows is a registry carrying name as both a route and an alias. |
| +func twoRows(t *testing.T, name 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"}, |
| + registry.Route{Host: name, Kind: "service", Addr: "10.0.0.1:2", Status: "ready"}, |
| + ) |
| + if err := reg.UpsertAlias(registry.RouteAlias{Alias: name, Host: "app.acct.oncarlos.test", Account: "acct", App: "app"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + return reg |
| +} |
| + |
| +// Astra P3 on 259abef0: a hostname with one row "pointing" and one not is |
| +// PUBLISHED, whichever row comes first. It is decided once, by the cached |
| +// look and the upgrade look, never fresh-first; with the cache stale and |
| +// the upgrade succeeding, both rows end "pointing". |
| +func TestStampHealthMixedRowsArePublished(t *testing.T) { |
| + const name = "shop.example.com" |
| + for _, pointing := range []string{"route", "alias"} { |
| + t.Run(pointing+" row pointing", func(t *testing.T) { |
| + reg := twoRows(t, name) |
| + var err error |
| + if pointing == "route" { |
| + err = reg.SetDNSStatus(name, "pointing", 4000) |
| + } else { |
| + err = reg.SetAliasDNSStatus(name, "pointing", 4000) |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + asked := map[string]int{} |
| + var firsts, upgrades []string |
| + cfg := freshCfg(counted(func(h string) ([]string, error) { |
| + if h == name { |
| + return nxdomain(h) |
| + } |
| + return pointingAt(h) |
| + }, asked), nxdomain, &firsts) |
| + cfg.ResolveUpgrade = func(h string) ([]string, error) { |
| + upgrades = append(upgrades, h) |
| + return pointingAt(h) |
| + } |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(firsts) != 0 || len(upgrades) != 1 || asked[name] != 1 { |
| + t.Fatalf("fresh-first looks %v, upgrade looks %v, cached looks %d; want none, one and one", firsts, upgrades, asked[name]) |
| + } |
| + if rt, a := mustGet(t, reg, name), aliasRow(t, reg, name); rt.DNSStatus != "pointing" || a.DNSStatus != "pointing" { |
| + t.Fatalf("route %q, alias %q; want both pointing", rt.DNSStatus, a.DNSStatus) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// And its place in the fresh budget is its least recently checked row's, |
| +// whichever row that is: checked at 100 and 300, it goes before a name |
| +// checked at 200. |
| +func TestStampHealthDuplicateRowsTakeTheOldestCheck(t *testing.T) { |
| + defer domains.SetFreshPassMax(1)() |
| + const name = "shop.example.com" |
| + for _, oldest := range []string{"route", "alias"} { |
| + t.Run(oldest+" row oldest", func(t *testing.T) { |
| + for trial := 0; trial < 10; trial++ { |
| + reg := twoRows(t, name) |
| + routeAt, aliasAt := int64(100), int64(300) |
| + if oldest == "alias" { |
| + routeAt, aliasAt = 300, 100 |
| + } |
| + if err := reg.SetDNSStatus(name, "elsewhere", routeAt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.SetAliasDNSStatus(name, "elsewhere", aliasAt); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.UpsertAlias(registry.RouteAlias{Alias: "other.example.com", Host: "app.acct.oncarlos.test", Account: "acct", App: "app"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.SetAliasDNSStatus("other.example.com", "elsewhere", 200); err != nil { |
| + t.Fatal(err) |
| + } |
| + var calls []string |
| + cfg := freshCfg(pointingAt, nxdomain, &calls) |
| + if err := domains.StampHealth(context.Background(), reg, cfg, nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(calls) != 1 || calls[0] != name { |
| + t.Fatalf("fresh lookups = %v, want [%s]: the duplicate's oldest check is 100", calls, name) |
| + } |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/domains/freshdns_test.go b/internal/domains/freshdns_test.go| index 7d6fd2cd9..8af6496f1 100644 |
| --- a/internal/domains/freshdns_test.go |
| +++ b/internal/domains/freshdns_test.go |
| @@ -3,6 +3,7 @@ package domains_test |
| import ( |
| "context" |
| "errors" |
| + "fmt" |
| "net" |
| "net/netip" |
| "strings" |
| @@ -122,14 +123,54 @@ 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 |
| + cached []string // "NS name" or "HOST name", every cached query in order |
| +} |
| + |
| +// note records a cached-resolver query of kind ("NS" or "HOST") for name. |
| +func (w *world) note(kind, name string) { |
| + w.mu.Lock() |
| + w.cached = append(w.cached, kind+" "+strings.TrimSuffix(name, ".")) |
| + w.mu.Unlock() |
| +} |
| + |
| +// cachedFor counts the cached-resolver queries, of any kind, for name. |
| +func (w *world) cachedFor(name string) int { |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + n := 0 |
| + for _, c := range w.cached { |
| + if c[strings.Index(c, " ")+1:] == name { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +// noCachedBelow is the #724 guard: the cache heard nothing about name or |
| +// any label between it and registrable, and no NS query went to anything |
| +// but registrable itself. |
| +func noCachedBelow(t *testing.T, w *world, name, registrable string) { |
| + t.Helper() |
| + for l := name; l != registrable && strings.Contains(l, "."); l = l[strings.Index(l, ".")+1:] { |
| + if n := w.cachedFor(l); n != 0 { |
| + t.Fatalf("cached resolver asked about %s %d times: %v", l, n, w.cached) |
| + } |
| + } |
| + w.mu.Lock() |
| + defer w.mu.Unlock() |
| + for _, c := range w.cached { |
| + if strings.HasPrefix(c, "NS ") && c != "NS "+registrable { |
| + t.Fatalf("cached NS query other than for %s: %v", registrable, w.cached) |
| + } |
| + } |
| } |
| func (w *world) resolver(now *time.Time) *domains.FreshResolver { |
| return &domains.FreshResolver{ |
| LookupNS: func(_ context.Context, name string) ([]*net.NS, error) { |
| + w.note("NS", name) |
| hs, ok := w.ns[name] |
| if !ok { |
| return nil, errNotFound |
| @@ -141,17 +182,12 @@ func (w *world) resolver(now *time.Time) *domains.FreshResolver { |
| return out, nil |
| }, |
| LookupHost: func(_ context.Context, host string) ([]string, error) { |
| + w.note("HOST", host) |
| 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) |
| @@ -185,10 +221,12 @@ 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") |
| + w := oneZone(fa) |
| + 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) |
| } |
| + noCachedBelow(t, w, "shop.example.com", "example.com") |
| if got := fa.asked.Load(); got != "shop.example.com." { |
| t.Fatalf("authority asked for %v, want shop.example.com.", got) |
| } |
| @@ -210,11 +248,15 @@ func TestFreshResolverReportsAuthoritativeNXDOMAIN(t *testing.T) { |
| r.RCode = dnsmessage.RCodeNameError |
| return true |
| }) |
| - _, err := oneZone(fa).resolver(clock()).Resolve("shop.example.com") |
| + w := oneZone(fa) |
| + _, err := w.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) |
| } |
| + // #724: the record does not exist yet, and nothing of ours asked the |
| + // cache about it. |
| + noCachedBelow(t, w, "shop.example.com", "example.com") |
| } |
| func TestFreshResolverIgnoresNonAuthoritativeAnswers(t *testing.T) { |
| @@ -304,32 +346,6 @@ func TestFreshResolverMovesPastASilentServer(t *testing.T) { |
| } |
| } |
| -// 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{ |
| @@ -392,8 +408,8 @@ func TestFreshResolverBacksOffAfterAFailure(t *testing.T) { |
| } |
| 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). |
| + // The registrable domain has no NS set: an error. Only the registrable |
| + // domain is asked for one; never the TLD, never a label below. |
| var asked []string |
| r := &domains.FreshResolver{ |
| LookupNS: func(_ context.Context, name string) ([]*net.NS, error) { |
| @@ -409,10 +425,8 @@ func TestFreshResolverStopsAtTheTopLevel(t *testing.T) { |
| 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) |
| - } |
| + if len(asked) != 1 || asked[0] != "nowhere.org" { |
| + t.Fatalf("asked for NS sets %v, want only [nowhere.org]", asked) |
| } |
| } |
| @@ -433,98 +447,1211 @@ func TestFreshResolverSkipsSpecialUseNames(t *testing.T) { |
| } |
| } |
| -// 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 |
| +// Astra R2 P2-2: an in-zone CNAME target the verified zone gives no |
| +// address for 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.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 |
| +} |
| + |
| +// The custom domain is its registrable domain, a zone apex with its own A |
| +// records: the walk starts and ends there. |
| +func TestFreshResolverResolvesAnApex(t *testing.T) { |
| + fa := startAuthority(t, "example.com", authoritative(aRecord("example.com.", edgeIP))) |
| + w := oneZone(fa) |
| + ips, err := w.resolver(clock()).Resolve("example.com") |
| + if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| + t.Fatalf("Resolve = %v, %v; want [%s]", ips, err, edgeIP) |
| + } |
| + noCachedBelow(t, w, "example.com", "example.com") |
| +} |
| + |
| +func nxdomainAnswer(_ dnsmessage.Question, r *dnsmessage.Message) bool { |
| + r.Authoritative = true |
| + r.RCode = dnsmessage.RCodeNameError |
| + return true |
| +} |
| + |
| +// referral answers every non-SOA query as a parent that delegated child: |
| +// no authority, child's NS record (host ns.<child>) in the authority |
| +// section, and glue for it when glueIP is set. |
| +func referral(child, glueIP string) func(dnsmessage.Question, *dnsmessage.Message) bool { |
| + return func(_ dnsmessage.Question, r *dnsmessage.Message) bool { |
| + r.Authorities = []dnsmessage.Resource{{ |
| + Header: dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName(child + "."), Type: dnsmessage.TypeNS, Class: dnsmessage.ClassINET, TTL: 300}, |
| + Body: &dnsmessage.NSResource{NS: dnsmessage.MustNewName("ns." + child + ".")}, |
| + }} |
| + if glueIP != "" { |
| + r.Additionals = []dnsmessage.Resource{aRecord("ns."+child+".", glueIP)} |
| + } |
| return true |
| - }) |
| + } |
| +} |
| + |
| +func TestRegistrableDomain(t *testing.T) { |
| + for name, want := range map[string]string{ |
| + "example.com": "example.com", |
| + "shop.example.com": "example.com", |
| + "shop.eu.example.com": "example.com", |
| + "shop.co.uk": "shop.co.uk", |
| + "shop.example.co.uk": "example.co.uk", |
| + "shop.api.eu.github.io": "github.io", // private PSL rules climbed past |
| + "shop.api.missing.eu.compute.amazonaws.com": "amazonaws.com", |
| + "shop.example.foo.ck": "example.foo.ck", // ICANN wildcard *.ck |
| + "shop.example.test": "example.test", // unlisted TLD |
| + "co.uk": "", |
| + } { |
| + got, ok := domains.RegistrableDomain(name) |
| + if want == "" && ok || want != "" && got != want { |
| + t.Errorf("RegistrableDomain(%s) = %q, %v; want %q", name, got, ok, want) |
| + } |
| + } |
| +} |
| + |
| +// #724 / Astra R1 P2-1: a nonexistent intermediate label (eu.example.com) |
| +// is primed just like the name, and RFC 8020 NXDOMAIN cuts deny every |
| +// descendant. The registrable domain answers for the whole path, so the |
| +// cache hears about neither. |
| +func TestFreshResolverNestedNameWithAMissingIntermediate(t *testing.T) { |
| + cases := map[string]struct { |
| + answer func(dnsmessage.Question, *dnsmessage.Message) bool |
| + found bool |
| + }{ |
| + "record absent": {nxdomainAnswer, false}, |
| + "record present": {authoritative(cnameRecord("shop.eu.example.com.", "edge.oncarlos.test.")), true}, |
| + } |
| + for name, tc := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + w := oneZone(startAuthority(t, "example.com", tc.answer)) |
| + ips, err := w.resolver(clock()).Resolve("shop.eu.example.com") |
| + if tc.found && (err != nil || len(ips) != 1 || ips[0] != edgeIP) { |
| + t.Fatalf("Resolve = %v, %v; want [%s]", ips, err, edgeIP) |
| + } |
| + if !tc.found && !isNotFoundErr(err) { |
| + t.Fatalf("Resolve error = %v, want the authoritative not-found", err) |
| + } |
| + noCachedBelow(t, w, "shop.eu.example.com", "example.com") |
| + }) |
| + } |
| +} |
| + |
| +// Astra R2 P1-2: public-suffix entries outside the ICANN section, and |
| +// wildcard rules, do not prove the label below them exists. The walk |
| +// starts at the ICANN registrable domain, and the absent labels between |
| +// it and the name never reach the cache. |
| +func TestFreshResolverPrivateAndWildcardSuffixes(t *testing.T) { |
| + for name, reg := range map[string]string{ |
| + "shop.api.eu.github.io": "github.io", |
| + "shop.api.missing.eu.compute.amazonaws.com": "amazonaws.com", |
| + "shop.example.foo.ck": "example.foo.ck", |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + fa := startAuthority(t, reg, nxdomainAnswer) |
| + w := &world{ |
| + ns: map[string][]string{reg: {"ns1." + reg + "."}}, |
| + hosts: map[string][]string{"ns1." + reg: {"192.0.2.53"}}, |
| + routes: map[string]*fakeAuthority{"192.0.2.53:53": fa}, |
| + } |
| + if _, err := w.resolver(clock()).Resolve(name); !isNotFoundErr(err) { |
| + t.Fatalf("Resolve error = %v, want the authoritative not-found", err) |
| + } |
| + noCachedBelow(t, w, name, reg) |
| + }) |
| + } |
| +} |
| + |
| +// shop.co.uk is its own registrable domain: it is asked directly, and |
| +// co.uk never is. |
| +func TestFreshResolverNameUnderAnICANNSuffix(t *testing.T) { |
| + fa := startAuthority(t, "shop.co.uk", authoritative(aRecord("shop.co.uk.", edgeIP))) |
| w := &world{ |
| + ns: map[string][]string{"shop.co.uk": {"ns.provider.net."}}, |
| + hosts: map[string][]string{"ns.provider.net": {"192.0.2.61"}}, |
| + routes: map[string]*fakeAuthority{"192.0.2.61:53": fa}, |
| + } |
| + ips, err := w.resolver(clock()).Resolve("shop.co.uk") |
| + if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| + t.Fatalf("Resolve = %v, %v; want [%s]", ips, err, edgeIP) |
| + } |
| + if w.cachedFor("co.uk") != 0 { |
| + t.Fatalf("asked the cache about co.uk: %v", w.cached) |
| + } |
| +} |
| + |
| +// eu.example.com is a delegated child zone: example.com refers down, the |
| +// child is verified and answers. Its nameserver comes from glue when it is |
| +// inside the child (the cache would be asked about a label below the |
| +// registrable domain otherwise) and from the cache when it is not. |
| +func TestFreshResolverFollowsAReferralToTheChildZone(t *testing.T) { |
| + for _, tc := range []struct { |
| + name, nsHost, glue string |
| + }{ |
| + {"in-zone nameserver, glue", "ns.eu.example.com", "192.0.2.40"}, |
| + {"out-of-zone nameserver, cache", "ns.provider.net", ""}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + child := startAuthority(t, "eu.example.com", authoritative(aRecord("shop.eu.example.com.", edgeIP))) |
| + parent := startAuthority(t, "example.com", func(_ dnsmessage.Question, r *dnsmessage.Message) bool { |
| + r.Authorities = []dnsmessage.Resource{{ |
| + Header: dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName("eu.example.com."), Type: dnsmessage.TypeNS, Class: dnsmessage.ClassINET, TTL: 300}, |
| + Body: &dnsmessage.NSResource{NS: dnsmessage.MustNewName(tc.nsHost + ".")}, |
| + }} |
| + if tc.glue != "" { |
| + r.Additionals = []dnsmessage.Resource{aRecord(tc.nsHost+".", tc.glue)} |
| + } |
| + return true |
| + }) |
| + w := oneZone(parent) |
| + w.hosts["ns.provider.net"] = []string{"192.0.2.40"} |
| + w.routes["192.0.2.40:53"] = child |
| + ips, err := w.resolver(clock()).Resolve("shop.eu.example.com") |
| + if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| + t.Fatalf("Resolve = %v, %v; want the child zone's answer", ips, err) |
| + } |
| + if child.queries.Load() < 2 { |
| + t.Fatalf("child got %d queries, want its SOA verified and then the A", child.queries.Load()) |
| + } |
| + noCachedBelow(t, w, "shop.eu.example.com", "example.com") |
| + }) |
| + } |
| +} |
| + |
| +// A referral is only followed DOWN the name's path. Sideways, upward, to |
| +// the same zone (a loop) or below the name: refused, and the server it |
| +// names is never dialled. |
| +func TestFreshResolverRefusesAReferralOffThePath(t *testing.T) { |
| + for _, child := range []string{"other.example.com", "com", "example.com", "x.shop.example.com", "example.net"} { |
| + t.Run(child, func(t *testing.T) { |
| + hostile := startAuthority(t, "", authoritative(aRecord("shop.example.com.", edgeIP))) |
| + w := oneZone(startAuthority(t, "example.com", referral(child, "192.0.2.66"))) |
| + w.hosts["ns."+child] = []string{"192.0.2.66"} |
| + w.routes["192.0.2.66:53"] = hostile |
| + if ips, err := w.resolver(clock()).Resolve("shop.example.com"); err == nil { |
| + t.Fatalf("Resolve = %v, want a refusal of the referral to %s", ips, child) |
| + } |
| + if hostile.queries.Load() != 0 { |
| + t.Fatalf("followed the referral to %s: dialled %v", child, w.dialed) |
| + } |
| + }) |
| + } |
| + // A child that refers back up to its parent: a loop, refused. |
| + t.Run("child refers back up", func(t *testing.T) { |
| + child := startAuthority(t, "eu.example.com", referral("example.com", "192.0.2.53")) |
| + w := oneZone(startAuthority(t, "example.com", referral("eu.example.com", "192.0.2.40"))) |
| + w.routes["192.0.2.40:53"] = child |
| + if ips, err := w.resolver(clock()).Resolve("shop.eu.example.com"); err == nil { |
| + t.Fatalf("Resolve = %v, want the loop refused", ips) |
| + } |
| + }) |
| +} |
| + |
| +// Delegation deeper than freshMaxZones referrals fails closed: the zone |
| +// past the bound is never asked. |
| +// deepName sits four delegations below example.com, past freshMaxZones. |
| +const deepName = "shop.a.b.c.d.example.com" |
| + |
| +// deepGapName sits in the same last zone under a label that is no zone |
| +// (eu): neither it nor its immediate parent has an NS set. |
| +const deepGapName = "shop.eu.a.b.c.d.example.com" |
| + |
| +// deepWorld is the healthy hierarchy example.com -> d -> c -> b -> |
| +// a.b.c.d.example.com, each its own zone, the last serving deepName and |
| +// deepGapName pointing here. The cache also knows the last zone's NS set, as a |
| +// resolver that has followed the delegation would. last is its server. |
| +func deepWorld(t *testing.T) (w *world, last *fakeAuthority) { |
| + t.Helper() |
| + zones := []string{"example.com", "d.example.com", "c.d.example.com", "b.c.d.example.com", "a.b.c.d.example.com"} |
| + 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"}, |
| + "example.com": {"ns1.example.com."}, |
| + "a.b.c.d.example.com": {"ns.provider.net."}, |
| }, |
| - routes: map[string]*fakeAuthority{"192.0.2.9:53": wrong, "192.0.2.53:53": right}, |
| + hosts: map[string][]string{"ns1.example.com": {"192.0.2.10"}, "ns.provider.net": {"192.0.2.14"}}, |
| + routes: map[string]*fakeAuthority{}, |
| + } |
| + for i, z := range zones { |
| + addr := fmt.Sprintf("192.0.2.%d", 10+i) |
| + var fa *fakeAuthority |
| + if i+1 < len(zones) { |
| + fa = startAuthority(t, z, referral(zones[i+1], fmt.Sprintf("192.0.2.%d", 11+i))) |
| + } else { |
| + fa = startAuthority(t, z, authoritative(aRecord(deepName+".", edgeIP), aRecord(deepGapName+".", edgeIP))) |
| + last = fa |
| + } |
| + w.routes[addr+":53"] = fa |
| + } |
| + return w, last |
| +} |
| + |
| +func TestFreshResolverBoundsTheReferrals(t *testing.T) { |
| + w, last := deepWorld(t) |
| + name := deepName |
| + if ips, err := w.resolver(clock()).Resolve(name); err == nil { |
| + t.Fatalf("Resolve = %v, want delegation past the bound refused", ips) |
| + } |
| + if last.queries.Load() != 0 { |
| + t.Fatal("asked the zone past the referral bound") |
| + } |
| + noCachedBelow(t, w, name, "example.com") |
| +} |
| + |
| +// Astra R3 P1 on #724: ResolveUpgrade, for a published name only, asks the |
| +// name's nearest zone, so a delegation deeper than the top-down walk |
| +// follows, which main reached, still resolves. |
| +func TestFreshResolverUpgradeReachesADeepDelegation(t *testing.T) { |
| + w, last := deepWorld(t) |
| + ips, err := w.resolver(clock()).ResolveUpgrade(deepName) |
| + if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| + t.Fatalf("ResolveUpgrade = %v, %v; want [%s] from the nearest zone", ips, err, edgeIP) |
| + } |
| + if last.queries.Load() == 0 { |
| + t.Fatal("the nearest zone was never asked") |
| + } |
| +} |
| + |
| +// nodata answers every non-SOA query as zone's server does for a name that |
| +// exists with no record of the type asked: authority, no answer, and |
| +// zone's SOA in the authority section. |
| +func nodata(zone string) func(dnsmessage.Question, *dnsmessage.Message) bool { |
| + return func(_ dnsmessage.Question, r *dnsmessage.Message) bool { |
| + r.Authoritative = true |
| + r.Authorities = []dnsmessage.Resource{soaRecord(zone)} |
| + return true |
| + } |
| +} |
| + |
| +// byType answers A queries with a and AAAA queries with aaaa. |
| +func byType(a, aaaa func(dnsmessage.Question, *dnsmessage.Message) bool) func(dnsmessage.Question, *dnsmessage.Message) bool { |
| + return func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| + if q.Type == dnsmessage.TypeAAAA { |
| + return aaaa(q, r) |
| + } |
| + return a(q, r) |
| + } |
| +} |
| + |
| +func aaaaRecord(name, ip string) dnsmessage.Resource { |
| + return dnsmessage.Resource{ |
| + Header: dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName(name), Type: dnsmessage.TypeAAAA, Class: dnsmessage.ClassINET, TTL: 300}, |
| + Body: &dnsmessage.AAAAResource{AAAA: netip.MustParseAddr(ip).As16()}, |
| } |
| +} |
| + |
| +// referralShaped is an authoritative reply with no answer and only NS |
| +// records in the authority section: empty, but no proof of NODATA. |
| +func referralShaped(_ dnsmessage.Question, r *dnsmessage.Message) bool { |
| + r.Authoritative = true |
| + r.Authorities = []dnsmessage.Resource{{ |
| + Header: dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName("example.com."), Type: dnsmessage.TypeNS, Class: dnsmessage.ClassINET, TTL: 300}, |
| + Body: &dnsmessage.NSResource{NS: dnsmessage.MustNewName("ns1.example.com.")}, |
| + }} |
| + return true |
| +} |
| + |
| +// Astra R3 P2-2 and item 1 of the last round: an authoritative "exists, no |
| +// address record" (NODATA for A, then for AAAA from the same server, each |
| +// carrying the zone's SOA) is not "no such name": it is errNoData. It does |
| +// not back off, and the cache hears nothing about the name. |
| +func TestFreshResolverTellsNoDataFromNXDOMAIN(t *testing.T) { |
| + fa := startAuthority(t, "example.com", nodata("example.com")) |
| + w := oneZone(fa) |
| + r := w.resolver(clock()) |
| + _, err := r.Resolve("shop.example.com") |
| + if err == nil || isNotFoundErr(err) || !errors.Is(err, domains.ErrFreshNoData) { |
| + t.Fatalf("Resolve error = %v, want errNoData", err) |
| + } |
| + if got := fa.queries.Load(); got != 3 { |
| + t.Fatalf("authority got %d queries, want 3: SOA, A, then AAAA from the same server", got) |
| + } |
| + noCachedBelow(t, w, "shop.example.com", "example.com") |
| + sent := fa.queries.Load() |
| + _, _ = r.Resolve("shop.example.com") |
| + if fa.queries.Load() == sent { |
| + t.Fatal("NODATA put the name into the failure backoff") |
| + } |
| +} |
| + |
| +// After a NODATA for A the same server's AAAA records are the answer. |
| +func TestFreshResolverReadsAAAAAfterNoData(t *testing.T) { |
| + const edge6 = "2001:db8::7" |
| + fa := startAuthority(t, "example.com", byType(nodata("example.com"), authoritative(aaaaRecord("shop.example.com.", edge6)))) |
| + w := oneZone(fa) |
| 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) |
| + if err != nil || len(ips) != 1 || ips[0] != edge6 { |
| + t.Fatalf("Resolve = %v, %v; want [%s]", ips, err, edge6) |
| } |
| + noCachedBelow(t, w, "shop.example.com", "example.com") |
| } |
| -// 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."}, |
| +// An empty authoritative reply is NODATA only with the verified zone's own |
| +// SOA in its authority section. Without it, for the A or the AAAA |
| +// question, the lookup is a failure: not errNoData, not "no such name", |
| +// and it backs off. |
| +func TestFreshResolverNoDataNeedsTheZonesSOA(t *testing.T) { |
| + good := nodata("example.com") |
| + bad := map[string]func(dnsmessage.Question, *dnsmessage.Message) bool{ |
| + "missing SOA": authoritative(), |
| + "wrong-owner SOA": nodata("example.net"), |
| + "SOA of a name below the zone": nodata("shop.example.com"), |
| + "referral-shaped authoritative": referralShaped, |
| + "SOA beside an unrelated answer": func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| + r.Authoritative = true |
| + r.Answers = []dnsmessage.Resource{aRecord("other.example.com.", edgeIP)} |
| + r.Authorities = []dnsmessage.Resource{soaRecord("example.com")} |
| + return true |
| }, |
| - hosts: map[string][]string{ |
| - "ns.oldprovider.net": {"192.0.2.9", "192.0.2.10"}, |
| - "ns1.example.com": {"192.0.2.53"}, |
| + } |
| + for name, reply := range bad { |
| + for q, answer := range map[string]func(dnsmessage.Question, *dnsmessage.Message) bool{ |
| + "A": byType(reply, good), |
| + "AAAA": byType(good, reply), |
| + } { |
| + t.Run(name+" for "+q, func(t *testing.T) { |
| + fa := startAuthority(t, "example.com", answer) |
| + w := oneZone(fa) |
| + r := w.resolver(clock()) |
| + ips, err := r.Resolve("shop.example.com") |
| + if err == nil || errors.Is(err, domains.ErrFreshNoData) || isNotFoundErr(err) { |
| + t.Fatalf("Resolve = %v, %v; want a fresh failure", ips, err) |
| + } |
| + sent := fa.queries.Load() |
| + if _, err := r.Resolve("shop.example.com"); !errors.Is(err, domains.ErrFreshBackingOff) || fa.queries.Load() != sent { |
| + t.Fatalf("second Resolve = %v after %d more queries, want the backoff", err, fa.queries.Load()-sent) |
| + } |
| + noCachedBelow(t, w, "shop.example.com", "example.com") |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// A truncated reply (TC bit) is a failure for that server, whatever it |
| +// carries: the next server's answer is the one used, and alone it is no |
| +// answer. |
| +func TestFreshResolverTruncatedReplyIsNotAnAnswer(t *testing.T) { |
| + truncated := func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| + r.Authoritative, r.Truncated = true, true |
| + r.Answers = []dnsmessage.Resource{aRecord(q.Name.String(), "198.51.100.9")} |
| + return true |
| + } |
| + t.Run("next server answers", func(t *testing.T) { |
| + tc := startAuthority(t, "example.com", truncated) |
| + 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": tc, "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 second server's [%s]", ips, err, edgeIP) |
| + } |
| + if tc.queries.Load() < 2 { |
| + t.Fatal("the truncating server was never asked for the A record") |
| + } |
| + }) |
| + t.Run("alone", func(t *testing.T) { |
| + w := oneZone(startAuthority(t, "example.com", truncated)) |
| + ips, err := w.resolver(clock()).Resolve("shop.example.com") |
| + if err == nil || isNotFoundErr(err) || errors.Is(err, domains.ErrFreshNoData) { |
| + t.Fatalf("Resolve = %v, %v; want a fresh failure", ips, err) |
| + } |
| + }) |
| +} |
| + |
| +// A referral whose authority section names two different NS owners is |
| +// refused, even when both lie on the name's path; neither is dialled. |
| +func TestFreshResolverRefusesAReferralNamingTwoZones(t *testing.T) { |
| + child := startAuthority(t, "", authoritative(aRecord("shop.b.a.example.com.", edgeIP))) |
| + parent := startAuthority(t, "example.com", func(_ dnsmessage.Question, r *dnsmessage.Message) bool { |
| + for _, owner := range []string{"a.example.com.", "b.a.example.com."} { |
| + r.Authorities = append(r.Authorities, dnsmessage.Resource{ |
| + Header: dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName(owner), Type: dnsmessage.TypeNS, Class: dnsmessage.ClassINET, TTL: 300}, |
| + Body: &dnsmessage.NSResource{NS: dnsmessage.MustNewName("ns.provider.net.")}, |
| + }) |
| + } |
| + return true |
| + }) |
| + w := oneZone(parent) |
| + w.hosts["ns.provider.net"] = []string{"192.0.2.40"} |
| + w.routes["192.0.2.40:53"] = child |
| + if ips, err := w.resolver(clock()).Resolve("shop.b.a.example.com"); err == nil { |
| + t.Fatalf("Resolve = %v, want the two-owner referral refused", ips) |
| + } |
| + if child.queries.Load() != 0 || w.cachedFor("ns.provider.net") != 0 { |
| + t.Fatalf("followed a referral naming two zones: dialled %v, cached %v", w.dialed, w.cached) |
| + } |
| +} |
| + |
| +// Fable R3 P2-5: at most freshMaxNSHosts of a zone's nameserver hosts are |
| +// looked up through the cache, however many it lists. |
| +func TestFreshResolverBoundsNameserverHostLookups(t *testing.T) { |
| + w := &world{ns: map[string][]string{"example.com": {}}, hosts: map[string][]string{}} |
| + for i := 0; i < 40; i++ { |
| + w.ns["example.com"] = append(w.ns["example.com"], fmt.Sprintf("ns%d.provider.net.", i)) |
| + } |
| + for name, resolve := range map[string]func(*domains.FreshResolver) func(string) ([]string, error){ |
| + "new name": func(r *domains.FreshResolver) func(string) ([]string, error) { return r.Resolve }, |
| + "published name": func(r *domains.FreshResolver) func(string) ([]string, error) { return r.ResolveUpgrade }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + w.cached = nil |
| + if _, err := resolve(w.resolver(clock()))("shop.example.com"); err == nil { |
| + t.Fatal("Resolve succeeded with no nameserver address") |
| + } |
| + hosts := 0 |
| + for _, c := range w.cached { |
| + if strings.HasPrefix(c, "HOST ") { |
| + hosts++ |
| + } |
| + } |
| + if hosts != domains.FreshMaxNSHosts { |
| + t.Fatalf("%d cached nameserver-host lookups, want %d: %v", hosts, domains.FreshMaxNSHosts, w.cached) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Fable P2 of the last round: ResolveUpgrade asks the nearest zone FIRST, |
| +// with the whole Timeout. Here the registrable domain's server is silent |
| +// and one attempt at it is all the Timeout there is: asked first, the |
| +// top-down walk would leave the nearest zone no time. |
| +func TestFreshResolverUpgradeAsksTheNearestZoneFirst(t *testing.T) { |
| + w, last := deepWorld(t) |
| + silent := startAuthority(t, "example.com", nil) |
| + w.routes["192.0.2.10:53"] = silent |
| + r := w.resolver(clock()) |
| + r.Timeout, r.AttemptTimeout = 400*time.Millisecond, 400*time.Millisecond |
| + ips, err := r.ResolveUpgrade(deepName) |
| + if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| + t.Fatalf("ResolveUpgrade = %v, %v; want [%s] from the nearest zone", ips, err, edgeIP) |
| + } |
| + if last.queries.Load() == 0 || silent.queries.Load() != 0 { |
| + t.Fatalf("nearest zone got %d queries and the registrable domain %d; want the nearest zone alone", last.queries.Load(), silent.queries.Load()) |
| + } |
| +} |
| + |
| +// The nearest-zone look leaves the registrable domain to the top-down walk |
| +// (asked once, not twice) and never asks about the TLD. |
| +func TestFreshResolverUpgradeNearestZones(t *testing.T) { |
| + for name, want := range map[string]string{ |
| + // Directly under the registrable domain: only the name itself is |
| + // tried as a nearest zone, then the walk. |
| + "shop.example.com": "NS shop.example.com,NS example.com,HOST ns1.example.com", |
| + // An apex: the walk alone. Not "NS com". |
| + "example.com": "NS example.com,HOST ns1.example.com", |
| + // Deeper: parent, name, then the walk. |
| + "shop.eu.example.com": "NS eu.example.com,NS shop.eu.example.com,NS example.com,HOST ns1.example.com", |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + w := oneZone(startAuthority(t, "example.com", authoritative(aRecord(name+".", edgeIP)))) |
| + ips, err := w.resolver(clock()).ResolveUpgrade(name) |
| + if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| + t.Fatalf("ResolveUpgrade = %v, %v; want [%s] from the top-down walk", ips, err, edgeIP) |
| + } |
| + if got := strings.Join(w.cached, ","); got != want { |
| + t.Fatalf("cached queries = %s, want %s", got, want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// onPathWorld is example.com served ONLY by eu.example.com, a host on the |
| +// path of shop.eu.example.com, which points here. |
| +func onPathWorld(t *testing.T) *world { |
| + t.Helper() |
| + fa := startAuthority(t, "example.com", authoritative(aRecord("shop.eu.example.com.", edgeIP))) |
| + return &world{ |
| + ns: map[string][]string{"example.com": {"eu.example.com."}}, |
| + hosts: map[string][]string{"eu.example.com": {"192.0.2.53"}}, |
| + routes: map[string]*fakeAuthority{"192.0.2.53:53": fa}, |
| + } |
| +} |
| + |
| +// Astra P1 of the last round: the on-path nameserver skip is for new names |
| +// only. A published name's look may ask the cache for any nameserver host, |
| +// at the registrable domain and on a referral (glue-less, in the child). |
| +func TestFreshResolverOnPathSkipIsForNewNamesOnly(t *testing.T) { |
| + t.Run("registrable NS set", func(t *testing.T) { |
| + w := onPathWorld(t) |
| + if ips, err := w.resolver(clock()).Resolve("shop.eu.example.com"); err == nil { |
| + t.Fatalf("Resolve = %v, want no server for a new name", ips) |
| + } |
| + noCachedBelow(t, w, "shop.eu.example.com", "example.com") |
| + ips, err := w.resolver(clock()).ResolveUpgrade("shop.eu.example.com") |
| + if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| + t.Fatalf("ResolveUpgrade = %v, %v; want [%s]", ips, err, edgeIP) |
| + } |
| + }) |
| + t.Run("referral without glue", func(t *testing.T) { |
| + w := oneZone(startAuthority(t, "example.com", referral("b.a.example.com", ""))) |
| + w.hosts["ns.b.a.example.com"] = []string{"192.0.2.40"} |
| + w.routes["192.0.2.40:53"] = startAuthority(t, "b.a.example.com", authoritative(aRecord("shop.b.a.example.com.", edgeIP))) |
| + ips, err := w.resolver(clock()).ResolveUpgrade("shop.b.a.example.com") |
| + if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| + t.Fatalf("ResolveUpgrade = %v, %v; want [%s]", ips, err, edgeIP) |
| + } |
| + }) |
| +} |
| + |
| +// The two-strike map never evicts a pending first strike. Full of them, a |
| +// new failure counts as the second strike and is not recorded. |
| +func TestFreshResolverStrikeMapFullOfPendingStrikes(t *testing.T) { |
| + r := &domains.FreshResolver{} |
| + if r.Strike("shop.example.com") { |
| + t.Fatal("first strike reported as the second") |
| + } |
| + for i := 0; i < 2*domains.FreshMaxBackoff; i++ { |
| + r.Strike(fmt.Sprintf("n%d.example.com", i)) |
| + } |
| + if got := domains.FreshStrikeState(r, "shop.example.com"); got != 1 { |
| + t.Fatalf("pending strike state = %d after the map overflowed, want 1 (kept)", got) |
| + } |
| + if !r.Strike("late.example.com") { |
| + t.Fatal("a new failure with the map full of pending strikes was held; want it to count as the second strike") |
| + } |
| + if got := domains.FreshStrikeState(r, "late.example.com"); got != 0 { |
| + t.Fatalf("late name recorded (%d) in a full map", got) |
| + } |
| + if !r.Strike("shop.example.com") { |
| + t.Fatal("the pending strike was forgotten: its second failure was held again") |
| + } |
| +} |
| + |
| +// Names that have taken their second strike are the ones that make room. |
| +func TestFreshResolverStrikeMapEvictsTakenStrikesFirst(t *testing.T) { |
| + r := &domains.FreshResolver{} |
| + for i := 0; i < domains.FreshMaxBackoff; i++ { |
| + r.Strike(fmt.Sprintf("n%d.example.com", i)) |
| + } |
| + for _, done := range []string{"n7.example.com", "n8.example.com"} { |
| + if !r.Strike(done) { |
| + t.Fatalf("%s: second strike not reported", done) |
| + } |
| + } |
| + for _, fresh := range []string{"x.example.com", "y.example.com"} { |
| + if r.Strike(fresh) { |
| + t.Fatalf("%s: held expected, a taken strike could make room", fresh) |
| + } |
| + if got := domains.FreshStrikeState(r, fresh); got != 1 { |
| + t.Fatalf("%s state = %d, want 1 (pending)", fresh, got) |
| + } |
| + } |
| + for i := 0; i < domains.FreshMaxBackoff; i++ { |
| + n := fmt.Sprintf("n%d.example.com", i) |
| + want := 1 |
| + if i == 7 || i == 8 { |
| + want = 0 |
| + } |
| + if got := domains.FreshStrikeState(r, n); got != want { |
| + t.Fatalf("%s state = %d, want %d: only the taken strikes are evicted", n, got, want) |
| + } |
| + } |
| + if !r.Strike("z.example.com") { |
| + t.Fatal("no taken strike left to evict: the new failure must count as the second strike") |
| + } |
| +} |
| + |
| +// Astra R3 P2-3 / Fable P3-4: a nameserver host that is the name or one of |
| +// its levels below the registrable domain (a stale NS entry) is never |
| +// looked up through the cache, at the registrable domain or on a referral. |
| +// Every cached query is listed. |
| +func TestFreshResolverNeverLooksUpAnOnPathNameserver(t *testing.T) { |
| + t.Run("registrable NS set", func(t *testing.T) { |
| + fa := startAuthority(t, "example.com", nxdomainAnswer) |
| + w := &world{ |
| + ns: map[string][]string{"example.com": {"ns.provider.net.", "eu.example.com.", "shop.eu.example.com."}}, |
| + hosts: map[string][]string{"ns.provider.net": {"192.0.2.53"}}, |
| + routes: map[string]*fakeAuthority{"192.0.2.53:53": fa}, |
| + } |
| + if _, err := w.resolver(clock()).Resolve("shop.eu.example.com"); !isNotFoundErr(err) { |
| + t.Fatalf("Resolve error = %v, want the authoritative not-found", err) |
| + } |
| + if got := strings.Join(w.cached, ","); got != "NS example.com,HOST ns.provider.net" { |
| + t.Fatalf("cached queries = %s, want only NS example.com and HOST ns.provider.net", got) |
| + } |
| + }) |
| + t.Run("referral NS set", func(t *testing.T) { |
| + child := startAuthority(t, "b.a.example.com", nxdomainAnswer) |
| + parent := startAuthority(t, "example.com", func(_ dnsmessage.Question, r *dnsmessage.Message) bool { |
| + for _, h := range []string{"a.example.com.", "ns.provider.net."} { |
| + r.Authorities = append(r.Authorities, dnsmessage.Resource{ |
| + Header: dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName("b.a.example.com."), Type: dnsmessage.TypeNS, Class: dnsmessage.ClassINET, TTL: 300}, |
| + Body: &dnsmessage.NSResource{NS: dnsmessage.MustNewName(h)}, |
| + }) |
| + } |
| + return true |
| + }) |
| + w := oneZone(parent) |
| + w.hosts["ns.provider.net"] = []string{"192.0.2.40"} |
| + w.routes["192.0.2.40:53"] = child |
| + if _, err := w.resolver(clock()).Resolve("shop.b.a.example.com"); !isNotFoundErr(err) { |
| + t.Fatalf("Resolve error = %v, want the child's not-found", err) |
| + } |
| + if got := strings.Join(w.cached, ","); got != "NS example.com,HOST ns1.example.com,HOST ns.provider.net" { |
| + t.Fatalf("cached queries = %s, want no lookup of a.example.com", got) |
| + } |
| + }) |
| +} |
| + |
| +// Astra R3 P2-4: Timeout bounds the whole lookup, not only each exchange. |
| +func TestFreshResolverTimeoutBoundsTheWholeLookup(t *testing.T) { |
| + t.Run("below one attempt", func(t *testing.T) { |
| + w := oneZone(startAuthority(t, "example.com", nil)) |
| + r := w.resolver(clock()) |
| + r.Timeout, r.AttemptTimeout = 150*time.Millisecond, time.Second |
| + start := time.Now() |
| + if _, err := r.Resolve("shop.example.com"); err == nil { |
| + t.Fatal("Resolve against a silent server succeeded") |
| + } |
| + if took := time.Since(start); took > 400*time.Millisecond { |
| + t.Fatalf("Resolve took %s with Timeout 150ms", took) |
| + } |
| + }) |
| + t.Run("timely exchanges, too many of them", func(t *testing.T) { |
| + // Each zone answers in 120 ms, inside AttemptTimeout; four zones |
| + // need 480 ms, past the 350 ms Timeout. |
| + name := "shop.b.c.d.example.com" |
| + zones := []string{"example.com", "d.example.com", "c.d.example.com", "b.c.d.example.com"} |
| + w := &world{ |
| + ns: map[string][]string{"example.com": {"ns1.example.com."}}, |
| + hosts: map[string][]string{"ns1.example.com": {"192.0.2.10"}}, |
| + routes: map[string]*fakeAuthority{}, |
| + } |
| + for i, z := range zones { |
| + var answer func(dnsmessage.Question, *dnsmessage.Message) bool |
| + if i+1 < len(zones) { |
| + answer = referral(zones[i+1], fmt.Sprintf("192.0.2.%d", 11+i)) |
| + } else { |
| + answer = authoritative(aRecord(name+".", edgeIP)) |
| + } |
| + slow := func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| + time.Sleep(120 * time.Millisecond) |
| + return answer(q, r) |
| + } |
| + w.routes[fmt.Sprintf("192.0.2.%d:53", 10+i)] = startAuthority(t, z, slow) |
| + } |
| + r := w.resolver(clock()) |
| + r.Timeout, r.AttemptTimeout = 350*time.Millisecond, 300*time.Millisecond |
| + start := time.Now() |
| + if ips, err := r.Resolve(name); err == nil { |
| + t.Fatalf("Resolve = %v, want the overall deadline to stop the walk", ips) |
| + } |
| + if took := time.Since(start); took > 600*time.Millisecond { |
| + t.Fatalf("Resolve took %s with Timeout 350ms", took) |
| + } |
| + }) |
| + t.Run("during cached discovery", func(t *testing.T) { |
| + r := &domains.FreshResolver{ |
| + LookupNS: func(ctx context.Context, _ string) ([]*net.NS, error) { |
| + select { |
| + case <-ctx.Done(): |
| + return nil, ctx.Err() |
| + case <-time.After(3 * time.Second): |
| + return []*net.NS{{Host: "ns1.example.com."}}, nil |
| + } |
| + }, |
| + LookupHost: func(context.Context, string) ([]string, error) { return nil, errNotFound }, |
| + Timeout: 150 * time.Millisecond, |
| + } |
| + start := time.Now() |
| + if _, err := r.Resolve("shop.example.com"); err == nil { |
| + t.Fatal("Resolve succeeded") |
| + } |
| + if took := time.Since(start); took > time.Second { |
| + t.Fatalf("Resolve took %s: the cached discovery ignored the deadline", took) |
| + } |
| + }) |
| +} |
| + |
| +// Astra R2 P2: every zone is verified before it is trusted, the |
| +// registrable domain's and a referred child's alike. A server for another |
| +// zone, or one whose SOA is owned by another name, offers an |
| +// authoritative-looking positive answer; it is reached, and refused. |
| +func TestFreshResolverVerifiesEveryZone(t *testing.T) { |
| + hostiles := map[string]func(t *testing.T) *fakeAuthority{ |
| + "wrong zone": func(t *testing.T) *fakeAuthority { |
| + return startAuthority(t, "oldprovider.net", authoritative(aRecord("shop.eu.example.com.", edgeIP))) |
| + }, |
| + "SOA owner mismatch": func(t *testing.T) *fakeAuthority { |
| + return startAuthority(t, "", func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| + r.Authoritative = true |
| + if q.Type == dnsmessage.TypeSOA { |
| + r.Answers = []dnsmessage.Resource{soaRecord("example.net")} |
| + return true |
| + } |
| + r.Answers = []dnsmessage.Resource{aRecord("shop.eu.example.com.", edgeIP)} |
| + return true |
| + }) |
| }, |
| - 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") |
| + for kind, mk := range hostiles { |
| + t.Run(kind+" at the registrable domain", func(t *testing.T) { |
| + hostile := mk(t) |
| + w := oneZone(hostile) |
| + if ips, err := w.resolver(clock()).Resolve("shop.eu.example.com"); err == nil { |
| + t.Fatalf("Resolve = %v, want the unverified answer refused", ips) |
| + } |
| + if hostile.queries.Load() == 0 { |
| + t.Fatal("the hostile server was never reached") |
| + } |
| + }) |
| + t.Run(kind+" at a referred child", func(t *testing.T) { |
| + hostile := mk(t) |
| + w := oneZone(startAuthority(t, "example.com", referral("eu.example.com", "192.0.2.40"))) |
| + w.routes["192.0.2.40:53"] = hostile |
| + if ips, err := w.resolver(clock()).Resolve("shop.eu.example.com"); err == nil { |
| + t.Fatalf("Resolve = %v, want the unverified answer refused", ips) |
| + } |
| + if hostile.queries.Load() == 0 { |
| + t.Fatal("the hostile server was never reached") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Glue is tenant input like any nameserver address: a non-public one is |
| +// never dialled. |
| +// A nameserver inside the referred child with no glue is not looked up |
| +// through the cache either (Fable R3 P2-3): the cache would be asked about |
| +// a name below the registrable domain. |
| +func TestFreshResolverNeverDialsNonPublicGlue(t *testing.T) { |
| + for name, glue := range map[string]string{"non-public glue": "10.0.0.5", "no glue": ""} { |
| + t.Run(name, func(t *testing.T) { |
| + w := oneZone(startAuthority(t, "example.com", referral("eu.example.com", glue))) |
| + w.hosts["ns.eu.example.com"] = []string{"192.0.2.40"} |
| + w.routes["192.0.2.40:53"] = startAuthority(t, "eu.example.com", authoritative(aRecord("shop.eu.example.com.", edgeIP))) |
| + if _, err := w.resolver(clock()).Resolve("shop.eu.example.com"); err == nil { |
| + t.Fatal("Resolve succeeded") |
| + } |
| + for _, d := range w.dialed { |
| + if d != "192.0.2.53:53" { |
| + t.Fatalf("dialled %v", w.dialed) |
| + } |
| + } |
| + if w.cachedFor("ns.eu.example.com") != 0 { |
| + t.Fatalf("looked up the in-child nameserver through the cache: %v", w.cached) |
| + } |
| + noCachedBelow(t, w, "shop.eu.example.com", "example.com") |
| + }) |
| + } |
| +} |
| + |
| +// The registrable domain's servers are silent: the lookup fails inside |
| +// Timeout and nothing below the registrable domain reaches the cache. |
| +func TestFreshResolverSilentRegistrableFailsInsideTimeout(t *testing.T) { |
| + w := oneZone(startAuthority(t, "example.com", nil)) |
| + w.hosts["ns1.example.com"] = []string{"192.0.2.53", "192.0.2.54"} |
| + w.routes["192.0.2.54:53"] = w.routes["192.0.2.53:53"] |
| + r := w.resolver(clock()) |
| + start := time.Now() |
| + if _, err := r.Resolve("shop.eu.example.com"); err == nil { |
| + t.Fatal("Resolve against silent servers succeeded") |
| + } |
| + if took := time.Since(start); took > r.Timeout+500*time.Millisecond { |
| + t.Fatalf("Resolve took %s, past Timeout %s", took, r.Timeout) |
| + } |
| + noCachedBelow(t, w, "shop.eu.example.com", "example.com") |
| +} |
| + |
| +// Forget ends a name's backoff: the next Resolve asks again. |
| +func TestFreshResolverForgetEndsTheBackoff(t *testing.T) { |
| + fa := startAuthority(t, "example.com", nil) |
| + r := oneZone(fa).resolver(clock()) |
| + if _, err := r.Resolve("shop.example.com"); err == nil { |
| + t.Fatal("Resolve against a dead server succeeded") |
| + } |
| + sent := fa.queries.Load() |
| + r.Forget("Shop.Example.com.") |
| + _, _ = r.Resolve("shop.example.com") |
| + if fa.queries.Load() == sent { |
| + t.Fatal("Resolve after Forget did not ask again") |
| + } |
| +} |
| + |
| +// Astra P1 on 259abef0: a published name with a label that is no zone |
| +// between it and its zone, under a delegation deeper than the top-down |
| +// walk follows. The nearest look climbs past the label (no NS set, no |
| +// cost) to the zone, as main did. A new name never climbs: the cache |
| +// hears nothing below the registrable domain. |
| +func TestFreshResolverUpgradeClimbsPastNonZoneLabels(t *testing.T) { |
| + w, last := deepWorld(t) |
| + ips, err := w.resolver(clock()).ResolveUpgrade(deepGapName) |
| if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| - t.Fatalf("Resolve = %v, %v; want [%s]", ips, err, edgeIP) |
| + t.Fatalf("ResolveUpgrade = %v, %v; want [%s] from a.b.c.d.example.com", ips, err, edgeIP) |
| + } |
| + want := "NS eu.a.b.c.d.example.com,NS " + deepGapName + ",NS a.b.c.d.example.com,HOST ns.provider.net" |
| + if got := strings.Join(w.cached, ","); got != want { |
| + t.Fatalf("cached queries = %s, want %s", got, want) |
| } |
| - 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) |
| + w, last = deepWorld(t) |
| + if ips, err := w.resolver(clock()).Resolve(deepGapName); err == nil { |
| + t.Fatalf("Resolve = %v, want the new name's walk refused at the referral bound", ips) |
| + } |
| + if last.queries.Load() != 0 { |
| + t.Fatal("a new name reached the zone past the referral bound") |
| + } |
| + noCachedBelow(t, w, deepGapName, "example.com") |
| +} |
| + |
| +// The climb tries at most freshMaxZones levels that have an NS set, never |
| +// the registrable domain (the walk asks it once) and never the TLD. |
| +func TestFreshResolverUpgradeClimbIsBounded(t *testing.T) { |
| + w := &world{ns: map[string][]string{"example.com": {"ns1.example.com."}}, hosts: map[string][]string{}} |
| + for _, z := range []string{"a.b.c.d.example.com", "b.c.d.example.com", "c.d.example.com", "d.example.com"} { |
| + w.ns[z] = []string{"ns.provider.net."} |
| + } |
| + if ips, err := w.resolver(clock()).ResolveUpgrade(deepName); err == nil { |
| + t.Fatalf("ResolveUpgrade = %v, want a failure: no nameserver has an address", ips) |
| + } |
| + var got []string |
| + for _, c := range w.cached { |
| + if strings.HasPrefix(c, "NS ") { |
| + got = append(got, c) |
| } |
| } |
| + want := "NS a.b.c.d.example.com,NS " + deepName + ",NS b.c.d.example.com,NS c.d.example.com,NS example.com" |
| + if strings.Join(got, ",") != want { |
| + t.Fatalf("cached NS queries = %s, want %s", strings.Join(got, ","), want) |
| + } |
| } |
| -// 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) |
| +// cohost answers as ONE server holding every zone in zones, each delegated |
| +// from the one before, the way a DNS host serves a customer's zone and its |
| +// sub-zone from the same machines. Every query is answered from the |
| +// deepest zone that encloses it: SOA queries as startAuthority does, other |
| +// queries by leaf in the last zone and as NODATA with the enclosing zone's |
| +// SOA above it. It never refers. Use with startAuthority(t, "", ...). |
| +func cohost(leaf func(dnsmessage.Question, *dnsmessage.Message) bool, zones ...string) func(dnsmessage.Question, *dnsmessage.Message) bool { |
| + return func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| + qn := strings.ToLower(strings.TrimSuffix(q.Name.String(), ".")) |
| + deepest := "" |
| + for _, z := range zones { |
| + if (qn == z || strings.HasSuffix(qn, "."+z)) && len(z) > len(deepest) { |
| + deepest = z |
| + } |
| + } |
| + switch { |
| + case deepest == "": |
| + r.RCode = dnsmessage.RCodeRefused |
| + case q.Type == dnsmessage.TypeSOA && qn == deepest: |
| + r.Authoritative = true |
| + r.Answers = []dnsmessage.Resource{soaRecord(deepest)} |
| + case q.Type == dnsmessage.TypeSOA || deepest != zones[len(zones)-1]: |
| + r.Authoritative = true |
| + r.Authorities = []dnsmessage.Resource{soaRecord(deepest)} |
| + default: |
| + return leaf(q, r) |
| + } |
| + return true |
| } |
| } |
| -func isNotFoundErr(err error) bool { |
| - var dnsErr *net.DNSError |
| - return errors.As(err, &dnsErr) && dnsErr.IsNotFound |
| +// Astra P1 on 259abef0: one server holds example.com and the delegated |
| +// eu.example.com, and answers for shop.eu.example.com from the child, with |
| +// the child's SOA. That SOA is not proof (it is not the verified zone's), |
| +// but it is a hint: the child is verified on the same server and the name |
| +// asked again under it. The cache hears nothing more. |
| +func TestFreshResolverFollowsACoHostedChildZone(t *testing.T) { |
| + const name, edge6 = "shop.eu.example.com", "2001:db8::7" |
| + for kind, tc := range map[string]struct { |
| + leaf func(dnsmessage.Question, *dnsmessage.Message) bool |
| + want string |
| + queries int32 |
| + }{ |
| + // SOA example.com, A (the hint), SOA eu.example.com, A, AAAA. |
| + "no address record": {nodata("eu.example.com"), "", 5}, |
| + // An address is an answer wherever the server keeps it: no hint. |
| + "A record": {authoritative(aRecord(name+".", edgeIP)), edgeIP, 2}, |
| + "AAAA record": {byType(nodata("eu.example.com"), authoritative(aaaaRecord(name+".", edge6))), edge6, 5}, |
| + } { |
| + t.Run(kind, func(t *testing.T) { |
| + fa := startAuthority(t, "", cohost(tc.leaf, "example.com", "eu.example.com")) |
| + w := oneZone(fa) |
| + ips, err := w.resolver(clock()).Resolve(name) |
| + if tc.want == "" { |
| + if !errors.Is(err, domains.ErrFreshNoData) { |
| + t.Fatalf("Resolve = %v, %v; want errNoData from the verified child", ips, err) |
| + } |
| + } else if err != nil || len(ips) != 1 || ips[0] != tc.want { |
| + t.Fatalf("Resolve = %v, %v; want [%s]", ips, err, tc.want) |
| + } |
| + if got := fa.queries.Load(); got != tc.queries { |
| + t.Fatalf("server got %d queries, want %d", got, tc.queries) |
| + } |
| + if got := strings.Join(w.cached, ","); got != "NS example.com,HOST ns1.example.com" { |
| + t.Fatalf("cached queries = %s; the hint must cost none", got) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The mismatched SOA is never trusted, only followed. An owner that is not |
| +// on the name's path is no hint at all (nothing more is asked); a child |
| +// the server cannot show an SOA for is a failure; and a child the hinting |
| +// server cannot verify is looked for on the zone's other server. |
| +func TestFreshResolverCoHostedHintIsNeverTrusted(t *testing.T) { |
| + const name = "shop.eu.example.com" |
| + failure := func(t *testing.T, r *domains.FreshResolver, fa *fakeAuthority, queries int32) { |
| + t.Helper() |
| + ips, err := r.Resolve(name) |
| + if err == nil || errors.Is(err, domains.ErrFreshNoData) || isNotFoundErr(err) { |
| + t.Fatalf("Resolve = %v, %v; want a fresh failure", ips, err) |
| + } |
| + if got := fa.queries.Load(); got != queries { |
| + t.Fatalf("server got %d queries, want %d", got, queries) |
| + } |
| + if _, err := r.Resolve(name); !errors.Is(err, domains.ErrFreshBackingOff) { |
| + t.Fatalf("second Resolve = %v, want the backoff", err) |
| + } |
| + } |
| + for owner, why := range map[string]string{ |
| + "us.example.com": "a sibling of the name's path", |
| + "deep.shop.eu.example.com": "below the name", |
| + "eu.example.net": "outside the verified zone", |
| + } { |
| + t.Run("off the path: "+why, func(t *testing.T) { |
| + // The server would verify owner if asked; it must not be asked. |
| + fa := startAuthority(t, "", func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| + if q.Type != dnsmessage.TypeSOA { |
| + return nodata(owner)(q, r) |
| + } |
| + r.Authoritative = true |
| + r.Answers = []dnsmessage.Resource{soaRecord(strings.TrimSuffix(q.Name.String(), "."))} |
| + return true |
| + }) |
| + w := oneZone(fa) |
| + failure(t, w.resolver(clock()), fa, 2) // SOA example.com, A |
| + noCachedBelow(t, w, name, "example.com") |
| + }) |
| + } |
| + t.Run("child not verified", func(t *testing.T) { |
| + // Holds example.com only, yet answers under eu.example.com's SOA. |
| + fa := startAuthority(t, "example.com", nodata("eu.example.com")) |
| + w := oneZone(fa) |
| + failure(t, w.resolver(clock()), fa, 3) // SOA example.com, A, SOA eu.example.com |
| + noCachedBelow(t, w, name, "example.com") |
| + }) |
| + t.Run("the zone's other server verifies it", func(t *testing.T) { |
| + liar := startAuthority(t, "example.com", nodata("eu.example.com")) |
| + both := startAuthority(t, "", cohost(authoritative(aRecord(name+".", edgeIP)), "example.com", "eu.example.com")) |
| + 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": liar, "192.0.2.2:53": both}, |
| + } |
| + ips, err := w.resolver(clock()).Resolve(name) |
| + if err != nil || len(ips) != 1 || ips[0] != edgeIP { |
| + t.Fatalf("Resolve = %v, %v; want [%s] from the server that holds the child", ips, err, edgeIP) |
| + } |
| + if liar.queries.Load() != 3 || both.queries.Load() != 2 { |
| + t.Fatalf("hinting server got %d queries and the other %d; want 3 (SOA, A, SOA of the child) and 2 (SOA of the child, A)", liar.queries.Load(), both.queries.Load()) |
| + } |
| + noCachedBelow(t, w, name, "example.com") |
| + }) |
| } |
| -// 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) { |
| +// Hints count against the referral bound: a server that keeps naming one |
| +// more child is followed freshMaxZones times and no further. |
| +func TestFreshResolverBoundsCoHostedHints(t *testing.T) { |
| + zones := []string{"example.com", "d.example.com", "c.d.example.com", "b.c.d.example.com", "a.b.c.d.example.com"} |
| + var mu sync.Mutex |
| + next := 0 |
| + var verified []string |
| fa := startAuthority(t, "", func(q dnsmessage.Question, r *dnsmessage.Message) bool { |
| + mu.Lock() |
| + defer mu.Unlock() |
| r.Authoritative = true |
| if q.Type == dnsmessage.TypeSOA { |
| - r.Answers = []dnsmessage.Resource{soaRecord("example.com")} |
| + zone := strings.TrimSuffix(q.Name.String(), ".") |
| + verified = append(verified, zone) |
| + r.Answers = []dnsmessage.Resource{soaRecord(zone)} |
| return true |
| } |
| - r.Answers = []dnsmessage.Resource{cnameRecord("shop.example.com.", "www.example.com.")} |
| + // Each A query is answered under the SOA of the next zone down. |
| + if next+1 < len(zones) { |
| + next++ |
| + } |
| + r.Authorities = []dnsmessage.Resource{soaRecord(zones[next])} |
| 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) |
| + if ips, err := w.resolver(clock()).Resolve(deepName); err == nil || errors.Is(err, domains.ErrFreshNoData) { |
| + t.Fatalf("Resolve = %v, %v; want hints past the bound refused", ips, err) |
| + } |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if got, want := strings.Join(verified, ","), strings.Join(zones[:4], ","); got != want { |
| + t.Fatalf("zones verified = %s, want %s and no deeper", got, want) |
| + } |
| + noCachedBelow(t, w, deepName, "example.com") |
| +} |
| + |
| +const costName = "shop.c.b.a.example.com" |
| + |
| +// costWorld is the most expensive healthy-looking hierarchy the walk |
| +// follows: example.com -> a -> b.a -> c.b.a.example.com, each zone on two |
| +// servers reached in order. The FIRST server of every zone answers with |
| +// first(zone) and gets the lookup nowhere; the SECOND refers to the next |
| +// zone (one NS host, two glue addresses, so the order holds), and in the |
| +// last zone it answers like the first. The cache also knows each child's |
| +// NS set, for the published-name look. servers is every server. |
| +func costWorld(t *testing.T, first func(zone string) func(dnsmessage.Question, *dnsmessage.Message) bool) (w *world, servers []*fakeAuthority) { |
| + t.Helper() |
| + zones := []string{"example.com", "a.example.com", "b.a.example.com", "c.b.a.example.com"} |
| + addr := func(zone, server int) string { return fmt.Sprintf("192.0.2.%d", 10+2*zone+server) } |
| + w = &world{ |
| + ns: map[string][]string{"example.com": {"ns1.example.com."}}, |
| + hosts: map[string][]string{"ns1.example.com": {addr(0, 0), addr(0, 1)}}, |
| + routes: map[string]*fakeAuthority{}, |
| + } |
| + for i, z := range zones { |
| + second := first(z) |
| + if i+1 < len(zones) { |
| + child, host := zones[i+1], "ns."+zones[i+1] |
| + w.ns[child] = []string{host + "."} |
| + w.hosts[host] = []string{addr(i+1, 0), addr(i+1, 1)} |
| + second = func(_ dnsmessage.Question, r *dnsmessage.Message) bool { |
| + r.Authorities = []dnsmessage.Resource{{ |
| + Header: dnsmessage.ResourceHeader{Name: dnsmessage.MustNewName(child + "."), Type: dnsmessage.TypeNS, Class: dnsmessage.ClassINET, TTL: 300}, |
| + Body: &dnsmessage.NSResource{NS: dnsmessage.MustNewName(host + ".")}, |
| + }} |
| + r.Additionals = []dnsmessage.Resource{aRecord(host+".", addr(i+1, 0)), aRecord(host+".", addr(i+1, 1))} |
| + return true |
| + } |
| + } |
| + for n, answer := range []func(dnsmessage.Question, *dnsmessage.Message) bool{first(z), second} { |
| + fa := startAuthority(t, z, answer) |
| + w.routes[addr(i, n)+":53"] = fa |
| + servers = append(servers, fa) |
| + } |
| + } |
| + return w, servers |
| +} |
| + |
| +func exchanges(servers []*fakeAuthority) (n int32) { |
| + for _, fa := range servers { |
| + n += fa.queries.Load() |
| + } |
| + return n |
| +} |
| + |
| +// Astra P2 on 259abef0: the maxima in resolve's cost comment, counted. A |
| +// server that answers NODATA for A and then fails the AAAA exchange has |
| +// cost three exchanges before the next server is tried, in every zone. |
| +func TestFreshResolverCostOfAFailedAAAABeforeARetry(t *testing.T) { |
| + failedAAAA := func(zone string) func(dnsmessage.Question, *dnsmessage.Message) bool { |
| + return byType(nodata(zone), func(_ dnsmessage.Question, r *dnsmessage.Message) bool { |
| + r.RCode = dnsmessage.RCodeServerFailure |
| + return true |
| + }) |
| + } |
| + t.Run("new name", func(t *testing.T) { |
| + w, servers := costWorld(t, failedAAAA) |
| + if ips, err := w.resolver(clock()).Resolve(costName); err == nil || errors.Is(err, domains.ErrFreshNoData) { |
| + t.Fatalf("Resolve = %v, %v; want a fresh failure", ips, err) |
| + } |
| + // Three zones that hand on at 3 + 2, the last at 3 + 3. |
| + if got := exchanges(servers); got != 21 { |
| + t.Fatalf("%d authoritative exchanges, want 21, the maximum for Resolve", got) |
| + } |
| + noCachedBelow(t, w, costName, "example.com") |
| + }) |
| + t.Run("published name", func(t *testing.T) { |
| + w, servers := costWorld(t, failedAAAA) |
| + if ips, err := w.resolver(clock()).ResolveUpgrade(costName); err == nil { |
| + t.Fatalf("ResolveUpgrade = %v, want a failure", ips) |
| + } |
| + // The nearest look asks c.b.a (6), b.a (5) and a (5), then the |
| + // walk's 21. Servers that answered differently each time they |
| + // were asked could make every nearest zone cost 6: 39. |
| + if got := exchanges(servers); got != 37 { |
| + t.Fatalf("%d authoritative exchanges, want 37 (16 nearest, 21 walk)", got) |
| + } |
| + }) |
| +} |
| + |
| +// The other maximum: a reply ending in an out-of-zone CNAME target sends |
| +// the target to the cache, and when that lookup fails the next server is |
| +// tried, which may send it again. |
| +func TestFreshResolverCostOfAFailedCNAMELookupBeforeARetry(t *testing.T) { |
| + const target = "edge.provider.net" |
| + w, servers := costWorld(t, func(string) func(dnsmessage.Question, *dnsmessage.Message) bool { |
| + return authoritative(cnameRecord(costName+".", target+".")) |
| + }) |
| + r := w.resolver(clock()) |
| + lookupHost := r.LookupHost |
| + r.LookupHost = func(ctx context.Context, host string) ([]string, error) { |
| + if host == target { |
| + w.note("HOST", host) |
| + return nil, errors.New("server misbehaving") |
| + } |
| + return lookupHost(ctx, host) |
| + } |
| + if ips, err := r.Resolve(costName); err == nil || isNotFoundErr(err) { |
| + t.Fatalf("Resolve = %v, %v; want a fresh failure", ips, err) |
| + } |
| + // One in each zone that hands on, two in the last. |
| + if got := w.cachedFor(target); got != 5 { |
| + t.Fatalf("%d cached lookups of the CNAME target, want 5", got) |
| + } |
| + // SOA and A from both servers of all four zones. |
| + if got := exchanges(servers); got != 16 { |
| + t.Fatalf("%d authoritative exchanges, want 16", got) |
| + } |
| + noCachedBelow(t, w, costName, "example.com") |
| +} |
| + |
| +// Astra P2 on 259abef0: Retain gives back what removed names hold. A |
| +// strike map full of pending strikes for names the deployment no longer |
| +// carries is emptied of them, a name still carried keeps its pending |
| +// strike, and the next new failure is held again instead of counting as |
| +// the second strike. |
| +func TestFreshResolverRetainReclaimsRemovedNames(t *testing.T) { |
| + r := &domains.FreshResolver{} |
| + r.Strike("shop.example.com") |
| + for i := 0; i < 2*domains.FreshMaxBackoff; i++ { |
| + r.Strike(fmt.Sprintf("n%d.example.com", i)) |
| + } |
| + if !r.Strike("late.example.com") { |
| + t.Fatal("fixture: the map is not full of pending strikes") |
| + } |
| + r.Retain([]string{"Shop.Example.com.", "late.example.com"}) |
| + if got := domains.FreshStrikeState(r, "n7.example.com"); got != 0 { |
| + t.Fatalf("removed name's strike state = %d, want 0 (reclaimed)", got) |
| + } |
| + if r.Strike("late.example.com") { |
| + t.Fatal("a new failure after the reclaim counted as the second strike; want it held") |
| + } |
| + if !r.Strike("shop.example.com") { |
| + t.Fatal("Retain forgot the pending strike of a name still present") |
| + } |
| +} |
| + |
| +// Retain drops a removed name's failure backoff too, and keeps a present |
| +// name's. |
| +func TestFreshResolverRetainPrunesTheBackoff(t *testing.T) { |
| + fa := startAuthority(t, "example.com", nil) |
| + r := oneZone(fa).resolver(clock()) |
| + r.Timeout, r.AttemptTimeout = 100*time.Millisecond, 50*time.Millisecond |
| + if _, err := r.Resolve("shop.example.com"); err == nil { |
| + t.Fatal("Resolve against a silent server succeeded") |
| + } |
| + sent := fa.queries.Load() |
| + r.Retain([]string{"shop.example.com"}) |
| + if _, err := r.Resolve("shop.example.com"); !errors.Is(err, domains.ErrFreshBackingOff) || fa.queries.Load() != sent { |
| + t.Fatalf("Resolve after Retain kept the name = %v, want the backoff", err) |
| + } |
| + r.Retain([]string{"other.example.com"}) |
| + if _, err := r.Resolve("shop.example.com"); errors.Is(err, domains.ErrFreshBackingOff) || fa.queries.Load() == sent { |
| + t.Fatalf("Resolve after Retain dropped the name = %v, want a real lookup", err) |
| } |
| } |
diff --git a/internal/domains/reconcile.go b/internal/domains/reconcile.go| index 61f120601..540659ebf 100644 |
| --- a/internal/domains/reconcile.go |
| +++ b/internal/domains/reconcile.go |
| @@ -14,6 +14,7 @@ import ( |
| "os" |
| "path/filepath" |
| "slices" |
| + "sort" |
| "strings" |
| "time" |
| @@ -42,9 +43,25 @@ 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 |
| + // ResolveFresh asks without any cache (#724); see dnsVerdicts. nil |
| // leaves every verdict to Resolve alone. |
| ResolveFresh func(host string) ([]string, error) |
| + // ResolveUpgrade is the fresh look for a published name's upgrade: the |
| + // name's nearest zones first, then ResolveFresh's walk (FreshResolver's |
| + // ResolveUpgrade); nil uses ResolveFresh. Never used for a new name. |
| + ResolveUpgrade func(host string) ([]string, error) |
| + // FreshForget ends ResolveFresh's failure backoff for a host (the same |
| + // resolver's Forget); dnsVerdicts calls it when a name it looked at |
| + // fresh before publication is published. nil skips that. |
| + FreshForget func(host string) |
| + // FreshStrike is the same resolver's Strike: the two-strike rule for a |
| + // new name whose fresh look failed (see dnsVerdicts). nil takes the |
| + // cached look on the first failure. |
| + FreshStrike func(host string) (second bool) |
| + // FreshRetain is the same resolver's Retain: dnsVerdicts hands it the |
| + // pass's hostnames, so the resolver drops what it remembers about |
| + // names the deployment no longer carries. nil skips that. |
| + FreshRetain func(hosts []string) |
| // AcmeDir is the edge's autocert DirCache directory; "" skips TLS |
| // stamping entirely. |
| AcmeDir string |
| @@ -498,24 +515,18 @@ func StampHealth(ctx context.Context, reg *registry.Registry, cfg Config, routes |
| // "pointing" — refusing that news would be the same lie in the |
| // opposite direction. |
| 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]}) |
| + candidates = append(candidates, freshCandidate{rt.Host, rt.DNSStatus, rt.DNSCheckedAt, &routeStatus[i]}) |
| } |
| for i, a := range aliases { |
| - candidates = append(candidates, freshCandidate{a.Alias, &aliasStatus[i]}) |
| + candidates = append(candidates, freshCandidate{a.Alias, a.DNSStatus, a.DNSCheckedAt, &aliasStatus[i]}) |
| } |
| - freshUpgrade(cfg, edge, candidates) |
| + dnsVerdicts(cfg, edge, candidates) |
| for i, rt := range routes { |
| status := routeStatus[i] |
| - if status == unresolvedDNS && rt.DNSStatus != "" { |
| + if status == heldDNS || status == unresolvedDNS && rt.DNSStatus != "" { |
| continue |
| } |
| if err := reg.SetDNSStatus(rt.Host, status, now); err != nil { |
| @@ -524,7 +535,7 @@ func StampHealth(ctx context.Context, reg *registry.Registry, cfg Config, routes |
| } |
| for i, a := range aliases { |
| status := aliasStatus[i] |
| - if status == unresolvedDNS && a.DNSStatus != "" { |
| + if status == heldDNS || status == unresolvedDNS && a.DNSStatus != "" { |
| continue |
| } |
| if err := reg.SetAliasDNSStatus(a.Alias, status, now); err != nil { |
| @@ -557,6 +568,11 @@ func StampHealth(ctx context.Context, reg *registry.Registry, cfg Config, routes |
| // difference between blaming the customer and owning the outage. |
| const unresolvedDNS = "unresolved" |
| +// heldDNS is not a stamp: it is dnsVerdicts saying "this pass decided |
| +// nothing about this name, leave its stamp and check time alone" (a new |
| +// name's first fresh failure, see hostVerdicts). Section 4 never writes it. |
| +const heldDNS = "\x00held" |
| + |
| // dnsStatus resolves host and classifies the answer against edge. Three |
| // distinct unknowns, deliberately: |
| // |
| @@ -572,6 +588,11 @@ const unresolvedDNS = "unresolved" |
| // never drift apart. |
| func dnsStatus(resolve func(host string) ([]string, error), host string, edge map[string]bool) string { |
| ips, err := resolve(host) |
| + return classifyDNS(ips, err, edge) |
| +} |
| + |
| +// classifyDNS is dnsStatus's verdict for one lookup's result. |
| +func classifyDNS(ips []string, err error, edge map[string]bool) string { |
| if err != nil { |
| var dnsErr *net.DNSError |
| if errors.As(err, &dnsErr) && dnsErr.IsNotFound { |
| @@ -587,11 +608,14 @@ 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. |
| +// freshCandidate is one name section 4 stamps: its stamp before this pass |
| +// (prev) and when that was checked (0 = never), and where dnsVerdicts |
| +// writes this pass's verdict. |
| type freshCandidate struct { |
| - host string |
| - status *string |
| + host string |
| + prev string |
| + checked int64 |
| + status *string |
| } |
| // The per-pass bound on fresh lookups (#724). Each costs at most the |
| @@ -604,59 +628,192 @@ var ( |
| freshPassTime = 30 * time.Second |
| ) |
| -// freshUpgrade gives a customer hostname that does not point here yet a |
| -// second, uncached look (#724). |
| +// dnsVerdicts sets each candidate's verdict for section 4, from the cached |
| +// resolver (cfg.Resolve) and, for customer hostnames, an uncached look |
| +// (cfg.ResolveFresh, #724). |
| +// |
| +// Each hostname is decided ONCE per pass, and the verdict goes to every row |
| +// carrying it (a host can be both a route and an alias). Decided per row, |
| +// the second row's fresh failure would count as the second strike inside |
| +// the same pass and take the cached look the first had just held. A host is |
| +// treated as published if any of its rows was "pointing", and as checked |
| +// when its least recently checked row was. |
| +// |
| +// The pass's hostnames go to cfg.FreshRetain first: these are every route |
| +// and alias the box carries, so whatever the resolver remembers about any |
| +// other name (a failure backoff, a pending strike) belongs to a name that |
| +// has been removed, and is dropped. |
| +func dnsVerdicts(cfg Config, edge map[string]bool, candidates []freshCandidate) { |
| + key := func(host string) string { return strings.ToLower(strings.TrimSuffix(host, ".")) } |
| + var hosts []freshCandidate |
| + at := map[string]int{} |
| + for _, c := range candidates { |
| + i, ok := at[key(c.host)] |
| + if !ok { |
| + at[key(c.host)] = len(hosts) |
| + hosts = append(hosts, freshCandidate{c.host, c.prev, c.checked, new(string)}) |
| + continue |
| + } |
| + if c.prev == "pointing" { |
| + hosts[i].prev = "pointing" |
| + } |
| + if c.checked < hosts[i].checked { |
| + hosts[i].checked = c.checked |
| + } |
| + } |
| + if cfg.FreshRetain != nil { |
| + names := make([]string, len(hosts)) |
| + for i, h := range hosts { |
| + names[i] = h.host |
| + } |
| + cfg.FreshRetain(names) |
| + } |
| + hostVerdicts(cfg, edge, hosts) |
| + for _, c := range candidates { |
| + *c.status = *hosts[at[key(c.host)]].status |
| + } |
| +} |
| + |
| +// hostVerdicts is dnsVerdicts for candidates with distinct hostnames. |
| // |
| -// 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"). |
| +// A name that was NOT "pointing" before this pass is looked at fresh |
| +// FIRST, and the cached resolver is not asked about it at all unless the |
| +// fresh look fails twice in a row or the name is past the budget. The |
| +// customer attaches a hostname and then adds the record (the order attach |
| +// prints), so such a name may not exist yet, and a cached query for it |
| +// would plant a negative entry in systemd-resolved and the VPC resolver |
| +// behind it for the zone's SOA minimum. The cert issuer gates its orders on |
| +// those same caches; if nothing of ours asks them about the name before it |
| +// exists, its first lookup after the record goes live is a clean miss. The |
| +// fresh verdicts are the cached path's: addresses including an edge are |
| +// "pointing", other addresses "elsewhere", an authoritative not-found "". |
| +// An authoritative "exists, no address record" (NODATA for A and for AAAA, |
| +// each with the zone's SOA; an AAAA record is read and classified like any |
| +// address) is "" too, with no cached query: the cache would keep a |
| +// per-type negative entry for it just as it keeps a "no such name". A |
| +// fresh FAILURE (no authority, backoff, timeout) follows the two-strike |
| +// rule: the first in a row decides nothing (the stamp is held and the next |
| +// pass asks fresh again), the second takes the cached look as before #724. |
| // |
| -// 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. |
| +// A name that WAS "pointing" keeps the cached-first path: a positive cache |
| +// entry is cheap and cannot be a primed miss. Its fresh look may only |
| +// UPGRADE a cached "" or "elsewhere" to "pointing" (the cached answer can |
| +// lag a moved record by its TTL); any other fresh result leaves the cached |
| +// verdict as it was. So the fresh path can never unpublish a name: it |
| +// decides the verdict only for names that were not "pointing" before this |
| +// pass, and a published name stays decided by the cached path plus that |
| +// upgrade, as before. The upgrade look is ResolveUpgrade: the name's |
| +// nearest zones first, as on main, then top-down from the registrable |
| +// domain if they give no answer. A cached lookup that FAILED is not |
| +// upgraded either: that is our resolver's fault, handled by section 4's |
| +// hold-last-verdict rule. |
| // |
| -// Eligible names are visited in a random order and the pass stops after |
| +// 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, and |
| +// both are stamped by the cached path alone. Eligible names share one |
| +// budget, published names' upgrades first (Astra R1 on the #724 follow-up: |
| +// new names must not starve a published name's re-check and so unpublish |
| +// it), in a random order; then new names, never-checked first and the |
| +// longest since checked after them. The pass stops looking fresh 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 |
| - } |
| +// through across passes instead of stretching any one of them. A |
| +// not-pointing name past the budget gets the cached look, as before #724. |
| +func hostVerdicts(cfg Config, edge map[string]bool, candidates []freshCandidate) { |
| apps := strings.ToLower(cfg.AppsDomain) |
| - var eligible []freshCandidate |
| + eligible := func(host string) bool { |
| + h := strings.ToLower(strings.TrimSuffix(host, ".")) |
| + return cfg.ResolveFresh != nil && freshPublicName(h) && |
| + (apps == "" || (h != apps && !strings.HasSuffix(h, "."+apps))) |
| + } |
| + // Fresh-first names wait for the budget loop; everything else gets its |
| + // cached verdict now, and a published name the cache does not read as |
| + // pointing joins the loop for an upgrade. Upgrades go FIRST: a backlog |
| + // of new names must never spend the budget a published name needs to |
| + // stay published. Random order within each group. |
| + var upgrades, firsts []freshCandidate |
| for _, c := range candidates { |
| - if *c.status != "" && *c.status != "elsewhere" { |
| + if !eligible(c.host) { |
| + *c.status = dnsStatus(cfg.Resolve, c.host, edge) |
| continue |
| } |
| - h := strings.ToLower(strings.TrimSuffix(c.host, ".")) |
| - if !freshPublicName(h) || (apps != "" && (h == apps || strings.HasSuffix(h, "."+apps))) { |
| + if c.prev != "pointing" { |
| + *c.status = unresolvedDNS |
| + firsts = append(firsts, c) |
| continue |
| } |
| - eligible = append(eligible, c) |
| + *c.status = dnsStatus(cfg.Resolve, c.host, edge) |
| + if *c.status == "" || *c.status == "elsewhere" { |
| + upgrades = append(upgrades, c) |
| + } |
| } |
| - rand.Shuffle(len(eligible), func(i, j int) { eligible[i], eligible[j] = eligible[j], eligible[i] }) |
| + // INVARIANT (Astra R2 on #724): a fresh failure recorded while a name |
| + // was unpublished never suppresses a look after it is published. A |
| + // fresh-first name that ends this pass "pointing", by the fresh look or |
| + // the cached fallback, has its backoff cleared, so its next upgrade look |
| + // is really sent. A failure recorded while the name is published (an |
| + // upgrade look) still backs off as before. |
| + defer func() { |
| + if cfg.FreshForget == nil { |
| + return |
| + } |
| + for _, c := range firsts { |
| + if *c.status == "pointing" { |
| + cfg.FreshForget(c.host) |
| + } |
| + } |
| + }() |
| + rand.Shuffle(len(upgrades), func(i, j int) { upgrades[i], upgrades[j] = upgrades[j], upgrades[i] }) |
| + // New names: never-checked first (a fresh attach is the case #724 is |
| + // for), then the longest since checked, so standing non-pointing names |
| + // cannot crowd a new one out of the budget (Fable R3 on #724). |
| + rand.Shuffle(len(firsts), func(i, j int) { firsts[i], firsts[j] = firsts[j], firsts[i] }) |
| + sort.SliceStable(firsts, func(i, j int) bool { return firsts[i].checked < firsts[j].checked }) |
| + pending := append(upgrades, firsts...) |
| start := time.Now() |
| - for n, c := range eligible { |
| - if n >= freshPassMax || time.Since(start) >= freshPassTime { |
| + spent := 0 |
| + for n, c := range pending { |
| + if spent >= freshPassMax || time.Since(start) >= freshPassTime { |
| + // Out of budget: a fresh-first name falls back to the cached |
| + // look; an upgrade candidate keeps its cached verdict. |
| + for _, rest := range pending[n:] { |
| + if rest.prev != "pointing" { |
| + *rest.status = dnsStatus(cfg.Resolve, rest.host, edge) |
| + } |
| + } |
| return |
| } |
| - ips, err := cfg.ResolveFresh(c.host) |
| - if err != nil { |
| - continue |
| + resolve := cfg.ResolveFresh |
| + if c.prev == "pointing" && cfg.ResolveUpgrade != nil { |
| + // Published, so it exists: the nearest-zone look cannot prime |
| + // anything. A new name NEVER takes this path. |
| + resolve = cfg.ResolveUpgrade |
| + } |
| + ips, err := resolve(c.host) |
| + if !errors.Is(err, errBackingOff) { |
| + spent++ // an answer from the backoff sent nothing |
| } |
| - for _, ip := range ips { |
| - if edge[ip] { |
| + fresh := classifyDNS(ips, err, edge) |
| + switch { |
| + case c.prev == "pointing": |
| + if fresh == "pointing" { |
| *c.status = "pointing" |
| - break |
| } |
| + case errors.Is(err, errNoData): |
| + // The name exists with no address record of either family. No |
| + // cached look: it would plant the negative #724 is about. |
| + *c.status = "" |
| + case fresh == unresolvedDNS: |
| + // Two strikes: the first failure in a row decides nothing and |
| + // asks nobody else (the resolver forgives it, so the next pass |
| + // asks fresh again); only the second takes the cached look. |
| + if cfg.FreshStrike != nil && !cfg.FreshStrike(c.host) { |
| + *c.status = heldDNS |
| + } else { |
| + *c.status = dnsStatus(cfg.Resolve, c.host, edge) |
| + } |
| + default: |
| + *c.status = fresh |
| } |
| } |
| } |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 60fca0784..4803d52fd 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -3822,15 +3822,23 @@ 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, |
| } |
| + // #724: the uncached look, first for a customer hostname that is not |
| + // published yet and as a second look for one whose cached answer stops |
| + // pointing here. For a name not yet published the cached resolver only |
| + // finds the registrable domain's nameservers, nameserver addresses and |
| + // our own CNAME target; a published name's look may also ask it for the |
| + // name's nearest zones. Each pass tells the resolver which names are |
| + // still carried (FreshRetain), so it forgets the rest. |
| + fresh := &domains.FreshResolver{ |
| + LookupNS: net.DefaultResolver.LookupNS, |
| + LookupHost: net.DefaultResolver.LookupHost, |
| + } |
| + cfg.ResolveFresh = fresh.Resolve |
| + cfg.ResolveUpgrade = fresh.ResolveUpgrade |
| + cfg.FreshForget = fresh.Forget |
| + cfg.FreshStrike = fresh.Strike |
| + cfg.FreshRetain = fresh.Retain |
| // EdgeIPs is deliberately left nil here — a Config out of this function |
| // alone stamps nothing. domainsLoop installs the fold once it has a |
| // store; see the doc comment. |
diff --git a/internal/host/host_test.go b/internal/host/host_test.go| index c52acf253..f1a3b8b89 100644 |
| --- a/internal/host/host_test.go |
| +++ b/internal/host/host_test.go |
| @@ -772,8 +772,8 @@ func TestDomainsTickConfig(t *testing.T) { |
| } |
| // #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") |
| + if got.ResolveFresh == nil || got.ResolveUpgrade == nil || got.FreshForget == nil || got.FreshStrike == nil || got.FreshRetain == nil { |
| + t.Error("ResolveFresh/ResolveUpgrade/FreshForget/FreshStrike/FreshRetain not populated on a configured deployment") |
| } |
| // No explicit edge IPs: the box's own public IP (IMDS) is the default. |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 329163528..1b8631110 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -146,3 +146,4 @@ plan14-root-reads-security-review-mitigations.tsv a6f3f9eec4aac5ea88f20d0e52eaa0 |
| plan14-root-reads-cli-registry-words.tsv 8924fafc5b6083858a72f45c764081abe3bcad6a6de71901470586c076c64bb6 |
| plan14-root-reads-billing-dashboard-1.tsv 8924fafc5b6083858a72f45c764081abe3bcad6a6de71901470586c076c64bb6 |
| plan14-root-reads-billing-dash-3-cost.tsv 8924fafc5b6083858a72f45c764081abe3bcad6a6de71901470586c076c64bb6 |
| +plan14-root-reads-no-negative-prime-724.tsv ab10145ee873e26b87a653f728cd0c9737592fefe94b659ac5988201c195cb7a |
diff --git a/internal/provision/testdata/plan14-root-reads-no-negative-prime-724.tsv b/internal/provision/testdata/plan14-root-reads-no-negative-prime-724.tsv| new file mode 100644 |
| index 000000000..8dab61aa7 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-no-negative-prime-724.tsv |
| @@ -0,0 +1,13 @@ |
| +# Census overlay no-negative-prime-724, written by census-propose (#369). census-ruling-no-negative-prime-724, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-no-negative-prime-724.md. |
| +# 1 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 3 new dispositions: 1 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 1 quiet units retired while they read nothing, 0 other. |
| +@legacy c27819c501ee7be78b134989641e2c5d8f2ad104ee72892d8fa0552392a7f7ee 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);rev3=census-ruling-no-negative-prime-724;basis=builds the one FreshResolver per config as a local and wires five of its methods into domains.Config: Resolve (ResolveFresh), ResolveUpgrade (new: for names already "pointing" only, asks the name's nearest zones first, climbing its levels below the registrable domain through cached NS sets, at most three levels that have one, and then the same top-down walk), Forget (FreshForget, clears that resolver's in-memory backoff and strike for a host), Strike (new FreshStrike, the in-memory two-strike rule for a new name's fresh failure) and Retain (new FreshRetain, drops that resolver's in-memory backoff and strike entries for names not in the pass's route and alias hostnames; it only deletes map entries, sends and reads nothing); drops LookupCNAME from the resolver; comment updated to say which cached lookups each path makes; reads nothing new, no file, path, env var or command input added (#724) data-literal@469,data-literal@510 4c595e5641a0d9fd91b111f354639adaed399158fe1871cbf7373eebada4a6f8 |
| +@legacy dcbe7775e0b06683acd3bbc80dc58256a17cb8b2124153bb4dbaf2246923fe81 internal/domains/freshdns.go FreshResolver.query legacy accepted-legacy accepted-legacy;rev3=census-ruling-no-negative-prime-724;basis=new: the body of the old FreshResolver.exchange moved here unchanged except that it takes the question type as an argument (A, SOA, and now AAAA after a NODATA for A, to the same verified server) and no longer checks the authority and truncation flags (exchange still does, for SOA verification and the AAAA question; ask checks truncation and reads a non-authoritative reply only as a referral down the name's path; an authoritative empty reply under the SOA of a child zone on the name's path is only a hint to verify that child by its own SOA on the same already-public servers and ask again, never an answer). The file:Read is the same conn.Read of one UDP reply from a nameserver that passed publicNameserver, with the same exact question matching; no file, path or new input (#724) file:Read@1214 f91e835feced403f06169f7fbec3816dbf5b4b53177915197b61a1ee40bff8ba |
| +@legacy 4dfdb094052ad77607f1975bca6537ed46fe8d057e53c36d1469bd8ac0d11a04 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);rev3=census-ruling-no-negative-prime-724;basis=section 4 now hands each route and alias, with its previous stamp (the two new registry:DNSStatus reads, rt.DNSStatus and a.DNSStatus, same rows already listed), to dnsVerdicts, which first hands the pass's hostnames to Config.FreshRetain (the resolver forgets its in-memory backoff and strike for names no longer carried) and then decides each hostname once per pass and applies the verdict to every row carrying it: a name not "pointing" before this pass and eligible for a fresh lookup (public name, not under the apps domain, ResolveFresh set) is looked at uncached first within the same 64-lookup/30 s budget (shared, with previously "pointing" names' upgrade looks serviced before any fresh-first name so new names cannot starve a published one) and stamped from it (edge address, A or AAAA, "pointing", other "elsewhere", authoritative not-found "", authoritative NODATA for A and AAAA with the zone's SOA "" with no cached query), falling back to the cached lookup past the budget or on the second fresh failure in a row; the first fresh failure in a row is held (stamp and check time untouched, the resolver forgives it so the next pass asks fresh again); a previously "pointing" name keeps cached-first plus the upgrade-only fresh look (ResolveUpgrade, nearest zones first), so the fresh path still never unpublishes; a fresh-first name that ends the pass "pointing" (fresh or cached) has its fresh failure backoff cleared through Config.FreshForget, so an onboarding failure never suppresses the upgrade look that keeps it published; new names are ordered never-checked first then oldest check, and lookups answered from the backoff do not count against the budget; StampHealth's own body is unchanged by the last round; no new file, path or command input; the dropped Alias/Host/Route/RouteAlias sites are the old indexed loops folded into the candidate build (#724) registry:Alias@3189,registry:Alias@3775,registry:Alias@3865,registry:Alias@4299,registry:Alias@4363,registry:Alias@4451,registry:DNSCheckedAt@3067,registry:DNSCheckedAt@3211,registry:DNSStatus@3053,registry:DNSStatus@3198,registry:DNSStatus@3403,registry:DNSStatus@3699,registry:Host@3044,registry:Host@3475,registry:Host@3559,registry:Host@4068,registry:Host@4127,registry:Host@4209,whole:Route@199,whole:Route@236,whole:Route@2871,whole:Route@2984,whole:Route@3310,whole:Route@4022,whole:RouteAlias@2917,whole:RouteAlias@3128,whole:RouteAlias@3605,whole:RouteAlias@4252,whole:RouteAlias@780 a1345c0d3076a9cd7ff17bc95fed36df451b5391dce43eb77d8b5151a6d5fb13 |
| +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);rev3=census-ruling-no-negative-prime-724;basis=builds the one FreshResolver per config as a local and wires five of its methods into domains.Config: Resolve (ResolveFresh), ResolveUpgrade (new: for names already "pointing" only, asks the name's nearest zones first, climbing its levels below the registrable domain through cached NS sets, at most three levels that have one, and then the same top-down walk), Forget (FreshForget, clears that resolver's in-memory backoff and strike for a host), Strike (new FreshStrike, the in-memory two-strike rule for a new name's fresh failure) and Retain (new FreshRetain, drops that resolver's in-memory backoff and strike entries for names not in the pass's route and alias hostnames; it only deletes map entries, sends and reads nothing); drops LookupCNAME from the resolver; comment updated to say which cached lookups each path makes; reads nothing new, no file, path, env var or command input added (#724) data-literal@469,data-literal@510 4c595e5641a0d9fd91b111f354639adaed399158fe1871cbf7373eebada4a6f8 |
| +internal/domains/freshdns.go FreshResolver.query legacy accepted-legacy accepted-legacy;rev3=census-ruling-no-negative-prime-724;basis=new: the body of the old FreshResolver.exchange moved here unchanged except that it takes the question type as an argument (A, SOA, and now AAAA after a NODATA for A, to the same verified server) and no longer checks the authority and truncation flags (exchange still does, for SOA verification and the AAAA question; ask checks truncation and reads a non-authoritative reply only as a referral down the name's path; an authoritative empty reply under the SOA of a child zone on the name's path is only a hint to verify that child by its own SOA on the same already-public servers and ask again, never an answer). The file:Read is the same conn.Read of one UDP reply from a nameserver that passed publicNameserver, with the same exact question matching; no file, path or new input (#724) file:Read@1214 f91e835feced403f06169f7fbec3816dbf5b4b53177915197b61a1ee40bff8ba |
| +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);rev3=census-ruling-no-negative-prime-724;basis=section 4 now hands each route and alias, with its previous stamp (the two new registry:DNSStatus reads, rt.DNSStatus and a.DNSStatus, same rows already listed), to dnsVerdicts, which first hands the pass's hostnames to Config.FreshRetain (the resolver forgets its in-memory backoff and strike for names no longer carried) and then decides each hostname once per pass and applies the verdict to every row carrying it: a name not "pointing" before this pass and eligible for a fresh lookup (public name, not under the apps domain, ResolveFresh set) is looked at uncached first within the same 64-lookup/30 s budget (shared, with previously "pointing" names' upgrade looks serviced before any fresh-first name so new names cannot starve a published one) and stamped from it (edge address, A or AAAA, "pointing", other "elsewhere", authoritative not-found "", authoritative NODATA for A and AAAA with the zone's SOA "" with no cached query), falling back to the cached lookup past the budget or on the second fresh failure in a row; the first fresh failure in a row is held (stamp and check time untouched, the resolver forgives it so the next pass asks fresh again); a previously "pointing" name keeps cached-first plus the upgrade-only fresh look (ResolveUpgrade, nearest zones first), so the fresh path still never unpublishes; a fresh-first name that ends the pass "pointing" (fresh or cached) has its fresh failure backoff cleared through Config.FreshForget, so an onboarding failure never suppresses the upgrade look that keeps it published; new names are ordered never-checked first then oldest check, and lookups answered from the backoff do not count against the budget; StampHealth's own body is unchanged by the last round; no new file, path or command input; the dropped Alias/Host/Route/RouteAlias sites are the old indexed loops folded into the candidate build (#724) registry:Alias@3189,registry:Alias@3775,registry:Alias@3865,registry:Alias@4299,registry:Alias@4363,registry:Alias@4451,registry:DNSCheckedAt@3067,registry:DNSCheckedAt@3211,registry:DNSStatus@3053,registry:DNSStatus@3198,registry:DNSStatus@3403,registry:DNSStatus@3699,registry:Host@3044,registry:Host@3475,registry:Host@3559,registry:Host@4068,registry:Host@4127,registry:Host@4209,whole:Route@199,whole:Route@236,whole:Route@2871,whole:Route@2984,whole:Route@3310,whole:Route@4022,whole:RouteAlias@2917,whole:RouteAlias@3128,whole:RouteAlias@3605,whole:RouteAlias@4252,whole:RouteAlias@780 a1345c0d3076a9cd7ff17bc95fed36df451b5391dce43eb77d8b5151a6d5fb13 |
| +@remove internal/domains/freshdns.go FreshResolver.exchange |
| +@removed internal/domains/freshdns.go FreshResolver.exchange H3 census-ruling-no-negative-prime-724;basis=quiet: now a wrapper over query that keeps the authority and truncation checks; its socket read moved to FreshResolver.query (#724) |
| +@coverage internal/domains 2370e0f17ba78af0e6fb455605a834281f9275c68da1847b86ad601d150792f4 |
| +@coverage internal/host ce3ebe4a23d41ff37ce18672099a3810530e5e565b2d062e0347ffb99d3ba404 |