Make the API response contract a test; fix what it found
The console's TypeScript types are hand-written and apiFetch ends in
`JSON.parse(text) as T`, so nothing in the toolchain compared them with the
Go structs. A field that lost its json tag, or a response a struct never had,
showed up as an empty table in a browser and nowhere else: the Go suite was
green and the console was wrong. internal/app/contract_test.go now asserts the
exact JSON key set of every admin endpoint, driven through the real router
with the real hook implementations, plus a test that drives the two write
endpoints with the exact payload web/src builds.
The drift it found, all four fixed here:
blocklist.Source and SourceMeta had no json tags at all, so GET /api/blocklists
sent Go field names ("URL"/"Format") where the console expects snake_case: the
Sources table rendered blank rows and its per-row toggle posted
`name: undefined`. Tagged to match ParseStats.
acl.GroupSummary was flat where the console reads a nested `match` object — the
same shape config.Group has — so every group card read "matches nothing". The
four match fields are nested now, under a new acl.Match.
PUT /api/clients answered 400 `json: unknown field "ptr_suffixes"` to the
console's payload, because config.Group and config.Match carried yaml tags only
and the decoder runs with DisallowUnknownFields. Both structs have json tags
now; the same applies to config.UpstreamServer and UpstreamBootstrap.
PUT /api/upstreams answered 400 `json: unknown field "health"`, because the
console round-trips the whole server object it read, runtime health fields
included. They are accepted and ignored, because the server owns them, and they
are `yaml:"-"` so settings.yaml does not gain runtime state.
Also fixed, each with a test:
A duration on the wire was a nanosecond count. config.Duration had a
MarshalYAML but no MarshalJSON, so bootstraps[].refresh arrived as 30000000000
while the console typed the field as a string, and healthcheck_interval was a
float of seconds in one place and a string in another. Durations on the wire
are duration strings everywhere now — the same spelling config.yaml uses — and a
bare JSON number is still accepted and means seconds, not nanoseconds.
TestDurationJSONForm used to pin the old behaviour and now pins the new one,
saying in its comment that the old behaviour was the bug.
A log row's key set depended on the row. api.LogEntry was omitempty on
client_group, response, upstream and list, so a query with no ACL group
arrived without the key and the console rendered "undefined" where the column
should be empty. The contract test can only pin one shape if the server emits
one, so nothing on that struct is omitempty any more.
A dead peer stayed in the cluster peer list forever. Cluster.seen was only ever
added to and deleted from on an explicit `bye`, so a node that crashed — or
whose Valkey connection died — was reported as a live peer for the life of the
process, and its stale blocklist digest was flagged as divergence forever.
Peers() now reaps peers unheard for peer_ttl*4 and stamps each state with the
receiver's own clock, so clock skew between two machines can neither reap a
healthy peer nor keep a dead one. Discover() ages out the same way on the
publisher's own last_seen stamp, because the keyed Valkey record outlives a
crash: a live node keeps refreshing the key's TTL, so a dead node's field stayed
readable for the life of the fleet.
peer_ttl: 0 would have crashed the process. time.NewTicker(PeerTTL/2) panics on
a non-positive period and `EXPIRE key 0` deletes the heartbeat key, so a config
that left peer_ttl unset would have taken the process down at Start, or made
every instance believe it is alone in the fleet. Both go through peerTTL() and
peerDeadline(), which fall back to the default.
Two cluster tests raced on the wire, not on the product, and one was
environment-dependent rather than wrong. A node that joined after another's
heartbeat was in flight hears about it on the next tick, so "b does not see a"
read immediately after "a sees b" is a coin flip; the divergence test waited for
a digest on the wrong node's view of the fleet; and 127.0.0.1:1 is only
unbindable outside a container that sets
net.ipv4.ip_unprivileged_port_start=0, where it binds and the partial-bind test
fails with both transports up. That test now occupies a port with a live
listener in the test process, which is a deterministic EADDRINUSE on every
machine and every uid.
internal/server/counters_test.go covers the counter-key layer that no other
test touched: the "<transport>.<field>" keyspace, that the aggregate folds only
the known fields, and that the snapshot is safe while counters move.
Two pinned behaviours changed on purpose, each with a test that says so:
An RPZ record did not cover the name it names. rpzRule gave a bare owner name
the subdomain form (*.name), so analytics.example.org. in a policy zone blocked
cdn.analytics.example.org. and left analytics.example.org. resolving normally —
and an rpz-passthru. record did not allowlist its own domain either. RPZ
semantics say the record applies to the domain and everything under it, so a
bare owner now takes the apex form **.name; an owner written with an explicit *.
is still strict, so a zone that wants subdomain-only behaviour can still ask for
it. This changes which queries get blocked for an existing policy zone, which is
why it wanted a decision. TestExampleRPZZoneCoversTheApexItNames pins both
halves and the example zone now says which half it relies on.
metrics.OutcomeLocal had no producer. The engine reported a local-zone answer as
qlog.ActionAllow, which outcomeFor mapped to OutcomeUpstream, so every locally
answered query was counted as an upstream one and the outcome="local" series was
never published — the dashboard's local column was permanently empty.
Response.Local is now set on the local-zone path and outcomeFor consults it
first. That moves published counters, so the README's metrics section says so
too.
This commit is contained in:
1 parent
e8c5b414d9
commit
9881d2a095
23 files changed
+1302
-242
No files matched your search
+82
-27
@@ -9,6 +9,7 @@ package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
@@ -61,6 +62,37 @@ func (d *Duration) UnmarshalYAML(value *yaml.Node) error {
|
||||
return fmt.Errorf("invalid duration: %s", value.Value)
|
||||
}
|
||||
|
||||
// MarshalJSON writes the Go duration string ("30s"), matching MarshalYAML and
|
||||
// what the console's types declare. Without it a config.Duration on the wire
|
||||
// became a nanosecond count, so `bootstraps[].refresh` arrived as 30000000000
|
||||
// and the console's duration field was nonsense.
|
||||
func (d Duration) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(time.Duration(d).String())
|
||||
}
|
||||
|
||||
// UnmarshalJSON accepts the duration string the server writes, and a bare
|
||||
// number as SECONDS — not nanoseconds, which is what encoding/json would do by
|
||||
// default and what nobody means. Accepting the number keeps a hand-written
|
||||
// client (`{"healthcheck_interval": 30}`) working instead of silently meaning
|
||||
// 30ns.
|
||||
func (d *Duration) UnmarshalJSON(b []byte) error {
|
||||
var s string
|
||||
if err := json.Unmarshal(b, &s); err == nil {
|
||||
v, err := time.ParseDuration(strings.TrimSpace(s))
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid duration %q: %w", s, err)
|
||||
}
|
||||
*d = Duration(v)
|
||||
return nil
|
||||
}
|
||||
var n float64
|
||||
if err := json.Unmarshal(b, &n); err != nil {
|
||||
return fmt.Errorf("duration must be a string or a number of seconds: %s", b)
|
||||
}
|
||||
*d = Duration(n * float64(time.Second))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d Duration) MarshalYAML() (any, error) { return time.Duration(d).String(), nil }
|
||||
|
||||
func (d Duration) D() time.Duration { return time.Duration(d) }
|
||||
@@ -186,28 +218,46 @@ type Upstream struct {
|
||||
Bootstraps []UpstreamBootstrap `yaml:"bootstraps"`
|
||||
}
|
||||
|
||||
// UpstreamServer is one resolver. The json tags exist for the same reason as
|
||||
// config.Group's: PUT /api/upstreams decodes the console's payload with
|
||||
// DisallowUnknownFields, and the console round-trips the whole server object
|
||||
// it read from GET /api/upstreams — including the runtime health fields the
|
||||
// server owns. Accepting them (and ignoring them) is the contract; refusing
|
||||
// them made every save in the console answer 400.
|
||||
type UpstreamServer struct {
|
||||
// Addr is host:port; host may be an IP or a name resolved via Bootstraps.
|
||||
Addr string `yaml:"addr"`
|
||||
Addr string `yaml:"addr" json:"addr"`
|
||||
// Proto is "udp", "tcp" or "tls" (DoT, 8.4.1).
|
||||
Proto string `yaml:"proto"`
|
||||
Proto string `yaml:"proto" json:"proto"`
|
||||
// ServerName / InsecureSkipVerify are only used with proto: tls.
|
||||
ServerName string `yaml:"server_name"`
|
||||
InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
|
||||
ServerName string `yaml:"server_name" json:"server_name"`
|
||||
InsecureSkipVerify bool `yaml:"insecure_skip_verify" json:"insecure_skip_verify"`
|
||||
// HealthPath is a hostname used for health probes instead of the Addr host.
|
||||
HealthName string `yaml:"health_name"`
|
||||
HealthName string `yaml:"health_name" json:"health_name"`
|
||||
// Weight biases random selection (default 1).
|
||||
Weight int `yaml:"weight"`
|
||||
Weight int `yaml:"weight" json:"weight"`
|
||||
// MaxFails before the breaker opens; 0 uses the global threshold.
|
||||
MaxFails int `yaml:"max_fails"`
|
||||
Comment string `yaml:"comment,omitempty"`
|
||||
MaxFails int `yaml:"max_fails" json:"max_fails"`
|
||||
Comment string `yaml:"comment,omitempty" json:"comment,omitempty"`
|
||||
// Health and the counters below are read-only runtime state. They are
|
||||
// accepted on a write and ignored, because the server owns them; the
|
||||
// console sends back the object it read.
|
||||
Health string `yaml:"-" json:"health,omitempty"`
|
||||
LatencyMS float64 `yaml:"-" json:"latency_ms,omitempty"`
|
||||
AvgMS float64 `yaml:"-" json:"avg_ms,omitempty"`
|
||||
P95MS float64 `yaml:"-" json:"p95_ms,omitempty"`
|
||||
FailRate float64 `yaml:"-" json:"fail_rate,omitempty"`
|
||||
Queries uint64 `yaml:"-" json:"queries,omitempty"`
|
||||
Failures uint64 `yaml:"-" json:"failures,omitempty"`
|
||||
BreakerOpen bool `yaml:"-" json:"breaker_open,omitempty"`
|
||||
LastError string `yaml:"-" json:"last_error,omitempty"`
|
||||
}
|
||||
|
||||
type UpstreamBootstrap struct {
|
||||
Name string `yaml:"name"`
|
||||
Addresses []string `yaml:"addresses"`
|
||||
Name string `yaml:"name" json:"name"`
|
||||
Addresses []string `yaml:"addresses" json:"addresses"`
|
||||
// Refresh re-resolves periodically (for dyn names).
|
||||
Refresh Duration `yaml:"refresh"`
|
||||
Refresh Duration `yaml:"refresh" json:"refresh"`
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
@@ -304,42 +354,47 @@ type ACL struct {
|
||||
|
||||
// Group is a named set of clients sharing a policy. Groups are evaluated
|
||||
// top-to-bottom; the first match wins.
|
||||
//
|
||||
// The json tags are the same as the yaml ones and they are not decoration:
|
||||
// PUT /api/clients decodes the admin console's payload into this struct with
|
||||
// DisallowUnknownFields, and the console sends snake_case. A struct with only
|
||||
// yaml tags made every write answer 400 `json: unknown field "ptr_suffixes"`.
|
||||
type Group struct {
|
||||
Name string `yaml:"name"`
|
||||
Comment string `yaml:"comment,omitempty"`
|
||||
Match Match `yaml:"match"`
|
||||
Name string `yaml:"name" json:"name"`
|
||||
Comment string `yaml:"comment,omitempty" json:"comment,omitempty"`
|
||||
Match Match `yaml:"match" json:"match"`
|
||||
// Policy is "allow" (full resolution), "block_only" (blocklists still
|
||||
// apply, everything else resolves) or "deny" (REFUSED).
|
||||
Policy string `yaml:"policy"`
|
||||
Policy string `yaml:"policy" json:"policy"`
|
||||
// AllowDomains / DenyDomains are per-group overrides; the names support
|
||||
// the same wildcards as blocklists ("*.example.com", "**.example.com").
|
||||
AllowDomains []string `yaml:"allow_domains"`
|
||||
DenyDomains []string `yaml:"deny_domains"`
|
||||
AllowDomains []string `yaml:"allow_domains" json:"allow_domains"`
|
||||
DenyDomains []string `yaml:"deny_domains" json:"deny_domains"`
|
||||
// BlocklistToggle lets a group opt out of blocklist filtering.
|
||||
SkipBlocklist bool `yaml:"skip_blocklist"`
|
||||
SkipBlocklist bool `yaml:"skip_blocklist" json:"skip_blocklist"`
|
||||
// CacheToggle lets a group bypass the cache (fresh lookups only).
|
||||
SkipCache bool `yaml:"skip_cache"`
|
||||
SkipCache bool `yaml:"skip_cache" json:"skip_cache"`
|
||||
// RateLimit overrides ACL.DefaultRateLimit for this group.
|
||||
RateLimit int `yaml:"rate_limit"`
|
||||
RateLimit int `yaml:"rate_limit" json:"rate_limit"`
|
||||
// MaxConcurrent overrides Server.MaxConcurrentPerClient.
|
||||
MaxConcurrent int `yaml:"max_concurrent"`
|
||||
MaxConcurrent int `yaml:"max_concurrent" json:"max_concurrent"`
|
||||
// LogQueries forces query logging for this group regardless of sampling.
|
||||
LogQueries bool `yaml:"log_queries"`
|
||||
Upstreams []string `yaml:"upstreams"`
|
||||
LogQueries bool `yaml:"log_queries" json:"log_queries"`
|
||||
Upstreams []string `yaml:"upstreams" json:"upstreams"`
|
||||
}
|
||||
|
||||
// Match selects clients by network identity.
|
||||
type Match struct {
|
||||
// CIDRs are matched against the client address (v4 or v6).
|
||||
CIDRs []string `yaml:"cidrs"`
|
||||
CIDRs []string `yaml:"cidrs" json:"cidrs"`
|
||||
// Networks match DNS clients identified by a resolved PTR of their
|
||||
// reverse name; the name must end with one of the suffixes.
|
||||
PTRSuffixes []string `yaml:"ptr_suffixes"`
|
||||
PTRSuffixes []string `yaml:"ptr_suffixes" json:"ptr_suffixes"`
|
||||
// Tags are matched against the client tag set derived from PTR labels,
|
||||
// e.g. "laptop" for "laptop.lan.internal.".
|
||||
Tags []string `yaml:"tags"`
|
||||
Tags []string `yaml:"tags" json:"tags"`
|
||||
// Always matches (useful as a catch-all fallback group).
|
||||
Any bool `yaml:"any"`
|
||||
Any bool `yaml:"any" json:"any"`
|
||||
}
|
||||
|
||||
type QueryLog struct {
|
||||
|
||||
@@ -114,8 +114,18 @@ func TestDurationMarshalYAMLRoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Duration has no custom JSON unmarshaller; pin what encoding/json does with
|
||||
// it so a change here is a deliberate one.
|
||||
// TestDurationJSONForm pins the wire form of a Duration. This test used to
|
||||
// pin the encoding/json default — a bare nanosecond count, and a quoted
|
||||
// duration as an error — because a config.Duration had no custom JSON
|
||||
// marshaller at all.
|
||||
//
|
||||
// DECIDED: that default was wrong on both sides. The admin console declares
|
||||
// these fields as strings (`bootstraps[].refresh`, `healthcheck_interval`), the
|
||||
// same spelling config.yaml uses, and a nanosecond count on the wire is
|
||||
// something no client means. Duration now marshals to "5s" and unmarshals from
|
||||
// a duration string; a bare number is accepted as SECONDS rather than
|
||||
// nanoseconds, so a hand-written client asking for `{"healthcheck_interval":30}`
|
||||
// gets 30s and not 30ns.
|
||||
func TestDurationJSONForm(t *testing.T) {
|
||||
var got struct {
|
||||
D Duration `json:"d"`
|
||||
@@ -123,18 +133,35 @@ func TestDurationJSONForm(t *testing.T) {
|
||||
if err := json.Unmarshal([]byte(`{"d":5}`), &got); err != nil {
|
||||
t.Fatalf("bare number: %v", err)
|
||||
}
|
||||
if got.D.D() != 5*time.Nanosecond {
|
||||
t.Errorf("bare JSON number = %v (nanoseconds, not seconds)", got.D.D())
|
||||
if got.D.D() != 5*time.Second {
|
||||
t.Errorf("bare JSON number = %v, want 5s (a number is seconds, not nanoseconds)", got.D.D())
|
||||
}
|
||||
if err := json.Unmarshal([]byte(`{"d":"5s"}`), &got); err == nil {
|
||||
t.Errorf("quoted JSON duration decoded to %v; string form is unsupported", got.D.D())
|
||||
if err := json.Unmarshal([]byte(`{"d":"5s"}`), &got); err != nil {
|
||||
t.Fatalf("quoted duration: %v", err)
|
||||
}
|
||||
if got.D.D() != 5*time.Second {
|
||||
t.Errorf("quoted JSON duration = %v, want 5s", got.D.D())
|
||||
}
|
||||
if err := json.Unmarshal([]byte(`{"d":"nonsense"}`), &got); err == nil {
|
||||
t.Error("an unparseable duration string decoded without an error")
|
||||
}
|
||||
if err := json.Unmarshal([]byte(`{"d":true}`), &got); err == nil {
|
||||
t.Error("a boolean decoded as a duration without an error")
|
||||
}
|
||||
out, err := json.Marshal(Duration(5 * time.Second))
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
if string(out) != "5000000000" {
|
||||
t.Errorf("json.Marshal = %s, want nanoseconds", out)
|
||||
if string(out) != `"5s"` {
|
||||
t.Errorf("json.Marshal = %s, want \"5s\"", out)
|
||||
}
|
||||
// The yaml form is unchanged, so a config file and the API agree.
|
||||
y, err := Duration(90 * time.Second).MarshalYAML()
|
||||
if err != nil {
|
||||
t.Fatalf("MarshalYAML: %v", err)
|
||||
}
|
||||
if y != "1m30s" {
|
||||
t.Errorf("MarshalYAML = %v, want 1m30s", y)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user