web

package
v0.8.42 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 46 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const MaxClientQueryNumEntries = 1_000_000

MaxClientQueryNumEntries caps the size of AdminServer.clientQueryNum. The map is populated lazily by RecordQuery on every distinct client IP the resolver sees, and the TTL cleanup (default 5 minutes) only evicts entries idle past 2x the cleanup interval — between ticks a UDP-source-spoofing attacker can populate millions of entries from a single host, and even a busy ISP-side deployment can see 100k+ distinct legitimate clients in a 10-minute window. The cap stops unbounded growth without changing the per-client counter contract: on insert past the cap, the OLDEST-lastAccess entry is evicted. A returning client that was evicted simply restarts at 1 — the counter is a UI convenience, not a security boundary, so resetting it is acceptable when memory pressure forces eviction.

View Source
const MaxConcurrentDiagnosticTraces = 8

MaxConcurrentDiagnosticTraces bounds the process work created by diagnostic WebSockets. Production DNS traffic remains independent; only the explicitly requested, event-heavy diagnostic traces consume these slots.

View Source
const MaxNTAReasonBytes = 1024

MaxNTAReasonBytes caps the free-text reason field on an NTA install. The reason is held in memory for the NTA's lifetime (up to 30 days per the duration ceiling) and copied on every audit/list response. With MaxNTAEntries=10000, an uncapped reason field exposed a 10 GiB memory-amplification surface to an authenticated attacker who could re-install the same zone 10k times with megabyte-scale reasons; 1024 bytes is well above any human-readable explanation and well under the worst-case multi-NTA memory ceiling.

View Source
const MaxPasswordLength = 72

MaxPasswordLength caps the password at bcrypt's hard input limit. bcrypt silently truncates input to 72 bytes — without an explicit cap, two passwords sharing the same first 72 bytes hash identically. An operator who chose a 128-char passphrase would not learn that only the first 72 bytes are protective (the "long passphrase as extra security" mental model is a real attack surface here). The cap is enforced by ValidatePassword so the setup wizard and the change-password endpoint both refuse over-cap inputs with a clear message rather than silently accepting them.

View Source
const MaxQueryLogCapacity = 1_000_000

MaxQueryLogCapacity caps the QueryLog ring buffer size. Each QueryEntry is ~80 bytes (a few strings, int64s, a float64, a bool), so a 1M-entry ring holds ~80 MiB of buffered query history — enough for a dashboard to display many minutes of activity even on a busy resolver, and small enough that the worst-case footprint stays bounded. Without this cap, a typo in YAML (`query_log_buffer: 1000000000` instead of `1000000`) or a malicious config-raw PUT that planted a 1 GB+ value would allocate that slice upfront in NewQueryLog and OOM the resolver at startup.

View Source
const MaxQueryLogSubscribers = 256

MaxQueryLogSubscribers caps the number of concurrent WS subscribers the query-log fanout will hold. Each subscriber owns a `make(chan QueryEntry, 128)` channel — with a QueryEntry of ~80 bytes plus pointer overhead, that's ~10 KiB per subscriber. The `/api/queries/stream` endpoint is behind requireAuth, so only an authenticated client can hit Subscribe; even so, a misbehaving dashboard that opens-and-leaks WebSocket connections in a tight reload loop, or an authenticated attacker, could grow `ql.subs` past memory limits. 256 is well above any plausible legitimate load (one operator + a handful of monitoring scripts) and bounds the fanout footprint to ~2.5 MiB. When the cap is hit, Subscribe returns id=0 and a CLOSED channel so the caller's read loop exits immediately — the client gets a clean disconnect instead of a silently-dropped subscription.

View Source
const MaxRequestBodyBytes = 1 << 20 // 1 MiB

MaxRequestBodyBytes caps the size of any JSON request body the admin API will read. Every POST/PUT/PATCH handler decodes the body into a struct; without a cap, an attacker (or a buggy automation script) could POST a 1GB JSON blob and exhaust resolver RAM before the decoder failed. 1 MiB is well above any legitimate API request (the largest is a few-hundred-byte NTA install or blocklist domain list) and well below the threshold at which a single body would cause memory pressure. The middleware uses http.MaxBytesReader so Decode() naturally errors with http.MaxBytesError once the cap is exceeded, which jsonResponse turns into a clean 400.

