Implementation

TAK-OS DNS is a Go module named tak-os-dns; go.mod requires Go 1.26.0. The runtime is one statically built executable with embedded console assets. Read the architecture before changing ownership, publication or concurrency behaviour, and use the testing guide for validation.

Source map

Path Responsibility
cmd/tak-os-dns/main.go JSON structured logging, environment loading, engine construction, SIGINT/SIGTERM cancellation and exit status.
internal/app/options.go Startup environment parsing, address/domain/identity checks and legacy outbound key-map loading.
internal/app/keys.go Strong local key generation, reloadable Kubernetes/file credentials, key summaries and explicit private export.
internal/app/management.go CR/settings API hooks, topology supplier/persistence and self quarantine.
internal/peers/credentials.go Dynamic local HMAC-SHA256 provider, independent outbound key lookup and self disabling.
internal/peers/topology.go Authenticated paginated site catalogue, separate from local-only DNS snapshots.
internal/web/management.go Per-object CR, key and settings HTTP routes.
internal/app/app.go Dependency wiring, configuration reads/saves, local reconciliation, readiness, listener lifecycle and composed metrics.
internal/model/model.go Config/snapshot data types, DNS normalization and validation, canonical source records and content fingerprints.
internal/cache/cache.go Source-owned snapshots, immutable merged serving views, zone-scoped indexes, coherent publication stamps and query resolution.
internal/dnsserver/server.go UDP/TCP listeners, admission bounds, authoritative response framing, RD-aware refusal of unanswered stub referrals, EDNS, compression and RRset-safe truncation.
internal/peers/peers.go Peer status/scheduling, configured-source identity checks, signed request handling, persistent-connection page fetches and rollback checks.
internal/peers/journal.go Full/delta encoding, immutable payload tokens, bounded export caches and signed notification delivery.
internal/peers/retransfer.go Selected forced-full-transfer requests that preserve retained data and rollback watermarks.
internal/kube/client.go Small HTTP Kubernetes client, kubeconfig/in-cluster credentials, TLS trust and API errors.
internal/kube/resources.go CR CRUD/validation, per-object optimistic writes, complete CR collection versions and change detection.
internal/kube/discovery.go Persisted site metadata/provenance and status-only reconciliation.
internal/kube/secrets.go Secret lifecycle, settings and local DNS endpoint discovery.
internal/kube/watch.go Shared settings/config types and legacy helpers.
internal/kube/snapshot.go Complete paginated resource lists and generation of local records without mandatory zones.
internal/web/server.go Internal HTTP routes, strict request decoding, embedded static files and browser security headers.
internal/web/validate.go Bounded local/public DNS diagnostics and normalized comparisons.
internal/web/static/ Plain HTML, CSS and JavaScript console; no frontend compilation or package-manager step.
internal/telemetry/metrics.go Prometheus text counters/histograms with bounded query-type/RCODE labels.
deploy/ Example Kubernetes resources, Ingress example and offline manifest tests.
examples/config.json Versioned static configuration example.
test.sh Replace, build and run the local development container with writable file configuration.
scripts/container-smoke.sh Opt-in Docker runtime smoke harness.

The direct DNS dependency is github.com/miekg/dns; sigs.k8s.io/yaml supports kubeconfig parsing and YAML-to-JSON checks. Versions are pinned in go.mod and go.sum; consult those files for the complete dependency set. The Kubernetes client uses the standard HTTP stack rather than generated client-go informers.

Engine lifecycle

The executable validates startup options before creating the engine. File mode omits Kubernetes credentials and ingestion; Kubernetes mode constructs the API client. Configuration content is subsequently loaded by the running worker.

Engine.Run starts the DNS listeners, waits for both transports to activate and starts the internal HTTP listener. It launches a peer manager and a local worker that reloads configuration and publishes complete snapshots. Kubernetes mode also launches a one-second complete-CR change detector. A single-entry change channel requests an early local refresh after accepted configuration changes; the normal polling ticker remains the recovery mechanism.

The peer manager serializes refresh passes and drains separate coalescing refresh and notification queues. Ordinary queries read immutable cached data and perform no Kubernetes or peer network I/O. Export preparation can encode a new local publication once; later unchanged polls and continuation pages reuse cached data.

Readiness combines valid configuration, a successful local publication, initial peer-attempt completion and the stopping flag. Later source/configuration errors are reported while last-good state remains available. HTTP or DNS listener failure cancels the engine. On termination, HTTP/DNS drain and workers receive cancellation within the configured shutdown budget.

