Compare commits
14
Commits
29f210de86
...
v1.0.0-rc2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b79726acc6 | ||
|
|
aaccabad50 | ||
|
|
6b580a5a0f | ||
|
|
cb89e4f8cf | ||
|
|
9e6871817a | ||
|
|
3592302615 | ||
|
|
79761c29e1 | ||
|
|
b9686c6d7b | ||
|
|
5617c92fb3 | ||
|
|
2ae6110414 | ||
|
|
39e7bc9067 | ||
|
|
02cb1ec580 | ||
|
|
e8b40062da | ||
|
|
d1060315b7 |
+75
-9
@@ -1,9 +1,75 @@
|
|||||||
# .git is sent, without its config: the builder stage derives the version it
|
# .dockerignore does NOT use .gitignore semantics. Docker matches with
|
||||||
# stamps into the binary from it, and `git describe` does not need the config,
|
# moby/patternmatcher: filepath.Match plus `**`, so `*` does not cross
|
||||||
# which can hold a credential (a password in the remote URL, a CI token). No
|
# `/` and an unprefixed pattern is anchored at the context root. Every
|
||||||
# tracked file may be listed here: git in the build would see it as deleted
|
# depth-independent pattern therefore needs `**/`, or `config/.env` and
|
||||||
# and mark the version -dirty, and an excluded .md would silently drop out of
|
# `certs/server.key` still ship while this file reads as solved. Only
|
||||||
# the prettier check in Dockerfile.fmt.
|
# genuinely root-anchored entries go unprefixed. Never transplant these
|
||||||
.git/config
|
# into .gitignore, where `**/` is wrong.
|
||||||
bin/
|
#
|
||||||
node_modules/
|
# Matching is case-sensitive, so secrets use character ranges rather
|
||||||
|
# than an ALL-CAPS twin, which would still miss `Server.Key`.
|
||||||
|
#
|
||||||
|
# Extend with this repo's own host-built artifacts, written anchored:
|
||||||
|
# `/myapp`, never `**/myapp`, which also matches `cmd/myapp/` and
|
||||||
|
# deletes the package directory from the context.
|
||||||
|
|
||||||
|
# .git is sent without its config. Without a VERSION build argument the
|
||||||
|
# stage that compiles runs `git describe --tags --always` on .git, which
|
||||||
|
# does not need .git/config; that file can hold a credential, such as a
|
||||||
|
# password in a remote URL or the token the CI checkout step stores there.
|
||||||
|
# Each submodule keeps a config with the same exposure in its git directory
|
||||||
|
# under .git/modules/, nested again for a submodule's own submodules, or in
|
||||||
|
# its own .git directory when it keeps one.
|
||||||
|
# KNOWN GAP: a submodule whose name has a `config` segment (`config`,
|
||||||
|
# `deploy/config`, `config/lib`) loses its whole git directory, because
|
||||||
|
# `**/.git/modules/**/config` also matches that segment's directory
|
||||||
|
# under .git/modules/. Go's version stamping then fails the build;
|
||||||
|
# nothing leaks. Name such a submodule without that segment:
|
||||||
|
# `git submodule add --name`.
|
||||||
|
**/.git/config
|
||||||
|
**/.git/modules/**/config
|
||||||
|
|
||||||
|
# Agent scratch: one full checkout of the repo per in-flight agent.
|
||||||
|
# Anchored because it occurs once where agents run at the repo root.
|
||||||
|
# KNOWN GAP: a repo running agents in subdirectories still ships
|
||||||
|
# `services/api/.claude/` and must add its own anchored entry.
|
||||||
|
.claude
|
||||||
|
|
||||||
|
# Environment files. `*.env` covers bare `.env` and the `prod.env`
|
||||||
|
# convention. Re-include a committed template with a negation if the
|
||||||
|
# build needs one: `!docs/example.env`.
|
||||||
|
**/*.[eE][nN][vV]
|
||||||
|
**/.[eE][nN][vV].*
|
||||||
|
**/.[eE][nN][vV][rR][cC]
|
||||||
|
|
||||||
|
# Private keys and the bundles carrying them. Public certificates
|
||||||
|
# (*.crt, *.cer) are deliberately absent: they are legitimate inputs.
|
||||||
|
**/*.[pP][eE][mM]
|
||||||
|
**/*.[kK][eE][yY]
|
||||||
|
**/*.[pP]12
|
||||||
|
**/*.[pP][fF][xX]
|
||||||
|
**/[iI][dD]_[rR][sS][aA]
|
||||||
|
**/[iI][dD]_[dD][sS][aA]
|
||||||
|
**/[iI][dD]_[eE][cC][dD][sS][aA]
|
||||||
|
**/[iI][dD]_[eE][cC][dD][sS][aA]_[sS][kK]
|
||||||
|
**/[iI][dD]_[eE][dD]25519
|
||||||
|
**/[iI][dD]_[eE][dD]25519_[sS][kK]
|
||||||
|
|
||||||
|
# Dependencies: restored inside the image, never copied in.
|
||||||
|
**/node_modules
|
||||||
|
|
||||||
|
# OS metadata.
|
||||||
|
**/.DS_Store
|
||||||
|
**/Thumbs.db
|
||||||
|
|
||||||
|
# Editor state: never a build input, and it churns COPY.
|
||||||
|
**/*.swp
|
||||||
|
**/*.swo
|
||||||
|
**/*~
|
||||||
|
**/*.bak
|
||||||
|
**/.idea
|
||||||
|
**/.vscode
|
||||||
|
**/*.sublime-*
|
||||||
|
|
||||||
|
# This repository's host-built artifacts: `make build` writes bin/.
|
||||||
|
/bin
|
||||||
|
|||||||
@@ -10,3 +10,6 @@ insert_final_newline = true
|
|||||||
|
|
||||||
[Makefile]
|
[Makefile]
|
||||||
indent_style = tab
|
indent_style = tab
|
||||||
|
|
||||||
|
[*.go]
|
||||||
|
indent_style = tab
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ jobs:
|
|||||||
check:
|
check:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
# actions/checkout v4.2.2, 2026-02-28
|
# actions/checkout v4.2.2, 2026-02-22
|
||||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||||
# script/cibuild needs no token, so none is left in .git/config.
|
# script/cibuild needs no token, so none is left in .git/config.
|
||||||
with:
|
with:
|
||||||
|
|||||||
+52
-2
@@ -1,7 +1,57 @@
|
|||||||
bin/
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Editors
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
*.bak
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.sublime-*
|
||||||
|
|
||||||
|
# Agent scratch (worktrees of this repo, created and destroyed by
|
||||||
|
# in-flight tooling). Unanchored: .gitignore patterns already match at
|
||||||
|
# every depth, so no prefix is wanted here. This is not a .dockerignore
|
||||||
|
# entry and must not be given a `**/` prefix on the way into one.
|
||||||
|
.claude/
|
||||||
|
|
||||||
|
# Node
|
||||||
node_modules/
|
node_modules/
|
||||||
|
|
||||||
|
# Secrets. Unanchored like every entry above, so each matches at every
|
||||||
|
# depth. Matching is case-sensitive on Linux, so names use character
|
||||||
|
# ranges rather than a lowercase form that misses `Server.Key`.
|
||||||
|
|
||||||
|
# Environment files. `*.env` covers bare `.env` and the `prod.env`
|
||||||
|
# convention. Only the templates `example.env` and `sample.env` are
|
||||||
|
# re-included below. A repository that commits any other template adds
|
||||||
|
# its own negation after these lines, for example `!.env.example`.
|
||||||
|
*.[eE][nN][vV]
|
||||||
|
.[eE][nN][vV].*
|
||||||
|
.[eE][nN][vV][rR][cC]
|
||||||
|
!example.env
|
||||||
|
!sample.env
|
||||||
|
|
||||||
|
# Private keys and the bundles carrying them.
|
||||||
|
*.[pP][eE][mM]
|
||||||
|
*.[kK][eE][yY]
|
||||||
|
*.[pP]12
|
||||||
|
*.[pP][fF][xX]
|
||||||
|
[iI][dD]_[rR][sS][aA]
|
||||||
|
[iI][dD]_[dD][sS][aA]
|
||||||
|
[iI][dD]_[eE][cC][dD][sS][aA]
|
||||||
|
[iI][dD]_[eE][cC][dD][sS][aA]_[sS][kK]
|
||||||
|
[iI][dD]_[eE][dD]25519
|
||||||
|
[iI][dD]_[eE][dD]25519_[sS][kK]
|
||||||
|
|
||||||
|
# This repository's own entries, kept after the canonical content above.
|
||||||
|
*.log
|
||||||
|
*.out
|
||||||
|
*.test
|
||||||
|
bin/
|
||||||
vendor/
|
vendor/
|
||||||
data/
|
data/
|
||||||
.env
|
|
||||||
*.exe
|
*.exe
|
||||||
/dnswatcher
|
/dnswatcher
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ linters:
|
|||||||
disable:
|
disable:
|
||||||
# Genuinely incompatible with project patterns
|
# Genuinely incompatible with project patterns
|
||||||
- exhaustruct # Requires all struct fields
|
- exhaustruct # Requires all struct fields
|
||||||
|
- exhaustruct_v5 # Requires all struct fields (successor to exhaustruct)
|
||||||
- godot # Requires comments to end with periods
|
- godot # Requires comments to end with periods
|
||||||
- wrapcheck # Too verbose for internal packages
|
- wrapcheck # Too verbose for internal packages
|
||||||
- varnamelen # Short names like db, id are idiomatic Go
|
- varnamelen # Short names like db, id are idiomatic Go
|
||||||
|
|||||||
+1
-4
@@ -1,5 +1,2 @@
|
|||||||
bin/
|
|
||||||
data/
|
|
||||||
node_modules/
|
node_modules/
|
||||||
.claude/
|
yarn.lock
|
||||||
static/css/tailwind.min.css
|
|
||||||
|
|||||||
+83
-49
@@ -1,68 +1,102 @@
|
|||||||
# Lint stage - fast feedback on lint issues, before the build starts.
|
# Lint phase, built alone by script/lint. The linter is invoked directly
|
||||||
# The linter is invoked directly rather than through `make lint`: that
|
# rather than through `make lint`, which is itself a docker build and
|
||||||
# target shells out to `docker build -f Dockerfile.lint`, and there is
|
# would recurse into a daemon that does not exist in a build step.
|
||||||
# no docker daemon inside a docker build. For the same reason this stage
|
# golangci/golangci-lint:v2.14.0 (Debian-based), 2026-10-06
|
||||||
# runs only the Go half of `make fmt-check`; script/cibuild runs the
|
FROM golangci/golangci-lint@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f AS lint
|
||||||
# markdown half after this build.
|
|
||||||
# script/cibuild and script/docker name this stage in --no-cache-filter.
|
|
||||||
# golangci/golangci-lint:v2.12.2 (Debian-based), 2026-08-10
|
|
||||||
FROM golangci/golangci-lint:v2.12.2@sha256:5cceeef04e53efe1470638d4b4b4f5ceefd574955ab3941b2d9a68a8c9ad5240 AS lint
|
|
||||||
|
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
RUN script/fmt-check-go
|
|
||||||
RUN golangci-lint run --config .golangci.yml ./...
|
RUN golangci-lint run --config .golangci.yml ./...
|
||||||
|
|
||||||
# Build stage
|
# Test phase, built alone by script/test. -race needs cgo and so a C
|
||||||
# script/cibuild and script/docker name this stage in --no-cache-filter.
|
# compiler, which the Debian Go image ships and the alpine one does not.
|
||||||
# golang 1.25-alpine, 2026-02-28
|
# The tests query live DNS (TESTING.md), so this step needs the network.
|
||||||
FROM golang@sha256:f6751d823c26342f9506c03797d2527668d095b0a15f1862cddb4d927a7a4ced AS builder
|
# -count=1 keeps Go's test result cache out of both runs, as TESTING.md
|
||||||
|
# requires. -timeout 90s is a backstop above the 60-second cap on the
|
||||||
RUN apk add --no-cache git make gcc musl-dev binutils-gold
|
# suite. The rerun with -v only shows details: the build fails however
|
||||||
|
# it ends, because the first run already failed.
|
||||||
# A build context sent as a tar archive keeps its files' owners, and git
|
# golang 1.25.7-trixie, 2026-10-06
|
||||||
# refuses to read a checkout owned by another user. Trust this one
|
FROM golang@sha256:2b174ffcf56c7ad0c47d30d2630693265639ddf2a5141149c2da34db921791b4 AS test
|
||||||
# whoever owns it.
|
# The file permission tests skip themselves as root, so the tests run as
|
||||||
RUN git config --system --add safe.directory /src
|
# an ordinary user, whose home directory holds Go's build cache.
|
||||||
|
RUN useradd --create-home tester
|
||||||
# Force BuildKit to run the lint stage before proceeding
|
USER tester
|
||||||
COPY --from=lint /src/go.sum /dev/null
|
|
||||||
|
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
|
COPY . .
|
||||||
|
RUN go test -count=1 -race -timeout 90s -cover ./... || \
|
||||||
|
{ echo "--- Rerunning with -v for details ---"; \
|
||||||
|
go test -count=1 -race -timeout 90s -v ./...; exit 1; }
|
||||||
|
|
||||||
|
# Markdown formatting with prettier, at the version package.json and
|
||||||
|
# yarn.lock pin, so it is never installed on the host. script/fmt-check
|
||||||
|
# builds the fmt-check stage and script/fmt the fmt-out stage; the image
|
||||||
|
# does not depend on any of these stages, so a plain `docker build .`
|
||||||
|
# skips them.
|
||||||
|
# node:22-bookworm-slim, 2026-09-05
|
||||||
|
FROM node@sha256:83f487e0a63425e5b4d146fb5e5be574bcbe1b7b843d3ebafdd95eaf7767a7e5 AS nodedeps
|
||||||
|
# prettier lives outside /src, so the COPY of the repo cannot overwrite
|
||||||
|
# it and node_modules is not in the tree prettier walks.
|
||||||
|
WORKDIR /tools
|
||||||
|
COPY package.json yarn.lock ./
|
||||||
|
RUN yarn install --frozen-lockfile --non-interactive --no-progress
|
||||||
|
ENV PATH="/tools/node_modules/.bin:${PATH}"
|
||||||
|
WORKDIR /src
|
||||||
|
|
||||||
|
# --config rather than discovery: a missing .prettierrc is then an error
|
||||||
|
# instead of prettier's defaults, under which every wrap passes.
|
||||||
|
# --no-editorconfig so .prettierrc alone sets the style.
|
||||||
|
FROM nodedeps AS fmt-check
|
||||||
|
COPY . .
|
||||||
|
RUN prettier --config .prettierrc --no-editorconfig --check "**/*.md"
|
||||||
|
|
||||||
|
# Only the markdown is copied out, with its paths, so the export cannot
|
||||||
|
# put anything else back over the working tree.
|
||||||
|
FROM nodedeps AS fmt
|
||||||
|
COPY . .
|
||||||
|
RUN prettier --config .prettierrc --no-editorconfig --write "**/*.md" && \
|
||||||
|
mkdir -p /out && \
|
||||||
|
find . -name '*.md' -type f -exec cp --parents '{}' /out/ ';'
|
||||||
|
|
||||||
|
FROM scratch AS fmt-out
|
||||||
|
COPY --from=fmt /out/ /
|
||||||
|
|
||||||
|
# Build stage. Nothing is wanted from the lint and test phases; the
|
||||||
|
# copies are what make BuildKit build them first, so this stage cannot
|
||||||
|
# run unless lint and test passed.
|
||||||
|
# golang 1.25-alpine, 2026-02-28
|
||||||
|
FROM golang@sha256:f6751d823c26342f9506c03797d2527668d095b0a15f1862cddb4d927a7a4ced AS builder
|
||||||
|
COPY --from=lint /src/go.sum /dev/null
|
||||||
|
COPY --from=test /src/go.sum /dev/null
|
||||||
|
RUN apk add --no-cache git
|
||||||
|
# A tar-stream context keeps the sender's file owners, which git refuses.
|
||||||
|
RUN git config --system --add safe.directory /src
|
||||||
|
WORKDIR /src
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
# Run the tests - build fails if any test fails
|
# The VERSION build arg when one is given (script/docker and
|
||||||
RUN make test
|
# script/cibuild pass one), otherwise `git describe --tags --always` on
|
||||||
|
# the .git in the build context. With .git present, a version that is
|
||||||
# Version stamped into the binary: the VERSION build arg when one is
|
# still empty, dev or unknown fails the build: git is missing or could
|
||||||
# given and not empty (script/docker passes one), otherwise what
|
# not read the checkout.
|
||||||
# `git describe` says of the .git in the build context, so a plain
|
|
||||||
# `docker build .` of a clone stamps its tag or short commit. The build
|
|
||||||
# arg reaches make through the environment.
|
|
||||||
ARG VERSION
|
ARG VERSION
|
||||||
|
RUN VERSION="${VERSION:-$(git describe --tags --always)}"; \
|
||||||
# A context that carries .git, as a directory or as a file, must yield a
|
|
||||||
# real version: one that is empty, `dev` or `unknown` cannot be traced
|
|
||||||
# back to a commit.
|
|
||||||
RUN version="$(make version)"; \
|
|
||||||
if [ -e .git ]; then \
|
if [ -e .git ]; then \
|
||||||
case "$version" in \
|
case "$VERSION" in ""|dev|unknown) \
|
||||||
"" | dev | unknown) \
|
echo "version is '$VERSION' although .git is present" >&2; \
|
||||||
echo "version is \"$version\" although the build context carries .git" >&2; \
|
exit 1 ;; \
|
||||||
exit 1 ;; \
|
|
||||||
esac; \
|
esac; \
|
||||||
fi
|
fi; \
|
||||||
|
CGO_ENABLED=0 go build -trimpath \
|
||||||
|
-ldflags="-s -w -X main.Version=${VERSION}" \
|
||||||
|
-o /src/bin/dnswatcher ./cmd/dnswatcher/
|
||||||
|
|
||||||
RUN make build
|
# Runtime stage, and the last one: a plain `docker build .` builds this
|
||||||
|
# stage's chain and nothing else.
|
||||||
# Runtime stage
|
|
||||||
# alpine 3.21, 2026-02-28
|
# alpine 3.21, 2026-02-28
|
||||||
FROM alpine@sha256:c3f8e73fdb79deaebaa2037150150191b9dcbfba68b4a46d70103204c53f4709
|
FROM alpine@sha256:c3f8e73fdb79deaebaa2037150150191b9dcbfba68b4a46d70103204c53f4709
|
||||||
|
|
||||||
|
|||||||
@@ -1,54 +0,0 @@
|
|||||||
# prettier over the markdown, in a container, so it is never installed
|
|
||||||
# on the host. script/fmt-check-markdown builds the fmt-check stage;
|
|
||||||
# script/fmt builds fmt-out and takes the formatted files back.
|
|
||||||
|
|
||||||
# node:22-bookworm-slim, 2026-09-05
|
|
||||||
FROM node:22-bookworm-slim@sha256:83f487e0a63425e5b4d146fb5e5be574bcbe1b7b843d3ebafdd95eaf7767a7e5 AS nodedeps
|
|
||||||
|
|
||||||
# prettier lives outside /src so that a `COPY . .` of the repo cannot
|
|
||||||
# overwrite it, and so that node_modules never appears in the tree
|
|
||||||
# prettier is about to walk.
|
|
||||||
WORKDIR /tools
|
|
||||||
|
|
||||||
# package.json pins the version and yarn.lock pins the bytes:
|
|
||||||
# --frozen-lockfile installs exactly the lockfile's resolution and fails
|
|
||||||
# if package.json disagrees with it, so the tool cannot float between
|
|
||||||
# runs. yarn is the one in the image above.
|
|
||||||
COPY package.json yarn.lock ./
|
|
||||||
RUN yarn install --frozen-lockfile --non-interactive --no-progress
|
|
||||||
|
|
||||||
ENV PATH="/tools/node_modules/.bin:${PATH}"
|
|
||||||
|
|
||||||
WORKDIR /src
|
|
||||||
|
|
||||||
# Read-only markdown check. Must match $stage in
|
|
||||||
# script/fmt-check-markdown.
|
|
||||||
FROM nodedeps AS fmt-check
|
|
||||||
|
|
||||||
COPY . .
|
|
||||||
|
|
||||||
# --config, not discovery: a .prettierrc that failed to arrive would
|
|
||||||
# otherwise leave prettier on its defaults, where proseWrap is "preserve"
|
|
||||||
# and every wrap this check exists to enforce passes. Missing the file is
|
|
||||||
# a hard error instead. --no-editorconfig so that .prettierrc alone sets
|
|
||||||
# the style.
|
|
||||||
RUN prettier --config .prettierrc --no-editorconfig --check "**/*.md"
|
|
||||||
|
|
||||||
# Write path. Not a check: script/fmt builds this and takes the files.
|
|
||||||
FROM nodedeps AS fmt
|
|
||||||
|
|
||||||
COPY . .
|
|
||||||
|
|
||||||
RUN prettier --config .prettierrc --no-editorconfig --write "**/*.md"
|
|
||||||
|
|
||||||
# Only the markdown leaves, with its paths intact, so that the export
|
|
||||||
# below cannot put anything else back over the caller's working tree.
|
|
||||||
RUN mkdir -p /out && cd /src && \
|
|
||||||
find . -name '*.md' -type f -exec cp --parents '{}' /out/ ';'
|
|
||||||
|
|
||||||
# Export target: `docker build --target fmt-out --output type=local`
|
|
||||||
# writes /out's tree into a directory on the client, which is how
|
|
||||||
# script/fmt gets formatted markdown back without a bind mount.
|
|
||||||
# Must match $stage in script/fmt.
|
|
||||||
FROM scratch AS fmt-out
|
|
||||||
COPY --from=fmt /out/ /
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
# Lint-only image: used by script/lint. golangci-lint is never run on
|
|
||||||
# the host — the repo is COPYed into the build context and the linter
|
|
||||||
# runs as a build step, so a successful build IS a clean lint. This
|
|
||||||
# also works where the docker daemon is remote and bind mounts are
|
|
||||||
# impossible.
|
|
||||||
#
|
|
||||||
# `golangci-lint config verify` is deliberately NOT run here: it
|
|
||||||
# fetches its JSON schema over a live, unpinned HTTPS call, which would
|
|
||||||
# make linting network-dependent and defeat hash-pinning. The cost of
|
|
||||||
# that: unknown top-level keys in .golangci.yml are silently ignored,
|
|
||||||
# so a mistyped or wrong-schema key lints clean while applying nothing.
|
|
||||||
#
|
|
||||||
# golangci/golangci-lint:v2.12.2 (Debian-based), 2026-08-10
|
|
||||||
FROM golangci/golangci-lint:v2.12.2@sha256:5cceeef04e53efe1470638d4b4b4f5ceefd574955ab3941b2d9a68a8c9ad5240 AS deps
|
|
||||||
|
|
||||||
WORKDIR /src
|
|
||||||
|
|
||||||
# Dependencies first, so this stage stays cached across lint runs.
|
|
||||||
COPY go.mod go.sum ./
|
|
||||||
RUN go mod download
|
|
||||||
|
|
||||||
# Everything below is invalidated on every run by the
|
|
||||||
# --no-cache-filter=lint that script/lint passes: caching is explicitly
|
|
||||||
# waived for linting, and a cached build lints nothing.
|
|
||||||
FROM deps AS lint
|
|
||||||
|
|
||||||
COPY . .
|
|
||||||
|
|
||||||
RUN golangci-lint run --config .golangci.yml ./...
|
|
||||||
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
BINARY := dnswatcher
|
BINARY := dnswatcher
|
||||||
# VERSION given on the command line (`make build VERSION=...`) or in the
|
# VERSION given on the command line (`make build VERSION=...`) or in the
|
||||||
# environment, which is how the Dockerfile's VERSION build arg arrives,
|
# environment wins over what `git describe` says of this checkout. An
|
||||||
# wins over what `git describe` says of this checkout. An empty one counts
|
# empty one counts as not given; `override` is what replaces an empty
|
||||||
# as not given; `override` is what replaces an empty command-line value.
|
# command-line value.
|
||||||
ifeq ($(VERSION),)
|
ifeq ($(VERSION),)
|
||||||
override VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
|
override VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
|
||||||
endif
|
endif
|
||||||
@@ -25,7 +25,7 @@ setup:
|
|||||||
build:
|
build:
|
||||||
go build -ldflags "$(LDFLAGS)" -o bin/$(BINARY) ./cmd/dnswatcher
|
go build -ldflags "$(LDFLAGS)" -o bin/$(BINARY) ./cmd/dnswatcher
|
||||||
|
|
||||||
# Prints the version `make build` stamps; the Dockerfile checks it.
|
# Prints the version `make build` stamps.
|
||||||
version:
|
version:
|
||||||
@echo "$(VERSION)"
|
@echo "$(VERSION)"
|
||||||
|
|
||||||
|
|||||||
@@ -78,8 +78,9 @@ notification endpoint set, changes show only on the dashboard; see
|
|||||||
answer NXDOMAIN, that it does not exist, has no nameservers and is shown as
|
answer NXDOMAIN, that it does not exist, has no nameservers and is shown as
|
||||||
not existing (see Web Dashboard and HTTP API). A domain that exists but has no
|
not existing (see Web Dashboard and HTTP API). A domain that exists but has no
|
||||||
delegation of its own, such as `octocat.github.io`, has no nameservers either.
|
delegation of its own, such as `octocat.github.io`, has no nameservers either.
|
||||||
When the parent zone's servers do not answer, the check fails and the set from
|
When the parent zone's servers do not answer, or the lookup of the domain's
|
||||||
the previous check is kept.
|
own records (below) fails, the check fails and the set from the previous check
|
||||||
|
is kept.
|
||||||
- Any change triggers a notification:
|
- Any change triggers a notification:
|
||||||
- NS added to or removed from that set. A domain that had nameservers on the
|
- NS added to or removed from that set. A domain that had nameservers on the
|
||||||
previous check and no longer exists gets one with all of them removed.
|
previous check and no longer exists gets one with all of them removed.
|
||||||
@@ -99,10 +100,18 @@ notification endpoint set, changes show only on the dashboard; see
|
|||||||
records, stored per nameserver. Their changes are notified as a hostname's
|
records, stored per nameserver. Their changes are notified as a hostname's
|
||||||
are, as a record change, NS query failure, NS recovery, inconsistency or CNAME
|
are, as a record change, NS query failure, NS recovery, inconsistency or CNAME
|
||||||
address change, in a message that starts `Domain:` where a hostname's starts
|
address change, in a message that starts `Domain:` where a hostname's starts
|
||||||
`Hostname:`. A domain with no delegation of its own has these records asked at
|
`Hostname:`. A nameserver removed from the domain's delegation gets only the
|
||||||
the servers of the zone it is in, as a hostname has. A domain that does not
|
NS change notification above. A domain listed in
|
||||||
exist has none: they are not asked for, and those saved by an earlier check
|
`DNSWATCHER_SKIP_RECORD_NOTIFICATIONS` gets no record change or inconsistency
|
||||||
are removed without a notification.
|
notification. A domain with no delegation of its own has these records asked
|
||||||
|
at the servers of the zone it is in, as a hostname has. When none of those
|
||||||
|
servers answers, the lookup of its NS record set fails, and they are saved as
|
||||||
|
failed and notified as a hostname's are (see below). A nameserver the domain's
|
||||||
|
records were asked at on the previous check but not on this one gets a
|
||||||
|
hostname's NS change notification (see below), unless it was in the domain's
|
||||||
|
delegation on the previous check, as when that delegation is withdrawn. A
|
||||||
|
domain that does not exist has none: they are not asked for, and those saved
|
||||||
|
by an earlier check are removed without a notification.
|
||||||
|
|
||||||
### DNS Hostname Monitoring (Subdomains)
|
### DNS Hostname Monitoring (Subdomains)
|
||||||
|
|
||||||
@@ -114,7 +123,13 @@ notification endpoint set, changes show only on the dashboard; see
|
|||||||
trace moves from a name to its parent only when the servers asked answer that
|
trace moves from a name to its parent only when the servers asked answer that
|
||||||
the name has no delegation of its own, or does not exist. When they do not
|
the name has no delegation of its own, or does not exist. When they do not
|
||||||
answer, the check fails and the hostname's records from the previous check are
|
answer, the check fails and the hostname's records from the previous check are
|
||||||
kept.
|
kept, unless they are the nameservers the previous check saved for the
|
||||||
|
hostname. Each of those is then saved as failed, with the reason, as a
|
||||||
|
domain's nameservers are when none of them answers, so it gets an NS query
|
||||||
|
failure notification, and an NS recovery notification when it answers again
|
||||||
|
(see below). A trace that gets no answer before it reaches them, as when the
|
||||||
|
host running dnswatcher loses its network, fails the check without a
|
||||||
|
notification.
|
||||||
- Queries **each** authoritative nameserver independently for **all** record
|
- Queries **each** authoritative nameserver independently for **all** record
|
||||||
types: A, AAAA, CNAME, MX, TXT, SRV, CAA, NS.
|
types: A, AAAA, CNAME, MX, TXT, SRV, CAA, NS.
|
||||||
- Each record type is a query of its own. When a nameserver answers some types
|
- Each record type is a query of its own. When a nameserver answers some types
|
||||||
@@ -136,10 +151,14 @@ notification endpoint set, changes show only on the dashboard; see
|
|||||||
lower case, because names are case-insensitive and nameservers may answer in
|
lower case, because names are case-insensitive and nameservers may answer in
|
||||||
any letter case. TXT and CAA values keep their letter case; they are not
|
any letter case. TXT and CAA values keep their letter case; they are not
|
||||||
lower-cased.
|
lower-cased.
|
||||||
- Any observable change in any nameserver's response triggers a notification.
|
- Any observable change in any nameserver's response triggers a notification,
|
||||||
This includes:
|
except a record change or an inconsistency for a domain or hostname listed in
|
||||||
|
`DNSWATCHER_SKIP_RECORD_NOTIFICATIONS`. This includes:
|
||||||
- **Record change**: A nameserver returns different records than it did on
|
- **Record change**: A nameserver returns different records than it did on
|
||||||
the previous check (additions, removals, value changes).
|
the previous check (additions, removals, value changes). For a domain or
|
||||||
|
hostname listed in `DNSWATCHER_SKIP_RECORD_NOTIFICATIONS`, neither a
|
||||||
|
record change nor an inconsistency is notified; its records are still
|
||||||
|
checked and saved, and its other notifications are sent.
|
||||||
- **NS query failure**: A nameserver that previously responded becomes
|
- **NS query failure**: A nameserver that previously responded becomes
|
||||||
unreachable (timeout, SERVFAIL, REFUSED, network error). This is distinct
|
unreachable (timeout, SERVFAIL, REFUSED, network error). This is distinct
|
||||||
from "responded with no records": a nameserver that answers NXDOMAIN or
|
from "responded with no records": a nameserver that answers NXDOMAIN or
|
||||||
@@ -151,6 +170,10 @@ notification endpoint set, changes show only on the dashboard; see
|
|||||||
- **NS recovery**: A previously-unreachable nameserver starts responding
|
- **NS recovery**: A previously-unreachable nameserver starts responding
|
||||||
again. Its records are not compared with those from before it failed, so a
|
again. Its records are not compared with those from before it failed, so a
|
||||||
change made while it was failing is not reported as a record change.
|
change made while it was failing is not reported as a record change.
|
||||||
|
- **NS change**: A nameserver of the zone the hostname is in on the previous
|
||||||
|
check is not one now, whether or not it answered. One notification lists
|
||||||
|
every such nameserver on a `Removed:` line. Nothing is sent for a
|
||||||
|
nameserver that joins the zone.
|
||||||
- **Inconsistency detected**: Two nameservers return different record sets
|
- **Inconsistency detected**: Two nameservers return different record sets
|
||||||
for the same hostname and did not already differ on the previous check.
|
for the same hostname and did not already differ on the previous check.
|
||||||
Every pair of nameservers is compared. The alert is sent once for each
|
Every pair of nameservers is compared. The alert is sent once for each
|
||||||
@@ -160,7 +183,8 @@ notification endpoint set, changes show only on the dashboard; see
|
|||||||
failed on it, and answers differently is reported on the check where it
|
failed on it, and answers differently is reported on the check where it
|
||||||
answers. So is a pair that differs in a record type whose query to either
|
answers. So is a pair that differs in a record type whose query to either
|
||||||
nameserver failed on the previous check. If a pair agrees again and later
|
nameserver failed on the previous check. If a pair agrees again and later
|
||||||
disagrees, the alert is sent again.
|
disagrees, the alert is sent again. For a domain or hostname listed in
|
||||||
|
`DNSWATCHER_SKIP_RECORD_NOTIFICATIONS`, no inconsistency is notified.
|
||||||
- **CNAME address change**: The addresses at the end of a name's CNAME chain
|
- **CNAME address change**: The addresses at the end of a name's CNAME chain
|
||||||
differ from those of the previous check. They are found when its
|
differ from those of the previous check. They are found when its
|
||||||
nameservers answer with a CNAME and no address; a name that answers with
|
nameservers answer with a CNAME and no address; a name that answers with
|
||||||
@@ -186,9 +210,13 @@ notification endpoint set, changes show only on the dashboard; see
|
|||||||
- Any change in port availability triggers a notification:
|
- Any change in port availability triggers a notification:
|
||||||
- Port transitioned from open to closed (or vice versa).
|
- Port transitioned from open to closed (or vice versa).
|
||||||
- New IP appeared (from DNS change): its port state is recorded without a
|
- New IP appeared (from DNS change): its port state is recorded without a
|
||||||
port notification; the DNS change notification shows the new address.
|
port notification; the DNS change notification shows the new address. A
|
||||||
|
domain or hostname listed in `DNSWATCHER_SKIP_RECORD_NOTIFICATIONS` gets
|
||||||
|
no notification for an address added to its own A or AAAA records.
|
||||||
- IP disappeared (from DNS change) — noted in the DNS change notification;
|
- IP disappeared (from DNS change) — noted in the DNS change notification;
|
||||||
port state for that IP is removed. When none of a name's nameservers
|
port state for that IP is removed. A domain or hostname listed in
|
||||||
|
`DNSWATCHER_SKIP_RECORD_NOTIFICATIONS` gets no notification for an address
|
||||||
|
removed from its own A or AAAA records. When none of a name's nameservers
|
||||||
answered, its addresses are not known, so the port state saved for them is
|
answered, its addresses are not known, so the port state saved for them is
|
||||||
kept.
|
kept.
|
||||||
|
|
||||||
@@ -203,14 +231,22 @@ notification endpoint set, changes show only on the dashboard; see
|
|||||||
- Certificate CN, issuer, or SANs changed (replacement detected, reports old
|
- Certificate CN, issuer, or SANs changed (replacement detected, reports old
|
||||||
and new CN and issuer).
|
and new CN and issuer).
|
||||||
- TLS connection failure to a previously-reachable IP:443 (handshake error,
|
- TLS connection failure to a previously-reachable IP:443 (handshake error,
|
||||||
timeout, connection refused after previously succeeding).
|
timeout, or connection refused when port 443 closed after the port check
|
||||||
|
that found it open).
|
||||||
- TLS recovery: a previously-failing IP:443 now completes a handshake again.
|
- TLS recovery: a previously-failing IP:443 now completes a handshake again.
|
||||||
|
- A port check that finds port 443 closed removes the certificate entries for
|
||||||
|
that IP address, without a notification of its own: the port change
|
||||||
|
notification reports the closed port. When the port opens again, the next TLS
|
||||||
|
check saves the certificate as new, without a certificate change or recovery
|
||||||
|
notification.
|
||||||
|
|
||||||
### Notifications
|
### Notifications
|
||||||
|
|
||||||
**Every observable state change produces a notification.** dnswatcher is
|
**Every observable state change produces a notification.** dnswatcher is
|
||||||
designed as a real-time change feed — degradations, failures, recoveries, and
|
designed as a real-time change feed — degradations, failures, recoveries, and
|
||||||
routine changes are all reported equally.
|
routine changes are all reported equally. A domain or hostname listed in
|
||||||
|
`DNSWATCHER_SKIP_RECORD_NOTIFICATIONS` gets no record change or inconsistency
|
||||||
|
notification.
|
||||||
|
|
||||||
Supported notification backends:
|
Supported notification backends:
|
||||||
|
|
||||||
@@ -225,7 +261,9 @@ includes:
|
|||||||
|
|
||||||
- **DNS record changes**: Which hostname or domain, which nameserver, what
|
- **DNS record changes**: Which hostname or domain, which nameserver, what
|
||||||
record type, old values, new values.
|
record type, old values, new values.
|
||||||
- **DNS NS changes**: Which domain, which nameservers were added/removed.
|
- **DNS NS changes**: Which domain, which nameservers were added to or removed
|
||||||
|
from its delegation. For a hostname, or a domain with no delegation of its
|
||||||
|
own, which nameservers left the zone it is in.
|
||||||
- **NS address changes**: Which domain, which nameserver, its old and new
|
- **NS address changes**: Which domain, which nameserver, its old and new
|
||||||
addresses.
|
addresses.
|
||||||
- **CNAME address changes**: Which hostname or domain, the old and new addresses
|
- **CNAME address changes**: Which hostname or domain, the old and new addresses
|
||||||
@@ -270,8 +308,10 @@ clears them.
|
|||||||
port entry left with no name goes, so the dashboard and `/api/v1/status` no
|
port entry left with no name goes, so the dashboard and `/api/v1/status` no
|
||||||
longer list or count it. The first check's port checks remove the port entries
|
longer list or count it. The first check's port checks remove the port entries
|
||||||
of addresses no configured name has.
|
of addresses no configured name has.
|
||||||
- Each port check also removes the certificate entries for an address their name
|
- Each port check also removes, without a notification, the certificate entries
|
||||||
no longer resolves to, except while none of the name's nameservers answer.
|
for an address whose port 443 it found closed, and those for an address their
|
||||||
|
name no longer resolves to, except while none of the name's nameservers
|
||||||
|
answer.
|
||||||
|
|
||||||
### Web Dashboard
|
### Web Dashboard
|
||||||
|
|
||||||
@@ -409,23 +449,24 @@ following precedence (highest to lowest):
|
|||||||
|
|
||||||
### Environment Variables
|
### Environment Variables
|
||||||
|
|
||||||
| Variable | Description | Default |
|
| Variable | Description | Default |
|
||||||
| ----------------------------------- | ----------------------------------------------------------------------------------------------------------- | --------------------- |
|
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | --------------------- |
|
||||||
| `PORT` | HTTP listen port | `8080` |
|
| `PORT` | HTTP listen port; a port that cannot be bound, such as one already in use, stops startup | `8080` |
|
||||||
| `DNSWATCHER_DEBUG` | Enable debug logging | `false` |
|
| `DNSWATCHER_DEBUG` | Enable debug logging | `false` |
|
||||||
| `DNSWATCHER_DATA_DIR` | Directory for state file | `/var/lib/dnswatcher` |
|
| `DNSWATCHER_DATA_DIR` | Directory for state file | `/var/lib/dnswatcher` |
|
||||||
| `DNSWATCHER_TARGETS` | Comma-separated DNS names (auto-classified via PSL) | `""` |
|
| `DNSWATCHER_TARGETS` | Comma-separated DNS names (auto-classified via PSL) | `""` |
|
||||||
| `DNSWATCHER_SLACK_WEBHOOK` | Slack incoming webhook URL | `""` |
|
| `DNSWATCHER_SKIP_RECORD_NOTIFICATIONS` | Comma-separated names from `DNSWATCHER_TARGETS` for which no record change or inconsistency is notified; any other name stops startup | `""` |
|
||||||
| `DNSWATCHER_MATTERMOST_WEBHOOK` | Mattermost incoming webhook URL | `""` |
|
| `DNSWATCHER_SLACK_WEBHOOK` | Slack incoming webhook URL | `""` |
|
||||||
| `DNSWATCHER_NTFY_TOPIC` | ntfy topic URL | `""` |
|
| `DNSWATCHER_MATTERMOST_WEBHOOK` | Mattermost incoming webhook URL | `""` |
|
||||||
| `DNSWATCHER_DNS_INTERVAL` | DNS check interval, a positive duration such as `30m`; empty means the default, anything else stops startup | `1h` |
|
| `DNSWATCHER_NTFY_TOPIC` | ntfy topic URL | `""` |
|
||||||
| `DNSWATCHER_TLS_INTERVAL` | TLS check interval, a positive duration such as `6h`; empty means the default, anything else stops startup | `12h` |
|
| `DNSWATCHER_DNS_INTERVAL` | DNS check interval, a positive duration such as `30m`; empty means the default, anything else stops startup | `1h` |
|
||||||
| `DNSWATCHER_TLS_EXPIRY_WARNING` | Days before expiry to warn | `7` |
|
| `DNSWATCHER_TLS_INTERVAL` | TLS check interval, a positive duration such as `6h`; empty means the default, anything else stops startup | `12h` |
|
||||||
| `DNSWATCHER_SENTRY_DSN` | Sentry DSN for error reporting | `""` |
|
| `DNSWATCHER_TLS_EXPIRY_WARNING` | Days before expiry to warn | `7` |
|
||||||
| `DNSWATCHER_MAINTENANCE_MODE` | Only sets `maintenanceMode` in the health check response; changes nothing else | `false` |
|
| `DNSWATCHER_SENTRY_DSN` | Sentry DSN for error reporting | `""` |
|
||||||
| `DNSWATCHER_METRICS_USERNAME` | Basic auth username for /metrics, which is served only when this is set | `""` |
|
| `DNSWATCHER_MAINTENANCE_MODE` | Only sets `maintenanceMode` in the health check response; changes nothing else | `false` |
|
||||||
| `DNSWATCHER_METRICS_PASSWORD` | Basic auth password for /metrics | `""` |
|
| `DNSWATCHER_METRICS_USERNAME` | Basic auth username for /metrics, which is served only when this is set | `""` |
|
||||||
| `DNSWATCHER_SEND_TEST_NOTIFICATION` | Send a test notification after first scan completes | `false` |
|
| `DNSWATCHER_METRICS_PASSWORD` | Basic auth password for /metrics; required when `DNSWATCHER_METRICS_USERNAME` is set, and startup stops without it | `""` |
|
||||||
|
| `DNSWATCHER_SEND_TEST_NOTIFICATION` | Send a test notification after first scan completes | `false` |
|
||||||
|
|
||||||
**`DNSWATCHER_TARGETS` is required.** dnswatcher will refuse to start if no
|
**`DNSWATCHER_TARGETS` is required.** dnswatcher will refuse to start if no
|
||||||
monitoring targets are configured. A monitoring daemon with nothing to monitor
|
monitoring targets are configured. A monitoring daemon with nothing to monitor
|
||||||
@@ -450,6 +491,16 @@ or empty variable (`DNSWATCHER_DNS_INTERVAL=`) means the default. If either is
|
|||||||
set to anything else, including a bare number or a zero or negative duration,
|
set to anything else, including a bare number or a zero or negative duration,
|
||||||
dnswatcher refuses to start with an error naming the variable and the value.
|
dnswatcher refuses to start with an error naming the variable and the value.
|
||||||
|
|
||||||
|
**`PORT` and `DNSWATCHER_TLS_EXPIRY_WARNING`** take a whole number: 1 to 65535
|
||||||
|
for `PORT`, and a number of days, 1 or more, for
|
||||||
|
`DNSWATCHER_TLS_EXPIRY_WARNING`. `DNSWATCHER_DEBUG`,
|
||||||
|
`DNSWATCHER_MAINTENANCE_MODE` and `DNSWATCHER_SEND_TEST_NOTIFICATION` take
|
||||||
|
`true` or `false`; `1`, `t`, `T`, `TRUE` and `True` also mean true, and `0`,
|
||||||
|
`f`, `F`, `FALSE` and `False` also mean false. An unset or empty variable means
|
||||||
|
the default. Any other value, such as `PORT=http`,
|
||||||
|
`DNSWATCHER_TLS_EXPIRY_WARNING=7d` or `DNSWATCHER_DEBUG=yes`, makes dnswatcher
|
||||||
|
refuse to start with an error naming the variable and the value.
|
||||||
|
|
||||||
**`DNSWATCHER_SENTRY_DSN` reports crashes in HTTP requests to Sentry.** When it
|
**`DNSWATCHER_SENTRY_DSN` reports crashes in HTTP requests to Sentry.** When it
|
||||||
is set, a panic in an HTTP request handler is sent to Sentry, and the request
|
is set, a panic in an HTTP request handler is sent to Sentry, and the request
|
||||||
still gets a `500 Internal Server Error` answer. Nothing else is sent to Sentry:
|
still gets a `500 Internal Server Error` answer. Nothing else is sent to Sentry:
|
||||||
@@ -623,10 +674,20 @@ for A, AAAA and CNAME, the previous check's list is kept, or `null` when no
|
|||||||
earlier check saved one. A state file without it loads, and the first check
|
earlier check saved one. A state file without it loads, and the first check
|
||||||
after that saves it without a notification.
|
after that saves it without a notification.
|
||||||
|
|
||||||
|
A port entry's key is its address and port, and a certificate entry's key its
|
||||||
|
address, port 443 and hostname, joined by colons. An IPv6 address is written in
|
||||||
|
brackets in these keys, as in `[2001:db8::1]:443` and
|
||||||
|
`[2001:db8::1]:443:www.example.com`. `/api/v1/status` and the dashboard show the
|
||||||
|
same keys.
|
||||||
|
|
||||||
A port entry's `hostnames` lists every name that resolves to its address,
|
A port entry's `hostnames` lists every name that resolves to its address,
|
||||||
domains included. A port entry in the older format, with one `hostname` instead
|
domains included. A port entry in the older format, with one `hostname` instead
|
||||||
of the `hostnames` list, loads as a list of that one name.
|
of the `hostnames` list, loads as a list of that one name.
|
||||||
|
|
||||||
|
A state file that leaves out any of `domains`, `hostnames`, `ports` and
|
||||||
|
`certificates`, or holds `null` for one, loads with that section empty. A file
|
||||||
|
holding `{}` loads as empty state.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Entrypoints
|
## Entrypoints
|
||||||
@@ -643,48 +704,42 @@ provide:
|
|||||||
- `script/setup` — make a fresh clone ready for development: bootstrap plus the
|
- `script/setup` — make a fresh clone ready for development: bootstrap plus the
|
||||||
git pre-commit hook
|
git pre-commit hook
|
||||||
- `script/projectname` — print the project name (used for the Docker image tag)
|
- `script/projectname` — print the project name (used for the Docker image tag)
|
||||||
- `script/test` — run the test suite (race detector, coverage). Caching is
|
- `script/test` — run the test suite (race detector, coverage) by building the
|
||||||
waived for testing, exactly as it is for linting: `-count=1` forces every
|
`Dockerfile`'s test phase, which queries live DNS. `-count=1` keeps Go's test
|
||||||
invocation to execute, because the suite queries live DNS and a cached pass
|
result cache out. Failures are rerun with `-v` automatically, and the build
|
||||||
queries nothing. Failures are rerun with `-v` automatically, and the build
|
|
||||||
fails even if that rerun passes.
|
fails even if that rerun passes.
|
||||||
- `script/lint` — run golangci-lint, always inside Docker: it builds
|
- `script/lint` — run golangci-lint by building the `Dockerfile`'s lint phase,
|
||||||
`Dockerfile.lint`, which COPYs the repo into the digest-pinned `golangci-lint`
|
on the digest-pinned `golangci-lint` image, so a successful build is a clean
|
||||||
image and lints as a build step, so a successful build is a clean lint. The
|
lint. The linter is never installed or run on the host, and Docker is the only
|
||||||
linter is never installed or run on the host, and Docker is the only
|
prerequisite.
|
||||||
prerequisite. Caching is waived for linting: the lint stage is forced to
|
|
||||||
execute on every run with `--no-cache-filter`, because a cached build lints
|
|
||||||
nothing.
|
|
||||||
- `script/fmt` — format all code (gofmt -s, goimports) and all Markdown
|
- `script/fmt` — format all code (gofmt -s, goimports) and all Markdown
|
||||||
(prettier). goimports runs with `go run` at a pinned commit, never from your
|
(prettier). goimports runs with `go run` at a pinned commit, never from your
|
||||||
`PATH`. prettier runs inside Docker, built from `Dockerfile.fmt` on a
|
`PATH`. prettier runs inside Docker, in a stage of the `Dockerfile` on a
|
||||||
digest-pinned node image, at the version pinned by `package.json` and
|
digest-pinned node image, at the version pinned by `package.json` and
|
||||||
`yarn.lock`; it is never installed on the host.
|
`yarn.lock`; it is never installed on the host.
|
||||||
- `script/fmt-check` — check formatting (read-only) with the same tools, failing
|
- `script/fmt-check` — check formatting (read-only) with the same tools, failing
|
||||||
on any file `script/fmt` would change. It runs the two scripts below.
|
on any file `script/fmt` would change: gofmt and goimports on the host,
|
||||||
- `script/fmt-check-go` — the gofmt and goimports half, on the host. The
|
prettier inside Docker
|
||||||
`Dockerfile` lint stage runs it.
|
|
||||||
- `script/fmt-check-markdown` — the prettier half, inside Docker, forced to
|
|
||||||
execute on every run with `--no-cache-filter`
|
|
||||||
- `script/check` — run test, lint, and fmt-check
|
- `script/check` — run test, lint, and fmt-check
|
||||||
- `script/docker` — build the Docker image tagged via `script/projectname`, with
|
- `script/docker` — build the Docker image tagged via `script/projectname`, with
|
||||||
`--no-cache-filter=lint,builder` so the lint stage and the builder stage,
|
the version from `git describe` passed as `--build-arg VERSION`
|
||||||
which runs the tests, run on every invocation, and with the version from
|
- `script/cibuild` — CI entrypoint: `script/bootstrap`, then `script/check`,
|
||||||
`git describe` passed as `--build-arg VERSION`
|
then the image build `script/docker` does, which runs the lint and test phases
|
||||||
- `script/cibuild` — CI entrypoint: `docker build` with
|
again
|
||||||
`--no-cache-filter=lint,builder`, so the lint stage and the builder stage,
|
|
||||||
which runs the tests, run on every invocation, because a cached build lints
|
|
||||||
nothing and queries no DNS; then `script/fmt-check-markdown`
|
|
||||||
- `script/precommit` — run by the git pre-commit hook; `go mod tidy` guard, then
|
- `script/precommit` — run by the git pre-commit hook; `go mod tidy` guard, then
|
||||||
`script/check`
|
`script/check`
|
||||||
- `script/install-precommit` — install the git pre-commit hook
|
- `script/install-precommit` — install the git pre-commit hook
|
||||||
|
|
||||||
|
Linting and testing are phases of the `Dockerfile`, and the image is built only
|
||||||
|
when both pass. Every `docker build` in `script/` passes `--no-cache`, because a
|
||||||
|
cached build lints nothing and queries no DNS.
|
||||||
|
|
||||||
## Building
|
## Building
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
make build # Build binary to bin/dnswatcher
|
make build # Build binary to bin/dnswatcher
|
||||||
make version # Print the version make build stamps
|
make version # Print the version make build stamps
|
||||||
make test # Run tests with race detector
|
make test # Run tests with race detector in Docker (requires docker)
|
||||||
make lint # Run golangci-lint in Docker (requires docker)
|
make lint # Run golangci-lint in Docker (requires docker)
|
||||||
make fmt # Format code and Markdown (requires docker)
|
make fmt # Format code and Markdown (requires docker)
|
||||||
make check # Run all checks (test, lint, fmt-check)
|
make check # Run all checks (test, lint, fmt-check)
|
||||||
@@ -699,21 +754,20 @@ the environment, otherwise from `git describe --tags --always --dirty`, and
|
|||||||
`dev` without git metadata. An empty `VERSION` counts as not given. The version
|
`dev` without git metadata. An empty `VERSION` counts as not given. The version
|
||||||
appears in the startup log and in the health check response.
|
appears in the startup log and in the health check response.
|
||||||
|
|
||||||
The image takes it the same way, from the `.git` the build context carries, so a
|
The image takes it from `git describe --tags --always` on the `.git` the build
|
||||||
plain `docker build .` of a clone stamps the commit it was built from; a clone
|
context carries, so a plain `docker build .` of a clone stamps the commit it was
|
||||||
without tags stamps the short commit. A clone made with `--depth 1` carries at
|
built from; a clone without tags stamps the short commit. A clone made with
|
||||||
most a tag on its own commit, so such a clone of an untagged commit stamps the
|
`--depth 1` carries at most a tag on its own commit, so such a clone of an
|
||||||
short commit. In a build from a directory, `.dockerignore` keeps out
|
untagged commit stamps the short commit. In a build from a directory,
|
||||||
`.git/config`, which `git describe` does not need and which can hold a
|
`.dockerignore` keeps out `.git/config` and every submodule's git config, which
|
||||||
credential. Docker does not apply `.dockerignore` to a context sent as a tar
|
`git describe` does not need and which can hold a credential. Docker does not
|
||||||
archive, as upaas sends it, so that context carries `.git/config` into the
|
apply `.dockerignore` to a context sent as a tar archive, as upaas sends it, so
|
||||||
build. It also keeps its files' owners, so git in the build trusts the checkout
|
that context carries `.git/config` into the build. It also keeps its files'
|
||||||
whoever owns it. A non-empty `--build-arg VERSION=...` takes precedence;
|
owners, so git in the build trusts the checkout whoever owns it. A non-empty
|
||||||
`make docker` passes the version `git describe` gives on the host. The build
|
`--build-arg VERSION=...` takes precedence; `make docker` passes the version
|
||||||
fails when the context carries `.git`, as a directory or as a file, and the
|
`git describe` gives on the host. The build fails when the context carries
|
||||||
version comes out empty, `dev` or `unknown`. `.dockerignore` must list no
|
`.git`, as a directory or as a file, and the version comes out empty, `dev` or
|
||||||
tracked file: git in the build would see it as deleted and mark the version
|
`unknown`.
|
||||||
`-dirty`.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -786,7 +840,9 @@ docker run -d \
|
|||||||
nameservers answered, the addresses an earlier check found at the end of
|
nameservers answered, the addresses an earlier check found at the end of
|
||||||
the chain are used.
|
the chain are used.
|
||||||
4. **On change detection**: Send notifications to all configured endpoints,
|
4. **On change detection**: Send notifications to all configured endpoints,
|
||||||
update in-memory state, persist to disk.
|
update in-memory state, persist to disk. A record change or inconsistency for
|
||||||
|
a domain or hostname listed in `DNSWATCHER_SKIP_RECORD_NOTIFICATIONS` sends
|
||||||
|
no notification, but the state is still updated and saved.
|
||||||
5. **Shutdown**: The watcher stops checking and saves the final state to disk,
|
5. **Shutdown**: The watcher stops checking and saves the final state to disk,
|
||||||
and shutdown waits for that save before it goes on. Then it waits for
|
and shutdown waits for that save before it goes on. Then it waits for
|
||||||
in-flight notification deliveries to complete. Both waits share the fx
|
in-flight notification deliveries to complete. Both waits share the fx
|
||||||
|
|||||||
+353
-90
@@ -1,6 +1,6 @@
|
|||||||
---
|
---
|
||||||
title: Repository Policies
|
title: Repository Policies
|
||||||
last_modified: 2026-08-07
|
last_modified: 2026-10-04
|
||||||
---
|
---
|
||||||
|
|
||||||
This document covers repository structure, tooling, and workflow standards. Code
|
This document covers repository structure, tooling, and workflow standards. Code
|
||||||
@@ -60,17 +60,28 @@ style conventions are in separate documents:
|
|||||||
prerequisite since nvm requires bash. yarn is then pinned via
|
prerequisite since nvm requires bash. yarn is then pinned via
|
||||||
`corepack prepare yarn@<version> --activate`. Never install "latest" or "lts";
|
`corepack prepare yarn@<version> --activate`. Never install "latest" or "lts";
|
||||||
always exact versions. `script/cibuild` runs the CI build: it changes to the
|
always exact versions. `script/cibuild` runs the CI build: it changes to the
|
||||||
repo root and runs `docker build .`; the Gitea workflow calls it. Four further
|
repo root, runs `script/bootstrap`, runs `script/check`, and builds the image
|
||||||
scripts are our own extensions to the standard: `script/check` runs
|
with the version; the Gitea workflow calls it. **`script/cibuild` runs
|
||||||
`script/test`, `script/lint`, and `script/fmt-check`; `script/precommit` is
|
`script/bootstrap` first**, because the workflow checks out the repo and runs
|
||||||
what the git pre-commit hook runs, and it calls `script/check`;
|
nothing else, while `script/fmt-check` runs the formatter on the host: on a
|
||||||
`script/install-precommit` installs the git pre-commit hook (the `make hooks`
|
pristine checkout with nothing installed the run dies there, after the
|
||||||
target shims to it); and `script/projectname` (literally that filename) simply
|
containerised gates have passed. **The bootstrap alone is not enough**:
|
||||||
outputs the project's name. Scripts that need the name call
|
`script/bootstrap` installs node and yarn under nvm and leaves neither on the
|
||||||
`script/projectname` — e.g. `script/docker` assembles its image tag from it —
|
`PATH` of the shell that called it, so a bare `yarn` still exits 127. The host
|
||||||
so those scripts stay byte-identical across all repos. Repo-type-specific
|
entrypoints that need yarn — `script/fmt` and `script/fmt-check` — therefore
|
||||||
pre-commit extras (e.g. `go mod tidy` verification in Go repos) belong in
|
source nvm for the pinned node version before invoking it, exactly as
|
||||||
`script/precommit`, not in the hook itself. Model scripts are at
|
`script/bootstrap`'s own install step does. A runner carrying nothing but
|
||||||
|
docker and git then gets through `script/check`. Four further scripts are our
|
||||||
|
own extensions to the standard: `script/check` runs `script/test`,
|
||||||
|
`script/lint` and `script/fmt-check`; `script/precommit` is what the git
|
||||||
|
pre-commit hook runs, and it calls `script/check`; `script/install-precommit`
|
||||||
|
installs the git pre-commit hook (the `make hooks` target shims to it); and
|
||||||
|
`script/projectname` (literally that filename) simply outputs the project's
|
||||||
|
name. Scripts that need the name call `script/projectname` — e.g.
|
||||||
|
`script/docker` assembles its image tag from it — so those scripts stay
|
||||||
|
byte-identical across all repos. Repo-type-specific pre-commit extras (e.g.
|
||||||
|
`go mod tidy` verification in Go repos) belong in `script/precommit`, not in
|
||||||
|
the hook itself. Model scripts are at
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/script/<name>`. The README
|
`https://git.eeqj.de/sneak/prompts/raw/branch/main/script/<name>`. The README
|
||||||
must document the provided scripts in an **Entrypoints** section (see the
|
must document the provided scripts in an **Entrypoints** section (see the
|
||||||
README requirements below).
|
README requirements below).
|
||||||
@@ -89,87 +100,198 @@ style conventions are in separate documents:
|
|||||||
contributor should be able to understand the entire development workflow by
|
contributor should be able to understand the entire development workflow by
|
||||||
reading the Makefile.
|
reading the Makefile.
|
||||||
|
|
||||||
- Every repo should have a `Dockerfile`. All Dockerfiles must run `make check`
|
- Every repo should have a `Dockerfile`, and it carries the repo's gates: a
|
||||||
as a build step so the build fails if the branch is not green. For non-server
|
`lint` phase and a `test` phase, with the final stage depending on both so the
|
||||||
repos, the Dockerfile should bring up a development environment and run
|
image cannot be built unless they pass. For non-server repos the final stage
|
||||||
`make check`. For server repos, `make check` should run as an early build
|
brings up a development environment; for server repos it is the runtime image.
|
||||||
stage before the final image is assembled. Dockerfiles install development
|
The gate phases and the build stage start from their pinned base images and
|
||||||
prerequisites by running `script/bootstrap` rather than duplicating installs
|
install what those images lack either inline, as the canonical Go `Dockerfile`
|
||||||
inline; COPY `script/` and the dependency manifests (`package.json` +
|
below does for `git`, or by running `script/bootstrap`, as the `prompts`
|
||||||
`yarn.lock`, `go.mod` + `go.sum`, etc.) before running it so the bootstrap
|
repo's own `Dockerfile` does for its yarn packages. The development
|
||||||
layer stays cached until dependencies change.
|
environment stage installs development prerequisites by running
|
||||||
|
`script/bootstrap` rather than duplicating its installs inline. A stage that
|
||||||
|
runs `script/bootstrap` COPYs `script/` and the dependency manifests
|
||||||
|
(`package.json` + `yarn.lock`, `go.mod` + `go.sum`, etc.) before running it.
|
||||||
|
|
||||||
- **Dockerfiles must use a separate lint stage for fail-fast feedback.** Go
|
- **Linting and testing run in Docker, as phases of the `Dockerfile`.** There is
|
||||||
repos use a multistage build where linting runs in an independent stage based
|
no separate lint file. `script/lint` and `script/test` each build one phase
|
||||||
on the `golangci/golangci-lint` image (pinned by hash). This stage runs
|
and nothing else:
|
||||||
`make fmt-check` and `make lint` before the full build begins. The build stage
|
|
||||||
then declares an explicit dependency on the lint stage via
|
|
||||||
`COPY --from=lint /src/go.sum /dev/null`, which forces BuildKit to complete
|
|
||||||
linting before proceeding to compilation and tests. This ensures lint failures
|
|
||||||
surface in seconds rather than minutes, without blocking on dependency
|
|
||||||
download or compilation in the build stage.
|
|
||||||
|
|
||||||
The standard pattern for a Go repo Dockerfile is:
|
```sh
|
||||||
|
docker build --no-cache --target lint -t "$(script/projectname)-lint" .
|
||||||
|
docker build --no-cache --target test -t "$(script/projectname)-test" .
|
||||||
|
```
|
||||||
|
|
||||||
|
**A stage that is not the last one in the file is built only when the final
|
||||||
|
stage's chain depends on it, or when `--target` names it.** That is why the
|
||||||
|
two gates are always invoked by name here, and why the final stage carries a
|
||||||
|
`COPY --from=` of a harmless file from each of them: without that edge a
|
||||||
|
plain `docker build .` builds the last stage alone and exits 0 having linted
|
||||||
|
and tested nothing.
|
||||||
|
|
||||||
|
**Every `docker build` in `script/` is tagged**, here and in
|
||||||
|
`script/cibuild` and `script/docker`. An untagged build leaves a dangling
|
||||||
|
image behind on every invocation, on every developer host and every CI
|
||||||
|
runner; a tagged one replaces the previous image.
|
||||||
|
|
||||||
|
Inside a phase the tool is invoked directly — `golangci-lint`, `go test`,
|
||||||
|
`eslint`, `prettier` — never through `make lint` or `script/test`, which are
|
||||||
|
themselves a `docker build` and would recurse into a daemon that does not
|
||||||
|
exist in a build step. Formatting is the exception and stays on the host:
|
||||||
|
`script/fmt` writes the working tree, and `script/fmt-check` is its
|
||||||
|
read-only twin.
|
||||||
|
|
||||||
|
**No lint verdict may come from a host invocation of the linter.** On a
|
||||||
|
shared host golangci-lint reads a result cache keyed on file content rather
|
||||||
|
than location, so a second checkout of the same content is served the first
|
||||||
|
one's findings, and a host-global lock in `$TMPDIR` makes concurrent runs
|
||||||
|
exit non-zero with `parallel golangci-lint is running` — a status a caller
|
||||||
|
cannot tell from real findings. Both have produced wrong verdicts in this
|
||||||
|
org, in both directions. A container has its own cache, its own `TMPDIR` and
|
||||||
|
a digest-pinned binary, so neither is reachable.
|
||||||
|
|
||||||
|
- **Any build that runs checks is built with `--no-cache`.** Docker invalidates
|
||||||
|
a `COPY` layer only when the copied content changes, so on an unchanged tree
|
||||||
|
the check `RUN` is served from cache, nothing executes, and the build still
|
||||||
|
exits 0. Every `docker build` in `script/` therefore passes `--no-cache`:
|
||||||
|
`script/lint`, `script/test`, `script/cibuild` and `script/docker` are the
|
||||||
|
four, and there is no fifth — `script/check` runs the two gate phases and
|
||||||
|
`script/fmt-check`, and builds no image of its own. A bare `docker build .` is
|
||||||
|
not evidence that anything ran: a sub-second build reporting success is a
|
||||||
|
cache hit, not a result. Never invalidate by pruning — `docker builder prune`
|
||||||
|
and friends destroy a build cache shared with every other build on the host.
|
||||||
|
When a check is added or changed, prove it works by planting a defect it must
|
||||||
|
catch and watching the run fail on it, then revert the defect. A green run
|
||||||
|
alone shows neither that the check ran nor that it covers what it should.
|
||||||
|
|
||||||
|
- **The gate phases are separate stages, and the build stage depends on both.**
|
||||||
|
The lint phase is based on the `golangci/golangci-lint` image (pinned by
|
||||||
|
hash), so lint failures surface in seconds rather than after a full compile,
|
||||||
|
and the test phase is based on the Debian Go image. The canonical Go repo
|
||||||
|
`Dockerfile`:
|
||||||
|
|
||||||
```dockerfile
|
```dockerfile
|
||||||
# Lint stage — fast feedback on formatting and lint issues
|
# Lint phase
|
||||||
# golangci/golangci-lint:v2.x.x, YYYY-MM-DD
|
# golangci/golangci-lint:v2.x.x, YYYY-MM-DD
|
||||||
FROM golangci/golangci-lint@sha256:... AS lint
|
FROM golangci/golangci-lint@sha256:... AS lint
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN make fmt-check
|
RUN golangci-lint run --config .golangci.yml ./...
|
||||||
RUN make lint
|
|
||||||
|
|
||||||
# Build stage
|
# Test phase. -race needs cgo and so a C compiler, which the Debian Go
|
||||||
# golang:1.x-alpine, YYYY-MM-DD
|
# image ships and the alpine one does not.
|
||||||
FROM golang@sha256:... AS builder
|
# golang:1.x, YYYY-MM-DD
|
||||||
|
FROM golang@sha256:... AS test
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
|
|
||||||
# Force BuildKit to run the lint stage before proceeding
|
|
||||||
COPY --from=lint /src/go.sum /dev/null
|
|
||||||
|
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN make test
|
RUN go test -timeout 90s -race -cover ./... || \
|
||||||
|
{ echo "--- Rerunning with -v for details ---"; \
|
||||||
|
go test -timeout 90s -race -v ./...; exit 1; }
|
||||||
|
|
||||||
ARG VERSION=dev
|
# Build stage. Nothing is wanted from either phase above; the copies
|
||||||
RUN CGO_ENABLED=0 go build -trimpath \
|
# are what make BuildKit build them first, so this stage cannot run
|
||||||
-ldflags="-s -w -X main.Version=${VERSION}" \
|
# unless lint and test passed.
|
||||||
-o /app ./cmd/app/
|
# golang:1.x-alpine, YYYY-MM-DD
|
||||||
|
FROM golang@sha256:... AS builder
|
||||||
|
COPY --from=lint /src/go.sum /dev/null
|
||||||
|
COPY --from=test /src/go.sum /dev/null
|
||||||
|
RUN apk add --no-cache git
|
||||||
|
# A tar-stream context keeps the sender's file owners, which git refuses.
|
||||||
|
RUN git config --system --add safe.directory /src
|
||||||
|
WORKDIR /src
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY . .
|
||||||
|
|
||||||
# Runtime stage
|
# The VERSION build arg when one is given, otherwise
|
||||||
|
# `git describe --tags --always` on the .git in the build context. With
|
||||||
|
# .git present, a version that is still empty, dev or unknown fails the
|
||||||
|
# build: git is missing or could not read the checkout.
|
||||||
|
ARG VERSION
|
||||||
|
RUN VERSION="${VERSION:-$(git describe --tags --always)}"; \
|
||||||
|
if [ -e .git ]; then \
|
||||||
|
case "$VERSION" in ""|dev|unknown) \
|
||||||
|
echo "version is '$VERSION' although .git is present" >&2; \
|
||||||
|
exit 1 ;; \
|
||||||
|
esac; \
|
||||||
|
fi; \
|
||||||
|
CGO_ENABLED=0 go build -trimpath \
|
||||||
|
-ldflags="-s -w -X main.Version=${VERSION}" \
|
||||||
|
-o /app ./cmd/app/
|
||||||
|
|
||||||
|
# Runtime stage, and the last one
|
||||||
FROM alpine@sha256:...
|
FROM alpine@sha256:...
|
||||||
COPY --from=builder /app /usr/local/bin/app
|
COPY --from=builder /app /usr/local/bin/app
|
||||||
ENTRYPOINT ["app"]
|
ENTRYPOINT ["app"]
|
||||||
```
|
```
|
||||||
|
|
||||||
Key points:
|
Key points:
|
||||||
- The lint stage uses the `golangci/golangci-lint` image directly (it
|
- The lint phase uses the `golangci/golangci-lint` image directly (it has
|
||||||
includes both Go and the linter), so there is no need to install the
|
both Go and the linter), so nothing needs installing.
|
||||||
linter separately.
|
- `COPY --from=<phase> /src/go.sum /dev/null` is a no-op copy whose only
|
||||||
- `COPY --from=lint /src/go.sum /dev/null` is a no-op file copy that creates
|
purpose is the ordering edge. BuildKit runs stages in parallel by default,
|
||||||
a stage dependency. BuildKit runs stages in parallel by default; without
|
and a stage nothing depends on is not built at all, so without these two
|
||||||
this line, the build stage would not wait for lint to finish and a lint
|
lines a red gate would not fail the build.
|
||||||
failure might not fail the overall build.
|
- Keep the runtime stage last, and if you add a stage after it, give it the
|
||||||
|
same two copies. A plain `docker build .` builds the last stage's chain
|
||||||
|
and nothing else.
|
||||||
- If the project uses `//go:embed` directives that reference build artifacts
|
- If the project uses `//go:embed` directives that reference build artifacts
|
||||||
(e.g. a web frontend compiled in a separate stage), the lint stage must
|
(e.g. a web frontend compiled in a separate stage), the lint phase must
|
||||||
create placeholder files so the embed directives resolve. Example:
|
create placeholder files so the embed directives resolve. Example:
|
||||||
`RUN mkdir -p web/dist && touch web/dist/index.html web/dist/style.css`.
|
`RUN mkdir -p web/dist && touch web/dist/index.html web/dist/style.css`.
|
||||||
The lint stage should not depend on the actual build output — it exists to
|
- If the project requires CGO or system libraries for linting, install them
|
||||||
fail fast.
|
in the lint phase. The `golangci/golangci-lint` image is Debian-based and
|
||||||
- If the project requires CGO or system libraries for linting (e.g.
|
has no `apk`, so install with `apt-get` under the Debian package name
|
||||||
`vips-dev`), install them in the lint stage with `apk add`.
|
(`libvips-dev`, where alpine says `vips-dev`), and delete the package
|
||||||
- The build stage runs `make test` after compilation setup. Tests run in the
|
lists in the same `RUN`, so the layer does not keep them:
|
||||||
build stage, not the lint stage, because they may require compiled
|
|
||||||
artifacts or heavier dependencies.
|
```dockerfile
|
||||||
|
RUN apt-get update \
|
||||||
|
&& apt-get install -y --no-install-recommends libvips-dev \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
```
|
||||||
|
|
||||||
|
- `.dockerignore` lets `.git` into the build context. It keeps out every git
|
||||||
|
`config` at any depth (`**/.git/config`, `**/.git/modules/**/config`): the
|
||||||
|
repository's own, each submodule's under `.git/modules/`, and that of a
|
||||||
|
submodule keeping its own `.git` directory. `git describe` does not need
|
||||||
|
them, and each can hold a credential: a password in a remote URL, or the
|
||||||
|
token the CI checkout step stores there. A submodule whose name has a
|
||||||
|
`config` segment (`config`, `deploy/config`, `config/lib`) loses its whole
|
||||||
|
git directory to `**/.git/modules/**/config`, and Go's version stamping
|
||||||
|
then fails the build: give it a name without that segment
|
||||||
|
(`git submodule add --name`). The stage that compiles has `git` (the
|
||||||
|
Debian Go image has it; an alpine one needs `apk add --no-cache git`) and
|
||||||
|
takes the version from the `VERSION` build argument when one is given,
|
||||||
|
otherwise from `git describe --tags --always`. That gives the tag on a
|
||||||
|
tagged commit; on a later commit, the tag, the number of commits since it
|
||||||
|
and the short commit (`v1.2.3-4-gabc1234`); and the short commit when no
|
||||||
|
tag is reachable. The stage that compiles also marks its working directory
|
||||||
|
safe for git (`git config --system --add safe.directory /src`): a context
|
||||||
|
sent as a tar stream keeps the sender's file owners, and git refuses a
|
||||||
|
checkout owned by another user, so the version would come out empty.
|
||||||
|
`ARG VERSION` has no default, and the build fails if the context carries
|
||||||
|
`.git` and the version still comes out empty, `dev` or `unknown`. A plain
|
||||||
|
`docker build .` with no build arguments must succeed; a Dockerfile that
|
||||||
|
refuses an empty build argument drops that refusal and keeps the argument.
|
||||||
|
|
||||||
- Every repo should have a Gitea Actions workflow (`.gitea/workflows/`) that
|
- Every repo should have a Gitea Actions workflow (`.gitea/workflows/`) that
|
||||||
runs `script/cibuild` (which runs `docker build .`) on push. Since the
|
runs `script/cibuild` on push, and checks out the repo as its only other step.
|
||||||
Dockerfile already runs `make check`, a successful build implies all checks
|
That script bootstraps, runs the gate phases, and then builds the image, so a
|
||||||
pass.
|
successful run means every check passed; a bare `docker build .` does not
|
||||||
|
carry the same guarantee, because its gate phases may come from the cache. The
|
||||||
|
image build is uncached and so runs the gate phases a second time. That is the
|
||||||
|
price of the rule above, and it is worth paying: the image that ships is built
|
||||||
|
from a run of its own gates rather than from a cache entry. A separate
|
||||||
|
workflow limited to `main` by a `branches` list under `on: push` cannot be
|
||||||
|
checked by review: to try a change to it, add the feature branch to that list
|
||||||
|
and push, then remove the branch from the list again before merging. Keep any
|
||||||
|
job in it that publishes behind `if: github.ref_name == 'main'`, so the run
|
||||||
|
from the feature branch publishes nothing.
|
||||||
|
|
||||||
- Use platform-standard formatters: `black` for Python, `prettier` for
|
- Use platform-standard formatters: `black` for Python, `prettier` for
|
||||||
JS/CSS/Markdown/HTML, `go fmt` for Go. Always use default configuration with
|
JS/CSS/Markdown/HTML, `go fmt` for Go. Always use default configuration with
|
||||||
@@ -193,15 +315,17 @@ style conventions are in separate documents:
|
|||||||
suite that exceeds it fails. Under 20 seconds is the target. A suite between
|
suite that exceeds it fails. Under 20 seconds is the target. A suite between
|
||||||
20 and 60 seconds is still green, but the overage must be filed as an
|
20 and 60 seconds is still green, but the overage must be filed as an
|
||||||
improvement bug against that repo. Add a 90-second timeout to the test
|
improvement bug against that repo. Add a 90-second timeout to the test
|
||||||
invocation in the Makefile (`go test -timeout 90s`). The backstop deliberately
|
invocation (`go test -timeout 90s`). The backstop deliberately sits above the
|
||||||
sits above the hard cap so that it catches a genuinely hung test rather than a
|
hard cap so that it catches a genuinely hung test rather than a merely slow
|
||||||
merely slow one.
|
one.
|
||||||
|
|
||||||
- **`make test` should use the conditional verbose rerun pattern.** Run tests
|
- **The test command should use the conditional verbose rerun pattern.** Run
|
||||||
without `-v` (verbose) first. If tests fail, automatically rerun with `-v` to
|
tests without `-v` (verbose) first. If tests fail, automatically rerun with
|
||||||
show full output. This keeps CI logs and `docker build` output clean on
|
`-v` to show full output. This keeps CI logs and `docker build` output clean
|
||||||
success (just package/suite summaries) while providing full diagnostic detail
|
on success (just package/suite summaries) while providing full diagnostic
|
||||||
on failure (every test case, every assertion). The general shell pattern:
|
detail on failure (every test case, every assertion). The command lives in the
|
||||||
|
`test` phase of the `Dockerfile`, since `script/test` builds that phase; the
|
||||||
|
Makefile form below is the same pattern for any repo-local invocation:
|
||||||
|
|
||||||
```makefile
|
```makefile
|
||||||
test:
|
test:
|
||||||
@@ -214,11 +338,26 @@ style conventions are in separate documents:
|
|||||||
|
|
||||||
```makefile
|
```makefile
|
||||||
test:
|
test:
|
||||||
@go test -timeout 90s -race -cover ./... || \
|
@go test -count=1 -timeout 90s -race -cover ./... || \
|
||||||
{ echo "--- Rerunning with -v for details ---"; \
|
{ echo "--- Rerunning with -v for details ---"; \
|
||||||
go test -timeout 90s -race -v ./...; exit 1; }
|
go test -count=1 -timeout 90s -race -v ./...; exit 1; }
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`-count=1` is required on both invocations: it defeats Go's test _result_
|
||||||
|
cache, so neither run can report a stored pass in place of running the
|
||||||
|
tests. It leaves the build cache alone, so it costs the runtime of the suite
|
||||||
|
and no recompilation.
|
||||||
|
|
||||||
|
That cache is Go's own, separate from Docker's layer cache. Go stores a
|
||||||
|
passing result in its cache directory (`GOCACHE`), and when the same tests
|
||||||
|
run again on unchanged code it prints that result, marked `(cached)`,
|
||||||
|
without running them. That matters on a developer's machine, where this
|
||||||
|
target runs and the directory lasts from one run to the next. The `test`
|
||||||
|
phase of the `Dockerfile` needs no `-count=1`: its base image holds no
|
||||||
|
result for this repo's tests and nothing before its `go test` step runs a
|
||||||
|
test, so there is nothing to replay. `--no-cache` (above) is what makes that
|
||||||
|
step run on an unchanged tree.
|
||||||
|
|
||||||
Python example:
|
Python example:
|
||||||
|
|
||||||
```makefile
|
```makefile
|
||||||
@@ -244,10 +383,84 @@ style conventions are in separate documents:
|
|||||||
must be in `.gitignore`. No exceptions.
|
must be in `.gitignore`. No exceptions.
|
||||||
|
|
||||||
- `.gitignore` should be comprehensive from the start: OS files (`.DS_Store`),
|
- `.gitignore` should be comprehensive from the start: OS files (`.DS_Store`),
|
||||||
editor files (`.swp`, `*~`), language build artifacts, and `node_modules/`.
|
editor files (`.swp`, `*~`), in-repo agent scratch directories (`.claude/`),
|
||||||
Fetch the standard `.gitignore` from
|
language build artifacts, and `node_modules/`. Fetch the standard `.gitignore`
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when setting up
|
from `https://git.eeqj.de/sneak/prompts/raw/branch/main/.gitignore` when
|
||||||
a new repo.
|
setting up a new repo. These patterns are written to `.gitignore`'s own
|
||||||
|
semantics, in which an unanchored pattern already matches at every depth; they
|
||||||
|
are not a `.dockerignore` and must not be transplanted into one unmodified.
|
||||||
|
|
||||||
|
- **`.dockerignore` does not use `.gitignore` semantics, and copying patterns
|
||||||
|
across unmodified leaves secrets in the build context.** Docker matches with
|
||||||
|
`moby/patternmatcher`: `filepath.Match` semantics plus a `**` extension, so
|
||||||
|
`*` does not cross `/` and a pattern without a leading `**/` is anchored at
|
||||||
|
the build-context root. A `.dockerignore` listing `.env`, `*.pem` and `*.key`
|
||||||
|
therefore excludes only the copies at the repository root, while `config/.env`
|
||||||
|
and `certs/server.key` still reach the context and can land in an image layer
|
||||||
|
— which is more dangerous than a short file with no secret patterns at all,
|
||||||
|
because it reads as solved and stops anyone looking. Give every
|
||||||
|
depth-independent pattern the `**/` prefix and leave only genuinely
|
||||||
|
root-anchored entries unprefixed: `.claude`, and the repo's own host-built
|
||||||
|
binary, written `/myapp` and never `**/myapp`, which would also match
|
||||||
|
`cmd/myapp/` and delete the package directory from the context. Matching is
|
||||||
|
case-sensitive, and an ALL-CAPS twin per pattern still misses `Server.Key`, so
|
||||||
|
secret names use character ranges — `**/*.[kK][eE][yY]`, `**/*.[pP][eE][mM]`,
|
||||||
|
and likewise for `.envrc` and the extensionless SSH keys. Where such a pattern
|
||||||
|
also catches something the build needs, re-include it with a negation
|
||||||
|
(`!docs/example.env`); deleting the pattern reopens the exposure for every
|
||||||
|
other file it covers. Fetch the standard `.dockerignore` from
|
||||||
|
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.dockerignore` and extend
|
||||||
|
it with the repo's own artifacts.
|
||||||
|
|
||||||
|
- **In-repo agent scratch belongs in both files, written to each file's own
|
||||||
|
semantics.** `.claude/` holds one worktree per in-flight agent — an entire
|
||||||
|
additional checkout of the repo — so under `COPY . .` the build context
|
||||||
|
inflates by a multiple of the repo and another session's unreviewed work can
|
||||||
|
be copied into an image layer. In `.gitignore` the entry is `.claude/`,
|
||||||
|
unanchored. In `.dockerignore` it is `.claude`, anchored and with **no** `**/`
|
||||||
|
prefix, because the prefixed form would also delete any nested directory of
|
||||||
|
that name from the build. Anchoring carries a known gap that the canonical
|
||||||
|
`.dockerignore` states in its own comment, since consuming repos receive the
|
||||||
|
file and not the tracker: the directory is created in the agent's working
|
||||||
|
directory, so a repo running agents in subdirectories still ships
|
||||||
|
`services/api/.claude/` and must add its own anchored entry there.
|
||||||
|
|
||||||
|
- **A plain `docker build .` of a clone stamps the version that
|
||||||
|
`git describe --tags --always` gives**, derived from the `.git` in the build
|
||||||
|
context as the canonical `Dockerfile` above shows. Without its failure check,
|
||||||
|
a missing `git` or an unreadable checkout would leave `-X main.Version=` empty
|
||||||
|
and the build would still exit 0. `script/docker` and `script/cibuild` pass
|
||||||
|
the version they compute on the host; it takes precedence. They do this
|
||||||
|
byte-identically across repos:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# Own line: a failing command substitution inside an argument does not
|
||||||
|
# trip `set -e`, so the inline form degrades to an empty constant.
|
||||||
|
version="$(git describe --tags --always --dirty 2>/dev/null || true)"
|
||||||
|
[ -n "$version" ] || version="unknown"
|
||||||
|
docker build --no-cache \
|
||||||
|
--build-arg VERSION="$version" \
|
||||||
|
-t "$(script/projectname)" .
|
||||||
|
```
|
||||||
|
|
||||||
|
`--always` makes an untagged repo yield an abbreviated commit hash rather
|
||||||
|
than failing, and the `[ -n "$version" ]` line is the single place the
|
||||||
|
fallback is applied — a live check that fires on a build from an export with
|
||||||
|
no `.git` and on a repository with no commits yet. Do not fold it into the
|
||||||
|
substitution as `|| echo unknown`, which makes the guard unreachable. The
|
||||||
|
Dockerfile's side is `ARG VERSION` in the stage that compiles, declared
|
||||||
|
there because `ARG` is stage-scoped; passing `VERSION` to a repo whose
|
||||||
|
Dockerfile declares no such `ARG` is ignored and costs nothing, which is why
|
||||||
|
the scripts stay byte-identical. One consequence for CI: the standard
|
||||||
|
checkout action clones shallow and fetches no tags, so a repo that embeds a
|
||||||
|
tag-derived version must set `fetch-depth: 0` on its checkout step.
|
||||||
|
|
||||||
|
- **Verify `.dockerignore` by enumerating the image, not by reading the
|
||||||
|
patterns.** Plant files at the root _and_ at least two directories deep, build
|
||||||
|
a probe image that does `COPY . .`, and list what actually landed
|
||||||
|
(`docker run --rm --entrypoint find IMAGE /app`). The `transferring context`
|
||||||
|
size is not a substitute: a nested secret is a few bytes, and BuildKit
|
||||||
|
transfers only the delta from the previous build.
|
||||||
|
|
||||||
- **No build artifacts in version control.** Code-derived data (compiled
|
- **No build artifacts in version control.** Code-derived data (compiled
|
||||||
bundles, minified output, generated assets) must never be committed to the
|
bundles, minified output, generated assets) must never be committed to the
|
||||||
@@ -263,12 +476,56 @@ style conventions are in separate documents:
|
|||||||
- Make all changes on a feature branch. You can do whatever you want on a
|
- Make all changes on a feature branch. You can do whatever you want on a
|
||||||
feature branch.
|
feature branch.
|
||||||
|
|
||||||
- `.golangci.yml` is standardized and must _NEVER_ be modified by an agent, only
|
- `.golangci.yml` is standardized. The vendored copy in a consuming repo must
|
||||||
manually by the user. Fetch from
|
_NEVER_ be modified by an agent: fetch it from
|
||||||
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.golangci.yml`. The
|
`https://git.eeqj.de/sneak/prompts/raw/branch/main/.golangci.yml` and keep it
|
||||||
canonical golangci-lint version is v2.12.2 (released 2026-05-06), installed
|
byte-identical, so that no repo can quietly loosen its own linting. Linter
|
||||||
commit-pinned via
|
configuration changes are made to the canonical copy in the `prompts` repo and
|
||||||
`go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@c0d3ddc9cf3faa61a4e378e879ece580256d76e5`.
|
reach consuming repos by re-vendoring; an agent may open a PR against
|
||||||
|
canonical, which only the user merges. One list is exempt from byte-identity,
|
||||||
|
because it cannot be written once for every repo: the `deny` list of the
|
||||||
|
`test-support` depguard rule, where a repo names its own test-support packages
|
||||||
|
by full import path. A repo adds entries there and changes nothing else, and a
|
||||||
|
re-vendor carries its entries forward. The canonical golangci-lint version is
|
||||||
|
v2.14.0 (released 2026-09-24), pinned as the digest of the lint phase's base
|
||||||
|
image
|
||||||
|
(`golangci/golangci-lint@sha256:ad862ba6b3798cbe0fd9fd7408d498fd74fbd2623a92406b2fd3898faf0bf98f`,
|
||||||
|
which reports `2.14.0 built with go1.27.0 from 114493f9`). A module's `go`
|
||||||
|
directive must not name a newer Go minor version than the one golangci-lint
|
||||||
|
was built with, or golangci-lint refuses to lint it: this release lints
|
||||||
|
`go 1.27.1` but not `go 1.28`. That digest is the only pin, since no repo
|
||||||
|
installs golangci-lint on the host. A repo sets the lint phase digest to the
|
||||||
|
one named here and re-vendors `.golangci.yml` in the same commit, whichever of
|
||||||
|
the two prompted the change: the canonical copy can name linters that an older
|
||||||
|
golangci-lint rejects, and a newer golangci-lint can add linters that
|
||||||
|
`default: all` switches on until the canonical copy disables them.
|
||||||
|
|
||||||
|
- **`script/bootstrap` installs a pinned tool by comparing versions, never by
|
||||||
|
testing presence.** An `if ! command -v <tool>; then install; fi` guard tests
|
||||||
|
`PATH` only, so on an already-provisioned machine the pin is inert and a
|
||||||
|
version bump is a silent no-op — while the Dockerfile, installing into a clean
|
||||||
|
image, gets the pinned version, so a local `make check` and `make docker` can
|
||||||
|
disagree about what the tool even is. The canonical form:
|
||||||
|
- compares the installed version against the pin over the **whole** version
|
||||||
|
token; a parser that stops at the first `-` reports `2.12.2` for a host
|
||||||
|
running `2.12.2-rc1` and skips the install;
|
||||||
|
- treats absent, non-zero, empty or unrecognised `--version` output as a
|
||||||
|
mismatch, so the failure direction is a redundant install and never a
|
||||||
|
skipped one;
|
||||||
|
- after installing, re-resolves the binary the way callers do — `hash -r`,
|
||||||
|
then through `PATH`, not through the directory the installer wrote to —
|
||||||
|
and fails naming the resolved path, since an install that a shadowing
|
||||||
|
binary hides succeeds while changing nothing any caller sees;
|
||||||
|
- is actually called, and prints the version on both success paths: a
|
||||||
|
function defined and never invoked has the same exit status and the same
|
||||||
|
empty output as one that worked.
|
||||||
|
|
||||||
|
Keep it POSIX sh: no arrays, no `[[`, no `grep -P`.
|
||||||
|
|
||||||
|
A Go tool a repo needs on the host is installed with `go install` pinned to
|
||||||
|
a commit hash (`go install <package>@<commit hash>`). It is never tracked as
|
||||||
|
a `go.mod` tool dependency or through a `tools.go` file, either of which
|
||||||
|
pulls the tool's own dependencies into the repo's `go.mod` and `go.sum`.
|
||||||
|
|
||||||
- When pinning images or packages by hash, add a comment above the reference
|
- When pinning images or packages by hash, add a comment above the reference
|
||||||
with the version and date (YYYY-MM-DD).
|
with the version and date (YYYY-MM-DD).
|
||||||
@@ -382,12 +639,14 @@ style conventions are in separate documents:
|
|||||||
settings.
|
settings.
|
||||||
|
|
||||||
- Avoid putting files in the repo root unless necessary. Root should contain
|
- Avoid putting files in the repo root unless necessary. Root should contain
|
||||||
only project-level config files (`README.md`, `Makefile`, `Dockerfile`,
|
only project-level config files (`README.md`, `AGENTS.md`, `Makefile`,
|
||||||
`LICENSE`, `.gitignore`, `.editorconfig`, `REPO_POLICIES.md`, and
|
`Dockerfile`, `LICENSE`, `.gitignore`, `.editorconfig`, `REPO_POLICIES.md`,
|
||||||
language-specific config). Everything else goes in a subdirectory. Canonical
|
and language-specific config). Everything else goes in a subdirectory.
|
||||||
subdirectory names:
|
Canonical subdirectory names:
|
||||||
- `bin/` — executable scripts and tools
|
- `bin/` — executable scripts and tools
|
||||||
- `cmd/` — Go command entrypoints
|
- `cmd/` — Go command entrypoints; thin only: one `main.go` per binary whose
|
||||||
|
body is a single call into `internal/` or `pkg/`, no project logic in
|
||||||
|
`cmd/`
|
||||||
- `configs/` — configuration templates and examples
|
- `configs/` — configuration templates and examples
|
||||||
- `deploy/` — deployment manifests (k8s, compose, terraform)
|
- `deploy/` — deployment manifests (k8s, compose, terraform)
|
||||||
- `docs/` — documentation and markdown (README.md stays in root)
|
- `docs/` — documentation and markdown (README.md stays in root)
|
||||||
@@ -414,3 +673,7 @@ style conventions are in separate documents:
|
|||||||
- Go: `go.mod`, `go.sum`, `.golangci.yml`
|
- Go: `go.mod`, `go.sum`, `.golangci.yml`
|
||||||
- JS: `package.json`, `yarn.lock`, `.prettierrc`, `.prettierignore`
|
- JS: `package.json`, `yarn.lock`, `.prettierrc`, `.prettierignore`
|
||||||
- Python: `pyproject.toml`
|
- Python: `pyproject.toml`
|
||||||
|
|
||||||
|
- Guidance for coding agents lives in one `AGENTS.md` at the repository root. It
|
||||||
|
is never committed under a file or directory named after one agent tool, such
|
||||||
|
as `CLAUDE.md` or `.claude/`, and never split into separate memory files.
|
||||||
|
|||||||
+3
-3
@@ -38,7 +38,7 @@ works correctly in production.
|
|||||||
responses
|
responses
|
||||||
- **Do not add `-short` flags** to skip slow tests
|
- **Do not add `-short` flags** to skip slow tests
|
||||||
- **Do not increase `-timeout`** to hide hanging queries
|
- **Do not increase `-timeout`** to hide hanging queries
|
||||||
- **Do not remove `-count=1` from `script/test`** — Go's test cache replays a
|
- **Do not remove `-count=1` from the test phase of the `Dockerfile`** — Go's
|
||||||
previous run's output without querying anything, so a cached pass is not
|
test cache replays a previous run's output without querying anything, so a
|
||||||
evidence that live resolution works
|
cached pass is not evidence that live resolution works
|
||||||
- **Do not modify linter configuration** to suppress findings
|
- **Do not modify linter configuration** to suppress findings
|
||||||
|
|||||||
@@ -10,15 +10,45 @@
|
|||||||
|
|
||||||
# Status
|
# Status
|
||||||
|
|
||||||
pre-1.0. No git tags. Work lands on `next` by PR. Open work for 1.0 is tracked
|
pre-1.0. Work lands on `next` by PR. Open work for 1.0 is tracked on the 1.0
|
||||||
on the 1.0 milestone: https://git.eeqj.de/sneak/dnswatcher/milestone/7
|
milestone: https://git.eeqj.de/sneak/dnswatcher/milestone/7
|
||||||
|
|
||||||
# Next Step
|
# Next Step
|
||||||
|
|
||||||
trial run of the finished image: https://git.eeqj.de/sneak/dnswatcher/issues/149
|
1.0 tracking issue: https://git.eeqj.de/sneak/dnswatcher/issues/66
|
||||||
|
|
||||||
# Completed Steps
|
# Completed Steps
|
||||||
|
|
||||||
|
- 2026-10-13: a hostname or a domain whose zone's nameservers all stop answering
|
||||||
|
gets an NS Failure for each, then an NS Recovery (closes #284).
|
||||||
|
- 2026-10-13: an IPv6 address is written in brackets before its port, as in
|
||||||
|
`[2001:db8::1]:443`, in keys and Port Change notifications (closes #270).
|
||||||
|
- 2026-10-13: `TODO.md` names only open issues as next and future steps, and its
|
||||||
|
Status says nothing about git tags (closes #281).
|
||||||
|
- 2026-10-13: a port check that finds port 443 closed removes that address's
|
||||||
|
certificate entries, so none is left shown as `ok` (closes #265).
|
||||||
|
- 2026-10-13: a state file holding `{}`, or leaving out a section, loads with
|
||||||
|
that section empty; the first check no longer crashes on it (closes #267).
|
||||||
|
- 2026-10-13: a stop before the first scan completes sends no startup
|
||||||
|
notification; a scan that ran to the end still sends it (closes #271).
|
||||||
|
- 2026-10-13: a nameserver leaving a domain's delegation sends only NS Change;
|
||||||
|
one leaving a hostname's zone sends NS Change, not NS Failure (closes #262).
|
||||||
|
- 2026-10-13: `DNSWATCHER_METRICS_USERNAME` set without
|
||||||
|
`DNSWATCHER_METRICS_PASSWORD` stops startup (closes #268).
|
||||||
|
- 2026-10-13: a save syncs the state file to disk before renaming it into place,
|
||||||
|
so a crash cannot leave it empty and stop the next start (closes #264).
|
||||||
|
- 2026-10-13: a `PORT` that cannot be bound stops startup with an error naming
|
||||||
|
the address, instead of running without the HTTP server (closes #266).
|
||||||
|
- 2026-10-13: a bad `PORT`, `DNSWATCHER_TLS_EXPIRY_WARNING` or true/false
|
||||||
|
setting stops startup instead of being read as 0 or false (closes #269).
|
||||||
|
- 2026-10-13: a check saving the state while the dashboard or `/api/v1/status`
|
||||||
|
is read cannot crash the process (closes #261).
|
||||||
|
- 2026-10-06: canonical files re-fetched from `sneak/prompts` at `dd4027b`; lint
|
||||||
|
and test are phases of the `Dockerfile`, every scripted build uncached (closes
|
||||||
|
#257).
|
||||||
|
- 2026-10-05: a name listed in `DNSWATCHER_SKIP_RECORD_NOTIFICATIONS` gets no
|
||||||
|
Record Change or Inconsistency notification; a name listed there that is not
|
||||||
|
in `DNSWATCHER_TARGETS` stops startup (closes #255).
|
||||||
- 2026-10-02: a nameserver whose query for one record type failed while the
|
- 2026-10-02: a nameserver whose query for one record type failed while the
|
||||||
others answered with no records is `ok`, not `nodata` (closes #253).
|
others answered with no records is `ok`, not `nodata` (closes #253).
|
||||||
- 2026-10-02: a domain that does not exist is shown so, with no nameservers; no
|
- 2026-10-02: a domain that does not exist is shown so, with no nameservers; no
|
||||||
@@ -177,6 +207,4 @@ trial run of the finished image: https://git.eeqj.de/sneak/dnswatcher/issues/149
|
|||||||
|
|
||||||
# Future Steps
|
# Future Steps
|
||||||
|
|
||||||
- 1.0 readiness: run it with a real config and read the logs:
|
- DNSSEC validation, after 1.0: https://git.eeqj.de/sneak/dnswatcher/issues/59
|
||||||
https://git.eeqj.de/sneak/dnswatcher/issues/66
|
|
||||||
- review toward 1.0: https://git.eeqj.de/sneak/dnswatcher/issues/144
|
|
||||||
|
|||||||
+202
-45
@@ -5,6 +5,8 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -23,6 +25,9 @@ const (
|
|||||||
defaultTLSExpiryWarning = 7
|
defaultTLSExpiryWarning = 7
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// maxPort is the highest TCP port number.
|
||||||
|
const maxPort = 65535
|
||||||
|
|
||||||
// ErrNoTargets is returned when no monitoring targets are configured.
|
// ErrNoTargets is returned when no monitoring targets are configured.
|
||||||
var ErrNoTargets = errors.New(
|
var ErrNoTargets = errors.New(
|
||||||
"no monitoring targets configured: set DNSWATCHER_TARGETS environment variable",
|
"no monitoring targets configured: set DNSWATCHER_TARGETS environment variable",
|
||||||
@@ -35,6 +40,34 @@ var ErrInvalidInterval = errors.New(
|
|||||||
"interval must be a positive duration such as 30m or 1h",
|
"interval must be a positive duration such as 30m or 1h",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ErrNotInTargets is returned when DNSWATCHER_SKIP_RECORD_NOTIFICATIONS
|
||||||
|
// lists a name that is not in DNSWATCHER_TARGETS.
|
||||||
|
var ErrNotInTargets = errors.New("name is not in DNSWATCHER_TARGETS")
|
||||||
|
|
||||||
|
// ErrInvalidPort is returned when PORT is set but is not a whole number
|
||||||
|
// from 1 to 65535. An empty value counts as unset and means the default.
|
||||||
|
var ErrInvalidPort = errors.New("port must be a whole number from 1 to 65535")
|
||||||
|
|
||||||
|
// ErrInvalidTLSExpiryWarning is returned when DNSWATCHER_TLS_EXPIRY_WARNING
|
||||||
|
// is set but is not a whole number, 1 or more. An empty value counts as unset
|
||||||
|
// and means the default.
|
||||||
|
var ErrInvalidTLSExpiryWarning = errors.New(
|
||||||
|
"TLS expiry warning must be a whole number of days, 1 or more",
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrInvalidBool is returned when DNSWATCHER_DEBUG,
|
||||||
|
// DNSWATCHER_MAINTENANCE_MODE or DNSWATCHER_SEND_TEST_NOTIFICATION is set
|
||||||
|
// but is not a value strconv.ParseBool accepts. An empty value counts as
|
||||||
|
// unset and means the default.
|
||||||
|
var ErrInvalidBool = errors.New("value must be true or false")
|
||||||
|
|
||||||
|
// ErrNoMetricsPassword is returned when DNSWATCHER_METRICS_USERNAME is set and
|
||||||
|
// DNSWATCHER_METRICS_PASSWORD is empty. Basic Auth on /metrics would otherwise
|
||||||
|
// let in anyone who sends the username with an empty password.
|
||||||
|
var ErrNoMetricsPassword = errors.New(
|
||||||
|
"DNSWATCHER_METRICS_PASSWORD must be set when DNSWATCHER_METRICS_USERNAME is set",
|
||||||
|
)
|
||||||
|
|
||||||
// Params contains dependencies for Config.
|
// Params contains dependencies for Config.
|
||||||
type Params struct {
|
type Params struct {
|
||||||
fx.In
|
fx.In
|
||||||
@@ -45,24 +78,25 @@ type Params struct {
|
|||||||
|
|
||||||
// Config holds application configuration.
|
// Config holds application configuration.
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Port int
|
Port int
|
||||||
Debug bool
|
Debug bool
|
||||||
DataDir string
|
DataDir string
|
||||||
Domains []string
|
Domains []string
|
||||||
Hostnames []string
|
Hostnames []string
|
||||||
SlackWebhook string
|
SkipRecordNotifications []string
|
||||||
MattermostWebhook string
|
SlackWebhook string
|
||||||
NtfyTopic string
|
MattermostWebhook string
|
||||||
DNSInterval time.Duration
|
NtfyTopic string
|
||||||
TLSInterval time.Duration
|
DNSInterval time.Duration
|
||||||
TLSExpiryWarning int
|
TLSInterval time.Duration
|
||||||
SentryDSN string
|
TLSExpiryWarning int
|
||||||
MaintenanceMode bool
|
SentryDSN string
|
||||||
MetricsUsername string
|
MaintenanceMode bool
|
||||||
MetricsPassword string
|
MetricsUsername string
|
||||||
SendTestNotification bool
|
MetricsPassword string
|
||||||
params *Params
|
SendTestNotification bool
|
||||||
log *slog.Logger
|
params *Params
|
||||||
|
log *slog.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a new Config instance from environment and config files.
|
// New creates a new Config instance from environment and config files.
|
||||||
@@ -81,6 +115,10 @@ func New(_ fx.Lifecycle, params Params) (*Config, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if cfg.MetricsUsername != "" && cfg.MetricsPassword == "" {
|
||||||
|
return nil, ErrNoMetricsPassword
|
||||||
|
}
|
||||||
|
|
||||||
configureDebugLogging(cfg, params)
|
configureDebugLogging(cfg, params)
|
||||||
|
|
||||||
return cfg, nil
|
return cfg, nil
|
||||||
@@ -103,6 +141,7 @@ func setupViper(name string) {
|
|||||||
viper.SetDefault("DEBUG", false)
|
viper.SetDefault("DEBUG", false)
|
||||||
viper.SetDefault("DATA_DIR", "/var/lib/"+name)
|
viper.SetDefault("DATA_DIR", "/var/lib/"+name)
|
||||||
viper.SetDefault("TARGETS", "")
|
viper.SetDefault("TARGETS", "")
|
||||||
|
viper.SetDefault("SKIP_RECORD_NOTIFICATIONS", "")
|
||||||
viper.SetDefault("SLACK_WEBHOOK", "")
|
viper.SetDefault("SLACK_WEBHOOK", "")
|
||||||
viper.SetDefault("MATTERMOST_WEBHOOK", "")
|
viper.SetDefault("MATTERMOST_WEBHOOK", "")
|
||||||
viper.SetDefault("NTFY_TOPIC", "")
|
viper.SetDefault("NTFY_TOPIC", "")
|
||||||
@@ -120,16 +159,9 @@ func buildConfig(
|
|||||||
log *slog.Logger,
|
log *slog.Logger,
|
||||||
params *Params,
|
params *Params,
|
||||||
) (*Config, error) {
|
) (*Config, error) {
|
||||||
err := viper.ReadInConfig()
|
err := readConfigFile(log)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
var notFound viper.ConfigFileNotFoundError
|
return nil, err
|
||||||
if !errors.As(err, ¬Found) {
|
|
||||||
log.Error("config file malformed", "error", err)
|
|
||||||
|
|
||||||
return nil, fmt.Errorf(
|
|
||||||
"config file malformed: %w", err,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
dnsInterval, err := parseInterval("DNS_INTERVAL")
|
dnsInterval, err := parseInterval("DNS_INTERVAL")
|
||||||
@@ -147,30 +179,78 @@ func buildConfig(
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
skipRecordNotifications, err := parseSkipRecordNotifications(
|
||||||
|
domains, hostnames,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
port, err := parsePort()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
tlsExpiryWarning, err := parseTLSExpiryWarning()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
debug, err := parseBool("DEBUG")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
maintenanceMode, err := parseBool("MAINTENANCE_MODE")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
sendTestNotification, err := parseBool("SEND_TEST_NOTIFICATION")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
cfg := &Config{
|
cfg := &Config{
|
||||||
Port: viper.GetInt("PORT"),
|
Port: port,
|
||||||
Debug: viper.GetBool("DEBUG"),
|
Debug: debug,
|
||||||
DataDir: viper.GetString("DATA_DIR"),
|
DataDir: viper.GetString("DATA_DIR"),
|
||||||
Domains: domains,
|
Domains: domains,
|
||||||
Hostnames: hostnames,
|
Hostnames: hostnames,
|
||||||
SlackWebhook: viper.GetString("SLACK_WEBHOOK"),
|
SkipRecordNotifications: skipRecordNotifications,
|
||||||
MattermostWebhook: viper.GetString("MATTERMOST_WEBHOOK"),
|
SlackWebhook: viper.GetString("SLACK_WEBHOOK"),
|
||||||
NtfyTopic: viper.GetString("NTFY_TOPIC"),
|
MattermostWebhook: viper.GetString("MATTERMOST_WEBHOOK"),
|
||||||
DNSInterval: dnsInterval,
|
NtfyTopic: viper.GetString("NTFY_TOPIC"),
|
||||||
TLSInterval: tlsInterval,
|
DNSInterval: dnsInterval,
|
||||||
TLSExpiryWarning: viper.GetInt("TLS_EXPIRY_WARNING"),
|
TLSInterval: tlsInterval,
|
||||||
SentryDSN: viper.GetString("SENTRY_DSN"),
|
TLSExpiryWarning: tlsExpiryWarning,
|
||||||
MaintenanceMode: viper.GetBool("MAINTENANCE_MODE"),
|
SentryDSN: viper.GetString("SENTRY_DSN"),
|
||||||
MetricsUsername: viper.GetString("METRICS_USERNAME"),
|
MaintenanceMode: maintenanceMode,
|
||||||
MetricsPassword: viper.GetString("METRICS_PASSWORD"),
|
MetricsUsername: viper.GetString("METRICS_USERNAME"),
|
||||||
SendTestNotification: viper.GetBool("SEND_TEST_NOTIFICATION"),
|
MetricsPassword: viper.GetString("METRICS_PASSWORD"),
|
||||||
params: params,
|
SendTestNotification: sendTestNotification,
|
||||||
log: log,
|
params: params,
|
||||||
|
log: log,
|
||||||
}
|
}
|
||||||
|
|
||||||
return cfg, nil
|
return cfg, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// readConfigFile reads the config file, if there is one.
|
||||||
|
func readConfigFile(log *slog.Logger) error {
|
||||||
|
err := viper.ReadInConfig()
|
||||||
|
if err != nil {
|
||||||
|
var notFound viper.ConfigFileNotFoundError
|
||||||
|
if !errors.As(err, ¬Found) {
|
||||||
|
log.Error("config file malformed", "error", err)
|
||||||
|
|
||||||
|
return fmt.Errorf("config file malformed: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// parseInterval reads the DNSWATCHER_-prefixed setting key as a duration. A
|
// parseInterval reads the DNSWATCHER_-prefixed setting key as a duration. A
|
||||||
// value that does not parse, or is zero or negative, is an error naming the
|
// value that does not parse, or is zero or negative, is an error naming the
|
||||||
// variable and the value; an unset variable has its default from setupViper.
|
// variable and the value; an unset variable has its default from setupViper.
|
||||||
@@ -187,6 +267,53 @@ func parseInterval(key string) (time.Duration, error) {
|
|||||||
return interval, nil
|
return interval, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// parsePort reads PORT, which has no DNSWATCHER_ prefix, as a port number. A
|
||||||
|
// value that is not a whole number from 1 to 65535 is an error naming the
|
||||||
|
// variable and the value; an unset variable has its default from setupViper.
|
||||||
|
func parsePort() (int, error) {
|
||||||
|
value := viper.GetString("PORT")
|
||||||
|
|
||||||
|
port, err := strconv.Atoi(value)
|
||||||
|
if err != nil || port < 1 || port > maxPort {
|
||||||
|
return 0, fmt.Errorf("invalid PORT %q: %w", value, ErrInvalidPort)
|
||||||
|
}
|
||||||
|
|
||||||
|
return port, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseTLSExpiryWarning reads DNSWATCHER_TLS_EXPIRY_WARNING as a number of
|
||||||
|
// days. A value that is not a whole number, 1 or more, is an error naming the
|
||||||
|
// variable and the value; an unset variable has its default from setupViper.
|
||||||
|
func parseTLSExpiryWarning() (int, error) {
|
||||||
|
value := viper.GetString("TLS_EXPIRY_WARNING")
|
||||||
|
|
||||||
|
days, err := strconv.Atoi(value)
|
||||||
|
if err != nil || days < 1 {
|
||||||
|
return 0, fmt.Errorf(
|
||||||
|
"invalid DNSWATCHER_TLS_EXPIRY_WARNING %q: %w",
|
||||||
|
value, ErrInvalidTLSExpiryWarning,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return days, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseBool reads the DNSWATCHER_-prefixed setting key as true or false. A
|
||||||
|
// value strconv.ParseBool does not accept is an error naming the variable and
|
||||||
|
// the value; an unset variable has its default from setupViper.
|
||||||
|
func parseBool(key string) (bool, error) {
|
||||||
|
value := viper.GetString(key)
|
||||||
|
|
||||||
|
result, err := strconv.ParseBool(value)
|
||||||
|
if err != nil {
|
||||||
|
return false, fmt.Errorf(
|
||||||
|
"invalid DNSWATCHER_%s %q: %w", key, value, ErrInvalidBool,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
func parseAndValidateTargets() ([]string, []string, error) {
|
func parseAndValidateTargets() ([]string, []string, error) {
|
||||||
domains, hostnames, err := ClassifyTargets(
|
domains, hostnames, err := ClassifyTargets(
|
||||||
parseCSV(viper.GetString("TARGETS")),
|
parseCSV(viper.GetString("TARGETS")),
|
||||||
@@ -204,6 +331,36 @@ func parseAndValidateTargets() ([]string, []string, error) {
|
|||||||
return domains, hostnames, nil
|
return domains, hostnames, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// parseSkipRecordNotifications reads DNSWATCHER_SKIP_RECORD_NOTIFICATIONS,
|
||||||
|
// a comma-separated list of names from the targets. Each name is written
|
||||||
|
// as ClassifyTargets writes a target, in lower case without a trailing
|
||||||
|
// dot, and a name listed more than once is kept once. A name that is
|
||||||
|
// not one of domains or hostnames is an error naming it.
|
||||||
|
func parseSkipRecordNotifications(
|
||||||
|
domains, hostnames []string,
|
||||||
|
) ([]string, error) {
|
||||||
|
value := viper.GetString("SKIP_RECORD_NOTIFICATIONS")
|
||||||
|
|
||||||
|
var names []string
|
||||||
|
|
||||||
|
for _, listed := range parseCSV(value) {
|
||||||
|
name := strings.ToLower(strings.TrimSuffix(listed, "."))
|
||||||
|
|
||||||
|
if !slices.Contains(domains, name) && !slices.Contains(hostnames, name) {
|
||||||
|
return nil, fmt.Errorf(
|
||||||
|
"invalid DNSWATCHER_SKIP_RECORD_NOTIFICATIONS %q: %w",
|
||||||
|
listed, ErrNotInTargets,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !slices.Contains(names, name) {
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return names, nil
|
||||||
|
}
|
||||||
|
|
||||||
func parseCSV(input string) []string {
|
func parseCSV(input string) []string {
|
||||||
if input == "" {
|
if input == "" {
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -57,6 +57,7 @@ func TestNew_DefaultValues(t *testing.T) {
|
|||||||
assert.Empty(t, cfg.MetricsUsername)
|
assert.Empty(t, cfg.MetricsUsername)
|
||||||
assert.Empty(t, cfg.MetricsPassword)
|
assert.Empty(t, cfg.MetricsPassword)
|
||||||
assert.False(t, cfg.SendTestNotification)
|
assert.False(t, cfg.SendTestNotification)
|
||||||
|
assert.Empty(t, cfg.SkipRecordNotifications)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNew_EnvironmentOverrides(t *testing.T) {
|
func TestNew_EnvironmentOverrides(t *testing.T) {
|
||||||
@@ -115,7 +116,7 @@ func TestNew_OnlyEmptyCSVSegments(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TestNew_InvalidIntervalStopsStartup checks values that must stop startup;
|
// TestNew_InvalidIntervalStopsStartup checks values that must stop startup;
|
||||||
// TestNew_DefaultValues and TestNew_EmptyIntervalMeansDefault check that an
|
// TestNew_DefaultValues and TestNew_EmptyValueMeansDefault check that an
|
||||||
// unset or empty interval means the default.
|
// unset or empty interval means the default.
|
||||||
func TestNew_InvalidIntervalStopsStartup(t *testing.T) {
|
func TestNew_InvalidIntervalStopsStartup(t *testing.T) {
|
||||||
variables := []string{"DNSWATCHER_DNS_INTERVAL", "DNSWATCHER_TLS_INTERVAL"}
|
variables := []string{"DNSWATCHER_DNS_INTERVAL", "DNSWATCHER_TLS_INTERVAL"}
|
||||||
@@ -143,16 +144,107 @@ func TestNew_InvalidIntervalStopsStartup(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNew_EmptyIntervalMeansDefault(t *testing.T) {
|
func TestNew_EmptyValueMeansDefault(t *testing.T) {
|
||||||
viper.Reset()
|
viper.Reset()
|
||||||
t.Setenv("DNSWATCHER_TARGETS", "example.com")
|
t.Setenv("DNSWATCHER_TARGETS", "example.com")
|
||||||
t.Setenv("DNSWATCHER_DNS_INTERVAL", "")
|
t.Setenv("DNSWATCHER_DNS_INTERVAL", "")
|
||||||
t.Setenv("DNSWATCHER_TLS_INTERVAL", "")
|
t.Setenv("DNSWATCHER_TLS_INTERVAL", "")
|
||||||
|
t.Setenv("PORT", "")
|
||||||
|
t.Setenv("DNSWATCHER_TLS_EXPIRY_WARNING", "")
|
||||||
|
t.Setenv("DNSWATCHER_DEBUG", "")
|
||||||
|
t.Setenv("DNSWATCHER_MAINTENANCE_MODE", "")
|
||||||
|
t.Setenv("DNSWATCHER_SEND_TEST_NOTIFICATION", "")
|
||||||
|
|
||||||
cfg, err := config.New(nil, newTestParams(t))
|
cfg, err := config.New(nil, newTestParams(t))
|
||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
assert.Equal(t, time.Hour, cfg.DNSInterval)
|
assert.Equal(t, time.Hour, cfg.DNSInterval)
|
||||||
assert.Equal(t, 12*time.Hour, cfg.TLSInterval)
|
assert.Equal(t, 12*time.Hour, cfg.TLSInterval)
|
||||||
|
assert.Equal(t, 8080, cfg.Port)
|
||||||
|
assert.Equal(t, 7, cfg.TLSExpiryWarning)
|
||||||
|
assert.False(t, cfg.Debug)
|
||||||
|
assert.False(t, cfg.MaintenanceMode)
|
||||||
|
assert.False(t, cfg.SendTestNotification)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNew_InvalidNumberOrBoolStopsStartup checks values that must stop
|
||||||
|
// startup; TestNew_EnvironmentOverrides, the two tests after this one and
|
||||||
|
// TestNew_EmptyValueMeansDefault check values that must not.
|
||||||
|
func TestNew_InvalidNumberOrBoolStopsStartup(t *testing.T) {
|
||||||
|
notBools := []string{"yes", "on", "2", "tRUE"}
|
||||||
|
tests := []struct {
|
||||||
|
variable string
|
||||||
|
values []string
|
||||||
|
want error
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
variable: "PORT",
|
||||||
|
values: []string{"notaport", "0", "-1", "65536", "8080.5"},
|
||||||
|
want: config.ErrInvalidPort,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
variable: "DNSWATCHER_TLS_EXPIRY_WARNING",
|
||||||
|
values: []string{"abc", "7d", "0", "-5"},
|
||||||
|
want: config.ErrInvalidTLSExpiryWarning,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
variable: "DNSWATCHER_DEBUG",
|
||||||
|
values: notBools,
|
||||||
|
want: config.ErrInvalidBool,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
variable: "DNSWATCHER_MAINTENANCE_MODE",
|
||||||
|
values: notBools,
|
||||||
|
want: config.ErrInvalidBool,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
variable: "DNSWATCHER_SEND_TEST_NOTIFICATION",
|
||||||
|
values: notBools,
|
||||||
|
want: config.ErrInvalidBool,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
for _, value := range tt.values {
|
||||||
|
t.Run(tt.variable+"="+value, func(t *testing.T) {
|
||||||
|
viper.Reset()
|
||||||
|
t.Setenv("DNSWATCHER_TARGETS", "example.com")
|
||||||
|
t.Setenv(tt.variable, value)
|
||||||
|
|
||||||
|
_, err := config.New(nil, newTestParams(t))
|
||||||
|
require.ErrorIs(t, err, tt.want)
|
||||||
|
require.ErrorContains(t, err, tt.variable)
|
||||||
|
require.ErrorContains(t, err, strconv.Quote(value))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNew_LowestNumbersAndOtherSpellingsOfTrue(t *testing.T) {
|
||||||
|
viper.Reset()
|
||||||
|
t.Setenv("DNSWATCHER_TARGETS", "example.com")
|
||||||
|
t.Setenv("PORT", "1")
|
||||||
|
t.Setenv("DNSWATCHER_TLS_EXPIRY_WARNING", "1")
|
||||||
|
t.Setenv("DNSWATCHER_DEBUG", "1")
|
||||||
|
t.Setenv("DNSWATCHER_MAINTENANCE_MODE", "T")
|
||||||
|
t.Setenv("DNSWATCHER_SEND_TEST_NOTIFICATION", "True")
|
||||||
|
|
||||||
|
cfg, err := config.New(nil, newTestParams(t))
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, 1, cfg.Port)
|
||||||
|
assert.Equal(t, 1, cfg.TLSExpiryWarning)
|
||||||
|
assert.True(t, cfg.Debug)
|
||||||
|
assert.True(t, cfg.MaintenanceMode)
|
||||||
|
assert.True(t, cfg.SendTestNotification)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNew_HighestPort(t *testing.T) {
|
||||||
|
viper.Reset()
|
||||||
|
t.Setenv("DNSWATCHER_TARGETS", "example.com")
|
||||||
|
t.Setenv("PORT", "65535")
|
||||||
|
|
||||||
|
cfg, err := config.New(nil, newTestParams(t))
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, 65535, cfg.Port)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNew_DebugEnablesDebugLogging(t *testing.T) {
|
func TestNew_DebugEnablesDebugLogging(t *testing.T) {
|
||||||
@@ -235,6 +327,51 @@ func TestNew_TargetsWithTrailingComma(t *testing.T) {
|
|||||||
"trailing comma should be ignored")
|
"trailing comma should be ignored")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestNew_SkipRecordNotifications(t *testing.T) {
|
||||||
|
viper.Reset()
|
||||||
|
t.Setenv("DNSWATCHER_TARGETS", "example.net,www.example.net,example.org")
|
||||||
|
t.Setenv("DNSWATCHER_SKIP_RECORD_NOTIFICATIONS",
|
||||||
|
" WWW.Example.net. , example.net,www.example.net")
|
||||||
|
|
||||||
|
cfg, err := config.New(nil, newTestParams(t))
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t,
|
||||||
|
[]string{"www.example.net", "example.net"},
|
||||||
|
cfg.SkipRecordNotifications,
|
||||||
|
"names are written as targets are, each once",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNew_SkipRecordNotificationsNotInTargetsStopsStartup(t *testing.T) {
|
||||||
|
viper.Reset()
|
||||||
|
t.Setenv("DNSWATCHER_TARGETS", "example.net")
|
||||||
|
t.Setenv("DNSWATCHER_SKIP_RECORD_NOTIFICATIONS",
|
||||||
|
"example.net,www.example.net")
|
||||||
|
|
||||||
|
_, err := config.New(nil, newTestParams(t))
|
||||||
|
require.ErrorIs(t, err, config.ErrNotInTargets)
|
||||||
|
require.ErrorContains(t, err, "DNSWATCHER_SKIP_RECORD_NOTIFICATIONS")
|
||||||
|
require.ErrorContains(t, err, `"www.example.net"`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNew_MetricsUsernameWithoutPasswordStopsStartup checks an unset and an
|
||||||
|
// empty password; TestNew_EnvironmentOverrides checks a username with one.
|
||||||
|
func TestNew_MetricsUsernameWithoutPasswordStopsStartup(t *testing.T) {
|
||||||
|
viper.Reset()
|
||||||
|
t.Setenv("DNSWATCHER_TARGETS", "example.com")
|
||||||
|
t.Setenv("DNSWATCHER_METRICS_USERNAME", "prom")
|
||||||
|
|
||||||
|
_, err := config.New(nil, newTestParams(t))
|
||||||
|
require.ErrorIs(t, err, config.ErrNoMetricsPassword, "password unset")
|
||||||
|
require.ErrorContains(t, err, "DNSWATCHER_METRICS_PASSWORD")
|
||||||
|
|
||||||
|
viper.Reset()
|
||||||
|
t.Setenv("DNSWATCHER_METRICS_PASSWORD", "")
|
||||||
|
|
||||||
|
_, err = config.New(nil, newTestParams(t))
|
||||||
|
require.ErrorIs(t, err, config.ErrNoMetricsPassword, "password empty")
|
||||||
|
}
|
||||||
|
|
||||||
func TestNew_CustomDNSIntervalDuration(t *testing.T) {
|
func TestNew_CustomDNSIntervalDuration(t *testing.T) {
|
||||||
viper.Reset()
|
viper.Reset()
|
||||||
t.Setenv("DNSWATCHER_TARGETS", "example.com")
|
t.Setenv("DNSWATCHER_TARGETS", "example.com")
|
||||||
|
|||||||
@@ -2,6 +2,23 @@ package resolver
|
|||||||
|
|
||||||
import "errors"
|
import "errors"
|
||||||
|
|
||||||
|
// NoAnswerError is returned when the walk to a name's nameservers
|
||||||
|
// reached a zone through a referral and none of that zone's
|
||||||
|
// nameservers, Nameservers as the referral names them, answered. Err
|
||||||
|
// says why they did not.
|
||||||
|
type NoAnswerError struct {
|
||||||
|
Nameservers []string
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *NoAnswerError) Error() string {
|
||||||
|
return e.Err.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *NoAnswerError) Unwrap() error {
|
||||||
|
return e.Err
|
||||||
|
}
|
||||||
|
|
||||||
// Sentinel errors returned by the resolver.
|
// Sentinel errors returned by the resolver.
|
||||||
var (
|
var (
|
||||||
// ErrNoNameservers is returned when no authoritative NS
|
// ErrNoNameservers is returned when no authoritative NS
|
||||||
|
|||||||
@@ -31,9 +31,11 @@ func NewWithQueryTimeout(log *slog.Logger, timeout time.Duration) *Resolver {
|
|||||||
func (r *Resolver) FollowDelegation(
|
func (r *Resolver) FollowDelegation(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
domain string,
|
domain string,
|
||||||
|
zone string,
|
||||||
|
nameservers []string,
|
||||||
servers []string,
|
servers []string,
|
||||||
) ([]string, error) {
|
) ([]string, error) {
|
||||||
return r.followDelegation(ctx, domain, servers)
|
return r.followDelegation(ctx, domain, zone, nameservers, servers)
|
||||||
}
|
}
|
||||||
|
|
||||||
// FindAuthoritativeNameserversFrom exports findAuthoritativeNameservers
|
// FindAuthoritativeNameserversFrom exports findAuthoritativeNameservers
|
||||||
|
|||||||
@@ -204,20 +204,24 @@ func glueIPs(nsNames []string, glue map[string][]net.IP) []string {
|
|||||||
return ips
|
return ips
|
||||||
}
|
}
|
||||||
|
|
||||||
// followDelegation follows referrals from servers, the root servers, to
|
// followDelegation follows referrals to domain from servers, the
|
||||||
// domain and returns the NS set of domain's delegation. When the servers
|
// addresses of the servers of zone, and returns the NS set of domain's
|
||||||
// of the zone domain is in answer that domain does not exist, the error
|
// delegation. nameservers are the names a referral gave the servers of
|
||||||
// is ErrNXDomain. When they answer that it has no delegation of its own,
|
// zone; the walk to a name's nameservers starts at the root servers, the
|
||||||
|
// servers of zone ".", which no referral names. When the servers of the
|
||||||
|
// zone domain is in answer that domain does not exist, the error is
|
||||||
|
// ErrNXDomain. When they answer that it has no delegation of its own,
|
||||||
// because it is not the zone's apex, the set is empty and there is no
|
// because it is not the zone's apex, the set is empty and there is no
|
||||||
// error. Any other error means that no such answer came.
|
// error. Any other error means that no such answer came; it is a
|
||||||
|
// *NoAnswerError when the servers that did not answer are those of a
|
||||||
|
// zone a referral named.
|
||||||
func (r *Resolver) followDelegation(
|
func (r *Resolver) followDelegation(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
domain string,
|
domain string,
|
||||||
|
zone string,
|
||||||
|
nameservers []string,
|
||||||
servers []string,
|
servers []string,
|
||||||
) ([]string, error) {
|
) ([]string, error) {
|
||||||
// servers are the root servers, the servers of zone ".".
|
|
||||||
zone := "."
|
|
||||||
|
|
||||||
var withoutAddresses []string
|
var withoutAddresses []string
|
||||||
|
|
||||||
for range maxDelegation {
|
for range maxDelegation {
|
||||||
@@ -228,6 +232,12 @@ func (r *Resolver) followDelegation(
|
|||||||
resp, err := r.queryZone(
|
resp, err := r.queryZone(
|
||||||
ctx, servers, withoutAddresses, zone, domain, dns.TypeNS, 0,
|
ctx, servers, withoutAddresses, zone, domain, dns.TypeNS, 0,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// A query that ctx cut short says nothing about the servers.
|
||||||
|
if err != nil && len(nameservers) > 0 && checkCtx(ctx) == nil {
|
||||||
|
return nil, &NoAnswerError{Nameservers: nameservers, Err: err}
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -256,6 +266,7 @@ func (r *Resolver) followDelegation(
|
|||||||
return r.resolveNSIterative(ctx, domain)
|
return r.resolveNSIterative(ctx, domain)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
nameservers = authNS
|
||||||
servers, withoutAddresses = referralNameservers(resp)
|
servers, withoutAddresses = referralNameservers(resp)
|
||||||
zone = referralZone(resp)
|
zone = referralZone(resp)
|
||||||
}
|
}
|
||||||
@@ -626,7 +637,8 @@ func (r *Resolver) resolveARecord(
|
|||||||
// them. When the servers asked answer that the name has no delegation
|
// them. When the servers asked answer that the name has no delegation
|
||||||
// of its own, or does not exist, it tries each parent name in turn, so
|
// of its own, or does not exist, it tries each parent name in turn, so
|
||||||
// it returns the nameservers of the zone the name is in. When they do
|
// it returns the nameservers of the zone the name is in. When they do
|
||||||
// not answer, it returns the error and tries no parent name.
|
// not answer, it returns the error and tries no parent name; when a
|
||||||
|
// referral named them, the error is a *NoAnswerError naming them.
|
||||||
func (r *Resolver) FindAuthoritativeNameservers(
|
func (r *Resolver) FindAuthoritativeNameservers(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
domain string,
|
domain string,
|
||||||
@@ -655,7 +667,7 @@ func (r *Resolver) findAuthoritativeNameservers(
|
|||||||
|
|
||||||
candidate := strings.Join(labels[i:], ".") + "."
|
candidate := strings.Join(labels[i:], ".") + "."
|
||||||
|
|
||||||
nsNames, err := r.followDelegation(ctx, candidate, servers)
|
nsNames, err := r.followDelegation(ctx, candidate, ".", nil, servers)
|
||||||
if err != nil && !errors.Is(err, ErrNXDomain) {
|
if err != nil && !errors.Is(err, ErrNXDomain) {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -1067,7 +1079,7 @@ func (r *Resolver) LookupNS(
|
|||||||
}
|
}
|
||||||
|
|
||||||
return r.followDelegation(
|
return r.followDelegation(
|
||||||
ctx, dns.Fqdn(strings.ToLower(domain)), rootServerList(),
|
ctx, dns.Fqdn(strings.ToLower(domain)), ".", nil, rootServerList(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -121,7 +121,9 @@ func TestFindAuthoritativeNameservers_DelegatedSubdomain(
|
|||||||
// delegation of its own, so the lookup returns that walk's error, about
|
// delegation of its own, so the lookup returns that walk's error, about
|
||||||
// www.google.com, and tries no parent name: trying google.com and com
|
// www.google.com, and tries no parent name: trying google.com and com
|
||||||
// would end in ErrNoNameservers, or in the error of a walk for one of
|
// would end in ErrNoNameservers, or in the error of a walk for one of
|
||||||
// them.
|
// them. The servers that did not answer are those the walk started at,
|
||||||
|
// which no referral named, so the error is no NoAnswerError, as when
|
||||||
|
// the host running dnswatcher has lost its network.
|
||||||
func TestFindAuthoritativeNameservers_NoAnswer(t *testing.T) {
|
func TestFindAuthoritativeNameservers_NoAnswer(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -134,6 +136,9 @@ func TestFindAuthoritativeNameservers_NoAnswer(t *testing.T) {
|
|||||||
require.NotErrorIs(t, err, resolver.ErrNoNameservers)
|
require.NotErrorIs(t, err, resolver.ErrNoNameservers)
|
||||||
assert.Contains(t, err.Error(), "query www.google.com. @"+noAnswerAddress)
|
assert.Contains(t, err.Error(), "query www.google.com. @"+noAnswerAddress)
|
||||||
assert.Empty(t, nameservers)
|
assert.Empty(t, nameservers)
|
||||||
|
|
||||||
|
var noAnswer *resolver.NoAnswerError
|
||||||
|
assert.NotErrorAs(t, err, &noAnswer)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFindAuthoritativeNameservers_ReturnsSorted(
|
func TestFindAuthoritativeNameservers_ReturnsSorted(
|
||||||
@@ -954,12 +959,34 @@ func TestFollowDelegation_NoAnswer(t *testing.T) {
|
|||||||
r := resolver.NewWithQueryTimeout(slog.Default(), 100*time.Millisecond)
|
r := resolver.NewWithQueryTimeout(slog.Default(), 100*time.Millisecond)
|
||||||
|
|
||||||
nameservers, err := r.FollowDelegation(
|
nameservers, err := r.FollowDelegation(
|
||||||
t.Context(), "google.com.", []string{noAnswerAddress},
|
t.Context(), "google.com.", ".", nil, []string{noAnswerAddress},
|
||||||
)
|
)
|
||||||
require.Error(t, err)
|
require.Error(t, err)
|
||||||
assert.Empty(t, nameservers)
|
assert.Empty(t, nameservers)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestFollowDelegation_NoAnswerAfterReferral starts the walk for
|
||||||
|
// www.example.net at the servers of example.net as a referral names
|
||||||
|
// them, ns1.example.net and ns2.example.net, at 192.0.2.1, where nothing
|
||||||
|
// answers. The error is a NoAnswerError naming them, which the watcher
|
||||||
|
// compares with the nameservers it saved for the name.
|
||||||
|
func TestFollowDelegation_NoAnswerAfterReferral(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
r := resolver.NewWithQueryTimeout(slog.Default(), 100*time.Millisecond)
|
||||||
|
nameservers := []string{"ns1.example.net.", "ns2.example.net."}
|
||||||
|
|
||||||
|
_, err := r.FollowDelegation(
|
||||||
|
t.Context(), "www.example.net.", "example.net.", nameservers,
|
||||||
|
[]string{noAnswerAddress},
|
||||||
|
)
|
||||||
|
|
||||||
|
var noAnswer *resolver.NoAnswerError
|
||||||
|
require.ErrorAs(t, err, &noAnswer)
|
||||||
|
assert.Equal(t, nameservers, noAnswer.Nameservers)
|
||||||
|
assert.Contains(t, err.Error(), "query www.example.net. @"+noAnswerAddress)
|
||||||
|
}
|
||||||
|
|
||||||
// TestResolveNSIterative_NoDelegationOfItsOwn walks to the nameservers
|
// TestResolveNSIterative_NoDelegationOfItsOwn walks to the nameservers
|
||||||
// of www.google.com as the fallback walk does. As in
|
// of www.google.com as the fallback walk does. As in
|
||||||
// TestLookupNS_NoDelegationOfItsOwn, the set is empty, with no error.
|
// TestLookupNS_NoDelegationOfItsOwn, the set is empty, with no error.
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ import (
|
|||||||
const RequestTimeout time.Duration = requestTimeout
|
const RequestTimeout time.Duration = requestTimeout
|
||||||
|
|
||||||
// SetListenPort overrides the port Run binds. A test uses it to hand
|
// SetListenPort overrides the port Run binds. A test uses it to hand
|
||||||
// Run an unbindable port so ListenAndServe fails immediately and Run
|
// Run an unbindable port, so that Run stores its http.Server and then
|
||||||
// returns after storing its http.Server.
|
// returns an error without listening.
|
||||||
func SetListenPort(s *Server, port int) {
|
func SetListenPort(s *Server, port int) {
|
||||||
s.port = port
|
s.port = port
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -112,7 +113,7 @@ func New(
|
|||||||
}
|
}
|
||||||
|
|
||||||
lifecycle.Append(fx.Hook{
|
lifecycle.Append(fx.Hook{
|
||||||
OnStart: func(_ context.Context) error {
|
OnStart: func(ctx context.Context) error {
|
||||||
srv.startupTime = time.Now()
|
srv.startupTime = time.Now()
|
||||||
|
|
||||||
err := srv.enableSentry()
|
err := srv.enableSentry()
|
||||||
@@ -120,9 +121,7 @@ func New(
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
go srv.Run()
|
return srv.Run(ctx)
|
||||||
|
|
||||||
return nil
|
|
||||||
},
|
},
|
||||||
OnStop: func(ctx context.Context) error {
|
OnStop: func(ctx context.Context) error {
|
||||||
return srv.Shutdown(ctx)
|
return srv.Shutdown(ctx)
|
||||||
@@ -149,8 +148,10 @@ func newHTTPServer(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run starts the HTTP server.
|
// Run binds the listen port, then serves HTTP on it in a new goroutine
|
||||||
func (s *Server) Run() {
|
// and returns. A port that cannot be bound is returned as an error, so
|
||||||
|
// that startup stops instead of running without the HTTP server.
|
||||||
|
func (s *Server) Run(ctx context.Context) error {
|
||||||
s.SetupRoutes()
|
s.SetupRoutes()
|
||||||
|
|
||||||
listenAddr := fmt.Sprintf(":%d", s.port)
|
listenAddr := fmt.Sprintf(":%d", s.port)
|
||||||
@@ -158,10 +159,21 @@ func (s *Server) Run() {
|
|||||||
|
|
||||||
s.log.Info("http server starting", "addr", listenAddr)
|
s.log.Info("http server starting", "addr", listenAddr)
|
||||||
|
|
||||||
err := s.httpServer.ListenAndServe()
|
lc := &net.ListenConfig{}
|
||||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
|
||||||
s.log.Error("http server error", "error", err)
|
listener, err := lc.Listen(ctx, "tcp", listenAddr)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("starting http server: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
err := s.httpServer.Serve(listener)
|
||||||
|
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||||
|
s.log.Error("http server error", "error", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shutdown gracefully shuts down the server, then sends the error
|
// Shutdown gracefully shuts down the server, then sends the error
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package server_test
|
package server_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"net"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/spf13/viper"
|
"github.com/spf13/viper"
|
||||||
@@ -58,15 +60,13 @@ func buildServer(t *testing.T) *server.Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// TestRunWiresSocketTimeouts pins that the http.Server the running
|
// TestRunWiresSocketTimeouts pins that the http.Server the running
|
||||||
// server actually serves — the one Run builds and hands to
|
// server actually serves — the one Run builds and serves on the port
|
||||||
// ListenAndServe — carries every socket-level timeout, plus the two
|
// it binds — carries every socket-level timeout, plus the two
|
||||||
// relationships the values must satisfy.
|
// relationships the values must satisfy.
|
||||||
//
|
//
|
||||||
// Run is driven to completion with an unbindable port: it builds and
|
// Run is given an unbindable port: it builds and stores s.httpServer,
|
||||||
// stores s.httpServer, then ListenAndServe fails at once and Run
|
// then the bind fails and Run returns the error without ever
|
||||||
// returns without ever listening. The assertions run in the same
|
// listening. Nothing here measures elapsed time.
|
||||||
// goroutine after Run returns, so reading s.httpServer is free of any
|
|
||||||
// data race. Nothing here measures elapsed time.
|
|
||||||
//
|
//
|
||||||
// ReadTimeout must be at least ReadHeaderTimeout. net/http reads the
|
// ReadTimeout must be at least ReadHeaderTimeout. net/http reads the
|
||||||
// headers under ReadHeaderTimeout, then sets the read deadline for the
|
// headers under ReadHeaderTimeout, then sets the read deadline for the
|
||||||
@@ -84,7 +84,10 @@ func TestRunWiresSocketTimeouts(t *testing.T) {
|
|||||||
srv := buildServer(t)
|
srv := buildServer(t)
|
||||||
server.SetListenPort(srv, -1)
|
server.SetListenPort(srv, -1)
|
||||||
|
|
||||||
srv.Run()
|
err := srv.Run(t.Context())
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Run bound port -1")
|
||||||
|
}
|
||||||
|
|
||||||
hs := server.HTTPServerOf(srv)
|
hs := server.HTTPServerOf(srv)
|
||||||
if hs == nil {
|
if hs == nil {
|
||||||
@@ -133,3 +136,38 @@ func TestRunWiresSocketTimeouts(t *testing.T) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPortInUseStopsStartup(t *testing.T) {
|
||||||
|
// Bound on every address, as Run binds, so that Run's bind fails.
|
||||||
|
lc := &net.ListenConfig{}
|
||||||
|
|
||||||
|
taken, err := lc.Listen(t.Context(), "tcp", ":0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("binding a port for the test: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() { _ = taken.Close() }()
|
||||||
|
|
||||||
|
_, port, err := net.SplitHostPort(taken.Addr().String())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reading the bound port: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
viper.Reset()
|
||||||
|
t.Setenv("DNSWATCHER_TARGETS", "example.com")
|
||||||
|
t.Setenv("DNSWATCHER_DATA_DIR", t.TempDir())
|
||||||
|
t.Setenv("PORT", port)
|
||||||
|
|
||||||
|
app := newServerApp(fx.Invoke(func(*server.Server) {}))
|
||||||
|
|
||||||
|
err = app.Start(t.Context())
|
||||||
|
if err == nil {
|
||||||
|
_ = app.Stop(t.Context())
|
||||||
|
|
||||||
|
t.Fatal("startup succeeded on a port that is already bound")
|
||||||
|
}
|
||||||
|
|
||||||
|
if !strings.Contains(err.Error(), ":"+port) {
|
||||||
|
t.Errorf("startup error does not name port %s: %v", port, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+52
-4
@@ -4,8 +4,10 @@ package state
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"maps"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"slices"
|
"slices"
|
||||||
@@ -214,6 +216,24 @@ func (s *State) Load() error {
|
|||||||
return fmt.Errorf("parsing state file: %w", err)
|
return fmt.Errorf("parsing state file: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A section the file leaves out, or holds as null, loads empty: the
|
||||||
|
// setters write into these maps, and writing into a nil map panics.
|
||||||
|
if snapshot.Domains == nil {
|
||||||
|
snapshot.Domains = make(map[string]*DomainState)
|
||||||
|
}
|
||||||
|
|
||||||
|
if snapshot.Hostnames == nil {
|
||||||
|
snapshot.Hostnames = make(map[string]*HostnameState)
|
||||||
|
}
|
||||||
|
|
||||||
|
if snapshot.Ports == nil {
|
||||||
|
snapshot.Ports = make(map[string]*PortState)
|
||||||
|
}
|
||||||
|
|
||||||
|
if snapshot.Certificates == nil {
|
||||||
|
snapshot.Certificates = make(map[string]*CertificateState)
|
||||||
|
}
|
||||||
|
|
||||||
// A state file saved before each record value was stored once can
|
// A state file saved before each record value was stored once can
|
||||||
// hold a hostname's CNAME once for every record type asked for.
|
// hold a hostname's CNAME once for every record type asked for.
|
||||||
// Each value is kept once, so the first check does not see a
|
// Each value is kept once, so the first check does not see a
|
||||||
@@ -252,10 +272,20 @@ func (s *State) Save() error {
|
|||||||
return fmt.Errorf("creating data directory: %w", err)
|
return fmt.Errorf("creating data directory: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Atomic write: write to temp file, then rename
|
// Atomic write: write to temp file, then rename. The temp file is
|
||||||
|
// synced before the rename and the directory after it, or a crash
|
||||||
|
// can leave the renamed state file empty.
|
||||||
tmpPath := path + ".tmp"
|
tmpPath := path + ".tmp"
|
||||||
|
|
||||||
err = os.WriteFile(tmpPath, data, filePermissions)
|
//nolint:gosec // path is from trusted config
|
||||||
|
tmpFile, err := os.OpenFile(
|
||||||
|
tmpPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, filePermissions,
|
||||||
|
)
|
||||||
|
if err == nil {
|
||||||
|
_, err = tmpFile.Write(data)
|
||||||
|
err = errors.Join(err, tmpFile.Sync(), tmpFile.Close())
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("writing temp state file: %w", err)
|
return fmt.Errorf("writing temp state file: %w", err)
|
||||||
}
|
}
|
||||||
@@ -265,17 +295,35 @@ func (s *State) Save() error {
|
|||||||
return fmt.Errorf("renaming state file: %w", err)
|
return fmt.Errorf("renaming state file: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
dir, err := os.Open(filepath.Dir(path))
|
||||||
|
if err == nil {
|
||||||
|
err = errors.Join(dir.Sync(), dir.Close())
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("syncing data directory: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
s.log.Debug("state saved to disk", "path", path)
|
s.log.Debug("state saved to disk", "path", path)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetSnapshot returns a copy of the current snapshot.
|
// GetSnapshot returns a copy of the current snapshot, with copies of
|
||||||
|
// its maps, so that a caller can range over them while the state is
|
||||||
|
// written. The entries in the maps are not copied: an entry saved in the
|
||||||
|
// state must be replaced, never changed in place.
|
||||||
func (s *State) GetSnapshot() Snapshot {
|
func (s *State) GetSnapshot() Snapshot {
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
defer s.mu.RUnlock()
|
defer s.mu.RUnlock()
|
||||||
|
|
||||||
return *s.snapshot
|
snap := *s.snapshot
|
||||||
|
snap.Domains = maps.Clone(snap.Domains)
|
||||||
|
snap.Hostnames = maps.Clone(snap.Hostnames)
|
||||||
|
snap.Ports = maps.Clone(snap.Ports)
|
||||||
|
snap.Certificates = maps.Clone(snap.Certificates)
|
||||||
|
|
||||||
|
return snap
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetDomainState updates the state for a domain.
|
// SetDomainState updates the state for a domain.
|
||||||
|
|||||||
@@ -618,6 +618,53 @@ func TestSaveAtomicWrite(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestSaveOverLeftoverTempFile verifies that a temp file left by a
|
||||||
|
// crash, longer than the state Save writes, leaves nothing of itself in
|
||||||
|
// the state file, and that no temp file remains after Save.
|
||||||
|
func TestSaveOverLeftoverTempFile(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
dir := t.TempDir()
|
||||||
|
statePath := filepath.Join(dir, "state.json")
|
||||||
|
tmpPath := statePath + ".tmp"
|
||||||
|
|
||||||
|
err := os.WriteFile(tmpPath, []byte(strings.Repeat("x", 64*1024)), 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("writing leftover temp file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
s := state.NewForTestWithDataDir(dir)
|
||||||
|
|
||||||
|
populateState(t, s)
|
||||||
|
|
||||||
|
err = s.Save()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Save() error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
//nolint:gosec // test file with known path
|
||||||
|
data, err := os.ReadFile(statePath)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reading state file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var snap state.Snapshot
|
||||||
|
|
||||||
|
err = json.Unmarshal(data, &snap)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("state file is not complete JSON: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(snap.Domains) != 2 {
|
||||||
|
t.Errorf("state file has %d domains, want 2", len(snap.Domains))
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = os.Stat(tmpPath)
|
||||||
|
if !os.IsNotExist(err) {
|
||||||
|
t.Error("temp file should not exist after save")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestLoadMissingFile verifies that loading a nonexistent file is not an error.
|
// TestLoadMissingFile verifies that loading a nonexistent file is not an error.
|
||||||
func TestLoadMissingFile(t *testing.T) {
|
func TestLoadMissingFile(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
@@ -648,6 +695,58 @@ func TestLoadMissingFile(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestLoadFileWithoutSections loads a state file holding {}, and files
|
||||||
|
// that each leave out one section. Every section loads as an empty map.
|
||||||
|
// TestFirstCheckAfterLoadingFileWithoutSections in the watcher tests
|
||||||
|
// runs the first check after such a load.
|
||||||
|
func TestLoadFileWithoutSections(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
file string
|
||||||
|
}{
|
||||||
|
{"no sections", `{}`},
|
||||||
|
{"no domains", `{"hostnames": {}, "ports": {}, "certificates": {}}`},
|
||||||
|
{"no hostnames", `{"domains": {}, "ports": {}, "certificates": {}}`},
|
||||||
|
{"no ports", `{"domains": {}, "hostnames": {}, "certificates": {}}`},
|
||||||
|
{"no certificates", `{"domains": {}, "hostnames": {}, "ports": {}}`},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
dir := t.TempDir()
|
||||||
|
|
||||||
|
err := os.WriteFile(
|
||||||
|
filepath.Join(dir, "state.json"), []byte(tt.file), 0o600,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("writing state file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
s := state.NewForTestWithDataDir(dir)
|
||||||
|
|
||||||
|
err = s.Load()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Load() error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
want := state.Snapshot{
|
||||||
|
Domains: map[string]*state.DomainState{},
|
||||||
|
Hostnames: map[string]*state.HostnameState{},
|
||||||
|
Ports: map[string]*state.PortState{},
|
||||||
|
Certificates: map[string]*state.CertificateState{},
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := s.GetSnapshot(); !reflect.DeepEqual(got, want) {
|
||||||
|
t.Errorf("loaded %#v, want %#v", got, want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestLoadCorruptFile verifies that a corrupt state file returns an error.
|
// TestLoadCorruptFile verifies that a corrupt state file returns an error.
|
||||||
func TestLoadCorruptFile(t *testing.T) {
|
func TestLoadCorruptFile(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
@@ -995,7 +1094,8 @@ func TestPortStateUnmarshalJSON_BothFormats(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestGetSnapshot_ReturnsCopy verifies that GetSnapshot returns a value copy.
|
// TestGetSnapshot_ReturnsCopy verifies that the maps in the snapshot
|
||||||
|
// GetSnapshot returns are not the state's own.
|
||||||
func TestGetSnapshot_ReturnsCopy(t *testing.T) {
|
func TestGetSnapshot_ReturnsCopy(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -1005,15 +1105,67 @@ func TestGetSnapshot_ReturnsCopy(t *testing.T) {
|
|||||||
|
|
||||||
snap := s.GetSnapshot()
|
snap := s.GetSnapshot()
|
||||||
|
|
||||||
// Mutate the returned snapshot's map.
|
const added = "added.example.com"
|
||||||
snap.Domains["mutated.example.com"] = &state.DomainState{
|
|
||||||
Nameservers: []string{"ns1.mutated.com."},
|
snap.Domains[added] = &state.DomainState{}
|
||||||
|
snap.Hostnames[added] = &state.HostnameState{}
|
||||||
|
snap.Ports[added] = &state.PortState{}
|
||||||
|
snap.Certificates[added] = &state.CertificateState{}
|
||||||
|
|
||||||
|
if _, ok := s.GetDomainState(added); ok {
|
||||||
|
t.Error("the snapshot's Domains map is the state's own")
|
||||||
}
|
}
|
||||||
|
|
||||||
// The original domain data should still be accessible.
|
if _, ok := s.GetHostnameState(added); ok {
|
||||||
_, ok := s.GetDomainState("example.com")
|
t.Error("the snapshot's Hostnames map is the state's own")
|
||||||
if !ok {
|
}
|
||||||
t.Error("original domain should still exist")
|
|
||||||
|
if _, ok := s.GetPortState(added); ok {
|
||||||
|
t.Error("the snapshot's Ports map is the state's own")
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, ok := s.GetCertificateState(added); ok {
|
||||||
|
t.Error("the snapshot's Certificates map is the state's own")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestGetSnapshot_WhileWritten ranges over snapshots while another
|
||||||
|
// goroutine writes the state, as the dashboard does while a check runs.
|
||||||
|
// Under -race it fails when a snapshot's maps are the state's own.
|
||||||
|
func TestGetSnapshot_WhileWritten(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
s := state.NewForTestWithDataDir(t.TempDir())
|
||||||
|
|
||||||
|
const writes = 1000
|
||||||
|
|
||||||
|
written := make(chan struct{})
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
defer close(written)
|
||||||
|
|
||||||
|
for range writes {
|
||||||
|
s.SetDomainState("example.com", &state.DomainState{})
|
||||||
|
s.SetHostnameState(testHostname, &state.HostnameState{})
|
||||||
|
s.SetPortState(testIPv4+":443", &state.PortState{})
|
||||||
|
s.SetCertificateState(
|
||||||
|
testIPv4+":443:"+testHostname, &state.CertificateState{},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-written:
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
// json.Marshal ranges over each of the snapshot's maps.
|
||||||
|
_, err := json.Marshal(s.GetSnapshot())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -83,6 +83,30 @@ func TestCancelledCheckSavesNothing(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestStopBeforeFirstScanSendsNoStartupNotification runs a watcher with
|
||||||
|
// the startup notification on and its context already cancelled, so the
|
||||||
|
// first scan is cut short before its lookup is sent. The scan did not
|
||||||
|
// complete, so no startup notification may be sent.
|
||||||
|
func TestStopBeforeFirstScanSendsNoStartupNotification(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
cfg := defaultTestConfig(t)
|
||||||
|
cfg.Hostnames = []string{testHost}
|
||||||
|
cfg.SendTestNotification = true
|
||||||
|
|
||||||
|
w, deps := newTestWatcher(t, cfg)
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(t.Context())
|
||||||
|
cancel()
|
||||||
|
|
||||||
|
w.Run(ctx)
|
||||||
|
|
||||||
|
notifications := deps.notifier.getNotifications()
|
||||||
|
if len(notifications) != 0 {
|
||||||
|
t.Errorf("sent %v, want no notifications", notifications)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// newLoggingWatcher returns a watcher for a domain and a hostname, with
|
// newLoggingWatcher returns a watcher for a domain and a hostname, with
|
||||||
// the real resolver, that writes what it logs at warning level or above
|
// the real resolver, that writes what it logs at warning level or above
|
||||||
// into the returned buffer.
|
// into the returned buffer.
|
||||||
|
|||||||
@@ -122,6 +122,34 @@ func (w *Watcher) RunTLSChecks(ctx context.Context) {
|
|||||||
w.runTLSChecks(ctx)
|
w.runTLSChecks(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CheckHostnameResult exports checkHostnameResult for testing.
|
||||||
|
func (w *Watcher) CheckHostnameResult(
|
||||||
|
ctx context.Context,
|
||||||
|
hostname string,
|
||||||
|
results map[string]*resolver.NameserverResponse,
|
||||||
|
err error,
|
||||||
|
) bool {
|
||||||
|
return w.checkHostnameResult(ctx, hostname, results, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckDomainResult exports checkDomainResult for testing.
|
||||||
|
func (w *Watcher) CheckDomainResult(
|
||||||
|
ctx context.Context,
|
||||||
|
domain string,
|
||||||
|
nameservers []string,
|
||||||
|
err error,
|
||||||
|
) {
|
||||||
|
w.checkDomainResult(ctx, domain, nameservers, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FailedNameservers exports failedNameservers for testing.
|
||||||
|
func FailedNameservers(
|
||||||
|
err error,
|
||||||
|
prev *state.HostnameState,
|
||||||
|
) map[string]*resolver.NameserverResponse {
|
||||||
|
return failedNameservers(err, prev)
|
||||||
|
}
|
||||||
|
|
||||||
// BuildHostnameState exports buildHostnameState for testing.
|
// BuildHostnameState exports buildHostnameState for testing.
|
||||||
func BuildHostnameState(
|
func BuildHostnameState(
|
||||||
results map[string]*resolver.NameserverResponse,
|
results map[string]*resolver.NameserverResponse,
|
||||||
|
|||||||
@@ -20,7 +20,10 @@ type DNSResolver interface {
|
|||||||
) ([]string, error)
|
) ([]string, error)
|
||||||
|
|
||||||
// LookupAllRecords queries all record types for a hostname,
|
// LookupAllRecords queries all record types for a hostname,
|
||||||
// returning each nameserver's response keyed by nameserver.
|
// returning each nameserver's response keyed by nameserver. When
|
||||||
|
// the walk to the nameservers reached a zone through a referral and
|
||||||
|
// none of that zone's nameservers answered, the error is a
|
||||||
|
// *resolver.NoAnswerError naming them.
|
||||||
LookupAllRecords(
|
LookupAllRecords(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
hostname string,
|
hostname string,
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package watcher_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"maps"
|
||||||
|
"slices"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"sneak.berlin/go/dnswatcher/internal/state"
|
||||||
|
"sneak.berlin/go/dnswatcher/internal/watcher"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestIPv6AddressInBrackets runs the port checks, not the watcher's
|
||||||
|
// first, on hostname state built here for a hostname at an IPv6 address
|
||||||
|
// whose port 443 the previous check found closed. It is open now. Then
|
||||||
|
// it runs the TLS checks and the port checks again. The port and
|
||||||
|
// certificate keys and the Port Change notification write the address
|
||||||
|
// in brackets, so its last group cannot be read as the port, and the
|
||||||
|
// second port checks keep the certificate entry, whose address they read
|
||||||
|
// back from its key. When a last port check finds port 443 closed, the
|
||||||
|
// certificate entry is removed. Nothing is looked up.
|
||||||
|
func TestIPv6AddressInBrackets(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const aaaaType = "AAAA"
|
||||||
|
|
||||||
|
cfg := defaultTestConfig(t)
|
||||||
|
cfg.Hostnames = []string{host}
|
||||||
|
|
||||||
|
deps := newTestDeps(t, cfg)
|
||||||
|
w := watcher.NewForTest(
|
||||||
|
cfg, deps.state, nil,
|
||||||
|
deps.portChecker, deps.tlsChecker, deps.notifier,
|
||||||
|
)
|
||||||
|
w.SetFirstRun(false)
|
||||||
|
|
||||||
|
deps.state.SetHostnameState(host, saved(
|
||||||
|
map[string]*state.NameserverRecordState{
|
||||||
|
nsA: answered(map[string][]string{aaaaType: {"2001:db8::1"}}),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
deps.state.SetPortState("[2001:db8::1]:443", &state.PortState{
|
||||||
|
Hostnames: []string{host},
|
||||||
|
})
|
||||||
|
|
||||||
|
w.CheckAllPorts(t.Context())
|
||||||
|
w.RunTLSChecks(t.Context())
|
||||||
|
w.CheckAllPorts(t.Context())
|
||||||
|
|
||||||
|
snap := deps.state.GetSnapshot()
|
||||||
|
|
||||||
|
gotPorts := slices.Sorted(maps.Keys(snap.Ports))
|
||||||
|
wantPorts := []string{"[2001:db8::1]:443", "[2001:db8::1]:80"}
|
||||||
|
|
||||||
|
if !slices.Equal(gotPorts, wantPorts) {
|
||||||
|
t.Errorf("port entries %v, want %v", gotPorts, wantPorts)
|
||||||
|
}
|
||||||
|
|
||||||
|
gotCerts := slices.Sorted(maps.Keys(snap.Certificates))
|
||||||
|
wantCerts := []string{"[2001:db8::1]:443:www.example.net"}
|
||||||
|
|
||||||
|
if !slices.Equal(gotCerts, wantCerts) {
|
||||||
|
t.Errorf("certificate entries %v, want %v", gotCerts, wantCerts)
|
||||||
|
}
|
||||||
|
|
||||||
|
title := "Port Change: [2001:db8::1]:443"
|
||||||
|
want := `Hostnames: www.example.net
|
||||||
|
Address: [2001:db8::1]:443
|
||||||
|
Port now open`
|
||||||
|
|
||||||
|
got := deps.notifier.getNotifications()
|
||||||
|
if len(got) != 1 || got[0].Title != title || got[0].Message != want {
|
||||||
|
t.Errorf("sent %v, want one %q with message:\n%s", got, title, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
deps.portChecker.closed = true
|
||||||
|
|
||||||
|
w.CheckAllPorts(t.Context())
|
||||||
|
|
||||||
|
gotCerts = slices.Sorted(maps.Keys(deps.state.GetSnapshot().Certificates))
|
||||||
|
if len(gotCerts) != 0 {
|
||||||
|
t.Errorf("certificate entries %v with port 443 closed, want none", gotCerts)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"sneak.berlin/go/dnswatcher/internal/config"
|
|
||||||
"sneak.berlin/go/dnswatcher/internal/state"
|
"sneak.berlin/go/dnswatcher/internal/state"
|
||||||
"sneak.berlin/go/dnswatcher/internal/watcher"
|
"sneak.berlin/go/dnswatcher/internal/watcher"
|
||||||
)
|
)
|
||||||
@@ -74,21 +73,19 @@ b.ns.example.net.: 192.0.2.2`,
|
|||||||
func TestDomainRecordNotificationsNameTheDomain(t *testing.T) {
|
func TestDomainRecordNotificationsNameTheDomain(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
notifier := &mockNotifier{}
|
cfg := defaultTestConfig(t)
|
||||||
w := watcher.NewForTest(
|
cfg.Domains = []string{domain}
|
||||||
&config.Config{Domains: []string{domain}},
|
|
||||||
nil, nil, nil, nil, notifier,
|
deps := newTestDeps(t, cfg)
|
||||||
)
|
w := watcher.NewForTest(cfg, deps.state, nil, nil, nil, deps.notifier)
|
||||||
|
|
||||||
// nsA's address changes, which also makes it differ from nsC; nsB
|
// nsA's address changes, which also makes it differ from nsC; nsB
|
||||||
// fails; nsC answers again; nsD is gone.
|
// fails; nsC answers again.
|
||||||
nsD := "d.ns.example.net."
|
|
||||||
w.DetectHostnameChanges(t.Context(), domain,
|
w.DetectHostnameChanges(t.Context(), domain,
|
||||||
saved(map[string]*state.NameserverRecordState{
|
saved(map[string]*state.NameserverRecordState{
|
||||||
nsA: answered(map[string][]string{"A": {ip1}}),
|
nsA: answered(map[string][]string{"A": {ip1}}),
|
||||||
nsB: answered(map[string][]string{"A": {ip1}}),
|
nsB: answered(map[string][]string{"A": {ip1}}),
|
||||||
nsC: failed(),
|
nsC: failed(),
|
||||||
nsD: answered(map[string][]string{"A": {ip1}}),
|
|
||||||
}),
|
}),
|
||||||
saved(map[string]*state.NameserverRecordState{
|
saved(map[string]*state.NameserverRecordState{
|
||||||
nsA: answered(map[string][]string{"A": {ip2}}),
|
nsA: answered(map[string][]string{"A": {ip2}}),
|
||||||
@@ -102,18 +99,17 @@ func TestDomainRecordNotificationsNameTheDomain(t *testing.T) {
|
|||||||
t.Context(), domain, cnameState(ip1), cnameState(ip2),
|
t.Context(), domain, cnameState(ip1), cnameState(ip2),
|
||||||
)
|
)
|
||||||
|
|
||||||
// NS Failure is sent for nsB failing and for nsD being gone.
|
|
||||||
want := map[string]int{
|
want := map[string]int{
|
||||||
"Record Change": 1,
|
"Record Change": 1,
|
||||||
"Inconsistency": 1,
|
"Inconsistency": 1,
|
||||||
"NS Failure": 2,
|
"NS Failure": 1,
|
||||||
"NS Recovery": 1,
|
"NS Recovery": 1,
|
||||||
"CNAME Address Change": 1,
|
"CNAME Address Change": 1,
|
||||||
}
|
}
|
||||||
|
|
||||||
sent := make(map[string]int)
|
sent := make(map[string]int)
|
||||||
|
|
||||||
for _, n := range notifier.getNotifications() {
|
for _, n := range deps.notifier.getNotifications() {
|
||||||
kind, _, _ := strings.Cut(n.Title, ":")
|
kind, _, _ := strings.Cut(n.Title, ":")
|
||||||
sent[kind]++
|
sent[kind]++
|
||||||
|
|
||||||
@@ -128,6 +124,89 @@ func TestDomainRecordNotificationsNameTheDomain(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// nsB, which answered, and nsC, which did not, are no longer among the
|
||||||
|
// nameservers. One NS Change lists both, for the hostname and for the
|
||||||
|
// configured apex domain with no delegation of its own. Nothing is sent
|
||||||
|
// for the domain whose delegation on the previous check listed them:
|
||||||
|
// the check of its delegation sends its NS Change.
|
||||||
|
func TestRemovedNameserversAreAnNSChange(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
target string
|
||||||
|
// The domain's nameservers saved by the previous check.
|
||||||
|
delegation []string
|
||||||
|
// The NS Change sent, or "" for none.
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "hostname",
|
||||||
|
target: host,
|
||||||
|
want: `Hostname: www.example.net
|
||||||
|
Removed: b.ns.example.net., c.ns.example.net.`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "domain with no delegation of its own",
|
||||||
|
target: domain,
|
||||||
|
delegation: []string{},
|
||||||
|
want: `Domain: example.net
|
||||||
|
Removed: b.ns.example.net., c.ns.example.net.`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "domain whose delegation listed them",
|
||||||
|
target: domain,
|
||||||
|
delegation: []string{nsA, nsB, nsC},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
cfg := defaultTestConfig(t)
|
||||||
|
cfg.Domains = []string{domain}
|
||||||
|
|
||||||
|
deps := newTestDeps(t, cfg)
|
||||||
|
w := watcher.NewForTest(
|
||||||
|
cfg, deps.state, nil, nil, nil, deps.notifier,
|
||||||
|
)
|
||||||
|
|
||||||
|
deps.state.SetDomainState(domain, &state.DomainState{
|
||||||
|
Nameservers: tt.delegation,
|
||||||
|
})
|
||||||
|
|
||||||
|
prev := saved(map[string]*state.NameserverRecordState{
|
||||||
|
nsA: answered(map[string][]string{"A": {ip1}}),
|
||||||
|
nsB: answered(map[string][]string{"A": {ip1}}),
|
||||||
|
nsC: failed(),
|
||||||
|
})
|
||||||
|
current := saved(map[string]*state.NameserverRecordState{
|
||||||
|
nsA: answered(map[string][]string{"A": {ip1}}),
|
||||||
|
})
|
||||||
|
|
||||||
|
w.DetectHostnameChanges(t.Context(), tt.target, prev, current)
|
||||||
|
|
||||||
|
got := deps.notifier.getNotifications()
|
||||||
|
|
||||||
|
if tt.want == "" {
|
||||||
|
if len(got) != 0 {
|
||||||
|
t.Errorf("sent %v, want nothing", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
title := "NS Change: " + tt.target
|
||||||
|
if len(got) != 1 || got[0].Title != title ||
|
||||||
|
got[0].Message != tt.want {
|
||||||
|
t.Errorf("sent %v, want one %q with message:\n%s",
|
||||||
|
got, title, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// The startup notification counts the configured domains and hostnames,
|
// The startup notification counts the configured domains and hostnames,
|
||||||
// although the state's hostnames also hold the apex domain's own
|
// although the state's hostnames also hold the apex domain's own
|
||||||
// records. Nothing is looked up: the watcher has no resolver.
|
// records. Nothing is looked up: the watcher has no resolver.
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package watcher_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -14,6 +15,10 @@ import (
|
|||||||
"sneak.berlin/go/dnswatcher/internal/watcher"
|
"sneak.berlin/go/dnswatcher/internal/watcher"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// errNoReply is why a walk that got no reply from a zone's servers
|
||||||
|
// failed.
|
||||||
|
var errNoReply = errors.New("all servers failed: i/o timeout")
|
||||||
|
|
||||||
// answered is what a check saves for a nameserver that answered with
|
// answered is what a check saves for a nameserver that answered with
|
||||||
// these records.
|
// these records.
|
||||||
func answered(records map[string][]string) *state.NameserverRecordState {
|
func answered(records map[string][]string) *state.NameserverRecordState {
|
||||||
@@ -183,6 +188,134 @@ func TestNSFailureAlertNamesHostnameNameserverAndReason(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestZoneNameserversAllStopAnswering runs three checks of host from
|
||||||
|
// the point where its lookup has returned. On the first, nsA and nsB,
|
||||||
|
// the nameservers of its zone, answer. On the second, the lookup fails
|
||||||
|
// with the error the walk to them returns when neither answers (see
|
||||||
|
// the resolver's TestFollowDelegation_NoAnswerAfterReferral), given
|
||||||
|
// here because no live zone has nameservers that never answer. For a
|
||||||
|
// hostname it is the lookup of its records that fails, and for a domain
|
||||||
|
// with no delegation of its own the lookup of its delegation. Both are
|
||||||
|
// saved as failed, with the reason, and each gets an NS Failure. On the
|
||||||
|
// third, both answer, and each gets an NS Recovery. A domain's records
|
||||||
|
// are checked as a hostname's, so its first and third checks are too.
|
||||||
|
func TestZoneNameserversAllStopAnswering(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
records := map[string][]string{"A": {ip1}}
|
||||||
|
bothAnswer := map[string]*resolver.NameserverResponse{
|
||||||
|
nsA: response(records), nsB: response(records),
|
||||||
|
}
|
||||||
|
noAnswer := &resolver.NoAnswerError{
|
||||||
|
Nameservers: []string{nsA, nsB}, Err: errNoReply,
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
isDomain bool
|
||||||
|
}{
|
||||||
|
{"hostname", false},
|
||||||
|
{"domain with no delegation of its own", true},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
cfg := defaultTestConfig(t)
|
||||||
|
if tt.isDomain {
|
||||||
|
cfg.Domains = []string{host}
|
||||||
|
} else {
|
||||||
|
cfg.Hostnames = []string{host}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The watcher is given each lookup's result, so it has no
|
||||||
|
// resolver.
|
||||||
|
deps := newTestDeps(t, cfg)
|
||||||
|
w := watcher.NewForTest(
|
||||||
|
cfg, deps.state, nil,
|
||||||
|
deps.portChecker, deps.tlsChecker, deps.notifier,
|
||||||
|
)
|
||||||
|
w.SetFirstRun(false)
|
||||||
|
|
||||||
|
w.CheckHostnameResult(t.Context(), host, bothAnswer, nil)
|
||||||
|
|
||||||
|
if tt.isDomain {
|
||||||
|
w.CheckDomainResult(t.Context(), host, nil, noAnswer)
|
||||||
|
} else {
|
||||||
|
w.CheckHostnameResult(t.Context(), host, nil, noAnswer)
|
||||||
|
}
|
||||||
|
|
||||||
|
current, _ := deps.state.GetHostnameState(host)
|
||||||
|
|
||||||
|
for _, ns := range []string{nsA, nsB} {
|
||||||
|
got := current.RecordsByNameserver[ns]
|
||||||
|
if got.Status != failed().Status || got.Error != errNoReply.Error() {
|
||||||
|
t.Errorf(
|
||||||
|
"%s saved with status %q, error %q; want %q, %q",
|
||||||
|
ns, got.Status, got.Error, failed().Status, errNoReply,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if n := countNotifications(deps, "NS Failure: "+host); n != 2 {
|
||||||
|
t.Errorf("sent %d NS Failure notifications, want 2", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
w.CheckHostnameResult(t.Context(), host, bothAnswer, nil)
|
||||||
|
|
||||||
|
if n := countNotifications(deps, "NS Recovery: "+host); n != 2 {
|
||||||
|
t.Errorf("sent %d NS Recovery notifications, want 2", n)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFailedNameserversOnlyForThoseOfThePreviousCheck gives
|
||||||
|
// FailedNameservers lookup errors after a check in which nsA and nsB
|
||||||
|
// answered. Only an error that names both makes them failed.
|
||||||
|
func TestFailedNameserversOnlyForThoseOfThePreviousCheck(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
records := map[string][]string{"A": {ip1}}
|
||||||
|
bothAnswered := saved(map[string]*state.NameserverRecordState{
|
||||||
|
nsA: answered(records), nsB: answered(records),
|
||||||
|
})
|
||||||
|
noAnswer := func(nameservers ...string) error {
|
||||||
|
return &resolver.NoAnswerError{Nameservers: nameservers, Err: errNoReply}
|
||||||
|
}
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
err error
|
||||||
|
prev *state.HostnameState
|
||||||
|
wantFailed bool
|
||||||
|
}{
|
||||||
|
{"both did not answer", noAnswer(nsA, nsB), bothAnswered, true},
|
||||||
|
{
|
||||||
|
"the servers of a parent zone did not answer",
|
||||||
|
noAnswer(nsC), bothAnswered, false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"the zone's delegation lists only nsA now",
|
||||||
|
noAnswer(nsA), bothAnswered, false,
|
||||||
|
},
|
||||||
|
{"no root server answered", errNoReply, bothAnswered, false},
|
||||||
|
{"no previous check", noAnswer(nsA, nsB), nil, false},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
got := watcher.FailedNameservers(tt.err, tt.prev)
|
||||||
|
if (got != nil) != tt.wantFailed {
|
||||||
|
t.Errorf("returned %v, want failed: %v", got, tt.wantFailed)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// TestNameserverThatNeverAnswers asks a nameserver address where
|
// TestNameserverThatNeverAnswers asks a nameserver address where
|
||||||
// nothing answers, 192.0.2.1, and checks what the watcher saves for it.
|
// nothing answers, 192.0.2.1, and checks what the watcher saves for it.
|
||||||
// The deadline outlasts the resolver's first two-second try, as in the
|
// The deadline outlasts the resolver's first two-second try, as in the
|
||||||
|
|||||||
@@ -2,7 +2,9 @@ package watcher_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"maps"
|
"maps"
|
||||||
|
"net"
|
||||||
"slices"
|
"slices"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"sneak.berlin/go/dnswatcher/internal/state"
|
"sneak.berlin/go/dnswatcher/internal/state"
|
||||||
@@ -172,7 +174,7 @@ func TestCertificateStateForAnAddressGone(t *testing.T) {
|
|||||||
"A": {ip1}, "AAAA": {ip6},
|
"A": {ip1}, "AAAA": {ip6},
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
[]string{ip1 + ":443:" + host, ip6 + ":443:" + host},
|
[]string{ip1 + ":443:" + host, "[" + ip6 + "]:443:" + host},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"no nameserver answered",
|
"no nameserver answered",
|
||||||
@@ -182,7 +184,7 @@ func TestCertificateStateForAnAddressGone(t *testing.T) {
|
|||||||
[]string{
|
[]string{
|
||||||
ip1 + ":443:" + host,
|
ip1 + ":443:" + host,
|
||||||
ip2 + ":443:" + host,
|
ip2 + ":443:" + host,
|
||||||
ip6 + ":443:" + host,
|
"[" + ip6 + "]:443:" + host,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -205,7 +207,8 @@ func TestCertificateStateForAnAddressGone(t *testing.T) {
|
|||||||
|
|
||||||
for _, ip := range []string{ip1, ip2, ip6} {
|
for _, ip := range []string{ip1, ip2, ip6} {
|
||||||
deps.state.SetCertificateState(
|
deps.state.SetCertificateState(
|
||||||
ip+":443:"+host, &state.CertificateState{Status: "ok"},
|
net.JoinHostPort(ip, "443")+":"+host,
|
||||||
|
&state.CertificateState{Status: "ok"},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,3 +225,67 @@ func TestCertificateStateForAnAddressGone(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestCertificateStateForAPortClosed runs the port checks on hostname
|
||||||
|
// and port state built here for a configured hostname at ip1, whose
|
||||||
|
// port 443 the previous check found open and whose certificate entry
|
||||||
|
// is ok. The port is closed now: the certificate entry is removed, and
|
||||||
|
// only the Port Change is notified. When the port opens again, the next
|
||||||
|
// TLS check saves the certificate as new and notifies nothing about it.
|
||||||
|
// Nothing is looked up.
|
||||||
|
func TestCertificateStateForAPortClosed(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
cfg := defaultTestConfig(t)
|
||||||
|
cfg.Hostnames = []string{host}
|
||||||
|
|
||||||
|
deps := newTestDeps(t, cfg)
|
||||||
|
w := watcher.NewForTest(
|
||||||
|
cfg, deps.state, nil,
|
||||||
|
deps.portChecker, deps.tlsChecker, deps.notifier,
|
||||||
|
)
|
||||||
|
w.SetFirstRun(false)
|
||||||
|
|
||||||
|
certKey := ip1 + ":443:" + host
|
||||||
|
|
||||||
|
deps.state.SetHostnameState(host, saved(
|
||||||
|
map[string]*state.NameserverRecordState{
|
||||||
|
nsA: answered(map[string][]string{"A": {ip1}}),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
deps.state.SetPortState(ip1+":443", &state.PortState{
|
||||||
|
Open: true, Hostnames: []string{host},
|
||||||
|
})
|
||||||
|
deps.state.SetCertificateState(certKey, &state.CertificateState{
|
||||||
|
CommonName: host, Status: "ok",
|
||||||
|
})
|
||||||
|
deps.portChecker.closed = true
|
||||||
|
|
||||||
|
w.CheckAllPorts(t.Context())
|
||||||
|
|
||||||
|
if _, ok := deps.state.GetCertificateState(certKey); ok {
|
||||||
|
t.Errorf("certificate entry %s kept with port 443 closed", certKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
sent := deps.notifier.getNotifications()
|
||||||
|
if title := "Port Change: " + ip1 + ":443"; len(sent) != 1 ||
|
||||||
|
sent[0].Title != title {
|
||||||
|
t.Errorf("sent %v, want one %q", sent, title)
|
||||||
|
}
|
||||||
|
|
||||||
|
deps.portChecker.closed = false
|
||||||
|
|
||||||
|
w.CheckAllPorts(t.Context())
|
||||||
|
w.RunTLSChecks(t.Context())
|
||||||
|
|
||||||
|
cert, ok := deps.state.GetCertificateState(certKey)
|
||||||
|
if !ok || cert.Status != "ok" {
|
||||||
|
t.Errorf("certificate entry %s after port 443 opened: %+v", certKey, cert)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, n := range deps.notifier.getNotifications() {
|
||||||
|
if strings.HasPrefix(n.Title, "TLS") {
|
||||||
|
t.Errorf("sent %v, want no TLS notification", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package watcher_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"slices"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"sneak.berlin/go/dnswatcher/internal/config"
|
||||||
|
"sneak.berlin/go/dnswatcher/internal/state"
|
||||||
|
"sneak.berlin/go/dnswatcher/internal/watcher"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestSkipRecordNotificationsAlerts runs the hostname change detection
|
||||||
|
// for two names on the same check: nsA's address changes, so that nsA
|
||||||
|
// now differs from nsB, and nsC stops answering. The name in
|
||||||
|
// SkipRecordNotifications gets only the NS Failure; the other name also
|
||||||
|
// gets the Record Change and the Inconsistency.
|
||||||
|
func TestSkipRecordNotificationsAlerts(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
const skipped = "skipped.example.net"
|
||||||
|
|
||||||
|
prev := saved(map[string]*state.NameserverRecordState{
|
||||||
|
nsA: answered(map[string][]string{"A": {ip1}}),
|
||||||
|
nsB: answered(map[string][]string{"A": {ip1}}),
|
||||||
|
nsC: answered(map[string][]string{"A": {ip1}}),
|
||||||
|
})
|
||||||
|
current := saved(map[string]*state.NameserverRecordState{
|
||||||
|
nsA: answered(map[string][]string{"A": {ip2}}),
|
||||||
|
nsB: answered(map[string][]string{"A": {ip1}}),
|
||||||
|
nsC: failed(),
|
||||||
|
})
|
||||||
|
|
||||||
|
cfg := &config.Config{
|
||||||
|
Hostnames: []string{host, skipped},
|
||||||
|
SkipRecordNotifications: []string{skipped},
|
||||||
|
}
|
||||||
|
|
||||||
|
// The hostname change detection uses only the configuration and the
|
||||||
|
// notifier.
|
||||||
|
notifier := &mockNotifier{}
|
||||||
|
w := watcher.NewForTest(cfg, nil, nil, nil, nil, notifier)
|
||||||
|
|
||||||
|
w.DetectHostnameChanges(t.Context(), host, prev, current)
|
||||||
|
w.DetectHostnameChanges(t.Context(), skipped, prev, current)
|
||||||
|
|
||||||
|
sent := notifier.getNotifications()
|
||||||
|
titles := make([]string, 0, len(sent))
|
||||||
|
|
||||||
|
for _, n := range sent {
|
||||||
|
titles = append(titles, n.Title)
|
||||||
|
}
|
||||||
|
|
||||||
|
slices.Sort(titles)
|
||||||
|
|
||||||
|
want := []string{
|
||||||
|
"Inconsistency: " + host,
|
||||||
|
"NS Failure: " + skipped,
|
||||||
|
"NS Failure: " + host,
|
||||||
|
"Record Change: " + host,
|
||||||
|
}
|
||||||
|
|
||||||
|
if !slices.Equal(titles, want) {
|
||||||
|
t.Errorf("sent %v, want %v", titles, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSkipRecordNotificationsCheck checks testHost, which is in
|
||||||
|
// SkipRecordNotifications, from a saved state in which every nameserver
|
||||||
|
// live DNS lists answered with an address live DNS never returns. No
|
||||||
|
// Record Change and no Inconsistency is sent, and the check still saves
|
||||||
|
// what the nameservers answer.
|
||||||
|
func TestSkipRecordNotificationsCheck(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
cfg := defaultTestConfig(t)
|
||||||
|
cfg.Hostnames = []string{testHost}
|
||||||
|
cfg.SkipRecordNotifications = []string{testHost}
|
||||||
|
|
||||||
|
nameservers := lookupNameservers(t, testHost)
|
||||||
|
|
||||||
|
_, deps := runChecks(t, cfg, func(deps *testDeps) {
|
||||||
|
byNameserver := make(map[string]*state.NameserverRecordState)
|
||||||
|
for _, ns := range nameservers {
|
||||||
|
byNameserver[ns] = answered(map[string][]string{"A": {oldIP}})
|
||||||
|
}
|
||||||
|
|
||||||
|
deps.state.SetHostnameState(testHost, saved(byNameserver))
|
||||||
|
})
|
||||||
|
|
||||||
|
for _, title := range []string{
|
||||||
|
"Record Change: " + testHost,
|
||||||
|
"Inconsistency: " + testHost,
|
||||||
|
} {
|
||||||
|
if n := countNotifications(deps, title); n != 0 {
|
||||||
|
t.Errorf("sent %d %q, want 0", n, title)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A nameserver whose query for A failed keeps oldIP, so the check
|
||||||
|
// is that some address live DNS gave was saved.
|
||||||
|
hs, _ := deps.state.GetHostnameState(testHost)
|
||||||
|
fromLiveDNS := func(ip string) bool { return ip != oldIP }
|
||||||
|
|
||||||
|
if !slices.ContainsFunc(addresses(hs), fromLiveDNS) {
|
||||||
|
t.Errorf("saved addresses %v, want those live DNS gave", addresses(hs))
|
||||||
|
}
|
||||||
|
}
|
||||||
+175
-49
@@ -6,8 +6,10 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"maps"
|
"maps"
|
||||||
|
"net"
|
||||||
"slices"
|
"slices"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -133,7 +135,12 @@ func (w *Watcher) Run(ctx context.Context) {
|
|||||||
|
|
||||||
w.cleanupRemovedTargets()
|
w.cleanupRemovedTargets()
|
||||||
w.RunOnce(ctx)
|
w.RunOnce(ctx)
|
||||||
w.maybeSendTestNotification(ctx)
|
|
||||||
|
// RunOnce returns as usual when shutdown cuts the scan short, and
|
||||||
|
// the startup notification says the scan completed.
|
||||||
|
if ctx.Err() == nil {
|
||||||
|
w.maybeSendTestNotification(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
dnsTicker := time.NewTicker(w.config.DNSInterval)
|
dnsTicker := time.NewTicker(w.config.DNSInterval)
|
||||||
tlsTicker := time.NewTicker(w.config.TLSInterval)
|
tlsTicker := time.NewTicker(w.config.TLSInterval)
|
||||||
@@ -284,12 +291,25 @@ func (w *Watcher) logFailedLookup(
|
|||||||
w.log.Error(msg, args...)
|
w.log.Error(msg, args...)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// checkDomain looks up domain's delegation and checks domain with it
|
||||||
|
// (see checkDomainResult).
|
||||||
func (w *Watcher) checkDomain(
|
func (w *Watcher) checkDomain(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
domain string,
|
domain string,
|
||||||
) {
|
) {
|
||||||
nameservers, err := w.resolver.LookupNS(ctx, domain)
|
nameservers, err := w.resolver.LookupNS(ctx, domain)
|
||||||
|
|
||||||
|
w.checkDomainResult(ctx, domain, nameservers, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkDomainResult finishes a check of domain from nameservers and err,
|
||||||
|
// what the lookup of its delegation returned.
|
||||||
|
func (w *Watcher) checkDomainResult(
|
||||||
|
ctx context.Context,
|
||||||
|
domain string,
|
||||||
|
nameservers []string,
|
||||||
|
err error,
|
||||||
|
) {
|
||||||
// A domain that does not exist has no nameservers.
|
// A domain that does not exist has no nameservers.
|
||||||
nxdomain := errors.Is(err, resolver.ErrNXDomain)
|
nxdomain := errors.Is(err, resolver.ErrNXDomain)
|
||||||
if nxdomain {
|
if nxdomain {
|
||||||
@@ -304,6 +324,12 @@ func (w *Watcher) checkDomain(
|
|||||||
"error", err,
|
"error", err,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// For a domain with no delegation of its own, the servers that
|
||||||
|
// did not answer can be those of the zone it is in, at which
|
||||||
|
// its records are asked. They are then saved as failed, as a
|
||||||
|
// hostname's are.
|
||||||
|
w.checkHostnameResult(ctx, domain, nil, err)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -322,6 +348,20 @@ func (w *Watcher) checkDomain(
|
|||||||
ctx, nameservers, prevAddresses,
|
ctx, nameservers, prevAddresses,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// A domain that does not exist has no records of its own: none are
|
||||||
|
// asked for, and those saved by an earlier check are removed.
|
||||||
|
// Otherwise the apex domain's records are also checked and saved as
|
||||||
|
// a hostname's, so that the port and TLS checks find its addresses.
|
||||||
|
// Notifications about them name it as a domain (see nameLine). When
|
||||||
|
// their lookup fails, the check fails as when the NS lookup does, so
|
||||||
|
// the saved delegation and the saved records come from the same
|
||||||
|
// check, as detectNSDisappearances needs.
|
||||||
|
if nxdomain {
|
||||||
|
w.state.DeleteHostnameState(domain)
|
||||||
|
} else if !w.checkHostname(ctx, domain) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if hasPrev && !w.firstRun {
|
if hasPrev && !w.firstRun {
|
||||||
w.detectNSChanges(ctx, domain, prev.Nameservers, nameservers)
|
w.detectNSChanges(ctx, domain, prev.Nameservers, nameservers)
|
||||||
w.detectNSAddressChanges(ctx, domain, prevAddresses, addresses)
|
w.detectNSAddressChanges(ctx, domain, prevAddresses, addresses)
|
||||||
@@ -333,19 +373,6 @@ func (w *Watcher) checkDomain(
|
|||||||
NXDomain: nxdomain,
|
NXDomain: nxdomain,
|
||||||
LastChecked: now,
|
LastChecked: now,
|
||||||
})
|
})
|
||||||
|
|
||||||
// A domain that does not exist has no records of its own: none are
|
|
||||||
// asked for, and those saved by an earlier check are removed.
|
|
||||||
if nxdomain {
|
|
||||||
w.state.DeleteHostnameState(domain)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// The apex domain's records are also checked and saved as a
|
|
||||||
// hostname's, so that the port and TLS checks find its addresses.
|
|
||||||
// Notifications about them name it as a domain (see nameLine).
|
|
||||||
w.checkHostname(ctx, domain)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *Watcher) detectNSChanges(
|
func (w *Watcher) detectNSChanges(
|
||||||
@@ -456,10 +483,12 @@ func (w *Watcher) detectNSAddressChanges(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// checkHostname looks up hostname's records and checks them (see
|
||||||
|
// checkHostnameResult). It reports whether it saved them.
|
||||||
func (w *Watcher) checkHostname(
|
func (w *Watcher) checkHostname(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
hostname string,
|
hostname string,
|
||||||
) {
|
) bool {
|
||||||
results, err := w.resolver.LookupAllRecords(ctx, hostname)
|
results, err := w.resolver.LookupAllRecords(ctx, hostname)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
w.logFailedLookup(
|
w.logFailedLookup(
|
||||||
@@ -468,15 +497,70 @@ func (w *Watcher) checkHostname(
|
|||||||
"hostname", hostname,
|
"hostname", hostname,
|
||||||
"error", err,
|
"error", err,
|
||||||
)
|
)
|
||||||
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return w.checkHostnameResult(ctx, hostname, results, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkHostnameResult finishes a check of hostname from results and err,
|
||||||
|
// what the lookup of its records returned, and reports whether it saved
|
||||||
|
// them. When the lookup failed, it saves nothing, unless the nameservers
|
||||||
|
// that did not answer are those of the previous check (see
|
||||||
|
// failedNameservers).
|
||||||
|
func (w *Watcher) checkHostnameResult(
|
||||||
|
ctx context.Context,
|
||||||
|
hostname string,
|
||||||
|
results map[string]*resolver.NameserverResponse,
|
||||||
|
err error,
|
||||||
|
) bool {
|
||||||
prev, _ := w.state.GetHostnameState(hostname)
|
prev, _ := w.state.GetHostnameState(hostname)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
results = failedNameservers(err, prev)
|
||||||
|
if results == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
w.updateHostnameState(
|
w.updateHostnameState(
|
||||||
ctx, hostname, buildHostnameState(results, prev, time.Now().UTC()),
|
ctx, hostname, buildHostnameState(results, prev, time.Now().UTC()),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// failedNameservers returns a failed response for each nameserver in
|
||||||
|
// prev, a name's state from the previous check, with err as the reason,
|
||||||
|
// when err says that the walk to the name's nameservers reached their
|
||||||
|
// zone and none of them answered. For any other error, as when the walk
|
||||||
|
// got no answer before it reached their zone, or when prev is nil, it
|
||||||
|
// returns nil.
|
||||||
|
func failedNameservers(
|
||||||
|
err error,
|
||||||
|
prev *state.HostnameState,
|
||||||
|
) map[string]*resolver.NameserverResponse {
|
||||||
|
var noAnswer *resolver.NoAnswerError
|
||||||
|
if !errors.As(err, &noAnswer) || prev == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
saved := slices.Sorted(maps.Keys(prev.RecordsByNameserver))
|
||||||
|
if !slices.Equal(noAnswer.Nameservers, saved) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
results := make(map[string]*resolver.NameserverResponse)
|
||||||
|
|
||||||
|
for _, ns := range saved {
|
||||||
|
results[ns] = &resolver.NameserverResponse{
|
||||||
|
Nameserver: ns,
|
||||||
|
Records: make(map[string][]string),
|
||||||
|
Status: resolver.StatusError,
|
||||||
|
Error: err.Error(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results
|
||||||
}
|
}
|
||||||
|
|
||||||
// updateHostnameState finishes a check of hostname from newState, built
|
// updateHostnameState finishes a check of hostname from newState, built
|
||||||
@@ -730,12 +814,16 @@ func (w *Watcher) detectCNAMEAddressChanges(
|
|||||||
// failed on either check has no records to compare. The records kept
|
// failed on either check has no records to compare. The records kept
|
||||||
// for a record type whose query failed are compared too, but not those
|
// for a record type whose query failed are compared too, but not those
|
||||||
// of a type in UnknownTypes on either check, which the message leaves
|
// of a type in UnknownTypes on either check, which the message leaves
|
||||||
// out as well.
|
// out as well. Nothing is sent for a name in SkipRecordNotifications.
|
||||||
func (w *Watcher) detectRecordChanges(
|
func (w *Watcher) detectRecordChanges(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
hostname string,
|
hostname string,
|
||||||
prev, current *state.HostnameState,
|
prev, current *state.HostnameState,
|
||||||
) {
|
) {
|
||||||
|
if slices.Contains(w.config.SkipRecordNotifications, hostname) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
for ns, cur := range current.RecordsByNameserver {
|
for ns, cur := range current.RecordsByNameserver {
|
||||||
prevNS, ok := prev.RecordsByNameserver[ns]
|
prevNS, ok := prev.RecordsByNameserver[ns]
|
||||||
if !ok || prevNS.Status != statusOK || cur.Status != statusOK {
|
if !ok || prevNS.Status != statusOK || cur.Status != statusOK {
|
||||||
@@ -768,28 +856,53 @@ func (w *Watcher) detectRecordChanges(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// detectNSDisappearances sends one NS Change listing the nameservers of
|
||||||
|
// the previous check that are no longer those of the zone hostname is
|
||||||
|
// in. For a configured apex domain it leaves out those of the domain's
|
||||||
|
// saved delegation, which detectNSChanges notifies when they are removed
|
||||||
|
// from it. checkDomain saves a new delegation only after this runs, and
|
||||||
|
// only together with the records, so the saved delegation and the
|
||||||
|
// nameservers in prev come from the same check.
|
||||||
func (w *Watcher) detectNSDisappearances(
|
func (w *Watcher) detectNSDisappearances(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
hostname string,
|
hostname string,
|
||||||
prev, current *state.HostnameState,
|
prev, current *state.HostnameState,
|
||||||
) {
|
) {
|
||||||
for ns, prevNS := range prev.RecordsByNameserver {
|
var delegation []string
|
||||||
if _, ok := current.RecordsByNameserver[ns]; ok || prevNS.Status != statusOK {
|
|
||||||
continue
|
if w.isDomain(hostname) {
|
||||||
|
if domainState, ok := w.state.GetDomainState(hostname); ok {
|
||||||
|
delegation = domainState.Nameservers
|
||||||
}
|
}
|
||||||
|
|
||||||
msg := fmt.Sprintf(
|
|
||||||
"%s\nNameserver: %s disappeared",
|
|
||||||
w.nameLine(hostname), ns,
|
|
||||||
)
|
|
||||||
|
|
||||||
w.notify.SendNotification(
|
|
||||||
ctx,
|
|
||||||
"NS Failure: "+hostname,
|
|
||||||
msg,
|
|
||||||
"error",
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var removed []string
|
||||||
|
|
||||||
|
for ns := range prev.RecordsByNameserver {
|
||||||
|
_, ok := current.RecordsByNameserver[ns]
|
||||||
|
if !ok && !slices.Contains(delegation, ns) {
|
||||||
|
removed = append(removed, ns)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(removed) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
slices.Sort(removed)
|
||||||
|
|
||||||
|
msg := fmt.Sprintf(
|
||||||
|
"%s\nRemoved: %s",
|
||||||
|
w.nameLine(hostname),
|
||||||
|
strings.Join(removed, ", "),
|
||||||
|
)
|
||||||
|
|
||||||
|
w.notify.SendNotification(
|
||||||
|
ctx,
|
||||||
|
"NS Change: "+hostname,
|
||||||
|
msg,
|
||||||
|
"warning",
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// detectNSFailures notifies when a nameserver that answered on the
|
// detectNSFailures notifies when a nameserver that answered on the
|
||||||
@@ -835,11 +948,18 @@ func (w *Watcher) detectNSFailures(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// detectInconsistencies notifies each pair of nameservers that newly
|
||||||
|
// disagree (see newlyDisagreeingPairs). Nothing is sent for a name in
|
||||||
|
// SkipRecordNotifications.
|
||||||
func (w *Watcher) detectInconsistencies(
|
func (w *Watcher) detectInconsistencies(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
hostname string,
|
hostname string,
|
||||||
prev, current *state.HostnameState,
|
prev, current *state.HostnameState,
|
||||||
) {
|
) {
|
||||||
|
if slices.Contains(w.config.SkipRecordNotifications, hostname) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
for _, pair := range newlyDisagreeingPairs(prev, current) {
|
for _, pair := range newlyDisagreeingPairs(prev, current) {
|
||||||
ns1, ns2 := pair[0], pair[1]
|
ns1, ns2 := pair[0], pair[1]
|
||||||
state1 := current.RecordsByNameserver[ns1]
|
state1 := current.RecordsByNameserver[ns1]
|
||||||
@@ -932,7 +1052,8 @@ func (w *Watcher) checkAllPorts(ctx context.Context) {
|
|||||||
|
|
||||||
// Phase 3: Remove port state entries that no longer have
|
// Phase 3: Remove port state entries that no longer have
|
||||||
// any hostname referencing them, and certificate entries for
|
// any hostname referencing them, and certificate entries for
|
||||||
// an address their name no longer has.
|
// an address whose port 443 is closed or that their name no
|
||||||
|
// longer has.
|
||||||
w.cleanupStalePorts(associations)
|
w.cleanupStalePorts(associations)
|
||||||
w.cleanupStaleCertificates()
|
w.cleanupStaleCertificates()
|
||||||
}
|
}
|
||||||
@@ -953,7 +1074,7 @@ func (w *Watcher) buildPortAssociations() map[string][]string {
|
|||||||
ips := w.collectIPs(name)
|
ips := w.collectIPs(name)
|
||||||
for _, ip := range ips {
|
for _, ip := range ips {
|
||||||
for _, port := range monitoredPorts {
|
for _, port := range monitoredPorts {
|
||||||
key := fmt.Sprintf("%s:%d", ip, port)
|
key := net.JoinHostPort(ip, strconv.Itoa(port))
|
||||||
if assoc[key] == nil {
|
if assoc[key] == nil {
|
||||||
assoc[key] = make(map[string]bool)
|
assoc[key] = make(map[string]bool)
|
||||||
}
|
}
|
||||||
@@ -978,18 +1099,15 @@ func (w *Watcher) buildPortAssociations() map[string][]string {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// parsePortKey splits an "ip:port" key into its components.
|
// parsePortKey splits an "ip:port" key, written by net.JoinHostPort,
|
||||||
|
// into its components.
|
||||||
func parsePortKey(key string) (string, int) {
|
func parsePortKey(key string) (string, int) {
|
||||||
lastColon := strings.LastIndex(key, ":")
|
ip, port, err := net.SplitHostPort(key)
|
||||||
if lastColon < 0 {
|
if err != nil {
|
||||||
return key, 0
|
return key, 0
|
||||||
}
|
}
|
||||||
|
|
||||||
ip := key[:lastColon]
|
p, err := strconv.Atoi(port)
|
||||||
|
|
||||||
var p int
|
|
||||||
|
|
||||||
_, err := fmt.Sscanf(key[lastColon+1:], "%d", &p)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return ip, 0
|
return ip, 0
|
||||||
}
|
}
|
||||||
@@ -1019,13 +1137,21 @@ func (w *Watcher) cleanupStalePorts(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// cleanupStaleCertificates removes the certificate entries for an
|
// cleanupStaleCertificates removes the certificate entries for an
|
||||||
// address their name no longer resolves to. An entry saved for a name
|
// address whose port 443 was found closed, and for an address their
|
||||||
// none of whose nameservers answered is kept: that name's addresses are
|
// name no longer resolves to. An entry saved for a name none of whose
|
||||||
// not known, not gone.
|
// nameservers answered is kept unless its port is closed: that name's
|
||||||
|
// addresses are not known, not gone.
|
||||||
func (w *Watcher) cleanupStaleCertificates() {
|
func (w *Watcher) cleanupStaleCertificates() {
|
||||||
for _, key := range w.state.GetAllCertificateKeys() {
|
for _, key := range w.state.GetAllCertificateKeys() {
|
||||||
ip, hostname := parseCertKey(key)
|
ip, hostname := parseCertKey(key)
|
||||||
|
|
||||||
|
ps, ok := w.state.GetPortState(net.JoinHostPort(ip, strconv.Itoa(tlsPort)))
|
||||||
|
if ok && !ps.Open {
|
||||||
|
w.state.DeleteCertificateState(key)
|
||||||
|
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
if slices.Contains(w.collectIPs(hostname), ip) ||
|
if slices.Contains(w.collectIPs(hostname), ip) ||
|
||||||
w.noNameserverAnswered(hostname) {
|
w.noNameserverAnswered(hostname) {
|
||||||
continue
|
continue
|
||||||
@@ -1134,7 +1260,7 @@ func (w *Watcher) checkSinglePort(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
key := fmt.Sprintf("%s:%d", ip, port)
|
key := net.JoinHostPort(ip, strconv.Itoa(port))
|
||||||
now := time.Now().UTC()
|
now := time.Now().UTC()
|
||||||
prev, hasPrev := w.state.GetPortState(key)
|
prev, hasPrev := w.state.GetPortState(key)
|
||||||
|
|
||||||
@@ -1196,7 +1322,7 @@ func (w *Watcher) checkTLSForHostname(
|
|||||||
ips := w.collectIPs(hostname)
|
ips := w.collectIPs(hostname)
|
||||||
|
|
||||||
for _, ip := range ips {
|
for _, ip := range ips {
|
||||||
portKey := fmt.Sprintf("%s:%d", ip, tlsPort)
|
portKey := net.JoinHostPort(ip, strconv.Itoa(tlsPort))
|
||||||
|
|
||||||
ps, ok := w.state.GetPortState(portKey)
|
ps, ok := w.state.GetPortState(portKey)
|
||||||
if !ok || !ps.Open {
|
if !ok || !ps.Open {
|
||||||
@@ -1220,7 +1346,7 @@ func (w *Watcher) checkTLSCert(
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
certKey := fmt.Sprintf("%s:%d:%s", ip, tlsPort, hostname)
|
certKey := net.JoinHostPort(ip, strconv.Itoa(tlsPort)) + ":" + hostname
|
||||||
now := time.Now().UTC()
|
now := time.Now().UTC()
|
||||||
prev, hasPrev := w.state.GetCertificateState(certKey)
|
prev, hasPrev := w.state.GetCertificateState(certKey)
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"net"
|
||||||
"os"
|
"os"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
@@ -139,6 +140,22 @@ func (m *mockNotifier) getNotifications() []notification {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// cancelOnNotify is a mockNotifier that calls cancel at each
|
||||||
|
// notification, as if shutdown cut the check short there.
|
||||||
|
type cancelOnNotify struct {
|
||||||
|
*mockNotifier
|
||||||
|
|
||||||
|
cancel context.CancelFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n cancelOnNotify) SendNotification(
|
||||||
|
ctx context.Context,
|
||||||
|
title, message, priority string,
|
||||||
|
) {
|
||||||
|
n.mockNotifier.SendNotification(ctx, title, message, priority)
|
||||||
|
n.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
// --- Helpers to build a Watcher and run its checks against live DNS ---
|
// --- Helpers to build a Watcher and run its checks against live DNS ---
|
||||||
|
|
||||||
type testDeps struct {
|
type testDeps struct {
|
||||||
@@ -461,6 +478,54 @@ func TestDomainPortAndTLSChecks(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestFirstCheckAfterLoadingFileWithoutSections loads a state file
|
||||||
|
// holding {}, and one that leaves out the certificates section, and runs
|
||||||
|
// the first check. It saves domain, hostname, port and certificate
|
||||||
|
// entries; a section loaded as nil made it panic.
|
||||||
|
func TestFirstCheckAfterLoadingFileWithoutSections(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
file string
|
||||||
|
}{
|
||||||
|
{"no sections", `{}`},
|
||||||
|
{"no certificates", `{"domains": {}, "hostnames": {}, "ports": {}}`},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
cfg := defaultTestConfig(t)
|
||||||
|
cfg.Domains = []string{testSmallDomain}
|
||||||
|
|
||||||
|
_, deps := runChecks(t, cfg, func(deps *testDeps) {
|
||||||
|
err := os.WriteFile(cfg.StatePath(), []byte(tt.file), 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("writing the state file: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = deps.state.Load()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("loading the state file: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
snap := deps.state.GetSnapshot()
|
||||||
|
if len(snap.Domains) == 0 || len(snap.Hostnames) == 0 ||
|
||||||
|
len(snap.Ports) == 0 || len(snap.Certificates) == 0 {
|
||||||
|
t.Errorf(
|
||||||
|
"saved %d domain, %d hostname, %d port and %d "+
|
||||||
|
"certificate entries, want at least one of each",
|
||||||
|
len(snap.Domains), len(snap.Hostnames),
|
||||||
|
len(snap.Ports), len(snap.Certificates),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestNSChangeDetection(t *testing.T) {
|
func TestNSChangeDetection(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -558,6 +623,11 @@ func TestDomainThatDoesNotExist(t *testing.T) {
|
|||||||
// nameservers and without nxdomain, and its records, asked at the
|
// nameservers and without nxdomain, and its records, asked at the
|
||||||
// codeberg.page servers, are saved. Those are testSmallDomain's two
|
// codeberg.page servers, are saved. Those are testSmallDomain's two
|
||||||
// nameservers; github.io, the zone of the README's example, has eight.
|
// nameservers; github.io, the zone of the README's example, has eight.
|
||||||
|
// The previous check saved a delegation to oldNS1, now withdrawn, and
|
||||||
|
// records asked at oldNS1. A first check is cut short at its first
|
||||||
|
// notification, as shutdown would, and a second runs in full: across
|
||||||
|
// them the NS Change of its delegation removes oldNS1, and no other NS
|
||||||
|
// Change lists it again.
|
||||||
func TestDomainWithNoDelegationOfItsOwn(t *testing.T) {
|
func TestDomainWithNoDelegationOfItsOwn(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
@@ -569,9 +639,30 @@ func TestDomainWithNoDelegationOfItsOwn(t *testing.T) {
|
|||||||
var deps *testDeps
|
var deps *testDeps
|
||||||
|
|
||||||
livednstest.Retry(t, "watcher checks", func(ctx context.Context) error {
|
livednstest.Retry(t, "watcher checks", func(ctx context.Context) error {
|
||||||
var w *watcher.Watcher
|
deps = newTestDeps(t, cfg)
|
||||||
|
|
||||||
w, deps = newTestWatcher(t, cfg)
|
firstCtx, cancel := context.WithCancel(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
w := watcher.NewForTest(
|
||||||
|
cfg,
|
||||||
|
deps.state,
|
||||||
|
resolver.NewFromLogger(slog.Default()),
|
||||||
|
deps.portChecker,
|
||||||
|
deps.tlsChecker,
|
||||||
|
cancelOnNotify{mockNotifier: deps.notifier, cancel: cancel},
|
||||||
|
)
|
||||||
|
|
||||||
|
deps.state.SetDomainState(domain, &state.DomainState{
|
||||||
|
Nameservers: []string{oldNS1},
|
||||||
|
})
|
||||||
|
deps.state.SetHostnameState(domain, saved(
|
||||||
|
map[string]*state.NameserverRecordState{
|
||||||
|
oldNS1: answered(map[string][]string{"A": {oldIP}}),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
|
||||||
|
w.RunOnce(firstCtx)
|
||||||
|
|
||||||
err := checkOnce(ctx, w, deps)
|
err := checkOnce(ctx, w, deps)
|
||||||
|
|
||||||
@@ -593,6 +684,22 @@ func TestDomainWithNoDelegationOfItsOwn(t *testing.T) {
|
|||||||
if _, ok := deps.state.GetHostnameState(domain); !ok {
|
if _, ok := deps.state.GetHostnameState(domain); !ok {
|
||||||
t.Errorf("no records saved for %s", domain)
|
t.Errorf("no records saved for %s", domain)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
title := "NS Change: " + domain
|
||||||
|
want := "Domain: " + domain + "\nAdded: \nRemoved: " + oldNS1
|
||||||
|
|
||||||
|
var changes []notification
|
||||||
|
|
||||||
|
for _, n := range deps.notifier.getNotifications() {
|
||||||
|
if n.Title == title {
|
||||||
|
changes = append(changes, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(changes) != 1 || changes[0].Message != want {
|
||||||
|
t.Errorf("sent %v, want one %q with message:\n%s",
|
||||||
|
changes, title, want)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNSAddressChangeDetection(t *testing.T) {
|
func TestNSAddressChangeDetection(t *testing.T) {
|
||||||
@@ -718,7 +825,8 @@ func TestPortStateChange(t *testing.T) {
|
|||||||
|
|
||||||
hs, _ := deps.state.GetHostnameState(testHost)
|
hs, _ := deps.state.GetHostnameState(testHost)
|
||||||
assertNotified(
|
assertNotified(
|
||||||
t, deps, "Port Change: "+addresses(hs)[0]+":443", "warning",
|
t, deps, "Port Change: "+net.JoinHostPort(addresses(hs)[0], "443"),
|
||||||
|
"warning",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -925,11 +1033,12 @@ func TestDNSRunsBeforePortAndTLSChecks(t *testing.T) {
|
|||||||
|
|
||||||
// Port and TLS checks must use the addresses this check found.
|
// Port and TLS checks must use the addresses this check found.
|
||||||
for _, ip := range addresses(snap.Hostnames[testHost]) {
|
for _, ip := range addresses(snap.Hostnames[testHost]) {
|
||||||
if _, ok := snap.Ports[ip+":80"]; !ok {
|
portKey := net.JoinHostPort(ip, "80")
|
||||||
t.Error("port check used stale DNS: missing " + ip + ":80")
|
if _, ok := snap.Ports[portKey]; !ok {
|
||||||
|
t.Error("port check used stale DNS: missing " + portKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
certKey := ip + ":443:" + testHost
|
certKey := net.JoinHostPort(ip, "443") + ":" + testHost
|
||||||
if _, ok := snap.Certificates[certKey]; !ok {
|
if _, ok := snap.Certificates[certKey]; !ok {
|
||||||
t.Error("TLS check used stale DNS: missing " + certKey)
|
t.Error("TLS check used stale DNS: missing " + certKey)
|
||||||
}
|
}
|
||||||
@@ -1049,7 +1158,7 @@ func TestSendTestNotification_Disabled(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNSFailureAndRecovery(t *testing.T) {
|
func TestNSChangeAndRecovery(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
cfg := defaultTestConfig(t)
|
cfg := defaultTestConfig(t)
|
||||||
@@ -1059,7 +1168,7 @@ func TestNSFailureAndRecovery(t *testing.T) {
|
|||||||
|
|
||||||
// The saved state has every nameserver live DNS lists as one that
|
// The saved state has every nameserver live DNS lists as one that
|
||||||
// did not answer, and, as answering, one that live DNS does not
|
// did not answer, and, as answering, one that live DNS does not
|
||||||
// list, which then disappears.
|
// list, which the check then finds removed.
|
||||||
_, deps := runChecks(t, cfg, func(deps *testDeps) {
|
_, deps := runChecks(t, cfg, func(deps *testDeps) {
|
||||||
byNameserver := map[string]*state.NameserverRecordState{
|
byNameserver := map[string]*state.NameserverRecordState{
|
||||||
oldNS1: answered(map[string][]string{"A": {oldIP}}),
|
oldNS1: answered(map[string][]string{"A": {oldIP}}),
|
||||||
@@ -1071,7 +1180,7 @@ func TestNSFailureAndRecovery(t *testing.T) {
|
|||||||
deps.state.SetHostnameState(testHost, saved(byNameserver))
|
deps.state.SetHostnameState(testHost, saved(byNameserver))
|
||||||
})
|
})
|
||||||
|
|
||||||
assertNotified(t, deps, "NS Failure: "+testHost, "error")
|
assertNotified(t, deps, "NS Change: "+testHost, "warning")
|
||||||
assertNotified(t, deps, "NS Recovery: "+testHost, "success")
|
assertNotified(t, deps, "NS Recovery: "+testHost, "success")
|
||||||
|
|
||||||
// A nameserver that did not answer has no records to compare, so
|
// A nameserver that did not answer has no records to compare, so
|
||||||
|
|||||||
+8
-8
@@ -3,12 +3,12 @@
|
|||||||
# this repo. Idempotent: every install is guarded by a check so already
|
# this repo. Idempotent: every install is guarded by a check so already
|
||||||
# installed tools are skipped. Base tooling comes from nix, apt, brew,
|
# installed tools are skipped. Base tooling comes from nix, apt, brew,
|
||||||
# or apk (detected in that order); assumes nothing is present.
|
# or apk (detected in that order); assumes nothing is present.
|
||||||
# goimports is not installed here: script/fmt and script/fmt-check-go
|
# goimports is not installed here: script/fmt and script/fmt-check run
|
||||||
# run it with `go run` at a pinned commit.
|
# it with `go run` at a pinned commit.
|
||||||
# The linter is NOT installed here: golangci-lint runs via docker only
|
# The linter is NOT installed here: golangci-lint runs via docker only
|
||||||
# (script/lint), pinned by image digest, so its only prerequisite is a
|
# (script/lint), pinned by image digest, so its only prerequisite is a
|
||||||
# working docker. Nor is prettier: script/fmt and
|
# working docker. Nor is prettier: script/fmt and script/fmt-check run
|
||||||
# script/fmt-check-markdown run it in a container from Dockerfile.fmt.
|
# it in a stage of the Dockerfile.
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
||||||
@@ -67,12 +67,12 @@ main() {
|
|||||||
if missing make; then pkg_install gnumake make make make; fi
|
if missing make; then pkg_install gnumake make make make; fi
|
||||||
if missing go; then pkg_install go golang go go; fi
|
if missing go; then pkg_install go golang go go; fi
|
||||||
|
|
||||||
# Linting and the markdown formatter run via docker only. Warn,
|
# Testing, linting and the markdown formatter run via docker only.
|
||||||
# don't fail: building and testing work without it.
|
# Warn, don't fail: make build works without it.
|
||||||
if missing docker; then
|
if missing docker; then
|
||||||
echo "bootstrap: WARNING: docker not found; install it to" \
|
echo "bootstrap: WARNING: docker not found; install it to" \
|
||||||
"run make lint, make fmt, make fmt-check, make check" \
|
"run make test, make lint, make fmt, make fmt-check," \
|
||||||
"and make docker." >&2
|
"make check and make docker." >&2
|
||||||
fi
|
fi
|
||||||
|
|
||||||
go mod download
|
go mod download
|
||||||
|
|||||||
+17
-12
@@ -1,14 +1,10 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/cibuild: run the CI build. The Dockerfile's lint stage runs
|
# script/cibuild: run the CI build. It bootstraps first: a CI runner
|
||||||
# the Go half of make fmt-check and golangci-lint; its builder stage
|
# checks out and runs this and nothing else, and script/fmt-check runs
|
||||||
# runs make test and make build. The markdown half of make fmt-check
|
# the formatter on the host, which a pristine checkout cannot do.
|
||||||
# runs after that build, as its own build of Dockerfile.fmt, because
|
# --no-cache for the same reason as script/docker: the gate phases the
|
||||||
# there is no docker inside a docker build.
|
# final stage depends on are RUN steps, and a cached one is a check that
|
||||||
#
|
# did not run.
|
||||||
# --no-cache-filter=lint,builder runs both stages on every invocation;
|
|
||||||
# otherwise an unchanged tree is served from the layer cache and passes
|
|
||||||
# without linting or querying live DNS. script/fmt-check-markdown busts
|
|
||||||
# its own cache the same way.
|
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
||||||
@@ -16,8 +12,17 @@ ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
|
|||||||
|
|
||||||
main() {
|
main() {
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
docker build --no-cache-filter=lint,builder .
|
"$SCRIPT_DIR/bootstrap"
|
||||||
"$SCRIPT_DIR/fmt-check-markdown"
|
"$SCRIPT_DIR/check"
|
||||||
|
# Own line: a failing command substitution inside an argument does
|
||||||
|
# not trip `set -e`, so the inline form degrades silently to an
|
||||||
|
# empty constant. The VERSION build argument takes precedence over
|
||||||
|
# the version a build stage derives from the .git in the context.
|
||||||
|
version="$(git describe --tags --always --dirty 2>/dev/null || true)"
|
||||||
|
[ -n "$version" ] || version="unknown"
|
||||||
|
docker build --no-cache \
|
||||||
|
--build-arg VERSION="$version" \
|
||||||
|
-t "$("$SCRIPT_DIR/projectname")" .
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
+6
-8
@@ -1,10 +1,8 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/docker: build the Docker image tagged with the project name.
|
# script/docker: build the Docker image tagged with the project name.
|
||||||
# The tag comes from script/projectname.
|
# Identical in all repos; the tag comes from script/projectname.
|
||||||
#
|
# --no-cache because the gate phases the final stage depends on are RUN
|
||||||
# --no-cache-filter=lint,builder runs the lint stage and the builder
|
# steps, and a cached one is a check that did not run.
|
||||||
# stage (make test) on every invocation; otherwise an unchanged tree is
|
|
||||||
# served from the layer cache without linting or querying live DNS.
|
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
||||||
@@ -14,11 +12,11 @@ main() {
|
|||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
# Own line: a failing command substitution inside an argument does
|
# Own line: a failing command substitution inside an argument does
|
||||||
# not trip `set -e`, so the inline form degrades silently to an
|
# not trip `set -e`, so the inline form degrades silently to an
|
||||||
# empty constant. The VERSION build arg takes precedence over what
|
# empty constant. The VERSION build argument takes precedence over
|
||||||
# the build would derive from the .git in its context.
|
# the version a build stage derives from the .git in the context.
|
||||||
version="$(git describe --tags --always --dirty 2>/dev/null || true)"
|
version="$(git describe --tags --always --dirty 2>/dev/null || true)"
|
||||||
[ -n "$version" ] || version="unknown"
|
[ -n "$version" ] || version="unknown"
|
||||||
docker build --no-cache-filter=lint,builder \
|
docker build --no-cache \
|
||||||
--build-arg VERSION="$version" \
|
--build-arg VERSION="$version" \
|
||||||
-t "$("$SCRIPT_DIR/projectname")" .
|
-t "$("$SCRIPT_DIR/projectname")" .
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-14
@@ -1,6 +1,6 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/fmt: format all files (writes). Go with gofmt and goimports on
|
# script/fmt: format all files (writes). Go with gofmt and goimports on
|
||||||
# the host, markdown with the prettier pinned by Dockerfile.fmt.
|
# the host, markdown with prettier in the Dockerfile's fmt stage.
|
||||||
#
|
#
|
||||||
# goimports runs with `go run` at a pinned commit, never from PATH, so
|
# goimports runs with `go run` at a pinned commit, never from PATH, so
|
||||||
# every machine formats with the same version and nothing installs it.
|
# every machine formats with the same version and nothing installs it.
|
||||||
@@ -8,21 +8,15 @@
|
|||||||
# The markdown pass is a `docker build --output type=local` rather than a
|
# The markdown pass is a `docker build --output type=local` rather than a
|
||||||
# `docker run -v`, so it needs no bind mount and behaves the same against
|
# `docker run -v`, so it needs no bind mount and behaves the same against
|
||||||
# a remote daemon; the formatted documents come back out of the build and
|
# a remote daemon; the formatted documents come back out of the build and
|
||||||
# are copied over the tree here.
|
# are copied over the tree here. --output writes files and makes no
|
||||||
#
|
# image, so there is nothing to tag.
|
||||||
# Unlike script/fmt-check-markdown this does not bust the cache: it is
|
|
||||||
# not a gate, and any edit to a document changes the COPY layer above the
|
|
||||||
# prettier step, so a cached result is a result over this exact tree.
|
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
||||||
|
|
||||||
# goimports v0.42.0, 2026-08-07. Must match script/fmt-check-go.
|
# goimports v0.42.0, 2026-08-07. Must match script/fmt-check.
|
||||||
GOIMPORTS_REF="golang.org/x/tools/cmd/goimports@009367f5c17a8d4c45a961a3a509277190a9a6f0"
|
GOIMPORTS_REF="golang.org/x/tools/cmd/goimports@009367f5c17a8d4c45a961a3a509277190a9a6f0"
|
||||||
|
|
||||||
# Must match the export stage name in Dockerfile.fmt.
|
|
||||||
stage=fmt-out
|
|
||||||
|
|
||||||
die() {
|
die() {
|
||||||
echo "script/fmt: $*" >&2
|
echo "script/fmt: $*" >&2
|
||||||
exit 1
|
exit 1
|
||||||
@@ -36,10 +30,9 @@ main() {
|
|||||||
tmp="$(mktemp -d "${TMPDIR:-/tmp}/dnswatcher-fmt.XXXXXX")"
|
tmp="$(mktemp -d "${TMPDIR:-/tmp}/dnswatcher-fmt.XXXXXX")"
|
||||||
trap 'rm -rf "$tmp"' EXIT INT TERM
|
trap 'rm -rf "$tmp"' EXIT INT TERM
|
||||||
|
|
||||||
docker build \
|
docker build --no-cache \
|
||||||
--target "$stage" \
|
--target fmt-out \
|
||||||
--output "type=local,dest=$tmp/out" \
|
--output "type=local,dest=$tmp/out" .
|
||||||
-f Dockerfile.fmt .
|
|
||||||
|
|
||||||
# An empty export means prettier was handed nothing, which must not
|
# An empty export means prettier was handed nothing, which must not
|
||||||
# read as "already formatted".
|
# read as "already formatted".
|
||||||
|
|||||||
+27
-4
@@ -1,14 +1,37 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/fmt-check: check formatting (read-only). Same tools and scope
|
# script/fmt-check: check formatting (read-only). Same tools and scope
|
||||||
# as script/fmt, but fails instead of writing: the Go on the host, the
|
# as script/fmt, but fails instead of writing and names what it would
|
||||||
# markdown with prettier in a container.
|
# change: the Go on the host, the markdown with prettier in the
|
||||||
|
# Dockerfile's fmt-check stage.
|
||||||
|
#
|
||||||
|
# --no-cache because a cached check layer is a check that did not run.
|
||||||
|
# The tag makes each build replace the previous image instead of leaving
|
||||||
|
# a dangling one behind.
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
||||||
|
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
|
||||||
|
|
||||||
|
# goimports v0.42.0, 2026-08-07. Must match script/fmt.
|
||||||
|
GOIMPORTS_REF="golang.org/x/tools/cmd/goimports@009367f5c17a8d4c45a961a3a509277190a9a6f0"
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
"$SCRIPT_DIR/fmt-check-go"
|
cd "$ROOT"
|
||||||
"$SCRIPT_DIR/fmt-check-markdown"
|
files="$(gofmt -s -l .)"
|
||||||
|
if [ -n "$files" ]; then
|
||||||
|
echo "gofmt: files not formatted:" >&2
|
||||||
|
echo "$files" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
files="$(go run "$GOIMPORTS_REF" -l .)"
|
||||||
|
if [ -n "$files" ]; then
|
||||||
|
echo "goimports: files not formatted:" >&2
|
||||||
|
echo "$files" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
docker build --no-cache \
|
||||||
|
--target fmt-check \
|
||||||
|
-t "$("$SCRIPT_DIR/projectname")-fmt-check" .
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/fmt-check-go: fail unless every Go source is formatted the way
|
|
||||||
# script/fmt would leave it, and name the files that are not. Read-only.
|
|
||||||
#
|
|
||||||
# Its own script because the Dockerfile's lint stage runs this half
|
|
||||||
# alone: there is no docker inside a docker build to run the markdown
|
|
||||||
# half in.
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
|
||||||
|
|
||||||
# goimports v0.42.0, 2026-08-07. Must match script/fmt.
|
|
||||||
GOIMPORTS_REF="golang.org/x/tools/cmd/goimports@009367f5c17a8d4c45a961a3a509277190a9a6f0"
|
|
||||||
|
|
||||||
main() {
|
|
||||||
cd "$ROOT"
|
|
||||||
files="$(gofmt -s -l .)"
|
|
||||||
if [ -n "$files" ]; then
|
|
||||||
echo "gofmt: files not formatted:" >&2
|
|
||||||
echo "$files" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
files="$(go run "$GOIMPORTS_REF" -l .)"
|
|
||||||
if [ -n "$files" ]; then
|
|
||||||
echo "goimports: files not formatted:" >&2
|
|
||||||
echo "$files" >&2
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# script/fmt-check-markdown: fail unless every .md is formatted the way
|
|
||||||
# script/fmt would leave it. Read-only.
|
|
||||||
#
|
|
||||||
# prettier is never installed on the host: it runs in a container built
|
|
||||||
# from Dockerfile.fmt, pinned by package.json and yarn.lock.
|
|
||||||
# --no-cache-filter is here for the reason script/lint gives: a cached
|
|
||||||
# build checks nothing.
|
|
||||||
#
|
|
||||||
# Its own script because script/cibuild runs this half alone, after the
|
|
||||||
# Dockerfile's lint stage has checked the Go.
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
|
||||||
|
|
||||||
# Must match the markdown check stage name in Dockerfile.fmt.
|
|
||||||
stage=fmt-check
|
|
||||||
|
|
||||||
main() {
|
|
||||||
cd "$ROOT"
|
|
||||||
docker build \
|
|
||||||
--progress=plain \
|
|
||||||
--no-cache-filter="$stage" \
|
|
||||||
--target "$stage" \
|
|
||||||
-f Dockerfile.fmt \
|
|
||||||
.
|
|
||||||
}
|
|
||||||
|
|
||||||
main "$@"
|
|
||||||
+12
-17
@@ -1,28 +1,23 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/lint: run the linter. golangci-lint is never installed or run
|
# script/lint: run the linter. Linting is a phase of the Dockerfile and
|
||||||
# on the host: it runs via docker only, one way, everywhere. This
|
# this builds that phase alone; the linter is never installed or run on
|
||||||
# builds Dockerfile.lint, which COPYs the repo into the digest-pinned
|
# a developer host, where a shared result cache and a host-global lock
|
||||||
# golangci-lint image and lints as a build step, so a successful build
|
# make its answer untrustworthy.
|
||||||
# means a clean lint.
|
|
||||||
#
|
#
|
||||||
# --no-cache-filter=lint forces the lint stage (source copy + linter
|
# The phase is not the last stage in the file, so it is built only when
|
||||||
# run) to execute on every invocation. Without it an unchanged tree
|
# --target names it. --no-cache because a cached lint layer is a lint
|
||||||
# returns success in well under a second having linted nothing. The
|
# that did not run. The tag makes each build replace the previous image
|
||||||
# deps stage (base image + go mod download) stays cached, and no global
|
# instead of leaving a dangling one behind.
|
||||||
# cache invalidation is performed. --progress=plain keeps the linter's
|
|
||||||
# own output visible.
|
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
||||||
|
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
docker build \
|
docker build --no-cache \
|
||||||
--progress=plain \
|
|
||||||
--no-cache-filter=lint \
|
|
||||||
--target lint \
|
--target lint \
|
||||||
-f Dockerfile.lint \
|
-t "$("$SCRIPT_DIR/projectname")-lint" .
|
||||||
.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
+10
-26
@@ -1,35 +1,19 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# script/test: run the test suite.
|
# script/test: run the test suite. Testing is a phase of the Dockerfile
|
||||||
#
|
# and this builds that phase alone, on the same terms as script/lint:
|
||||||
# -count=1 disables Go's test cache, and is load-bearing here. This
|
# --target because a phase that is not the last stage is built only when
|
||||||
# suite queries live DNS on every run by policy (TESTING.md); a cached
|
# named, --no-cache because a cached test layer is a test that did not
|
||||||
# result is a replay of an earlier run's output with no query made at
|
# run, and a tag so each build replaces the previous image.
|
||||||
# all. On an unchanged tree the whole suite would return success in
|
|
||||||
# under a second having resolved nothing, which makes the repeated-run
|
|
||||||
# green that is used as evidence for flakiness fixes worthless. Do not
|
|
||||||
# remove it.
|
|
||||||
#
|
|
||||||
# Conditional verbose rerun per REPO_POLICIES.md: run quiet first so
|
|
||||||
# CI and docker build logs stay readable, and rerun with -v only on
|
|
||||||
# failure. The rerun also carries -count=1 (a cached replay of the
|
|
||||||
# failure would show nothing new), and the exit status is forced to 1
|
|
||||||
# no matter how the rerun ends: the first failure already proved the
|
|
||||||
# suite broken, so a flaky test that passes the second time must not
|
|
||||||
# turn the build green.
|
|
||||||
#
|
|
||||||
# -timeout 90s is a deliberate backstop above the 60s hard cap on
|
|
||||||
# suite duration. Do not lower it.
|
|
||||||
set -eu
|
set -eu
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd -P)"
|
||||||
|
ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
cd "$ROOT"
|
cd "$ROOT"
|
||||||
go test -count=1 -race -timeout 90s -cover ./... || {
|
docker build --no-cache \
|
||||||
echo "--- Rerunning with -v for details ---" >&2
|
--target test \
|
||||||
go test -count=1 -race -timeout 90s -v ./... || true
|
-t "$("$SCRIPT_DIR/projectname")-test" .
|
||||||
exit 1
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
|
|||||||
Reference in New Issue
Block a user