View Source
const MaxWebSocketMessageBytes = 4 << 10 // 4 KiB

withBodyCap wraps a handler so that any read from r.Body returns http.MaxBytesError once MaxRequestBodyBytes has been read. This is MaxWebSocketMessageBytes caps the size of any single WebSocket message the admin API will read from a client. All three live-stream endpoints (queries, trace, time-series) receive only tiny JSON control messages — subscription updates, trace start/cancel — that are well under 1 KiB in normal use. The coder/websocket library's default is 32 KiB, which is large enough that a regression to the library default (or a future bump in upstream) would silently widen the attack surface for an authenticated client trying to bloat the server's per-conn read buffer. Pinning to 4 KiB makes the bound explicit at every Accept site and keeps headroom for tagged messages without permitting megabyte-scale floods.

WebSocket lifecycle:

  • Accept: every handler calls websocket.Accept followed immediately by conn.SetReadLimit(MaxWebSocketMessageBytes).
  • Read: a goroutine reads JSON control messages. A message exceeding the 4 KiB read limit causes a protocol error that closes the conn.
  • Write: messages are pushed with a 5-second timeout per write (context.WithTimeout). A stalled client that does not drain its receive buffer will eventually cause the write to fail, which triggers conn.Close(StatusNormalClosure).
  • Ping: the push goroutine sends a WebSocket ping every 10 seconds. If the peer does not respond with a pong, the coder/websocket library's built-in timeout (PongTimeout, default ~10s) closes the connection.
  • Close: deferred conn.Close(StatusNormalClosure, reason) ensures the connection is torn down when the handler returns, even on panic. No separate idle-timeout goroutine is needed because the ping/pong cycle detects silent disconnects within ~20 seconds.
View Source
const MinPasswordLength = 8

MinPasswordLength is the minimum required password length.

Variables

View Source
var (
	Version   = "dev"
	BuildTime = "unknown"
	GoVersion = "unknown"
)

Version info variables — set at build time from main.go.

Functions

func HashPassword

func HashPassword(password string) (string, error)

HashPassword hashes a plaintext password using bcrypt. Returns an error if the password is shorter than MinPasswordLength.

func SPAHandler

func SPAHandler() http.Handler

SPAHandler serves the embedded React SPA, falling back to index.html for client-side routing.

func StartZabbixAgent

func StartZabbixAgent(ctx context.Context, addr string, m *metrics.Metrics, c *cache.Cache, logger *slog.Logger) error

StartZabbixAgent starts a TCP listener implementing the Zabbix agent protocol (ZBXD header).

func ValidatePassword

func ValidatePassword(password string) error

ValidatePassword checks if a password meets minimum requirements.

Types

type AdminServer

type AdminServer struct {
	// contains filtered or unexported fields
}

AdminServer provides the admin dashboard HTTP backend.

func NewAdminServer

func NewAdminServer(cfg *config.Config, c *cache.Cache, m *metrics.Metrics, r *resolver.Resolver, logger *slog.Logger, bl *blocklist.Manager) (*AdminServer, error)

NewAdminServer creates a new AdminServer. The bl parameter is optional and may be nil when the blocklist feature is disabled.

func (*AdminServer) CertManager added in v0.5.5

func (s *AdminServer) CertManager() *certmanager.Manager

CertManager returns the auto-TLS certificate manager (may be nil).

func (*AdminServer) RecordQuery

func (s *AdminServer) RecordQuery(client, qname, qtype, rcode string, cached bool, durationMs float64)

RecordQuery is called from the DNS handler hook to log a query.

func (*AdminServer) SetCertManager added in v0.5.5

func (s *AdminServer) SetCertManager(cm *certmanager.Manager)

SetCertManager sets the auto-TLS certificate manager.

func (*AdminServer) SetConfigPath

func (s *AdminServer) SetConfigPath(path string)

func (*AdminServer) SetDoHEnabled

func (s *AdminServer) SetDoHEnabled(enabled bool)