Configuration persistence

The configuration reference defines the public schema and reload rules. Internally, configuration reads/publication and UI saves are serialized with applyMu; the readiness/status mutex is not held across a cache rebuild. A completed resource refresh checks that its configuration version still matches before publishing, so an old candidate cannot overwrite a later accepted edit.

Kubernetes mode assembles DNSZone, DNSRecords and PeerSites only in the administration namespace. Services, Nodes, Ingresses and optional ExternalIPBindings are listed cluster-wide. Each CRUD operation validates one object and the proposed previously-valid aggregate before mutation, retains unrelated metadata/status, and uses that object's resourceVersion. Discovery uses the separate PeerSite status subresource. Aggregate configuration PUT is rejected to preserve administrative grouping and controller ownership. Settings update only queryLogging in the named ConfigMap and can create it when absent.

The local refresh obtains exact CR definitions and associated collection/object versions in the same read path as the snapshot, preventing newer metadata from being attached to older records. A one-second change detector also notices CR changes; these are complete reads, not generated client informers. Kubernetes resource kinds remain independent API observations.

Local and outbound keys have a separate lock/reload path. Initial local creation uses 32 crypto/rand bytes, GET-before-create and AlreadyExists recovery. Existing invalid keys are not overwritten; malformed updates retain last-valid material. Each local cycle reloads local/remote credentials, and successful management saves reload immediately. The DNS listener's dynamic TsigProvider queries current local material per sign/verify call, independent of configured outbound relationships. Remote credential replacement/removal triggers peer refresh. No remote keys are automatically distributed or written to other sites.

In file mode, reads and writes share fileMu. The configuration version is a SHA-256 of the exact file bytes. A save compares that version, normalizes and pretty-prints the candidate, and checks the complete final size including the trailing newline against the 2 MiB reader limit before changing the file. It writes a mode-0600 temporary file in the destination directory, syncs/closes it and atomically renames it into place. Failed validation/size checks preserve the existing file and serving state. These file locks coordinate this process only; there is no multi-process file compare-and-swap service.

File and HTTP JSON decoders reject unknown fields and additional JSON documents. File saves submit a whole configuration; Kubernetes UI/API writes individual CRs, Secrets and settings with independent versions. The management API reference documents its request and response contracts.

Kubernetes client and recovery

The client supports in-cluster service-account credentials, token/client-certificate kubeconfig credentials and an explicitly configured API URL. Credential token files are read for each request so token rotation is observed. Exec/auth-provider plugins are unsupported. TLS uses at least TLS 1.2 and the configured/system CA trust. Authentication setup and permissions belong in running and Kubernetes resources.

Configuration change detection performs complete current CR reads, normalizes the assembled result and publishes only changed versions. Local refresh additionally builds the source from coherent CR contents/watermarks. A failed list/validation retains the last-good source and reports an error. Source objects and credentials are polled/reloaded without deleting data on partial failure.

Resource ingestion requests lists with limit=500 and follows continuation tokens. A list operation has a 30-second context, a 10,000-page bound and a 1,000,000-object bound. Each page must have items and the same nonempty collection resource version; repeated continuation tokens are rejected. All required resource collections must complete before a source candidate is returned. The public name and address generation rules are specified in records. Metadata annotations are read from the same complete source lists. The reader suppresses ignored Services and their dependent bindings, then builds a class-to-Service-name registry from annotated exposed Services. Explicit-class Ingresses produce source-owned CNAMEs. Ambiguous class claims reject the candidate; classless, unmapped and ignored Ingresses are skipped. No IngressClass API read or additional RBAC is needed.

HTTP and observability boundaries

The console is embedded with Go's embed package. Changes to static/* require rebuilding the binary/image. The handler uses strict JSON request decoding, method checks, same-origin write checks and a restrictive content-security policy. It intentionally supplies no user login, application roles or TLS termination; those belong to the authenticated internal management route. See security.

DNS diagnostics accept names/types, not arbitrary resolver destinations. Runtime destinations are this pod, Google and Cloudflare; test code can inject local resolver mocks through a Go option. Validation concurrency and request timeouts are bounded independently of ordinary DNS query workers. Comparison details are in DNS validation.

Metrics combine the telemetry package with engine/cache/listener/peer state. Detailed query logging is controlled by the cluster configuration and can include queried names. TSIG secrets remain runtime credential state backed by Secrets/key files, outside serialized DNS configuration and discovery. Explicit private export is available only through the management key API. Metric names, coverage and troubleshooting use are documented in observability.

Static builds and container image

From the repository root:

go mod download
CGO_ENABLED=0 go build -trimpath -o /tmp/tak-os-dns ./cmd/tak-os-dns
docker build -t tak-os-dns:dev .

The multi-stage Dockerfile uses golang:alpine, downloads dependencies before copying the rest of the source and builds with CGO_ENABLED=0, -trimpath and -ldflags='-s -w'. Its final stage is FROM scratch, copying only the binary and CA certificate bundle. It runs as UID/GID 65532:65532, exposes DNS UDP/TCP 53 and HTTP TCP 8080, and starts /tak-os-dns. There is no shell or package manager in the runtime image.

The builder tag is floating rather than a pinned image digest. Release image selection and reproducibility are operational concerns; the source Go version requirement remains explicit in go.mod. Builds and tests do not themselves deploy, push an image or publish a release.

CI pipeline

.gitlab-ci.yml defines test, build, assemble and publish stages and includes shared container-build, Viking documentation and GitLab SAST templates. The locally defined Go jobs use golang:alpine and cache module downloads keyed by go.sum:

Job Repository-defined work
go-check Requires gofmt -l cmd internal to be empty; runs vet, a CGO-disabled build and ordinary tests.
go-race Installs GCC/musl development tools and runs CGO_ENABLED=1 go test -race ./....
ui-check Uses node:22-alpine, checks app.js syntax and runs scripts/ui-test.cjs for console helper/resource/key contracts.
go-benchmark Runs cache/listener benchmarks for one second with allocation reporting.
sast Uses the included security template in the test stage.
documentation-publish Runs on tags; uses protected CI authentication and shared Viking rewrite/delete/upload/publish steps for docs/.

The documentation job treats Markdown READMEs as folder landing pages, publishing under /components/tak-os-dns with docs/ removed from the URI prefix. Its Python image installs markdown-it-py and mdurl, plus the command-line tools needed by the shared template. External template internals and deployment-specific CI credentials are managed outside this repository; inspect those templates when changing the shared release process.

Making a change

Preserve source ownership, local-only exports, authoritative retention, address-over-CNAME masking, zone-independent positives, REFUSED unknown names, authoritative known-name NODATA and the prohibition on recursion. Keep topology metadata transitively shareable while record snapshots remain local-only; discovery never carries credentials. Validate complete candidates before publishing them, keep network calls outside cache locks and ordinary query handlers, and add tests at the boundary that changes.

Update the relevant design/reference/usage/operations documents and examples or manifests when behaviour changes. Folder READMEs are compact indexes. Keep TODO.md for concrete remaining work and limitations; unexecuted deployment, load and long-soak acceptance checks must remain open. The exact verification commands and their limits are in testing.

UI and container verification boundaries

The Node UI harness imports exported pure console helpers and checks resource/ credential data contracts and selected source-level security properties. CI's ui-check job runs it separately from Go tests; it checks version/metadata preservation, endpoint precedence and key/resource parsing without a full browser. It does not validate actual Ingress authentication, a real Kubernetes server or rendered browser layout.

The container smoke test mounts sample config read-only and provides a separate writable, owner-scoped tmpfs for TSIG_FILE so automatic key creation works while the root filesystem remains read-only. Smoke keys are ephemeral and removed with the test container; production credentials belong in Kubernetes Secrets.

SnapshotResources reuses the already normalized, flattened CR record order when assigning dnsrecords/ ownership back to each group. It avoids normalizing every zone again for each DNSRecords object, keeping ownership assignment linear in the grouped record count. Exact CR collection/object versions still accompany the definitions used for that snapshot; optimization does not replace validation or attach versions from a later unrelated configuration read.

Known-name type misses return NOERROR/NODATA with AA true; the authority SOA is attached only when present in the selected zone's generated metadata. Completely unknown owners remain REFUSED and never NXDOMAIN. This separates the selected single-family resolver compatibility policy from the RD-aware refusal of unanswered parent referrals. The response code alone does not distinguish positive NOERROR from NODATA.

For an independently known owner below a parent delegation, missing-type NODATA does not attach the parent's SOA. Only an applicable uncut zone can supply SOA authority; independent existence does not promote an existing parent-owned glue RRset into an authoritative answer.