SetDoHEnabled enables or disables the DoH endpoint.

func (*AdminServer) SetDoHHandler

func (s *AdminServer) SetDoHHandler(h server.Handler)

SetDoHHandler sets the DNS handler used for DoH requests.

func (*AdminServer) SetQuerySampleEvery added in v0.8.32

func (s *AdminServer) SetQuerySampleEvery(n uint64)

SetQuerySampleEvery sets how often cached successful queries get a full RecordQuery (top lists + query log + client counters). 0 or 1 records every query. Timeseries is always updated.

func (*AdminServer) SetRuntimeApplier added in v0.6.8

func (s *AdminServer) SetRuntimeApplier(fn func(*config.Config))

SetRuntimeApplier registers a callback invoked after a successful /api/config/raw save. The runtime uses it to hot-apply settings that do not require a process restart (e.g. security.private_address_filter, blocklist toggles). Settings the runtime cannot reload at runtime (listen addresses, TLS material, web server bind) still need a restart.

func (*AdminServer) Start

func (s *AdminServer) Start(ctx context.Context) error

Start starts the HTTP server and blocks until the context is cancelled.

func (*AdminServer) StartUpdateChecker

func (s *AdminServer) StartUpdateChecker(ctx context.Context)

StartUpdateChecker runs a background goroutine that periodically checks for updates.

type Bucket

type Bucket struct {
	Timestamp          string  `json:"timestamp"`
	Queries            int64   `json:"queries"`
	CacheHits          int64   `json:"cache_hits"`
	CacheMisses        int64   `json:"cache_misses"`
	Errors             int64   `json:"errors"`
	AvgLatencyMs       float64 `json:"avg_latency_ms"`
	CacheHitRatio      float64 `json:"cache_hit_ratio"`
	FallbackQueries    int64   `json:"fallback_queries"`
	FallbackRecoveries int64   `json:"fallback_recoveries"`
}

Bucket represents an aggregated time-series data point.

type QueryEntry

type QueryEntry struct {
	ID           uint64  `json:"id"`
	GlobalNum    uint64  `json:"global_num"`
	ClientNum    uint64  `json:"client_num"`
	Timestamp    string  `json:"ts"`
	Client       string  `json:"client"`
	QName        string  `json:"qname"`
	QType        string  `json:"qtype"`
	RCode        string  `json:"rcode"`
	Cached       bool    `json:"cached"`
	DurationMs   float64 `json:"duration_ms"`
	Blocked      bool    `json:"blocked"`
	DNSSECStatus string  `json:"dnssec_status,omitempty"`
}

QueryEntry represents a single DNS query log entry.

type QueryLog

type QueryLog struct {
	// contains filtered or unexported fields
}

QueryLog is a thread-safe ring buffer of DNS query entries with pub/sub support.

func NewQueryLog

func NewQueryLog(capacity int) *QueryLog

NewQueryLog creates a new QueryLog with the given ring buffer capacity. Values <= 0 fall back to the 1000-entry default; values above MaxQueryLogCapacity are clamped to MaxQueryLogCapacity rather than rejected so an over-eager config doesn't fail-stop the resolver — it just trims the buffer to the cap.

func (*QueryLog) Recent

func (ql *QueryLog) Recent(n int) []QueryEntry

Recent returns the last n entries in chronological order.

func (*QueryLog) Record

func (ql *QueryLog) Record(entry QueryEntry)

Record adds an entry to the ring buffer and fans out to all subscribers.

func (*QueryLog) Subscribe

func (ql *QueryLog) Subscribe() (uint64, <-chan QueryEntry)

Subscribe returns a unique subscription ID and a channel that receives new entries. When the subscriber cap is hit, returns id=0 and a closed channel so the caller's read loop exits immediately — the client gets a clean disconnect instead of a silently-dropped subscription.

func (*QueryLog) Unsubscribe

func (ql *QueryLog) Unsubscribe(id uint64)

Unsubscribe removes a subscriber and closes its channel. id=0 is the sentinel returned by Subscribe when the cap was hit; no-op in that case.

type SetupRequest

type SetupRequest struct {
	ListenAddr     string  `json:"listen_addr"`
	WebAddr        string  `json:"web_addr"`
	Username       string  `json:"username"`
	Password       string  `json:"password"`
	MaxCacheSize   int     `json:"max_cache_size"`
	MaxDepth       int     `json:"max_depth"`
	RateLimitRate  float64 `json:"rate_limit_rate"`
	RateLimitBurst int     `json:"rate_limit_burst"`
	LogLevel       string  `json:"log_level"`
	LogFormat      string  `json:"log_format"`
}

SetupRequest represents the JSON body for the setup completion endpoint.

type TimeSeriesAggregator

type TimeSeriesAggregator struct {
	// contains filtered or unexported fields
}

TimeSeriesAggregator collects rolling bucketed counters at 1-second intervals. Record is lock-free on the steady-state path (same second); rotation and Snapshot take mu.

func NewTimeSeriesAggregator

func NewTimeSeriesAggregator() *TimeSeriesAggregator

NewTimeSeriesAggregator creates a new time-series aggregator.

func (*TimeSeriesAggregator) ForceRotateForTest added in v0.8.32

func (ts *TimeSeriesAggregator) ForceRotateForTest()

ForceRotateForTest flushes hot counters into buckets without advancing the logical second. Used by unit tests that previously rewound current.ts.

func (*TimeSeriesAggregator) LatestBuckets added in v0.8.32

func (ts *TimeSeriesAggregator) LatestBuckets(n int) []Bucket

LatestBuckets returns up to n most recent sealed+current buckets (for WS delta).

func (*TimeSeriesAggregator) Record

func (ts *TimeSeriesAggregator) Record(cached bool, latencyMs float64, isError bool)

Record records a single query into the current time bucket.

func (*TimeSeriesAggregator) RecordFallback added in v0.6.2

func (ts *TimeSeriesAggregator) RecordFallback(query, recovery int64)

RecordFallback records one fallback query attempt and optionally one recovery.

func (*TimeSeriesAggregator) Snapshot

func (ts *TimeSeriesAggregator) Snapshot(window time.Duration) []Bucket

Snapshot returns all buckets within the given time window.

func (*TimeSeriesAggregator) SnapshotAggregated added in v0.5.2

func (ts *TimeSeriesAggregator) SnapshotAggregated(window, interval time.Duration) []Bucket

SnapshotAggregated returns buckets within the given window, aggregated into super-buckets of the given interval. For example, window=15m and interval=1m produces ~15 data points. Each super-bucket sums queries/hits/misses/errors and computes a weighted-average latency plus cache-hit ratio.

type TopEntry

type TopEntry struct {
	Key   string `json:"key"`
	Count int64  `json:"count"`
}

TopEntry represents a single entry in a top-N leaderboard.

type TopTracker

type TopTracker struct {
	// contains filtered or unexported fields
}

TopTracker is a concurrent top-N tracker that counts occurrences of string keys.

func NewTopTracker

func NewTopTracker(limit int) *TopTracker

NewTopTracker creates a new TopTracker with the given limit.

func (*TopTracker) Inc

func (t *TopTracker) Inc(key string)

Inc increments the count for the given key. If the map exceeds limit*10, low-count entries are pruned.

func (*TopTracker) Top

func (t *TopTracker) Top(n int) []TopEntry

Top returns the top N entries sorted descending by count.

func (*TopTracker) TopPage

func (t *TopTracker) TopPage(limit, offset int) ([]TopEntry, int)

TopPage returns a paginated top list sorted descending by count.

type UpdateInfo

type UpdateInfo struct {
	CurrentVersion  string `json:"current_version"`
	LatestVersion   string `json:"latest_version"`
	UpdateAvailable bool   `json:"update_available"`
	ReadOnly        bool   `json:"read_only"`
	ReadOnlyHint    string `json:"read_only_hint,omitempty"`
	ReleaseURL      string `json:"release_url,omitempty"`
	ReleaseNotes    string `json:"release_notes,omitempty"`
	AssetName       string `json:"asset_name,omitempty"`
}

UpdateInfo holds information about available updates.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL