Compare commits
@@ -0,0 +1,34 @@
|
|||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
# Benchmarks of server, BIND and Kea (test/bench, docs/SYSTEM-REQUIREMENTS.md).
|
||||||
|
# Started by hand; the results are printed as a Markdown table in the log
|
||||||
|
# (and in the job summary where the runner supports it).
|
||||||
|
name: bench
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: bench-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
bench:
|
||||||
|
name: Benchmark (server, BIND, Kea)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 90
|
||||||
|
env:
|
||||||
|
# The Docker daemon may be shared: unique compose project.
|
||||||
|
COMPOSE_PROJECT_NAME: ddi-bench-${{ github.run_id }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
|
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
cache: false
|
||||||
|
- name: Tools
|
||||||
|
run: command -v jq >/dev/null || { apt-get update -qq && apt-get install -y -qq --no-install-recommends jq; }
|
||||||
|
- name: Build
|
||||||
|
run: make build-go
|
||||||
|
- name: Benchmark
|
||||||
|
run: make bench
|
||||||
+29
-2
@@ -99,6 +99,8 @@ jobs:
|
|||||||
run: make lint-shell
|
run: make lint-shell
|
||||||
- name: SPDX headers
|
- name: SPDX headers
|
||||||
run: make lint-spdx
|
run: make lint-spdx
|
||||||
|
- name: No hard-coded product names (ADR 0018)
|
||||||
|
run: make lint-brand
|
||||||
|
|
||||||
release-dry-run:
|
release-dry-run:
|
||||||
name: Release build (dry run)
|
name: Release build (dry run)
|
||||||
@@ -126,10 +128,35 @@ jobs:
|
|||||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||||
with:
|
with:
|
||||||
node-version: "24"
|
node-version: "24"
|
||||||
- name: Build release artefacts
|
- name: Install nfpm
|
||||||
run: make release
|
run: scripts/ci/install-tools.sh "$HOME/.local/bin" nfpm
|
||||||
|
- name: Build release artefacts and packages
|
||||||
|
run: make release PACKAGES=1
|
||||||
- name: Verify checksums
|
- name: Verify checksums
|
||||||
run: cd dist && sha256sum -c SHA256SUMS
|
run: cd dist && sha256sum -c SHA256SUMS
|
||||||
|
- name: Inspect packages
|
||||||
|
run: |
|
||||||
|
ls -l dist/*.deb dist/*.rpm
|
||||||
|
# 3 binaries x 2 architectures x (deb, rpm)
|
||||||
|
test "$(ls dist/*.deb dist/*.rpm | wc -l)" -eq 12
|
||||||
|
for deb in dist/*_amd64.deb; do
|
||||||
|
dpkg-deb --info "$deb" >/dev/null
|
||||||
|
dpkg-deb --contents "$deb" >contents.txt
|
||||||
|
grep -q ' ./usr/bin/' contents.txt
|
||||||
|
grep -q ' ./usr/lib/systemd/system/.*\.service$' contents.txt
|
||||||
|
grep -q ' ./usr/share/doc/.*/LICENSE$' contents.txt
|
||||||
|
done
|
||||||
|
- name: Release signature (throwaway key)
|
||||||
|
run: |
|
||||||
|
command -v openssl >/dev/null || (apt-get update -qq && apt-get install -y -qq openssl)
|
||||||
|
scripts/sign-release.sh selftest
|
||||||
|
umask 077
|
||||||
|
key="$(mktemp)"
|
||||||
|
openssl genpkey -algorithm ed25519 -out "$key"
|
||||||
|
RELEASE_SIGNING_KEY="$(cat "$key")" scripts/sign-release.sh sign dist/SHA256SUMS
|
||||||
|
scripts/sign-release.sh public-key "$key" >"$key.pub"
|
||||||
|
scripts/sign-release.sh verify dist/SHA256SUMS dist/SHA256SUMS.sig "$key.pub"
|
||||||
|
rm -f "$key" "$key.pub" dist/SHA256SUMS.sig
|
||||||
- name: Smoke test of the released server binary
|
- name: Smoke test of the released server binary
|
||||||
env:
|
env:
|
||||||
DDI_DATABASE_URL: postgres://ddi:ddi-ci-only@postgres:5432/ddi?sslmode=disable
|
DDI_DATABASE_URL: postgres://ddi:ddi-ci-only@postgres:5432/ddi?sslmode=disable
|
||||||
|
|||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
# Installation test (ADR 0024): the release artifacts and scripts/install.sh
|
||||||
|
# in privileged systemd containers of every supported system. Needs a
|
||||||
|
# runner with access to a Docker daemon that allows privileged containers
|
||||||
|
# with cgroup v2 (see docs/adr/0003).
|
||||||
|
name: install
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: install-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
install:
|
||||||
|
name: Installation (${{ matrix.os }})
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
os: ["debian:12", "debian:13", "ubuntu:22.04", "ubuntu:24.04", "rocky:9"]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
|
||||||
|
with:
|
||||||
|
go-version-file: go.mod
|
||||||
|
cache: false
|
||||||
|
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||||
|
with:
|
||||||
|
node-version: "24"
|
||||||
|
- name: Build release artefacts
|
||||||
|
run: make release PLATFORMS="linux/$(go env GOARCH)"
|
||||||
|
- name: Build a newer release for the upgrade
|
||||||
|
run: |
|
||||||
|
make -o web -o web-deps release PLATFORMS="linux/$(go env GOARCH)" DIST_DIR=dist-next \
|
||||||
|
VERSION="$(git describe --tags --always)-next"
|
||||||
|
- name: Install, enroll, deploy, rerun, upgrade, uninstall
|
||||||
|
env:
|
||||||
|
RUN_ID: ${{ github.run_id }}
|
||||||
|
run: test/install/run.sh "${{ matrix.os }}" dist dist-next
|
||||||
@@ -23,12 +23,40 @@ jobs:
|
|||||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||||
with:
|
with:
|
||||||
node-version: "24"
|
node-version: "24"
|
||||||
- name: Ensure jq
|
- name: Ensure jq and openssl
|
||||||
run: command -v jq >/dev/null || (apt-get update -qq && apt-get install -y -qq jq)
|
run: |
|
||||||
|
command -v jq >/dev/null && command -v openssl >/dev/null ||
|
||||||
|
(apt-get update -qq && apt-get install -y -qq jq openssl)
|
||||||
|
- name: Install nfpm
|
||||||
|
run: scripts/ci/install-tools.sh "$HOME/.local/bin" nfpm
|
||||||
- name: Build
|
- name: Build
|
||||||
run: make release VERSION="${{ github.ref_name }}"
|
run: make release PACKAGES=1 VERSION="${{ github.ref_name }}"
|
||||||
- name: Verify checksums
|
- name: Verify checksums
|
||||||
run: cd dist && sha256sum -c SHA256SUMS
|
run: cd dist && sha256sum -c SHA256SUMS
|
||||||
|
# Ed25519 signature over SHA256SUMS (ADR 0024, docs/RELEASE.md) if the
|
||||||
|
# secret RELEASE_SIGNING_KEY (PEM private key) is set. The key only
|
||||||
|
# exists in a private temporary file during signing.
|
||||||
|
- name: Sign checksums
|
||||||
|
env:
|
||||||
|
RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }}
|
||||||
|
run: |
|
||||||
|
if [[ -z "${RELEASE_SIGNING_KEY:-}" ]]; then
|
||||||
|
echo "::warning::RELEASE_SIGNING_KEY is not set: the release is not signed"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
scripts/sign-release.sh sign dist/SHA256SUMS
|
||||||
|
# The installer must accept the signature: verify with its public
|
||||||
|
# key if one is configured there.
|
||||||
|
pub="$(mktemp)"
|
||||||
|
sed -n -e 's/^[[:space:]]*//' -e 's/.*\(-----BEGIN PUBLIC KEY-----\)/\1/' \
|
||||||
|
-e 's/\(-----END PUBLIC KEY-----\).*/\1/' \
|
||||||
|
-e '/-----BEGIN PUBLIC KEY-----/,/-----END PUBLIC KEY-----/p' scripts/install.sh >"$pub" 2>/dev/null || true
|
||||||
|
if [[ -s "$pub" ]]; then
|
||||||
|
scripts/sign-release.sh verify dist/SHA256SUMS dist/SHA256SUMS.sig "$pub"
|
||||||
|
else
|
||||||
|
echo "::warning::no public key in scripts/install.sh: the installer will not check the signature"
|
||||||
|
fi
|
||||||
|
rm -f "$pub"
|
||||||
- name: Upload to release
|
- name: Upload to release
|
||||||
env:
|
env:
|
||||||
GITEA_API_URL: ${{ github.server_url }}/api/v1
|
GITEA_API_URL: ${{ github.server_url }}/api/v1
|
||||||
|
|||||||
@@ -25,6 +25,10 @@ BUILD_DATE ?= $(shell git log -1 --format=%cI 2>/dev/null)
|
|||||||
PLATFORMS ?= linux/amd64 linux/arm64
|
PLATFORMS ?= linux/amd64 linux/arm64
|
||||||
BIN_DIR ?= bin
|
BIN_DIR ?= bin
|
||||||
DIST_DIR ?= dist
|
DIST_DIR ?= dist
|
||||||
|
# nfpm for make packages / PACKAGES=1; scripts/ci/install-tools.sh installs
|
||||||
|
# the pinned version (NFPM_VERSION there).
|
||||||
|
NFPM ?= nfpm
|
||||||
|
export NFPM
|
||||||
|
|
||||||
COMPOSE_DEV := docker compose -f deploy/compose/compose.dev.yaml
|
COMPOSE_DEV := docker compose -f deploy/compose/compose.dev.yaml
|
||||||
|
|
||||||
@@ -103,7 +107,7 @@ fmt:
|
|||||||
|
|
||||||
## lint: run all linters
|
## lint: run all linters
|
||||||
.PHONY: lint
|
.PHONY: lint
|
||||||
lint: lint-go lint-proto lint-web lint-shell lint-spdx
|
lint: lint-go lint-proto lint-web lint-shell lint-spdx lint-brand
|
||||||
|
|
||||||
.PHONY: lint-go
|
.PHONY: lint-go
|
||||||
lint-go:
|
lint-go:
|
||||||
@@ -127,6 +131,11 @@ lint-shell:
|
|||||||
lint-spdx:
|
lint-spdx:
|
||||||
scripts/check-spdx.sh
|
scripts/check-spdx.sh
|
||||||
|
|
||||||
|
## lint-brand: no hard-coded product names in units, packages, installer (ADR 0018)
|
||||||
|
.PHONY: lint-brand
|
||||||
|
lint-brand:
|
||||||
|
scripts/check-brand.sh
|
||||||
|
|
||||||
## test: run Go and frontend unit tests
|
## test: run Go and frontend unit tests
|
||||||
.PHONY: test
|
.PHONY: test
|
||||||
test: test-go test-web
|
test: test-go test-web
|
||||||
@@ -150,6 +159,11 @@ test-integration:
|
|||||||
go test -tags integration -count=1 -v -timeout 20m \
|
go test -tags integration -count=1 -v -timeout 20m \
|
||||||
./server/internal/configgen/integration/ ./agent/role/integration/
|
./server/internal/configgen/integration/ ./agent/role/integration/
|
||||||
|
|
||||||
|
## bench: measure server, BIND and Kea with generated data (needs docker and bin/ from build-go)
|
||||||
|
.PHONY: bench
|
||||||
|
bench:
|
||||||
|
test/bench/run.sh
|
||||||
|
|
||||||
## vuln: scan dependencies for known vulnerabilities
|
## vuln: scan dependencies for known vulnerabilities
|
||||||
.PHONY: vuln
|
.PHONY: vuln
|
||||||
vuln:
|
vuln:
|
||||||
@@ -162,10 +176,23 @@ ci: lint check-generated test vuln build
|
|||||||
|
|
||||||
# --------------------------------------------------------------------------- release
|
# --------------------------------------------------------------------------- release
|
||||||
|
|
||||||
## release: cross-compile tarballs and SHA256SUMS into dist/
|
## release: cross-compile tarballs and SHA256SUMS into dist/ (PACKAGES=1: also .deb/.rpm)
|
||||||
.PHONY: release
|
.PHONY: release
|
||||||
release: web
|
release: web
|
||||||
scripts/build-release.sh -o $(DIST_DIR) -p "$(PLATFORMS)"
|
scripts/build-release.sh -o $(DIST_DIR) -p "$(PLATFORMS)"
|
||||||
|
ifeq ($(PACKAGES),1)
|
||||||
|
scripts/build-packages.sh -d $(DIST_DIR) -p "$(PLATFORMS)"
|
||||||
|
endif
|
||||||
|
|
||||||
|
## packages: .deb and .rpm from the tarballs in dist/ (after make release; needs nfpm)
|
||||||
|
.PHONY: packages
|
||||||
|
packages:
|
||||||
|
scripts/build-packages.sh -d $(DIST_DIR) -p "$(PLATFORMS)"
|
||||||
|
|
||||||
|
## sign-release: sign dist/SHA256SUMS with the Ed25519 key in RELEASE_SIGNING_KEY_FILE
|
||||||
|
.PHONY: sign-release
|
||||||
|
sign-release:
|
||||||
|
scripts/sign-release.sh sign $(DIST_DIR)/SHA256SUMS "$(RELEASE_SIGNING_KEY_FILE)"
|
||||||
|
|
||||||
# --------------------------------------------------------------------------- development
|
# --------------------------------------------------------------------------- development
|
||||||
|
|
||||||
|
|||||||
@@ -12,9 +12,11 @@ Selbst gehostete DDI-Lösung (DNS, DHCP, IP-Adressverwaltung) im Stil von VitalQ
|
|||||||
| M1 Server-Kern (Schema, Anmeldung lokal/OIDC/TOTP, Rollen, Audit, Lizenz, REST-API, Netze/Adressen, Oberfläche) | abgeschlossen (`v0.2.0`) |
|
| M1 Server-Kern (Schema, Anmeldung lokal/OIDC/TOTP, Rollen, Audit, Lizenz, REST-API, Netze/Adressen, Oberfläche) | abgeschlossen (`v0.2.0`) |
|
||||||
| M2 Config-Generator (BIND/Kea aus dem Datenmodell, geprüft mit echtem BIND 9.18/9.20 und Kea 2.6/3.2) | abgeschlossen (`v0.3.0`) |
|
| M2 Config-Generator (BIND/Kea aus dem Datenmodell, geprüft mit echtem BIND 9.18/9.20 und Kea 2.6/3.2) | abgeschlossen (`v0.3.0`) |
|
||||||
| M3 Agent verwaltet (Registrierung, mTLS, signierte Revisionen, Anwenden mit Prüfung/Health-Check/Rollback, Leases; End-to-End-Test mit BIND und Kea) | abgeschlossen (`v0.4.0`) |
|
| M3 Agent verwaltet (Registrierung, mTLS, signierte Revisionen, Anwenden mit Prüfung/Health-Check/Rollback, Leases; End-to-End-Test mit BIND und Kea) | abgeschlossen (`v0.4.0`) |
|
||||||
| M4–M6 | geplant, siehe [ARCHITECTURE.md](docs/ARCHITECTURE.md#11-meilensteine) |
|
| M4 Pull und Push (Betriebsmodi, „Jetzt ausrollen“, offene Änderungen, Diff, Rollback, Live-Status) | abgeschlossen (`v0.5.0`) |
|
||||||
|
| M5 Cluster und Zonen (DNS-Primary/Secondary mit TSIG, Kea-HA, Zonen und Records, dynamische Zonen, Lease-Übernahme) | abgeschlossen (`v0.6.0`) |
|
||||||
|
| M6 Auslieferung (Installer für Debian/Ubuntu/EL9, gehärtete systemd-Units, Pakete, Release-Signatur, Messungen, Betriebs- und Sicherheitsdoku) | abgeschlossen (`v0.7.0`) |
|
||||||
|
|
||||||
Der Management-Server verwaltet Netze und Adressen (QIP-artige Tabelle), Benutzer, Lizenz und Audit-Log. Aus den Daten erzeugt er die BIND- und Kea-Konfiguration als unveränderliche Revisionen (**Ausrollen**). Die Agents (`ddi-agent-dns`, `ddi-agent-dhcp`) registrieren sich mit einem Einmal-Token, holen die signierten Revisionen über mTLS, prüfen und aktivieren sie, rollen bei Fehlern zurück und melden Zustand und Leases (**Agents**, **Leases**).
|
Installation: [docs/INSTALL.md](docs/INSTALL.md). Der Management-Server verwaltet Netze und Adressen (QIP-artige Tabelle), Zonen und Records, DNS- und DHCP-Cluster, Benutzer, Lizenz und Audit-Log. Aus den Daten erzeugt er die BIND- und Kea-Konfiguration als unveränderliche Revisionen (**Ausrollen**). Die Agents (`ddi-agent-dns`, `ddi-agent-dhcp`) registrieren sich mit einem Einmal-Token, holen die signierten Revisionen über mTLS, prüfen und aktivieren sie, rollen bei Fehlern zurück und melden Zustand und Leases (**Agents**, **Leases**).
|
||||||
|
|
||||||
## Dokumentation
|
## Dokumentation
|
||||||
|
|
||||||
@@ -23,6 +25,11 @@ Der Management-Server verwaltet Netze und Adressen (QIP-artige Tabelle), Benutze
|
|||||||
- [Architekturentscheidungen (ADRs)](docs/adr/README.md)
|
- [Architekturentscheidungen (ADRs)](docs/adr/README.md)
|
||||||
- [REST-API](docs/API.md)
|
- [REST-API](docs/API.md)
|
||||||
- [Lizenzierung](docs/LICENSING.md)
|
- [Lizenzierung](docs/LICENSING.md)
|
||||||
|
- [Systemvoraussetzungen](docs/SYSTEM-REQUIREMENTS.md) (mit Messwerten)
|
||||||
|
- [Installation](docs/INSTALL.md)
|
||||||
|
- [Betrieb](docs/OPERATIONS.md) (Sicherung, Upgrade, Schlüssel, Fehlersuche)
|
||||||
|
- [Sicherheit](docs/SECURITY.md) (Bedrohungsmodell, Schlüsselverwaltung, Härtung)
|
||||||
|
- [Active Directory](docs/ACTIVE-DIRECTORY.md)
|
||||||
|
|
||||||
## Entwicklung
|
## Entwicklung
|
||||||
|
|
||||||
@@ -71,7 +78,7 @@ make dev-down # stoppen (Daten bleiben erhalten)
|
|||||||
|
|
||||||
### CI
|
### CI
|
||||||
|
|
||||||
Gitea Actions unter [.gitea/workflows/](.gitea/workflows/): Go (Lint, Tests mit Race-Detector, `govulncheck`), Protobuf, Web (ESLint, Typecheck, Tests, `npm audit`, Build), Shell/SPDX, Release-Probebau und ein Compose-Smoke-Test. Tags `v*` erzeugen ein Release mit Artefakten. Anforderungen an den Runner stehen in [ADR 0003](docs/adr/0003-git-host-gitea-actions.md).
|
Gitea Actions unter [.gitea/workflows/](.gitea/workflows/): Go (Lint, Tests mit Race-Detector, `govulncheck`), Protobuf, Web (ESLint, Typecheck, Tests, `npm audit`, Build), Shell/SPDX, Release-Probebau und ein Compose-Smoke-Test. Messungen von Server, BIND und Kea laufen auf Anforderung im Workflow `bench` (`make bench`, [test/bench/](test/bench/)); die Ergebnisse stehen in [SYSTEM-REQUIREMENTS.md](docs/SYSTEM-REQUIREMENTS.md). Tags `v*` erzeugen ein Release mit Artefakten. Anforderungen an den Runner stehen in [ADR 0003](docs/adr/0003-git-host-gitea-actions.md).
|
||||||
|
|
||||||
## Lizenz
|
## Lizenz
|
||||||
|
|
||||||
|
|||||||
+57
-5
@@ -121,12 +121,14 @@ func (a *Agent) Run(ctx context.Context) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// state returns a copy of the state (without the report queue).
|
// state returns a copy of the state (without the report queue and the
|
||||||
|
// handled deployments).
|
||||||
func (a *Agent) state() State {
|
func (a *Agent) state() State {
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
defer a.mu.Unlock()
|
defer a.mu.Unlock()
|
||||||
st := *a.st
|
st := *a.st
|
||||||
st.PendingReports = nil
|
st.PendingReports = nil
|
||||||
|
st.HandledDeployments = nil
|
||||||
return st
|
return st
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,7 +197,8 @@ func (a *Agent) refreshStatus(ctx context.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// enqueue adds a request. A pull is dropped if an equal or newer revision
|
// enqueue adds a request. A pull is dropped if an equal or newer revision
|
||||||
// is already queued; a push replaces queued pulls up to its revision.
|
// is already queued, a push if the same deployment is already queued; a
|
||||||
|
// push replaces queued pulls up to its revision.
|
||||||
func (a *Agent) enqueue(r applyRequest) {
|
func (a *Agent) enqueue(r applyRequest) {
|
||||||
a.qmu.Lock()
|
a.qmu.Lock()
|
||||||
if r.trigger == TriggerPull {
|
if r.trigger == TriggerPull {
|
||||||
@@ -206,6 +209,12 @@ func (a *Agent) enqueue(r applyRequest) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
if r.deploymentID != "" && slices.ContainsFunc(a.queue, func(q applyRequest) bool {
|
||||||
|
return q.trigger == TriggerPush && q.deploymentID == r.deploymentID
|
||||||
|
}) {
|
||||||
|
a.qmu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
a.queue = slices.DeleteFunc(a.queue, func(q applyRequest) bool {
|
a.queue = slices.DeleteFunc(a.queue, func(q applyRequest) bool {
|
||||||
return q.trigger == TriggerPull && q.revision <= r.revision
|
return q.trigger == TriggerPull && q.revision <= r.revision
|
||||||
})
|
})
|
||||||
@@ -247,8 +256,11 @@ func (a *Agent) applyLoop(ctx context.Context) {
|
|||||||
|
|
||||||
// handle decides whether a request leads to an apply.
|
// handle decides whether a request leads to an apply.
|
||||||
func (a *Agent) handle(ctx context.Context, r applyRequest) {
|
func (a *Agent) handle(ctx context.Context, r applyRequest) {
|
||||||
st := a.state()
|
|
||||||
log := a.log.With("revision", r.revision, "trigger", r.trigger, "deployment_id", r.deploymentID)
|
log := a.log.With("revision", r.revision, "trigger", r.trigger, "deployment_id", r.deploymentID)
|
||||||
|
if r.trigger == TriggerPush && a.skipHandled(log, r) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
st := a.state()
|
||||||
switch {
|
switch {
|
||||||
case r.trigger == TriggerPull && r.revision <= st.Applied:
|
case r.trigger == TriggerPull && r.revision <= st.Applied:
|
||||||
log.Debug("revision already applied or older", "applied", st.Applied)
|
log.Debug("revision already applied or older", "applied", st.Applied)
|
||||||
@@ -270,6 +282,38 @@ func (a *Agent) handle(ctx context.Context, r applyRequest) {
|
|||||||
a.apply(ctx, r, st, log)
|
a.apply(ctx, r, st, log)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// skipHandled reports whether a push belongs to a deployment that was
|
||||||
|
// handled before, which the server resends after a reconnect or announces
|
||||||
|
// while polling as long as it has no report. The revision is not applied
|
||||||
|
// again: if the report is still queued, the report loop delivers it;
|
||||||
|
// otherwise the remembered report is queued again so that the server can
|
||||||
|
// close the deployment.
|
||||||
|
func (a *Agent) skipHandled(log *slog.Logger, r applyRequest) bool {
|
||||||
|
a.mu.Lock()
|
||||||
|
prev, ok := a.st.handledDeployment(r.deploymentID)
|
||||||
|
if !ok {
|
||||||
|
a.mu.Unlock()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
queued := slices.ContainsFunc(a.st.PendingReports, func(p DeploymentReport) bool {
|
||||||
|
return p.DeploymentID == r.deploymentID
|
||||||
|
})
|
||||||
|
var err error
|
||||||
|
if !queued {
|
||||||
|
a.st.PendingReports = append(a.st.PendingReports, prev)
|
||||||
|
a.st.UpdatedAt = time.Now().UTC()
|
||||||
|
err = a.store.SaveState(a.st)
|
||||||
|
}
|
||||||
|
a.mu.Unlock()
|
||||||
|
if err != nil {
|
||||||
|
log.Error("cannot save state", "error", err)
|
||||||
|
}
|
||||||
|
log.Info("deployment already handled; not applying it again",
|
||||||
|
"outcome", prev.Outcome, "handled_revision", prev.Revision, "report_queued", queued)
|
||||||
|
notify(a.flushCh)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
// apply runs the pipeline of docs/adr/0021: fetch, verify, store, Validate,
|
// apply runs the pipeline of docs/adr/0021: fetch, verify, store, Validate,
|
||||||
// Activate, Health, rollback. Shutdown aborts it until Activate starts; from
|
// Activate, Health, rollback. Shutdown aborts it until Activate starts; from
|
||||||
// then on it is completed (bounded by the configured timeouts) so that the
|
// then on it is completed (bounded by the configured timeouts) so that the
|
||||||
@@ -488,6 +532,9 @@ func (a *Agent) finish(log *slog.Logger, r DeploymentReport, update func(*State)
|
|||||||
last := r
|
last := r
|
||||||
a.st.LastResult = &last
|
a.st.LastResult = &last
|
||||||
a.st.PendingReports = append(a.st.PendingReports, r)
|
a.st.PendingReports = append(a.st.PendingReports, r)
|
||||||
|
if r.Trigger == TriggerPush {
|
||||||
|
a.st.rememberDeployment(r)
|
||||||
|
}
|
||||||
a.st.UpdatedAt = time.Now().UTC()
|
a.st.UpdatedAt = time.Now().UTC()
|
||||||
err := a.store.SaveState(a.st)
|
err := a.store.SaveState(a.st)
|
||||||
a.mu.Unlock()
|
a.mu.Unlock()
|
||||||
@@ -535,12 +582,17 @@ func (a *Agent) flushReports(ctx context.Context) {
|
|||||||
rctx, cancel := context.WithTimeout(ctx, reportTimeout)
|
rctx, cancel := context.WithTimeout(ctx, reportTimeout)
|
||||||
err := a.source.ReportDeployment(rctx, r)
|
err := a.source.ReportDeployment(rctx, r)
|
||||||
cancel()
|
cancel()
|
||||||
if err != nil {
|
switch {
|
||||||
|
case errors.Is(err, ErrReportRefused):
|
||||||
|
a.log.Warn("deployment report refused; dropping it", "revision", r.Revision,
|
||||||
|
"deployment_id", r.DeploymentID, "error", err)
|
||||||
|
case err != nil:
|
||||||
a.log.Debug("cannot deliver deployment report; will retry", "revision", r.Revision,
|
a.log.Debug("cannot deliver deployment report; will retry", "revision", r.Revision,
|
||||||
"deployment_id", r.DeploymentID, "error", err)
|
"deployment_id", r.DeploymentID, "error", err)
|
||||||
return
|
return
|
||||||
|
default:
|
||||||
|
a.log.Info("deployment reported", "revision", r.Revision, "deployment_id", r.DeploymentID, "outcome", r.Outcome)
|
||||||
}
|
}
|
||||||
a.log.Info("deployment reported", "revision", r.Revision, "deployment_id", r.DeploymentID, "outcome", r.Outcome)
|
|
||||||
a.mu.Lock()
|
a.mu.Lock()
|
||||||
if i := slices.IndexFunc(a.st.PendingReports, func(p DeploymentReport) bool { return reflect.DeepEqual(p, r) }); i >= 0 {
|
if i := slices.IndexFunc(a.st.PendingReports, func(p DeploymentReport) bool { return reflect.DeepEqual(p, r) }); i >= 0 {
|
||||||
a.st.PendingReports = slices.Delete(a.st.PendingReports, i, i+1)
|
a.st.PendingReports = slices.Delete(a.st.PendingReports, i, i+1)
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"slices"
|
"slices"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -385,7 +386,7 @@ func TestPendingReportsBounded(t *testing.T) {
|
|||||||
f := newFixture(t, KindDNS)
|
f := newFixture(t, KindDNS)
|
||||||
f.src.setReportErr(errors.New("down"))
|
f.src.setReportErr(errors.New("down"))
|
||||||
for i := 0; i < maxPendingReports+5; i++ {
|
for i := 0; i < maxPendingReports+5; i++ {
|
||||||
f.push(1, "dep") // fetch fails: rejected report each time
|
f.push(1, "dep-"+strconv.Itoa(i)) // fetch fails: rejected report each time
|
||||||
}
|
}
|
||||||
st, err := f.store.LoadState()
|
st, err := f.store.LoadState()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
+47
-1
@@ -14,8 +14,10 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
|
"os/exec"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -79,6 +81,8 @@ type cli struct {
|
|||||||
factory RoleFactory
|
factory RoleFactory
|
||||||
stdout io.Writer
|
stdout io.Writer
|
||||||
stderr io.Writer
|
stderr io.Writer
|
||||||
|
// systemctl runs systemctl (tests replace it).
|
||||||
|
systemctl func(args ...string) ([]byte, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *cli) flags(name string) (*flag.FlagSet, *string) {
|
func (c *cli) flags(name string) (*flag.FlagSet, *string) {
|
||||||
@@ -116,6 +120,7 @@ func (c *cli) enroll(args []string) int {
|
|||||||
fs.StringVar(&opts.CAHash, "ca-hash", "", "fingerprint of the agent CA (sha256:<hex>)")
|
fs.StringVar(&opts.CAHash, "ca-hash", "", "fingerprint of the agent CA (sha256:<hex>)")
|
||||||
fs.StringVar(&opts.ServerName, "server-name", "", "TLS server name (default: host of --server)")
|
fs.StringVar(&opts.ServerName, "server-name", "", "TLS server name (default: host of --server)")
|
||||||
fs.BoolVar(&opts.Force, "force", false, "replace an existing identity")
|
fs.BoolVar(&opts.Force, "force", false, "replace an existing identity")
|
||||||
|
noStart := fs.Bool("no-start", false, "do not enable and start the systemd service afterwards")
|
||||||
if code := parse(fs, args); code >= 0 {
|
if code := parse(fs, args); code >= 0 {
|
||||||
return code
|
return code
|
||||||
}
|
}
|
||||||
@@ -127,10 +132,11 @@ func (c *cli) enroll(args []string) int {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return c.fail(err)
|
return c.fail(err)
|
||||||
}
|
}
|
||||||
store, unlock, err := openLocked(cfg)
|
store, release, err := openLocked(cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return c.fail(err)
|
return c.fail(err)
|
||||||
}
|
}
|
||||||
|
unlock := sync.OnceFunc(release) // released early before starting the service
|
||||||
defer unlock()
|
defer unlock()
|
||||||
opts.Kind = c.kind
|
opts.Kind = c.kind
|
||||||
opts.Hostname, _ = os.Hostname()
|
opts.Hostname, _ = os.Hostname()
|
||||||
@@ -142,9 +148,46 @@ func (c *cli) enroll(args []string) int {
|
|||||||
}
|
}
|
||||||
_, _ = fmt.Fprintf(c.stdout, "Enrolled as agent %s (%s) with %s.\nIdentity stored in %s.\n",
|
_, _ = fmt.Fprintf(c.stdout, "Enrolled as agent %s (%s) with %s.\nIdentity stored in %s.\n",
|
||||||
id.AgentID, c.kind, id.Server, store.Dir())
|
id.AgentID, c.kind, id.Server, store.Dir())
|
||||||
|
if uid, err := handOverStateDir(store.Dir()); err != nil {
|
||||||
|
_, _ = fmt.Fprintf(c.stderr, "warning: could not hand %s over to its owner: %v\n", store.Dir(), err)
|
||||||
|
} else if uid >= 0 {
|
||||||
|
_, _ = fmt.Fprintf(c.stdout, "Files in %s now belong to the owner of the directory (UID %d).\n", store.Dir(), uid)
|
||||||
|
}
|
||||||
|
// The service takes the state lock itself.
|
||||||
|
unlock()
|
||||||
|
c.startService(*noStart)
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// startService enables and starts the agent's systemd service after an
|
||||||
|
// enrollment as root on a systemd host, so that a manual enrollment ends
|
||||||
|
// with a running agent (the installer leaves the unit waiting for the
|
||||||
|
// identity). Otherwise, or with --no-start, it says what to run.
|
||||||
|
func (c *cli) startService(noStart bool) {
|
||||||
|
unit := c.binary + ".service"
|
||||||
|
hint := func() {
|
||||||
|
_, _ = fmt.Fprintf(c.stdout, "Start the agent with: sudo systemctl enable --now %s\n", unit)
|
||||||
|
}
|
||||||
|
if noStart || os.Geteuid() != 0 || !systemdRunning() {
|
||||||
|
hint()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
run := c.systemctl
|
||||||
|
if run == nil {
|
||||||
|
run = func(args ...string) ([]byte, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
return exec.CommandContext(ctx, "systemctl", args...).CombinedOutput() //nolint:gosec // fixed program; arguments are "enable --now <own unit>"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if out, err := run("enable", "--now", unit); err != nil {
|
||||||
|
_, _ = fmt.Fprintf(c.stderr, "warning: systemctl enable --now %s failed: %v\n%s", unit, err, out)
|
||||||
|
hint()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_, _ = fmt.Fprintf(c.stdout, "Service %s enabled and started.\n", unit)
|
||||||
|
}
|
||||||
|
|
||||||
func openLocked(cfg *Config) (*Store, func(), error) {
|
func openLocked(cfg *Config) (*Store, func(), error) {
|
||||||
store, err := OpenStore(cfg.StateDir)
|
store, err := OpenStore(cfg.StateDir)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -201,6 +244,9 @@ func runAgent(ctx context.Context, kind Kind, factory RoleFactory, cfg *Config,
|
|||||||
return fmt.Errorf("%s role: %w", kind, err)
|
return fmt.Errorf("%s role: %w", kind, err)
|
||||||
}
|
}
|
||||||
log = log.With("agent_id", id.AgentID, "role", string(kind))
|
log = log.With("agent_id", id.AgentID, "role", string(kind))
|
||||||
|
if ls, ok := role.(LogSetter); ok {
|
||||||
|
ls.SetLogger(log)
|
||||||
|
}
|
||||||
hostname, _ := os.Hostname()
|
hostname, _ := os.Hostname()
|
||||||
src := NewServerSource(store, id, hostname, log)
|
src := NewServerSource(store, id, hostname, log)
|
||||||
agent, err := NewAgent(kind, cfg, role, store, id, src, log)
|
agent, err := NewAgent(kind, cfg, role, store, id, src, log)
|
||||||
|
|||||||
+14
-1
@@ -140,7 +140,7 @@ func TestMainEnrollStatusRun(t *testing.T) {
|
|||||||
if code := Main("ddi-agent-dns", KindDNS, nil, []string{"status", "--config", cfgPath}, &out, &errOut); code != 0 {
|
if code := Main("ddi-agent-dns", KindDNS, nil, []string{"status", "--config", cfgPath}, &out, &errOut); code != 0 {
|
||||||
t.Fatalf("status = %d: %s", code, errOut.String())
|
t.Fatalf("status = %d: %s", code, errOut.String())
|
||||||
}
|
}
|
||||||
for _, want := range []string{srv.agentID, "Applied revision:", "revision 1 succeeded", "Stored revisions: 1", stateDir} {
|
for _, want := range []string{srv.agentID, "Applied revision:", "revision 1 succeeded", "Stored revisions: 1", filepath.ToSlash(stateDir)} {
|
||||||
if !strings.Contains(out.String(), want) {
|
if !strings.Contains(out.String(), want) {
|
||||||
t.Errorf("status lacks %q:\n%s", want, out.String())
|
t.Errorf("status lacks %q:\n%s", want, out.String())
|
||||||
}
|
}
|
||||||
@@ -191,3 +191,16 @@ func TestMainConfigErrors(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestStartServiceHint: with --no-start (or without root/systemd) enroll
|
||||||
|
// only says how to start the service and never calls systemctl.
|
||||||
|
func TestStartServiceHint(t *testing.T) {
|
||||||
|
var out bytes.Buffer
|
||||||
|
called := false
|
||||||
|
c := &cli{binary: "ddi-agent-dns", stdout: &out, stderr: &out,
|
||||||
|
systemctl: func(...string) ([]byte, error) { called = true; return nil, nil }}
|
||||||
|
c.startService(true)
|
||||||
|
if called || !strings.Contains(out.String(), "systemctl enable --now ddi-agent-dns.service") {
|
||||||
|
t.Errorf("called=%v output %q", called, out.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -456,6 +456,14 @@ type fakeServer struct {
|
|||||||
polls int
|
polls int
|
||||||
commands chan *agentv1.Command
|
commands chan *agentv1.Command
|
||||||
enrollments int
|
enrollments int
|
||||||
|
// pushDeployment is announced by GetDesiredState until a report with
|
||||||
|
// this deployment ID arrives (open push, ADR 0022).
|
||||||
|
pushDeployment string
|
||||||
|
// reportCode makes ReportDeployment fail with this code if set.
|
||||||
|
reportCode codes.Code
|
||||||
|
// kick ends the current Connect stream (as the hub does on a mode
|
||||||
|
// change).
|
||||||
|
kick chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func newFakeServer(t *testing.T, role Kind) *fakeServer {
|
func newFakeServer(t *testing.T, role Kind) *fakeServer {
|
||||||
@@ -467,7 +475,7 @@ func newFakeServer(t *testing.T, role Kind) *fakeServer {
|
|||||||
enrollValidity: [2]time.Duration{-time.Minute, 14 * 24 * time.Hour},
|
enrollValidity: [2]time.Duration{-time.Minute, 14 * 24 * time.Hour},
|
||||||
mode: agentv1.OperatingMode_OPERATING_MODE_AUTO_PULL,
|
mode: agentv1.OperatingMode_OPERATING_MODE_AUTO_PULL,
|
||||||
pullInterval: 50 * time.Millisecond, heartbeat: 50 * time.Millisecond,
|
pullInterval: 50 * time.Millisecond, heartbeat: 50 * time.Millisecond,
|
||||||
commands: make(chan *agentv1.Command, 10),
|
commands: make(chan *agentv1.Command, 10), kick: make(chan struct{}, 1),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -632,6 +640,8 @@ func (f *fakeServer) Connect(stream agentv1.AgentService_ConnectServer) error {
|
|||||||
return err
|
return err
|
||||||
case <-stream.Context().Done():
|
case <-stream.Context().Done():
|
||||||
return nil
|
return nil
|
||||||
|
case <-f.kick:
|
||||||
|
return nil
|
||||||
case c := <-f.commands:
|
case c := <-f.commands:
|
||||||
if err := stream.Send(&agentv1.ConnectResponse{Message: &agentv1.ConnectResponse_Command{Command: c}}); err != nil {
|
if err := stream.Send(&agentv1.ConnectResponse{Message: &agentv1.ConnectResponse_Command{Command: c}}); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -647,7 +657,10 @@ func (f *fakeServer) GetDesiredState(ctx context.Context, _ *agentv1.GetDesiredS
|
|||||||
f.mu.Lock()
|
f.mu.Lock()
|
||||||
defer f.mu.Unlock()
|
defer f.mu.Unlock()
|
||||||
f.polls++
|
f.polls++
|
||||||
return &agentv1.GetDesiredStateResponse{DesiredRevision: f.desired, Mode: f.mode, PullInterval: durationpb.New(f.pullInterval)}, nil
|
return &agentv1.GetDesiredStateResponse{
|
||||||
|
DesiredRevision: f.desired, Mode: f.mode, PullInterval: durationpb.New(f.pullInterval),
|
||||||
|
DeploymentId: f.pushDeployment,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fakeServer) FetchBundle(ctx context.Context, req *agentv1.FetchBundleRequest) (*agentv1.FetchBundleResponse, error) {
|
func (f *fakeServer) FetchBundle(ctx context.Context, req *agentv1.FetchBundleRequest) (*agentv1.FetchBundleResponse, error) {
|
||||||
@@ -675,7 +688,13 @@ func (f *fakeServer) ReportDeployment(ctx context.Context, req *agentv1.ReportDe
|
|||||||
}
|
}
|
||||||
f.mu.Lock()
|
f.mu.Lock()
|
||||||
defer f.mu.Unlock()
|
defer f.mu.Unlock()
|
||||||
|
if f.reportCode != codes.OK {
|
||||||
|
return nil, status.Error(f.reportCode, "report refused")
|
||||||
|
}
|
||||||
f.reports = append(f.reports, req)
|
f.reports = append(f.reports, req)
|
||||||
|
if req.GetDeploymentId() != "" && req.GetDeploymentId() == f.pushDeployment {
|
||||||
|
f.pushDeployment = ""
|
||||||
|
}
|
||||||
return &agentv1.ReportDeploymentResponse{}, nil
|
return &agentv1.ReportDeploymentResponse{}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,366 @@
|
|||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package core
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
|
||||||
|
agentv1 "git.beugsiud.de/beug.k/DDI/proto/gen/ddi/agent/v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Tests for push deployments of docs/adr/0022-ausrollen-pull-push-m4.md.
|
||||||
|
|
||||||
|
// countCalls counts the role calls that start with prefix.
|
||||||
|
func (r *fakeRole) countCalls(prefix string) int {
|
||||||
|
n := 0
|
||||||
|
for _, c := range r.callLog() {
|
||||||
|
if strings.HasPrefix(c, prefix) {
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// activations counts the activations of a revision.
|
||||||
|
func (r *fakeRole) activations(rev uint64) int {
|
||||||
|
return r.countCalls(fmt.Sprintf("activate %d ", rev))
|
||||||
|
}
|
||||||
|
|
||||||
|
// validations counts the validations of a revision.
|
||||||
|
func (r *fakeRole) validations(rev uint64) int {
|
||||||
|
return r.countCalls(fmt.Sprintf("validate %d", rev))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fixture) pending() []DeploymentReport {
|
||||||
|
f.agent.mu.Lock()
|
||||||
|
defer f.agent.mu.Unlock()
|
||||||
|
return slices.Clone(f.agent.st.PendingReports)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPushAppliedOncePerDeployment(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
f := newFixture(t, KindDNS)
|
||||||
|
f.addBundle(t, 1)
|
||||||
|
f.push(1, "dep-1")
|
||||||
|
if n := f.role.activations(1); n != 1 {
|
||||||
|
t.Fatalf("activations of revision 1 = %d", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The server resends the open push (reconnect, polling) while the
|
||||||
|
// report is still queued: not applied again, the queued report is
|
||||||
|
// delivered once.
|
||||||
|
f.push(1, "dep-1")
|
||||||
|
if n := f.role.activations(1); n != 1 {
|
||||||
|
t.Errorf("resent push applied again (%d activations)", n)
|
||||||
|
}
|
||||||
|
if p := f.pending(); len(p) != 1 || p[0].DeploymentID != "dep-1" || p[0].Outcome != OutcomeSucceeded {
|
||||||
|
t.Fatalf("pending reports = %+v", p)
|
||||||
|
}
|
||||||
|
f.agent.flushReports(ctx)
|
||||||
|
if r := f.src.reported(); len(r) != 1 {
|
||||||
|
t.Fatalf("reports = %+v", r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resent after the report was delivered (the server did not record
|
||||||
|
// it): the remembered report is delivered again.
|
||||||
|
f.push(1, "dep-1")
|
||||||
|
if n := f.role.activations(1); n != 1 {
|
||||||
|
t.Errorf("resent push applied again (%d activations)", n)
|
||||||
|
}
|
||||||
|
f.agent.flushReports(ctx)
|
||||||
|
r := f.src.reported()
|
||||||
|
if len(r) != 2 || r[1].DeploymentID != "dep-1" || r[1].Outcome != OutcomeSucceeded ||
|
||||||
|
!r[1].StartedAt.Equal(r[0].StartedAt) || r[1].Trigger != TriggerPush {
|
||||||
|
t.Fatalf("reports = %+v", r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A new deployment of the same revision is applied again.
|
||||||
|
f.push(1, "dep-2")
|
||||||
|
if n := f.role.activations(1); n != 2 {
|
||||||
|
t.Errorf("activations of revision 1 = %d, want 2", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pushes without a deployment ID are never deduplicated (M3 behavior).
|
||||||
|
f.push(1, "")
|
||||||
|
f.push(1, "")
|
||||||
|
if n := f.role.activations(1); n != 4 {
|
||||||
|
t.Errorf("activations of revision 1 = %d, want 4", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRejectedPushNotRetriedForSameDeployment(t *testing.T) {
|
||||||
|
f := newFixture(t, KindDNS)
|
||||||
|
f.addBundle(t, 1)
|
||||||
|
f.pull(1)
|
||||||
|
f.addBundle(t, 2)
|
||||||
|
f.role.mu.Lock()
|
||||||
|
f.role.validateErr[2] = errors.New("bad zone")
|
||||||
|
f.role.mu.Unlock()
|
||||||
|
f.push(2, "dep-3")
|
||||||
|
if r := f.lastResult(t); r.Outcome != OutcomeRejected || r.DeploymentID != "dep-3" {
|
||||||
|
t.Fatalf("result = %+v", r)
|
||||||
|
}
|
||||||
|
f.role.mu.Lock()
|
||||||
|
delete(f.role.validateErr, 2)
|
||||||
|
f.role.mu.Unlock()
|
||||||
|
|
||||||
|
f.push(2, "dep-3")
|
||||||
|
if n := f.role.validations(2); n != 1 {
|
||||||
|
t.Errorf("validations of revision 2 = %d, want 1", n)
|
||||||
|
}
|
||||||
|
if st := f.agent.state(); st.Applied != 1 {
|
||||||
|
t.Errorf("applied = %d", st.Applied)
|
||||||
|
}
|
||||||
|
// A new push of the same revision retries it.
|
||||||
|
f.push(2, "dep-4")
|
||||||
|
if r := f.lastResult(t); r.Outcome != OutcomeSucceeded || r.DeploymentID != "dep-4" {
|
||||||
|
t.Errorf("result = %+v", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHandledDeploymentsPersistedAndBounded(t *testing.T) {
|
||||||
|
f := newFixture(t, KindDNS)
|
||||||
|
f.addBundle(t, 1)
|
||||||
|
for i := range maxHandledDeployments + 5 {
|
||||||
|
f.push(1, fmt.Sprintf("dep-%d", i))
|
||||||
|
}
|
||||||
|
st, err := f.store.LoadState()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
h := st.HandledDeployments
|
||||||
|
if len(h) != maxHandledDeployments || h[0].DeploymentID != "dep-5" ||
|
||||||
|
h[len(h)-1].DeploymentID != fmt.Sprintf("dep-%d", maxHandledDeployments+4) {
|
||||||
|
t.Fatalf("handled deployments = %+v", h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// After a restart, resent pushes are still recognized; forgotten ones
|
||||||
|
// are applied again.
|
||||||
|
g := newFixtureWithStore(t, KindDNS, f.store, f.signer)
|
||||||
|
g.addBundle(t, 1)
|
||||||
|
g.push(1, fmt.Sprintf("dep-%d", maxHandledDeployments+4))
|
||||||
|
if n := g.role.activations(1); n != 0 {
|
||||||
|
t.Errorf("remembered deployment applied again after restart (%d activations)", n)
|
||||||
|
}
|
||||||
|
g.push(1, "dep-0")
|
||||||
|
if n := g.role.activations(1); n != 1 {
|
||||||
|
t.Errorf("forgotten deployment: %d activations, want 1", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRememberDeployment(t *testing.T) {
|
||||||
|
var st State
|
||||||
|
st.rememberDeployment(DeploymentReport{Revision: 1}) // pulls are not remembered
|
||||||
|
st.rememberDeployment(DeploymentReport{DeploymentID: "a", Revision: 1, Message: strings.Repeat("x", 5000)})
|
||||||
|
st.rememberDeployment(DeploymentReport{DeploymentID: "b", Revision: 2})
|
||||||
|
st.rememberDeployment(DeploymentReport{DeploymentID: "a", Revision: 3})
|
||||||
|
if len(st.HandledDeployments) != 2 || st.HandledDeployments[0].DeploymentID != "b" ||
|
||||||
|
st.HandledDeployments[1].Revision != 3 {
|
||||||
|
t.Fatalf("handled = %+v", st.HandledDeployments)
|
||||||
|
}
|
||||||
|
st.rememberDeployment(DeploymentReport{DeploymentID: "c", Message: strings.Repeat("y", 5000)})
|
||||||
|
if r, ok := st.handledDeployment("c"); !ok || len(r.Message) > handledMessageLen {
|
||||||
|
t.Errorf("handled c = %v, message length %d", ok, len(r.Message))
|
||||||
|
}
|
||||||
|
if _, ok := st.handledDeployment(""); ok {
|
||||||
|
t.Error("empty deployment ID found")
|
||||||
|
}
|
||||||
|
if _, ok := st.handledDeployment("x"); ok {
|
||||||
|
t.Error("unknown deployment ID found")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnqueueDeduplicatesPushes(t *testing.T) {
|
||||||
|
f := newFixture(t, KindDNS)
|
||||||
|
a := f.agent
|
||||||
|
a.enqueue(applyRequest{revision: 3, trigger: TriggerPush, deploymentID: "d"})
|
||||||
|
a.enqueue(applyRequest{revision: 3, trigger: TriggerPush, deploymentID: "d"})
|
||||||
|
a.enqueue(applyRequest{revision: 3, trigger: TriggerPush, deploymentID: "e"})
|
||||||
|
a.enqueue(applyRequest{revision: 3, trigger: TriggerPush})
|
||||||
|
a.enqueue(applyRequest{revision: 3, trigger: TriggerPush})
|
||||||
|
var got []string
|
||||||
|
for {
|
||||||
|
r, ok := a.dequeue()
|
||||||
|
if !ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
got = append(got, r.deploymentID)
|
||||||
|
}
|
||||||
|
if want := []string{"d", "e", "", ""}; !slices.Equal(got, want) {
|
||||||
|
t.Errorf("queued deployments = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRefusedReportIsDropped(t *testing.T) {
|
||||||
|
f := newFixture(t, KindDNS)
|
||||||
|
f.addBundle(t, 1)
|
||||||
|
f.addBundle(t, 2)
|
||||||
|
f.pull(1)
|
||||||
|
f.push(2, "dep-gone")
|
||||||
|
f.src.setReportErr(fmt.Errorf("%w: deployment closed", ErrReportRefused))
|
||||||
|
f.agent.flushReports(context.Background())
|
||||||
|
if p := f.pending(); len(p) != 0 {
|
||||||
|
t.Errorf("refused reports still queued: %+v", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerSourceReportRefused(t *testing.T) {
|
||||||
|
srv := newFakeServer(t, KindDNS)
|
||||||
|
addr := srv.start(t)
|
||||||
|
store, id := enrollWith(t, srv, addr)
|
||||||
|
src := NewServerSource(store, id, "h", testLogger())
|
||||||
|
defer src.closeConn()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
rep := DeploymentReport{DeploymentID: "d", Revision: 1, Trigger: TriggerPush, Outcome: OutcomeSucceeded,
|
||||||
|
ActiveRevision: 1, StartedAt: time.Now(), FinishedAt: time.Now()}
|
||||||
|
if err := src.ReportDeployment(ctx, rep); err != nil {
|
||||||
|
t.Fatalf("report = %v", err)
|
||||||
|
}
|
||||||
|
srv.with(func(f *fakeServer) { f.reportCode = codes.FailedPrecondition })
|
||||||
|
if err := src.ReportDeployment(ctx, rep); !errors.Is(err, ErrReportRefused) {
|
||||||
|
t.Errorf("refused report = %v", err)
|
||||||
|
}
|
||||||
|
srv.with(func(f *fakeServer) { f.reportCode = codes.Unavailable })
|
||||||
|
if err := src.ReportDeployment(ctx, rep); err == nil || errors.Is(err, ErrReportRefused) {
|
||||||
|
t.Errorf("unavailable server = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerSourcePollingPush(t *testing.T) {
|
||||||
|
srv := newFakeServer(t, KindDNS)
|
||||||
|
addr := srv.start(t)
|
||||||
|
store, id := enrollWith(t, srv, addr)
|
||||||
|
srv.with(func(f *fakeServer) {
|
||||||
|
f.desired = 1
|
||||||
|
f.mode = agentv1.OperatingMode_OPERATING_MODE_MANUAL
|
||||||
|
f.streamDisabled = true
|
||||||
|
})
|
||||||
|
role, _ := runAgentAgainst(t, store, id, KindDNS)
|
||||||
|
polls := func() int {
|
||||||
|
n := 0
|
||||||
|
srv.with(func(f *fakeServer) { n = f.polls })
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
waitFor(t, "polls", func() bool { return polls() >= 3 })
|
||||||
|
if n := len(serverReports(srv)); n != 0 {
|
||||||
|
t.Fatalf("manual mode applied the desired revision (%d reports)", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An open push is announced by polling and applied in manual mode.
|
||||||
|
srv.with(func(f *fakeServer) {
|
||||||
|
f.desired = 2
|
||||||
|
f.pushDeployment = "dep-poll"
|
||||||
|
})
|
||||||
|
waitFor(t, "report of the push", func() bool { return len(serverReports(srv)) >= 1 })
|
||||||
|
r := serverReports(srv)[0]
|
||||||
|
if r.GetRevision() != 2 || r.GetDeploymentId() != "dep-poll" ||
|
||||||
|
r.GetTrigger() != agentv1.DeploymentTrigger_DEPLOYMENT_TRIGGER_PUSH ||
|
||||||
|
r.GetOutcome() != agentv1.DeploymentOutcome_DEPLOYMENT_OUTCOME_SUCCEEDED {
|
||||||
|
t.Fatalf("report = %v", r)
|
||||||
|
}
|
||||||
|
after := polls()
|
||||||
|
waitFor(t, "more polls", func() bool { return polls() >= after+3 })
|
||||||
|
if n := role.activations(2); n != 1 {
|
||||||
|
t.Errorf("activations of revision 2 = %d, want 1", n)
|
||||||
|
}
|
||||||
|
// A poll racing with the report may cause the same report to be sent
|
||||||
|
// again, never a second apply.
|
||||||
|
for _, rr := range serverReports(srv) {
|
||||||
|
if rr.GetDeploymentId() != "dep-poll" || !rr.GetStartedAt().AsTime().Equal(r.GetStartedAt().AsTime()) {
|
||||||
|
t.Errorf("unexpected report %v", rr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerSourceModeChangeAndResentPush(t *testing.T) {
|
||||||
|
srv := newFakeServer(t, KindDNS)
|
||||||
|
addr := srv.start(t)
|
||||||
|
store, id := enrollWith(t, srv, addr)
|
||||||
|
srv.with(func(f *fakeServer) {
|
||||||
|
f.desired = 1
|
||||||
|
f.mode = agentv1.OperatingMode_OPERATING_MODE_MANUAL
|
||||||
|
})
|
||||||
|
role, _ := runAgentAgainst(t, store, id, KindDNS)
|
||||||
|
counts := func() (hellos, heartbeats, acks int) {
|
||||||
|
srv.with(func(f *fakeServer) { hellos, heartbeats, acks = len(f.hellos), f.heartbeats, len(f.acks) })
|
||||||
|
return
|
||||||
|
}
|
||||||
|
waitFor(t, "heartbeats in manual mode", func() bool { _, hb, _ := counts(); return hb >= 3 })
|
||||||
|
if n := len(serverReports(srv)); n != 0 {
|
||||||
|
t.Fatalf("manual mode applied the desired revision (%d reports)", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Switching to auto_pull: the server closes the stream and the new
|
||||||
|
// Welcome carries the mode.
|
||||||
|
srv.with(func(f *fakeServer) { f.mode = agentv1.OperatingMode_OPERATING_MODE_AUTO_PULL })
|
||||||
|
srv.kick <- struct{}{}
|
||||||
|
waitFor(t, "report of revision 1", func() bool { return len(serverReports(srv)) == 1 })
|
||||||
|
if r := serverReports(srv)[0]; r.GetRevision() != 1 || r.GetTrigger() != agentv1.DeploymentTrigger_DEPLOYMENT_TRIGGER_PULL {
|
||||||
|
t.Fatalf("report = %v", r)
|
||||||
|
}
|
||||||
|
if h, _, _ := counts(); h < 2 {
|
||||||
|
t.Errorf("hellos = %d, want a reconnect", h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Back to manual with a newer revision: it is not applied.
|
||||||
|
srv.with(func(f *fakeServer) {
|
||||||
|
f.mode = agentv1.OperatingMode_OPERATING_MODE_MANUAL
|
||||||
|
f.desired = 2
|
||||||
|
})
|
||||||
|
srv.kick <- struct{}{}
|
||||||
|
waitFor(t, "third hello", func() bool { h, _, _ := counts(); return h >= 3 })
|
||||||
|
_, hb, _ := counts()
|
||||||
|
waitFor(t, "heartbeats after the mode change", func() bool { _, n, _ := counts(); return n >= hb+3 })
|
||||||
|
if n := role.activations(2); n != 0 || len(serverReports(srv)) != 1 {
|
||||||
|
t.Fatalf("manual mode applied revision 2 (%d activations)", n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The explicit push applies it.
|
||||||
|
push := func(cmdID string) *agentv1.Command {
|
||||||
|
return &agentv1.Command{CommandId: cmdID, Action: &agentv1.Command_ApplyRevision{
|
||||||
|
ApplyRevision: &agentv1.ApplyRevisionCommand{Revision: 2, DeploymentId: "dep-2"},
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
srv.commands <- push("c1")
|
||||||
|
waitFor(t, "report of the push", func() bool { return len(serverReports(srv)) == 2 })
|
||||||
|
first := serverReports(srv)[1]
|
||||||
|
if first.GetRevision() != 2 || first.GetDeploymentId() != "dep-2" ||
|
||||||
|
first.GetTrigger() != agentv1.DeploymentTrigger_DEPLOYMENT_TRIGGER_PUSH ||
|
||||||
|
first.GetOutcome() != agentv1.DeploymentOutcome_DEPLOYMENT_OUTCOME_SUCCEEDED {
|
||||||
|
t.Fatalf("report = %v", first)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The server resends the push (as after a reconnect) after the agent
|
||||||
|
// has dropped the delivered report from its queue: acknowledged, not
|
||||||
|
// applied again, the remembered report is delivered again.
|
||||||
|
waitFor(t, "empty report queue", func() bool {
|
||||||
|
st, err := store.LoadState()
|
||||||
|
return err == nil && len(st.PendingReports) == 0
|
||||||
|
})
|
||||||
|
srv.commands <- push("c2")
|
||||||
|
waitFor(t, "second ack and report", func() bool {
|
||||||
|
_, _, acks := counts()
|
||||||
|
return acks == 2 && len(serverReports(srv)) == 3
|
||||||
|
})
|
||||||
|
if n := role.activations(2); n != 1 {
|
||||||
|
t.Errorf("activations of revision 2 = %d, want 1", n)
|
||||||
|
}
|
||||||
|
again := serverReports(srv)[2]
|
||||||
|
if again.GetDeploymentId() != "dep-2" || !again.GetStartedAt().AsTime().Equal(first.GetStartedAt().AsTime()) {
|
||||||
|
t.Errorf("repeated report = %v", again)
|
||||||
|
}
|
||||||
|
srv.with(func(f *fakeServer) {
|
||||||
|
if !f.acks[1].GetAccepted() || f.acks[1].GetCommandId() != "c2" {
|
||||||
|
t.Errorf("acks = %v", f.acks)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ package core
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"log/slog"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -113,6 +114,13 @@ type LeaseSource interface {
|
|||||||
Leases(ctx context.Context) ([]Lease, error)
|
Leases(ctx context.Context) ([]Lease, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// LogSetter is implemented by roles that log on their own (e.g. the DNS
|
||||||
|
// role's dynamic updates). The core passes its logger, which carries the
|
||||||
|
// agent ID and role, before it uses the role.
|
||||||
|
type LogSetter interface {
|
||||||
|
SetLogger(log *slog.Logger)
|
||||||
|
}
|
||||||
|
|
||||||
// RoleFactory creates a role from its section of the agent configuration
|
// RoleFactory creates a role from its section of the agent configuration
|
||||||
// file. decode unmarshals that section (YAML) into the role's own struct; an
|
// file. decode unmarshals that section (YAML) into the role's own struct; an
|
||||||
// absent section decodes nothing, so roles must start from defaults.
|
// absent section decodes nothing, so roles must start from defaults.
|
||||||
|
|||||||
@@ -14,8 +14,10 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"google.golang.org/grpc"
|
"google.golang.org/grpc"
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
"google.golang.org/grpc/credentials"
|
"google.golang.org/grpc/credentials"
|
||||||
"google.golang.org/grpc/keepalive"
|
"google.golang.org/grpc/keepalive"
|
||||||
|
"google.golang.org/grpc/status"
|
||||||
"google.golang.org/protobuf/types/known/timestamppb"
|
"google.golang.org/protobuf/types/known/timestamppb"
|
||||||
|
|
||||||
"git.beugsiud.de/beug.k/DDI/internal/agentpki"
|
"git.beugsiud.de/beug.k/DDI/internal/agentpki"
|
||||||
@@ -353,8 +355,15 @@ func (s *ServerSource) poll(ctx context.Context, h SourceHandler) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
s.setIntervals(resp.GetPullInterval().AsDuration(), 0)
|
s.setIntervals(resp.GetPullInterval().AsDuration(), 0)
|
||||||
s.log.Debug("desired state polled", "desired_revision", resp.GetDesiredRevision(), "mode", resp.GetMode().String())
|
rev, dep := resp.GetDesiredRevision(), resp.GetDeploymentId()
|
||||||
h.Desired(resp.GetDesiredRevision(), resp.GetMode() != agentv1.OperatingMode_OPERATING_MODE_MANUAL)
|
s.log.Debug("desired state polled", "desired_revision", rev, "mode", resp.GetMode().String(), "deployment_id", dep)
|
||||||
|
if dep != "" && rev != 0 {
|
||||||
|
// An open push: applied in every mode (docs/adr/0022-ausrollen-pull-push-m4.md).
|
||||||
|
s.log.Info("open push received by polling", "revision", rev, "deployment_id", dep)
|
||||||
|
h.Push(rev, dep)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
h.Desired(rev, resp.GetMode() != agentv1.OperatingMode_OPERATING_MODE_MANUAL)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -477,9 +486,23 @@ func (s *ServerSource) ReportDeployment(ctx context.Context, r DeploymentReport)
|
|||||||
Outcome: outcomeToProto(r.Outcome), Message: r.Message, ActiveRevision: r.ActiveRevision,
|
Outcome: outcomeToProto(r.Outcome), Message: r.Message, ActiveRevision: r.ActiveRevision,
|
||||||
StartedAt: timestamppb.New(r.StartedAt), FinishedAt: timestamppb.New(r.FinishedAt),
|
StartedAt: timestamppb.New(r.StartedAt), FinishedAt: timestamppb.New(r.FinishedAt),
|
||||||
})
|
})
|
||||||
|
if refusedReportCodes[status.Code(err)] {
|
||||||
|
return fmt.Errorf("%w: %w", ErrReportRefused, err)
|
||||||
|
}
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// refusedReportCodes are the answers to ReportDeployment that a retry
|
||||||
|
// cannot change: the server considers the report invalid or does not
|
||||||
|
// expect it (any more).
|
||||||
|
var refusedReportCodes = map[codes.Code]bool{
|
||||||
|
codes.InvalidArgument: true,
|
||||||
|
codes.NotFound: true,
|
||||||
|
codes.AlreadyExists: true,
|
||||||
|
codes.FailedPrecondition: true,
|
||||||
|
codes.OutOfRange: true,
|
||||||
|
}
|
||||||
|
|
||||||
// ReportLeases implements Source.
|
// ReportLeases implements Source.
|
||||||
func (s *ServerSource) ReportLeases(ctx context.Context, b LeaseBatch) error {
|
func (s *ServerSource) ReportLeases(ctx context.Context, b LeaseBatch) error {
|
||||||
cl, err := s.client()
|
cl, err := s.client()
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
//go:build !(linux || darwin || freebsd || netbsd || openbsd || dragonfly)
|
||||||
|
|
||||||
|
package core
|
||||||
|
|
||||||
|
// handOverStateDir is a no-op where file ownership works differently; the
|
||||||
|
// agents only run on Linux.
|
||||||
|
func handOverStateDir(string) (int, error) { return -1, nil }
|
||||||
|
|
||||||
|
// systemdRunning is false outside Unix.
|
||||||
|
func systemdRunning() bool { return false }
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
//go:build linux || darwin || freebsd || netbsd || openbsd || dragonfly
|
||||||
|
|
||||||
|
package core
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
// handOverStateDir gives everything below the state directory to the owner
|
||||||
|
// of the directory. The installer creates the directory for the service
|
||||||
|
// user of the agent (e.g. bind); an enrollment run as root would otherwise
|
||||||
|
// leave files the service cannot read. The walk is confined to the
|
||||||
|
// directory (os.Root), so a symlink placed inside cannot redirect the
|
||||||
|
// ownership change. It returns the new owner's UID, or -1 if nothing was
|
||||||
|
// to do (not root, or the directory belongs to root).
|
||||||
|
func handOverStateDir(dir string) (int, error) {
|
||||||
|
if os.Geteuid() != 0 {
|
||||||
|
return -1, nil
|
||||||
|
}
|
||||||
|
info, err := os.Stat(dir)
|
||||||
|
if err != nil {
|
||||||
|
return -1, err
|
||||||
|
}
|
||||||
|
st, ok := info.Sys().(*syscall.Stat_t)
|
||||||
|
if !ok || st.Uid == 0 {
|
||||||
|
return -1, nil
|
||||||
|
}
|
||||||
|
uid, gid := int(st.Uid), int(st.Gid)
|
||||||
|
root, err := os.OpenRoot(dir)
|
||||||
|
if err != nil {
|
||||||
|
return -1, err
|
||||||
|
}
|
||||||
|
defer root.Close() //nolint:errcheck // read-only handle
|
||||||
|
err = fs.WalkDir(root.FS(), ".", func(path string, _ fs.DirEntry, err error) error {
|
||||||
|
if err != nil || path == "." {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return root.Lchown(path, uid, gid)
|
||||||
|
})
|
||||||
|
return uid, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// systemdRunning reports whether systemd manages this host.
|
||||||
|
func systemdRunning() bool {
|
||||||
|
_, err := os.Stat("/run/systemd/system")
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
+12
-2
@@ -4,9 +4,15 @@ package core
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ErrReportRefused marks a deployment report that the source refused for
|
||||||
|
// good (invalid, or for a deployment it no longer expects). Retrying it
|
||||||
|
// would block the reports queued behind it.
|
||||||
|
var ErrReportRefused = errors.New("deployment report refused")
|
||||||
|
|
||||||
// Source is where the agent learns its desired revision, fetches bundles and
|
// Source is where the agent learns its desired revision, fetches bundles and
|
||||||
// reports results (docs/adr/0010-agent-binaries-pro-rolle.md). M3 provides
|
// reports results (docs/adr/0010-agent-binaries-pro-rolle.md). M3 provides
|
||||||
// ServerSource (gRPC); a FileSource for standalone operation (M7) implements
|
// ServerSource (gRPC); a FileSource for standalone operation (M7) implements
|
||||||
@@ -18,7 +24,9 @@ type Source interface {
|
|||||||
// FetchBundle returns the signed bundle of a revision. The caller
|
// FetchBundle returns the signed bundle of a revision. The caller
|
||||||
// verifies it.
|
// verifies it.
|
||||||
FetchBundle(ctx context.Context, revision uint64) (*Bundle, error)
|
FetchBundle(ctx context.Context, revision uint64) (*Bundle, error)
|
||||||
// ReportDeployment delivers an apply outcome.
|
// ReportDeployment delivers an apply outcome. An error wrapping
|
||||||
|
// ErrReportRefused means that the report will never be accepted; the
|
||||||
|
// agent then drops it instead of retrying.
|
||||||
ReportDeployment(ctx context.Context, r DeploymentReport) error
|
ReportDeployment(ctx context.Context, r DeploymentReport) error
|
||||||
// ReportLeases delivers a batch of lease observations.
|
// ReportLeases delivers a batch of lease observations.
|
||||||
ReportLeases(ctx context.Context, b LeaseBatch) error
|
ReportLeases(ctx context.Context, b LeaseBatch) error
|
||||||
@@ -34,7 +42,9 @@ type SourceHandler interface {
|
|||||||
// false in manual mode, where only explicit pushes are applied.
|
// false in manual mode, where only explicit pushes are applied.
|
||||||
Desired(revision uint64, autoApply bool)
|
Desired(revision uint64, autoApply bool)
|
||||||
// Push asks for an explicit apply of a revision. Unlike Desired, it
|
// Push asks for an explicit apply of a revision. Unlike Desired, it
|
||||||
// also retries a revision that failed before.
|
// also retries a revision that failed before. A push whose deployment
|
||||||
|
// ID was handled before is not applied again; its report is delivered
|
||||||
|
// (again) instead.
|
||||||
Push(revision uint64, deploymentID string)
|
Push(revision uint64, deploymentID string)
|
||||||
// Status returns what the agent reports in Hello and heartbeats.
|
// Status returns what the agent reports in Hello and heartbeats.
|
||||||
Status(ctx context.Context) AgentStatus
|
Status(ctx context.Context) AgentStatus
|
||||||
|
|||||||
+45
-1
@@ -38,6 +38,13 @@ const KeepRevisions = 10
|
|||||||
// maxPendingReports bounds the queue of unsent deployment reports.
|
// maxPendingReports bounds the queue of unsent deployment reports.
|
||||||
const maxPendingReports = 100
|
const maxPendingReports = 100
|
||||||
|
|
||||||
|
// maxHandledDeployments bounds the remembered push deployments, and
|
||||||
|
// handledMessageLen the message kept with each of them.
|
||||||
|
const (
|
||||||
|
maxHandledDeployments = 20
|
||||||
|
handledMessageLen = 1024
|
||||||
|
)
|
||||||
|
|
||||||
// Store manages the agent's state directory. Writes are atomic: files are
|
// Store manages the agent's state directory. Writes are atomic: files are
|
||||||
// written to a temporary file, synced and renamed; directories are built
|
// written to a temporary file, synced and renamed; directories are built
|
||||||
// under a temporary name and renamed into place.
|
// under a temporary name and renamed into place.
|
||||||
@@ -114,7 +121,41 @@ type State struct {
|
|||||||
LeaseSequence uint64 `json:"lease_sequence,omitempty"`
|
LeaseSequence uint64 `json:"lease_sequence,omitempty"`
|
||||||
// PendingReports are deployment reports not yet accepted by the server.
|
// PendingReports are deployment reports not yet accepted by the server.
|
||||||
PendingReports []DeploymentReport `json:"pending_reports,omitempty"`
|
PendingReports []DeploymentReport `json:"pending_reports,omitempty"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
// HandledDeployments are the reports of the most recent push
|
||||||
|
// deployments (oldest first, at most maxHandledDeployments). A push
|
||||||
|
// with one of these deployment IDs is not applied again: the server
|
||||||
|
// resends open pushes after a reconnect and announces them while
|
||||||
|
// polling until it has the report (docs/adr/0022-ausrollen-pull-push-m4.md).
|
||||||
|
HandledDeployments []DeploymentReport `json:"handled_deployments,omitempty"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// handledDeployment returns the remembered report of a push deployment.
|
||||||
|
func (st *State) handledDeployment(id string) (DeploymentReport, bool) {
|
||||||
|
if id == "" {
|
||||||
|
return DeploymentReport{}, false
|
||||||
|
}
|
||||||
|
i := slices.IndexFunc(st.HandledDeployments, func(d DeploymentReport) bool { return d.DeploymentID == id })
|
||||||
|
if i < 0 {
|
||||||
|
return DeploymentReport{}, false
|
||||||
|
}
|
||||||
|
return st.HandledDeployments[i], true
|
||||||
|
}
|
||||||
|
|
||||||
|
// rememberDeployment records the report of a finished push deployment.
|
||||||
|
func (st *State) rememberDeployment(r DeploymentReport) {
|
||||||
|
if r.DeploymentID == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.Message = truncate(r.Message, handledMessageLen)
|
||||||
|
handled := slices.DeleteFunc(slices.Clone(st.HandledDeployments), func(d DeploymentReport) bool {
|
||||||
|
return d.DeploymentID == r.DeploymentID
|
||||||
|
})
|
||||||
|
handled = append(handled, r)
|
||||||
|
if n := len(handled); n > maxHandledDeployments {
|
||||||
|
handled = slices.Clone(handled[n-maxHandledDeployments:])
|
||||||
|
}
|
||||||
|
st.HandledDeployments = handled
|
||||||
}
|
}
|
||||||
|
|
||||||
// LoadState reads state.json; a missing file yields the zero state.
|
// LoadState reads state.json; a missing file yields the zero state.
|
||||||
@@ -138,6 +179,9 @@ func (s *Store) SaveState(st *State) error {
|
|||||||
if n := len(st.PendingReports); n > maxPendingReports {
|
if n := len(st.PendingReports); n > maxPendingReports {
|
||||||
st.PendingReports = slices.Clone(st.PendingReports[n-maxPendingReports:])
|
st.PendingReports = slices.Clone(st.PendingReports[n-maxPendingReports:])
|
||||||
}
|
}
|
||||||
|
if n := len(st.HandledDeployments); n > maxHandledDeployments {
|
||||||
|
st.HandledDeployments = slices.Clone(st.HandledDeployments[n-maxHandledDeployments:])
|
||||||
|
}
|
||||||
data, err := json.MarshalIndent(st, "", " ")
|
data, err := json.MarshalIndent(st, "", " ")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("encode state: %w", err)
|
return fmt.Errorf("encode state: %w", err)
|
||||||
|
|||||||
@@ -0,0 +1,249 @@
|
|||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package dhcp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.beugsiud.de/beug.k/DDI/agent/core"
|
||||||
|
"git.beugsiud.de/beug.k/DDI/agent/role/internal/fsutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
// UserFileName is the HA user file of a DHCP revision; it is also the only
|
||||||
|
// file name the configuration may reference as user file.
|
||||||
|
const UserFileName = "ddi-suite-ha-user"
|
||||||
|
|
||||||
|
// credentialNames are the HA credential files (ADR 0023). Kea 3.x refuses
|
||||||
|
// clear-text users and passwords in HTTP authentication, so both come from
|
||||||
|
// files, which the revision carries as secret artifacts.
|
||||||
|
var credentialNames = []string{PasswordFileName, UserFileName}
|
||||||
|
|
||||||
|
// revFile is a file inside a revision.
|
||||||
|
type revFile struct {
|
||||||
|
src string
|
||||||
|
mode fs.FileMode
|
||||||
|
}
|
||||||
|
|
||||||
|
// revFiles are the files of a revision.
|
||||||
|
type revFiles struct {
|
||||||
|
conf string // path inside the revision
|
||||||
|
confMode fs.FileMode
|
||||||
|
// creds are the HA credential files of the revision by file name.
|
||||||
|
creds map[string]revFile
|
||||||
|
}
|
||||||
|
|
||||||
|
// source returns the files of rev.
|
||||||
|
func source(rev core.Revision) (revFiles, error) {
|
||||||
|
out := revFiles{creds: map[string]revFile{}}
|
||||||
|
bad := false
|
||||||
|
for _, f := range rev.Files {
|
||||||
|
_, dup := out.creds[f.Path]
|
||||||
|
switch {
|
||||||
|
case f.CreateOnly:
|
||||||
|
bad = true
|
||||||
|
case f.Path == FileName && out.conf == "":
|
||||||
|
out.conf, out.confMode = filepath.Join(rev.Dir, FileName), fs.FileMode(f.Mode)
|
||||||
|
case slices.Contains(credentialNames, f.Path) && !dup:
|
||||||
|
out.creds[f.Path] = revFile{src: filepath.Join(rev.Dir, f.Path), mode: fs.FileMode(f.Mode)}
|
||||||
|
default:
|
||||||
|
bad = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if bad || out.conf == "" {
|
||||||
|
paths := make([]string, len(rev.Files))
|
||||||
|
for i, f := range rev.Files {
|
||||||
|
paths[i] = f.Path
|
||||||
|
}
|
||||||
|
return revFiles{}, fmt.Errorf("DHCP revision must contain exactly %s (and %s for HA), got %v",
|
||||||
|
FileName, strings.Join(credentialNames, ", "), paths)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// plan reads the configuration of rev and finds the live paths of its HA
|
||||||
|
// credential files by file name (empty without HA). The revision has a
|
||||||
|
// credential file exactly if the configuration references one.
|
||||||
|
func (r *Role) plan(rev core.Revision) (files revFiles, data []byte, live map[string]string, err error) {
|
||||||
|
if files, err = source(rev); err != nil {
|
||||||
|
return files, nil, nil, err
|
||||||
|
}
|
||||||
|
if data, err = fsutil.ReadFile(files.conf); err != nil {
|
||||||
|
return files, nil, nil, err
|
||||||
|
}
|
||||||
|
if live, err = haCredentialPaths(data); err != nil {
|
||||||
|
return files, nil, nil, err
|
||||||
|
}
|
||||||
|
for _, name := range credentialNames {
|
||||||
|
_, inRev := files.creds[name]
|
||||||
|
switch p, ok := live[name]; {
|
||||||
|
case inRev && !ok:
|
||||||
|
return files, nil, nil, fmt.Errorf("the revision has %s, but %s does not reference it", name, FileName)
|
||||||
|
case !inRev && ok:
|
||||||
|
return files, nil, nil, fmt.Errorf("%s references the HA credential file %q, but the revision has none", FileName, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return files, data, live, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate checks that the configuration uses this agent's control socket
|
||||||
|
// and valid HA credential file paths, and runs "kea-dhcp4 -t" on it. With
|
||||||
|
// HA, Kea reads the credential files while checking, so the check runs on a
|
||||||
|
// temporary copy of the configuration that refers to the revision's files
|
||||||
|
// instead of the live ones.
|
||||||
|
func (r *Role) Validate(ctx context.Context, rev core.Revision) error {
|
||||||
|
files, data, live, err := r.plan(rev)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := r.checkControlSocket(data); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
check := files.conf
|
||||||
|
if len(live) > 0 {
|
||||||
|
replace := map[string]string{}
|
||||||
|
for name, p := range live {
|
||||||
|
if err := fsutil.RequireDir(filepath.Dir(p)); err != nil {
|
||||||
|
return fmt.Errorf("HA credential file directory: %w", err)
|
||||||
|
}
|
||||||
|
replace[p] = files.creds[name].src
|
||||||
|
}
|
||||||
|
tmp, err := os.MkdirTemp("", "ddi-dhcp-validate-")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() { _ = os.RemoveAll(tmp) }()
|
||||||
|
test, err := replaceStrings(data, replace)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
check = filepath.Join(tmp, FileName)
|
||||||
|
if err := os.WriteFile(check, test, 0o600); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := r.run.Run(ctx, r.cfg.KeaDHCP4, "-t", check); err != nil {
|
||||||
|
return fmt.Errorf("configuration check failed: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// credentialRefs is the part of the configuration that names HA credential
|
||||||
|
// files: the clients of control socket authentication (Kea ARM 3.x,
|
||||||
|
// "HTTP/HTTPS Control Socket": user-file, password-file) and the HA peers
|
||||||
|
// (basic-auth-user-file, basic-auth-password-file).
|
||||||
|
type credentialRefs struct {
|
||||||
|
Dhcp4 *struct {
|
||||||
|
ControlSocket *authSocket `json:"control-socket"`
|
||||||
|
ControlSockets []authSocket `json:"control-sockets"`
|
||||||
|
HooksLibraries []struct {
|
||||||
|
Parameters *struct {
|
||||||
|
HighAvailability []struct {
|
||||||
|
Peers []struct {
|
||||||
|
UserFile string `json:"basic-auth-user-file"`
|
||||||
|
PasswordFile string `json:"basic-auth-password-file"`
|
||||||
|
} `json:"peers"`
|
||||||
|
} `json:"high-availability"`
|
||||||
|
} `json:"parameters"`
|
||||||
|
} `json:"hooks-libraries"`
|
||||||
|
} `json:"Dhcp4"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type authSocket struct {
|
||||||
|
Authentication *struct {
|
||||||
|
Directory string `json:"directory"`
|
||||||
|
Clients []struct {
|
||||||
|
UserFile string `json:"user-file"`
|
||||||
|
PasswordFile string `json:"password-file"`
|
||||||
|
} `json:"clients"`
|
||||||
|
} `json:"authentication"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// haCredentialPaths returns the HA credential files the configuration
|
||||||
|
// references, by file name. All references to one kind must name the same
|
||||||
|
// clean absolute path whose file name is PasswordFileName or UserFileName,
|
||||||
|
// and both files must share a directory: the agent writes the files there,
|
||||||
|
// so it must not be able to replace anything else.
|
||||||
|
func haCredentialPaths(data []byte) (map[string]string, error) {
|
||||||
|
var doc credentialRefs
|
||||||
|
if err := json.Unmarshal(data, &doc); err != nil {
|
||||||
|
return nil, fmt.Errorf("%s is not valid JSON: %w", FileName, err)
|
||||||
|
}
|
||||||
|
refs := map[string][]string{}
|
||||||
|
add := func(name, p string) {
|
||||||
|
if p != "" {
|
||||||
|
refs[name] = append(refs[name], p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if doc.Dhcp4 != nil {
|
||||||
|
socks := doc.Dhcp4.ControlSockets
|
||||||
|
if doc.Dhcp4.ControlSocket != nil {
|
||||||
|
socks = append(socks, *doc.Dhcp4.ControlSocket)
|
||||||
|
}
|
||||||
|
for _, s := range socks {
|
||||||
|
if s.Authentication == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, c := range s.Authentication.Clients {
|
||||||
|
if c.UserFile != "" {
|
||||||
|
add(UserFileName, keaCredentialPath(s.Authentication.Directory, c.UserFile))
|
||||||
|
}
|
||||||
|
if c.PasswordFile != "" {
|
||||||
|
add(PasswordFileName, keaCredentialPath(s.Authentication.Directory, c.PasswordFile))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, h := range doc.Dhcp4.HooksLibraries {
|
||||||
|
if h.Parameters == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, rel := range h.Parameters.HighAvailability {
|
||||||
|
for _, p := range rel.Peers {
|
||||||
|
add(UserFileName, p.UserFile)
|
||||||
|
add(PasswordFileName, p.PasswordFile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out := map[string]string{}
|
||||||
|
for _, name := range credentialNames {
|
||||||
|
rs := refs[name]
|
||||||
|
if len(rs) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
p := rs[0]
|
||||||
|
for _, o := range rs[1:] {
|
||||||
|
if o != p {
|
||||||
|
return nil, fmt.Errorf("%s references different HA credential files (%q and %q)", FileName, p, o)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := checkAbsPath(p); err != nil {
|
||||||
|
return nil, fmt.Errorf("HA credential file: %w", err)
|
||||||
|
}
|
||||||
|
if path.Base(p) != name {
|
||||||
|
return nil, fmt.Errorf("HA credential file %q: the file name must be %s", p, name)
|
||||||
|
}
|
||||||
|
out[name] = p
|
||||||
|
}
|
||||||
|
if pw, user := out[PasswordFileName], out[UserFileName]; pw != "" && user != "" && path.Dir(pw) != path.Dir(user) {
|
||||||
|
return nil, fmt.Errorf("HA credential files %q and %q must be in the same directory", pw, user)
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// keaCredentialPath joins the directory and file name of a credential file
|
||||||
|
// the way Kea does (BasicHttpAuthConfig::getFileContent): a '/' between
|
||||||
|
// them, a leading '/' of the file name dropped.
|
||||||
|
func keaCredentialPath(dir, file string) string {
|
||||||
|
if dir == "" || !strings.HasSuffix(dir, "/") {
|
||||||
|
dir += "/"
|
||||||
|
}
|
||||||
|
return dir + strings.TrimPrefix(file, "/")
|
||||||
|
}
|
||||||
+119
-52
@@ -1,10 +1,15 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
// Package dhcp is the agent role for the Kea DHCPv4 server (ADR 0005,
|
// Package dhcp is the agent role for the Kea DHCPv4 server (ADR 0005,
|
||||||
// ADR 0021). A DHCP revision consists of exactly one file, kea-dhcp4.conf.
|
// ADR 0021). A DHCP revision consists of kea-dhcp4.conf and, for a member
|
||||||
// The role installs it as Config.ConfigFile and makes kea-dhcp4 re-read it
|
// of a Kea HA pair (ADR 0023), the secret credential files
|
||||||
// with config-reload over its UNIX control socket. The Kea Control Agent is
|
// ddi-suite-ha-password and ddi-suite-ha-user (Kea 3.x accepts basic-auth
|
||||||
// not used (it is deprecated since Kea 2.7.2/3.0).
|
// credentials only from files). The role installs the configuration as
|
||||||
|
// Config.ConfigFile, writes the credential files to the paths the
|
||||||
|
// configuration references (file names as above, one existing directory)
|
||||||
|
// and makes kea-dhcp4 re-read the configuration with config-reload over its
|
||||||
|
// UNIX control socket. The Kea Control Agent is not used (it is deprecated
|
||||||
|
// since Kea 2.7.2/3.0).
|
||||||
package dhcp
|
package dhcp
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -13,9 +18,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/fs"
|
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -24,9 +27,13 @@ import (
|
|||||||
"git.beugsiud.de/beug.k/DDI/agent/role/internal/fsutil"
|
"git.beugsiud.de/beug.k/DDI/agent/role/internal/fsutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
// FileName is the only file of a DHCP revision.
|
// FileName is the configuration file of a DHCP revision.
|
||||||
const FileName = "kea-dhcp4.conf"
|
const FileName = "kea-dhcp4.conf"
|
||||||
|
|
||||||
|
// PasswordFileName is the HA password file of a DHCP revision; it is also
|
||||||
|
// the only file name the configuration may reference as password file.
|
||||||
|
const PasswordFileName = "ddi-suite-ha-password" //nolint:gosec // a file name, not a credential
|
||||||
|
|
||||||
// Role manages kea-dhcp4.
|
// Role manages kea-dhcp4.
|
||||||
type Role struct {
|
type Role struct {
|
||||||
cfg Config
|
cfg Config
|
||||||
@@ -83,36 +90,35 @@ func (r *Role) ServiceVersion(ctx context.Context) (string, error) {
|
|||||||
return "Kea " + v, nil
|
return "Kea " + v, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// source returns the path of the configuration inside rev.
|
// replaceStrings returns the JSON document data with every string value
|
||||||
func source(rev core.Revision) (string, fs.FileMode, error) {
|
// that is a key of replace replaced by its value (numbers are kept as
|
||||||
if len(rev.Files) != 1 || rev.Files[0].Path != FileName || rev.Files[0].CreateOnly {
|
// written).
|
||||||
paths := make([]string, len(rev.Files))
|
func replaceStrings(data []byte, replace map[string]string) ([]byte, error) {
|
||||||
for i, f := range rev.Files {
|
dec := json.NewDecoder(bytes.NewReader(data))
|
||||||
paths[i] = f.Path
|
dec.UseNumber()
|
||||||
|
var doc any
|
||||||
|
if err := dec.Decode(&doc); err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: %w", FileName, err)
|
||||||
|
}
|
||||||
|
var walk func(v any) any
|
||||||
|
walk = func(v any) any {
|
||||||
|
switch x := v.(type) {
|
||||||
|
case string:
|
||||||
|
if to, ok := replace[x]; ok {
|
||||||
|
return to
|
||||||
|
}
|
||||||
|
case map[string]any:
|
||||||
|
for k, e := range x {
|
||||||
|
x[k] = walk(e)
|
||||||
|
}
|
||||||
|
case []any:
|
||||||
|
for i, e := range x {
|
||||||
|
x[i] = walk(e)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return "", 0, fmt.Errorf("DHCP revision must contain exactly %s, got %v", FileName, paths)
|
return v
|
||||||
}
|
}
|
||||||
return filepath.Join(rev.Dir, FileName), fs.FileMode(rev.Files[0].Mode), nil
|
return json.Marshal(walk(doc))
|
||||||
}
|
|
||||||
|
|
||||||
// Validate checks that the configuration uses this agent's control socket
|
|
||||||
// and runs "kea-dhcp4 -t" on it.
|
|
||||||
func (r *Role) Validate(ctx context.Context, rev core.Revision) error {
|
|
||||||
src, _, err := source(rev)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
data, err := fsutil.ReadFile(src)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := r.checkControlSocket(data); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if _, err := r.run.Run(ctx, r.cfg.KeaDHCP4, "-t", src); err != nil {
|
|
||||||
return fmt.Errorf("configuration check failed: %w", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type socketConfig struct {
|
type socketConfig struct {
|
||||||
@@ -158,24 +164,70 @@ func (r *Role) checkControlSocket(data []byte) error {
|
|||||||
FileName, strings.Join(names, ", "), r.cfg.ControlSocket)
|
FileName, strings.Join(names, ", "), r.cfg.ControlSocket)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Activate installs the configuration and sends config-reload. If the
|
// Activate installs the HA credential files and the configuration and
|
||||||
// reload fails, the previous file is restored and reloaded again.
|
// sends config-reload. If the reload fails, the previous files are restored
|
||||||
// prev is not needed: the revision always replaces the single file.
|
// and reloaded again. Credential files of prev that rev no longer uses are
|
||||||
func (r *Role) Activate(ctx context.Context, rev core.Revision, _ *core.Revision) error {
|
// removed.
|
||||||
src, mode, err := source(rev)
|
func (r *Role) Activate(ctx context.Context, rev core.Revision, prev *core.Revision) error {
|
||||||
|
files, data, live, err := r.plan(rev)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
data, err := fsutil.ReadFile(src)
|
used := map[string]bool{}
|
||||||
if err != nil {
|
for _, p := range live {
|
||||||
return err
|
used[p] = true
|
||||||
|
}
|
||||||
|
var stale []string
|
||||||
|
if prev != nil {
|
||||||
|
if _, _, old, err := r.plan(*prev); err == nil {
|
||||||
|
for _, name := range credentialNames {
|
||||||
|
if p := old[name]; p != "" && !used[p] {
|
||||||
|
stale = append(stale, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
var backup fsutil.Backup
|
var backup fsutil.Backup
|
||||||
if err := backup.Save(r.cfg.ConfigFile); err != nil {
|
toSave := append([]string(nil), stale...)
|
||||||
return err
|
for _, name := range credentialNames {
|
||||||
|
if p := live[name]; p != "" {
|
||||||
|
toSave = append(toSave, p)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if err := fsutil.WriteFile(r.cfg.ConfigFile, data, mode, fsutil.OwnerFor(r.cfg.ConfigFile)); err != nil {
|
for _, p := range append(toSave, r.cfg.ConfigFile) {
|
||||||
return err
|
if err := backup.Save(p); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
restore := func(cause error) error {
|
||||||
|
errs := []error{cause}
|
||||||
|
if err := backup.Restore(); err != nil {
|
||||||
|
errs = append(errs, fmt.Errorf("restoring the previous configuration failed: %w", err))
|
||||||
|
}
|
||||||
|
return errors.Join(errs...)
|
||||||
|
}
|
||||||
|
// The credentials first: Kea reads them while loading the configuration.
|
||||||
|
for _, name := range credentialNames {
|
||||||
|
p := live[name]
|
||||||
|
if p == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
f := files.creds[name]
|
||||||
|
content, err := fsutil.ReadFile(f.src)
|
||||||
|
if err != nil {
|
||||||
|
return restore(err)
|
||||||
|
}
|
||||||
|
if err := fsutil.WriteFile(p, content, f.mode, fsutil.OwnerFor(p)); err != nil {
|
||||||
|
return restore(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := fsutil.WriteFile(r.cfg.ConfigFile, data, files.confMode, fsutil.OwnerFor(r.cfg.ConfigFile)); err != nil {
|
||||||
|
return restore(err)
|
||||||
|
}
|
||||||
|
for _, p := range stale {
|
||||||
|
if err := fsutil.Remove(p); err != nil {
|
||||||
|
return restore(fmt.Errorf("remove %s: %w", p, err))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
reloadErr := r.reload(ctx)
|
reloadErr := r.reload(ctx)
|
||||||
if reloadErr == nil {
|
if reloadErr == nil {
|
||||||
@@ -280,14 +332,26 @@ func describeStatus(a statusArgs) string {
|
|||||||
|
|
||||||
func (r *Role) checkInstalled(rev core.Revision) core.HealthCheck {
|
func (r *Role) checkInstalled(rev core.Revision) core.HealthCheck {
|
||||||
c := core.HealthCheck{Name: "configuration file", State: core.HealthOK}
|
c := core.HealthCheck{Name: "configuration file", State: core.HealthOK}
|
||||||
src, _, err := source(rev)
|
files, want, live, err := r.plan(rev)
|
||||||
var want, have []byte
|
var have []byte
|
||||||
if err == nil {
|
|
||||||
want, err = fsutil.ReadFile(src)
|
|
||||||
}
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
have, err = fsutil.ReadFile(r.cfg.ConfigFile)
|
have, err = fsutil.ReadFile(r.cfg.ConfigFile)
|
||||||
}
|
}
|
||||||
|
// The first credential file that differs; messages never show content.
|
||||||
|
var differs string
|
||||||
|
for _, name := range credentialNames {
|
||||||
|
p := live[name]
|
||||||
|
if err != nil || p == "" || differs != "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var w, h []byte
|
||||||
|
if w, err = fsutil.ReadFile(files.creds[name].src); err == nil {
|
||||||
|
h, err = fsutil.ReadFile(p)
|
||||||
|
}
|
||||||
|
if err == nil && !bytes.Equal(w, h) {
|
||||||
|
differs = p
|
||||||
|
}
|
||||||
|
}
|
||||||
switch {
|
switch {
|
||||||
case err != nil:
|
case err != nil:
|
||||||
c.State = core.HealthDegraded
|
c.State = core.HealthDegraded
|
||||||
@@ -295,6 +359,9 @@ func (r *Role) checkInstalled(rev core.Revision) core.HealthCheck {
|
|||||||
case !bytes.Equal(want, have):
|
case !bytes.Equal(want, have):
|
||||||
c.State = core.HealthDegraded
|
c.State = core.HealthDegraded
|
||||||
c.Message = fmt.Sprintf("%s differs from revision %d", r.cfg.ConfigFile, rev.Number)
|
c.Message = fmt.Sprintf("%s differs from revision %d", r.cfg.ConfigFile, rev.Number)
|
||||||
|
case differs != "":
|
||||||
|
c.State = core.HealthDegraded
|
||||||
|
c.Message = fmt.Sprintf("HA credential file %s differs from revision %d", differs, rev.Number)
|
||||||
default:
|
default:
|
||||||
c.Message = fmt.Sprintf("%s is revision %d", r.cfg.ConfigFile, rev.Number)
|
c.Message = fmt.Sprintf("%s is revision %d", r.cfg.ConfigFile, rev.Number)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,274 @@
|
|||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package dhcp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.beugsiud.de/beug.k/DDI/agent/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
// haKeaConfig is an HA member's configuration as the server's keagen writes
|
||||||
|
// it, with the user file at user and the password file at pw.
|
||||||
|
func haKeaConfig(socket, user, pw string) string {
|
||||||
|
return fmt.Sprintf(`{
|
||||||
|
"Dhcp4": {
|
||||||
|
"control-sockets": [
|
||||||
|
{"socket-type": "unix", "socket-name": %[1]q},
|
||||||
|
{"socket-type": "http", "socket-address": "192.0.2.2", "socket-port": 8001,
|
||||||
|
"authentication": {"type": "basic", "realm": "ddi-suite-ha",
|
||||||
|
"clients": [{"user-file": %[2]q, "password-file": %[3]q}]}}
|
||||||
|
],
|
||||||
|
"hooks-libraries": [
|
||||||
|
{"library": "libdhcp_lease_cmds.so"},
|
||||||
|
{"library": "libdhcp_ha.so", "parameters": {"high-availability": [{
|
||||||
|
"this-server-name": "primary", "mode": "hot-standby",
|
||||||
|
"multi-threading": {"enable-multi-threading": true, "http-dedicated-listener": false},
|
||||||
|
"peers": [
|
||||||
|
{"name": "primary", "url": "http://192.0.2.2:8001/", "role": "primary", "auto-failover": true,
|
||||||
|
"basic-auth-user-file": %[2]q, "basic-auth-password-file": %[3]q},
|
||||||
|
{"name": "secondary", "url": "http://192.0.2.3:8001/", "role": "standby", "auto-failover": true,
|
||||||
|
"basic-auth-user-file": %[2]q, "basic-auth-password-file": %[3]q}
|
||||||
|
]}]}}
|
||||||
|
],
|
||||||
|
"valid-lifetime": 4294967295,
|
||||||
|
"subnet4": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`, socket, user, pw)
|
||||||
|
}
|
||||||
|
|
||||||
|
// haFiles is an HA revision's files.
|
||||||
|
func haFiles(conf, user, pw string) map[string]string {
|
||||||
|
return map[string]string{FileName: conf, UserFileName: user, PasswordFileName: pw}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readFile(t *testing.T, p string) string {
|
||||||
|
t.Helper()
|
||||||
|
b, err := os.ReadFile(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func exists(p string) bool {
|
||||||
|
_, err := os.Lstat(p)
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateHA(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
dir := filepath.Dir(e.conf)
|
||||||
|
pw := filepath.Join(dir, PasswordFileName)
|
||||||
|
user := filepath.Join(dir, UserFileName)
|
||||||
|
var checked, checkedPath string
|
||||||
|
e.run.fn = func(name string, args []string) ([]byte, error) {
|
||||||
|
checkedPath = args[len(args)-1]
|
||||||
|
checked = readFile(t, checkedPath)
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
good := revision(t, 1, haFiles(haKeaConfig(e.kea.path, user, pw), "ha\n", "secret\n"))
|
||||||
|
if err := e.role.Validate(ctx, good); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// kea-dhcp4 -t reads the revision's credential files, not the live
|
||||||
|
// ones, and sees the configuration otherwise unchanged.
|
||||||
|
var doc map[string]any
|
||||||
|
if err := json.Unmarshal([]byte(checked), &doc); err != nil {
|
||||||
|
t.Fatalf("checked configuration: %v\n%s", err, checked)
|
||||||
|
}
|
||||||
|
for _, f := range []struct{ live, rev string }{
|
||||||
|
{pw, filepath.Join(good.Dir, PasswordFileName)},
|
||||||
|
{user, filepath.Join(good.Dir, UserFileName)},
|
||||||
|
} {
|
||||||
|
if strings.Contains(checked, `"`+f.live+`"`) || strings.Count(checked, `"`+f.rev+`"`) != 3 {
|
||||||
|
t.Errorf("checked configuration does not use %s:\n%s", f.rev, checked)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !strings.Contains(checked, "4294967295") || !strings.Contains(checked, e.kea.path) {
|
||||||
|
t.Errorf("checked configuration changed:\n%s", checked)
|
||||||
|
}
|
||||||
|
if exists(pw) || exists(user) || exists(checkedPath) {
|
||||||
|
t.Error("Validate wrote live credential files or left the temporary configuration behind")
|
||||||
|
}
|
||||||
|
|
||||||
|
cases := map[string]struct {
|
||||||
|
files map[string]string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
"credentials without reference": {
|
||||||
|
files: haFiles(keaConfig(e.kea.path), "ha\n", "secret\n"),
|
||||||
|
want: "does not reference it",
|
||||||
|
},
|
||||||
|
"reference without password": {
|
||||||
|
files: map[string]string{FileName: haKeaConfig(e.kea.path, user, pw), UserFileName: "ha\n"},
|
||||||
|
want: "the revision has none",
|
||||||
|
},
|
||||||
|
"reference without user": {
|
||||||
|
files: map[string]string{FileName: haKeaConfig(e.kea.path, user, pw), PasswordFileName: "x\n"},
|
||||||
|
want: "the revision has none",
|
||||||
|
},
|
||||||
|
"other password file name": {
|
||||||
|
files: haFiles(haKeaConfig(e.kea.path, user, filepath.Join(dir, "shadow")), "ha\n", "x\n"),
|
||||||
|
want: "file name must be " + PasswordFileName,
|
||||||
|
},
|
||||||
|
"other user file name": {
|
||||||
|
files: haFiles(haKeaConfig(e.kea.path, filepath.Join(dir, "passwd"), pw), "ha\n", "x\n"),
|
||||||
|
want: "file name must be " + UserFileName,
|
||||||
|
},
|
||||||
|
"relative path": {
|
||||||
|
files: haFiles(haKeaConfig(e.kea.path, user, "etc/"+PasswordFileName), "ha\n", "x\n"),
|
||||||
|
want: "HA credential file",
|
||||||
|
},
|
||||||
|
"different directories": {
|
||||||
|
files: haFiles(haKeaConfig(e.kea.path, filepath.Join(dir, "a", UserFileName), pw), "ha\n", "x\n"),
|
||||||
|
want: "same directory",
|
||||||
|
},
|
||||||
|
"missing directory": {
|
||||||
|
files: haFiles(haKeaConfig(e.kea.path, filepath.Join(dir, "nope", UserFileName), filepath.Join(dir, "nope", PasswordFileName)), "ha\n", "x\n"),
|
||||||
|
want: "HA credential file directory",
|
||||||
|
},
|
||||||
|
"different references": {
|
||||||
|
files: haFiles(strings.Replace(haKeaConfig(e.kea.path, user, pw), pw, filepath.Join(dir, "a", PasswordFileName), 1), "ha\n", "x\n"),
|
||||||
|
want: "different HA credential files",
|
||||||
|
},
|
||||||
|
"unexpected file": {
|
||||||
|
files: map[string]string{FileName: haKeaConfig(e.kea.path, user, pw), PasswordFileName: "x\n", UserFileName: "ha\n", "other": ""},
|
||||||
|
want: "exactly",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for name, c := range cases {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
err := e.role.Validate(ctx, revision(t, 1, c.files))
|
||||||
|
if err == nil || !strings.Contains(err.Error(), c.want) {
|
||||||
|
t.Fatalf("err = %v, want %q", err, c.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestActivateHA(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
dir := filepath.Dir(e.conf)
|
||||||
|
pw := filepath.Join(dir, PasswordFileName)
|
||||||
|
user := filepath.Join(dir, UserFileName)
|
||||||
|
conf := haKeaConfig(e.kea.path, user, pw)
|
||||||
|
e.kea.setHandler(func(req request) any { return ok(nil) })
|
||||||
|
|
||||||
|
rev1 := revision(t, 1, haFiles(conf, "ha-1\n", "secret-1\n"))
|
||||||
|
if err := e.role.Activate(ctx, rev1, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for p, want := range map[string]string{pw: "secret-1\n", user: "ha-1\n", e.conf: conf} {
|
||||||
|
if got := readFile(t, p); got != want {
|
||||||
|
t.Errorf("%s = %q", p, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, p := range []string{pw, user} {
|
||||||
|
if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o640 {
|
||||||
|
t.Errorf("%s: mode %o", p, fi.Mode().Perm())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c := e.role.checkInstalled(rev1); c.State != core.HealthOK {
|
||||||
|
t.Errorf("installed check: %+v", c)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Changed credentials on disk are noticed, without showing them.
|
||||||
|
for _, p := range []string{user, pw} {
|
||||||
|
old := readFile(t, p)
|
||||||
|
if err := os.WriteFile(p, []byte("edited\n"), 0o640); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
c := e.role.checkInstalled(rev1)
|
||||||
|
if c.State != core.HealthDegraded || !strings.Contains(c.Message, p) || strings.Contains(c.Message, "edited") {
|
||||||
|
t.Errorf("modified %s: %+v", p, c)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(p, []byte(old), 0o640); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A failed reload restores configuration and credential files.
|
||||||
|
if err := os.WriteFile(pw, []byte("edited\n"), 0o640); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rev2 := revision(t, 2, haFiles(conf, "ha-2\n", "secret-2\n"))
|
||||||
|
n := 0
|
||||||
|
var mu sync.Mutex
|
||||||
|
e.kea.setHandler(func(req request) any {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
n++
|
||||||
|
if n == 1 {
|
||||||
|
return map[string]any{"result": 1, "text": "HA configuration error"}
|
||||||
|
}
|
||||||
|
return ok(nil)
|
||||||
|
})
|
||||||
|
if err := e.role.Activate(ctx, rev2, &rev1); err == nil {
|
||||||
|
t.Fatal("reload failure not reported")
|
||||||
|
}
|
||||||
|
if got := readFile(t, pw); got != "edited\n" {
|
||||||
|
t.Errorf("password file not restored: %q", got)
|
||||||
|
}
|
||||||
|
if got := readFile(t, user); got != "ha-1\n" {
|
||||||
|
t.Errorf("user file not restored: %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Without HA the credential files of the previous revision go.
|
||||||
|
e.kea.setHandler(func(req request) any { return ok(nil) })
|
||||||
|
rev3 := revision(t, 3, map[string]string{FileName: keaConfig(e.kea.path)})
|
||||||
|
if err := e.role.Activate(ctx, rev3, &rev1); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if exists(pw) || exists(user) {
|
||||||
|
t.Error("credential files of the previous revision still exist")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestKeaCredentialPath(t *testing.T) {
|
||||||
|
for _, c := range []struct{ dir, file, want string }{
|
||||||
|
{"", "/etc/kea/pw", "/etc/kea/pw"},
|
||||||
|
{"", "pw", "/pw"},
|
||||||
|
{"/etc/kea", "pw", "/etc/kea/pw"},
|
||||||
|
{"/etc/kea/", "/pw", "/etc/kea/pw"},
|
||||||
|
} {
|
||||||
|
if got := keaCredentialPath(c.dir, c.file); got != c.want {
|
||||||
|
t.Errorf("keaCredentialPath(%q, %q) = %q, want %q", c.dir, c.file, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
got, err := haCredentialPaths([]byte(`{"Dhcp4": {"control-socket": {"socket-type": "http",
|
||||||
|
"authentication": {"directory": "/etc/kea", "clients": [{"user-file": "` + UserFileName + `", "password-file": "` + PasswordFileName + `"}]}}}}`))
|
||||||
|
if err != nil || got[PasswordFileName] != "/etc/kea/"+PasswordFileName || got[UserFileName] != "/etc/kea/"+UserFileName {
|
||||||
|
t.Errorf("directory and file: %v, %v", got, err)
|
||||||
|
}
|
||||||
|
if got, err := haCredentialPaths([]byte(`{"Dhcp4": {"hooks-libraries": [{"library": "x", "parameters": {}}]}}`)); len(got) != 0 || err != nil {
|
||||||
|
t.Errorf("no references: %v, %v", got, err)
|
||||||
|
}
|
||||||
|
if _, err := haCredentialPaths([]byte(`{"Dhcp4": `)); err == nil || !strings.Contains(err.Error(), "not valid JSON") {
|
||||||
|
t.Errorf("invalid JSON: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReplaceStrings(t *testing.T) {
|
||||||
|
out, err := replaceStrings([]byte(`{"a": "x", "b": ["x", "y", {"c": "x"}], "n": 18446744073709551615, "d": "xx"}`),
|
||||||
|
map[string]string{"x": "z", "y": "w"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if want := `{"a":"z","b":["z","w",{"c":"z"}],"d":"xx","n":18446744073709551615}`; string(out) != want {
|
||||||
|
t.Errorf("got %s, want %s", out, want)
|
||||||
|
}
|
||||||
|
if _, err := replaceStrings([]byte("{"), nil); err == nil {
|
||||||
|
t.Error("invalid JSON accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,9 +27,13 @@ type Config struct {
|
|||||||
NamedCheckconf string `yaml:"named_checkconf"`
|
NamedCheckconf string `yaml:"named_checkconf"`
|
||||||
NamedCheckzone string `yaml:"named_checkzone"`
|
NamedCheckzone string `yaml:"named_checkzone"`
|
||||||
Rndc string `yaml:"rndc"`
|
Rndc string `yaml:"rndc"`
|
||||||
|
// Nsupdate applies the DDI-managed records of dynamic zones (ADR 0026)
|
||||||
|
// as RFC 2136 updates sent to DNSAddress.
|
||||||
|
Nsupdate string `yaml:"nsupdate"`
|
||||||
// RndcArgs come before every rndc command, e.g. ["-k", "/etc/bind/rndc.key"].
|
// RndcArgs come before every rndc command, e.g. ["-k", "/etc/bind/rndc.key"].
|
||||||
RndcArgs []string `yaml:"rndc_args"`
|
RndcArgs []string `yaml:"rndc_args"`
|
||||||
// DNSAddress is where the health check sends SOA queries (ip:port).
|
// DNSAddress is where the health check sends SOA queries and nsupdate
|
||||||
|
// sends dynamic updates (ip:port).
|
||||||
DNSAddress string `yaml:"dns_address"`
|
DNSAddress string `yaml:"dns_address"`
|
||||||
// CommandTimeout bounds every program run.
|
// CommandTimeout bounds every program run.
|
||||||
CommandTimeout time.Duration `yaml:"command_timeout"`
|
CommandTimeout time.Duration `yaml:"command_timeout"`
|
||||||
@@ -45,6 +49,7 @@ func DefaultConfig() Config {
|
|||||||
NamedCheckconf: "named-checkconf",
|
NamedCheckconf: "named-checkconf",
|
||||||
NamedCheckzone: "named-checkzone",
|
NamedCheckzone: "named-checkzone",
|
||||||
Rndc: "rndc",
|
Rndc: "rndc",
|
||||||
|
Nsupdate: "nsupdate",
|
||||||
DNSAddress: "127.0.0.1:53",
|
DNSAddress: "127.0.0.1:53",
|
||||||
CommandTimeout: 60 * time.Second,
|
CommandTimeout: 60 * time.Second,
|
||||||
}
|
}
|
||||||
@@ -62,7 +67,7 @@ func (c *Config) Validate() error {
|
|||||||
}
|
}
|
||||||
for _, p := range []struct{ name, value string }{
|
for _, p := range []struct{ name, value string }{
|
||||||
{"named", c.Named}, {"named_checkconf", c.NamedCheckconf},
|
{"named", c.Named}, {"named_checkconf", c.NamedCheckconf},
|
||||||
{"named_checkzone", c.NamedCheckzone}, {"rndc", c.Rndc},
|
{"named_checkzone", c.NamedCheckzone}, {"rndc", c.Rndc}, {"nsupdate", c.Nsupdate},
|
||||||
} {
|
} {
|
||||||
if strings.TrimSpace(p.value) == "" || strings.ContainsAny(p.value, "\x00\n") {
|
if strings.TrimSpace(p.value) == "" || strings.ContainsAny(p.value, "\x00\n") {
|
||||||
errs = append(errs, fmt.Errorf("dns.%s: program name is empty or invalid", p.name))
|
errs = append(errs, fmt.Errorf("dns.%s: program name is empty or invalid", p.name))
|
||||||
|
|||||||
+167
-33
@@ -3,11 +3,23 @@
|
|||||||
// Package dns is the agent role for BIND 9 (ADR 0004, ADR 0021).
|
// Package dns is the agent role for BIND 9 (ADR 0004, ADR 0021).
|
||||||
//
|
//
|
||||||
// A DNS revision consists of ddi-suite.conf (top-level statements: ACLs and
|
// A DNS revision consists of ddi-suite.conf (top-level statements: ACLs and
|
||||||
// zones), ddi-suite-options.conf (statements for the options block) and one
|
// zones), ddi-suite-options.conf (statements for the options block),
|
||||||
// zone file per zone under zones/. The distribution's named.conf includes
|
// ddi-suite-keys.conf (TSIG keys, since M5) and one zone file per primary
|
||||||
// the two .conf files from Config.ConfDir; zone files go to Config.ZoneDir.
|
// zone under zones/. The distribution's named.conf includes the .conf files
|
||||||
// Initial files of dynamic zones are CreateOnly: BIND owns them once they
|
// from Config.ConfDir (the keys before ddi-suite.conf); zone files go to
|
||||||
// exist.
|
// Config.ZoneDir. Initial files of dynamic zones are CreateOnly: BIND owns
|
||||||
|
// them once they exist.
|
||||||
|
//
|
||||||
|
// Secondary zones have no file in the revision: BIND transfers them from
|
||||||
|
// their primaries and writes them to <zone_dir>/secondary/, which the role
|
||||||
|
// creates (with the mode and owner of zone_dir) and whose content it never
|
||||||
|
// touches. Revisions without keys file (before M5) get a keys file without
|
||||||
|
// keys, so that named.conf can always include it.
|
||||||
|
//
|
||||||
|
// A target that serves dynamic zones as primary also gets
|
||||||
|
// ddi-suite-update.key and dynamic-records.json (ADR 0026). They stay in
|
||||||
|
// the revision directory; after the reload the role applies the managed
|
||||||
|
// records of those zones with nsupdate (see dynamic.go).
|
||||||
package dns
|
package dns
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -15,11 +27,14 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"git.beugsiud.de/beug.k/DDI/agent/core"
|
"git.beugsiud.de/beug.k/DDI/agent/core"
|
||||||
"git.beugsiud.de/beug.k/DDI/agent/role/internal/command"
|
"git.beugsiud.de/beug.k/DDI/agent/role/internal/command"
|
||||||
@@ -31,8 +46,15 @@ import (
|
|||||||
const (
|
const (
|
||||||
confFile = "ddi-suite.conf"
|
confFile = "ddi-suite.conf"
|
||||||
optionsFile = "ddi-suite-options.conf"
|
optionsFile = "ddi-suite-options.conf"
|
||||||
|
keysFile = "ddi-suite-keys.conf"
|
||||||
zonesPrefix = "zones/"
|
zonesPrefix = "zones/"
|
||||||
zonePrefix = "db."
|
zonePrefix = "db."
|
||||||
|
// secondaryDir below the zone directory receives the files of
|
||||||
|
// secondary zones, written by BIND.
|
||||||
|
secondaryDir = "secondary"
|
||||||
|
// keysMode is the mode of the keys file written for revisions without
|
||||||
|
// one.
|
||||||
|
keysMode = 0o640
|
||||||
// journalSuffix is appended to a zone file name by BIND for the journal
|
// journalSuffix is appended to a zone file name by BIND for the journal
|
||||||
// of a dynamic zone (BIND 9 ARM, "journal" zone option: default is the
|
// of a dynamic zone (BIND 9 ARM, "journal" zone option: default is the
|
||||||
// zone file name with ".jnl" appended).
|
// zone file name with ".jnl" appended).
|
||||||
@@ -42,12 +64,19 @@ const (
|
|||||||
// Role manages BIND.
|
// Role manages BIND.
|
||||||
type Role struct {
|
type Role struct {
|
||||||
cfg Config
|
cfg Config
|
||||||
run command.Runner
|
run command.InputRunner
|
||||||
// dial is used for SOA queries (replaced in tests).
|
// dial is used for SOA queries (replaced in tests).
|
||||||
dial dialFunc
|
dial dialFunc
|
||||||
|
log *slog.Logger
|
||||||
|
// updateWait bounds the retries of dynamic updates while zones load,
|
||||||
|
// updateRetry is the pause between two attempts (replaced in tests).
|
||||||
|
updateWait, updateRetry time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ core.Role = (*Role)(nil)
|
var (
|
||||||
|
_ core.Role = (*Role)(nil)
|
||||||
|
_ core.LogSetter = (*Role)(nil)
|
||||||
|
)
|
||||||
|
|
||||||
// New creates the role from the "dns:" section of the agent configuration;
|
// New creates the role from the "dns:" section of the agent configuration;
|
||||||
// it matches core.RoleFactory. decode may be nil (no section).
|
// it matches core.RoleFactory. decode may be nil (no section).
|
||||||
@@ -61,11 +90,21 @@ func New(decode func(v any) error) (core.Role, error) {
|
|||||||
return newRole(cfg, command.Exec{Timeout: cfg.CommandTimeout})
|
return newRole(cfg, command.Exec{Timeout: cfg.CommandTimeout})
|
||||||
}
|
}
|
||||||
|
|
||||||
func newRole(cfg Config, run command.Runner) (*Role, error) {
|
func newRole(cfg Config, run command.InputRunner) (*Role, error) {
|
||||||
if err := cfg.Validate(); err != nil {
|
if err := cfg.Validate(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &Role{cfg: cfg, run: run, dial: defaultDial}, nil
|
return &Role{
|
||||||
|
cfg: cfg, run: run, dial: defaultDial, log: slog.New(slog.DiscardHandler),
|
||||||
|
updateWait: defaultUpdateWait, updateRetry: defaultUpdateRetry,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetLogger implements core.LogSetter.
|
||||||
|
func (r *Role) SetLogger(log *slog.Logger) {
|
||||||
|
if log != nil {
|
||||||
|
r.log = log
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Kind implements core.Role.
|
// Kind implements core.Role.
|
||||||
@@ -90,29 +129,49 @@ func parseNamedVersion(out string) (string, error) {
|
|||||||
return f[0] + " " + f[1], nil
|
return f[0] + " " + f[1], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// noKeys is the keys file written for revisions without one.
|
||||||
|
const noKeys = "// No TSIG keys: written by the DDI Suite DNS agent for a revision without\n" +
|
||||||
|
"// ddi-suite-keys.conf, so that named.conf can include it.\n"
|
||||||
|
|
||||||
// target is one revision file and where it goes on the host.
|
// target is one revision file and where it goes on the host.
|
||||||
type target struct {
|
type target struct {
|
||||||
file bundle.File
|
file bundle.File
|
||||||
src string // inside the revision directory
|
src string // inside the revision directory; "" if data is set
|
||||||
|
data []byte // content of files the role adds (keys file of old revisions)
|
||||||
dst string // live path
|
dst string // live path
|
||||||
zone string // zone name for zone files, "" for .conf files
|
zone string // zone name for zone files, "" for .conf files
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// content returns the file content of t.
|
||||||
|
func (t target) content() ([]byte, error) {
|
||||||
|
if t.data != nil {
|
||||||
|
return t.data, nil
|
||||||
|
}
|
||||||
|
return fsutil.ReadFile(t.src)
|
||||||
|
}
|
||||||
|
|
||||||
// plan maps the files of rev to their live paths. Only top-level *.conf
|
// plan maps the files of rev to their live paths. Only top-level *.conf
|
||||||
// files and zones/db.<zone> are allowed.
|
// files and zones/db.<zone> are allowed. A revision without keys file gets
|
||||||
|
// one without keys.
|
||||||
func (r *Role) plan(rev core.Revision) ([]target, error) {
|
func (r *Role) plan(rev core.Revision) ([]target, error) {
|
||||||
out := make([]target, 0, len(rev.Files))
|
out := make([]target, 0, len(rev.Files)+1)
|
||||||
var haveConf, haveOptions bool
|
var haveConf, haveOptions, haveKeys bool
|
||||||
for _, f := range rev.Files {
|
for _, f := range rev.Files {
|
||||||
if err := bundle.CheckPath(f.Path); err != nil {
|
if err := bundle.CheckPath(f.Path); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
if isUpdateFile(f.Path) {
|
||||||
|
// Revision data for dynamic updates, used from the revision
|
||||||
|
// directory (see loadDynamic).
|
||||||
|
continue
|
||||||
|
}
|
||||||
t := target{file: f, src: filepath.Join(rev.Dir, filepath.FromSlash(f.Path))}
|
t := target{file: f, src: filepath.Join(rev.Dir, filepath.FromSlash(f.Path))}
|
||||||
switch {
|
switch {
|
||||||
case !strings.Contains(f.Path, "/") && strings.HasSuffix(f.Path, ".conf"):
|
case !strings.Contains(f.Path, "/") && strings.HasSuffix(f.Path, ".conf"):
|
||||||
t.dst = filepath.Join(r.cfg.ConfDir, f.Path)
|
t.dst = filepath.Join(r.cfg.ConfDir, f.Path)
|
||||||
haveConf = haveConf || f.Path == confFile
|
haveConf = haveConf || f.Path == confFile
|
||||||
haveOptions = haveOptions || f.Path == optionsFile
|
haveOptions = haveOptions || f.Path == optionsFile
|
||||||
|
haveKeys = haveKeys || f.Path == keysFile
|
||||||
case strings.HasPrefix(f.Path, zonesPrefix):
|
case strings.HasPrefix(f.Path, zonesPrefix):
|
||||||
name := strings.TrimPrefix(f.Path, zonesPrefix)
|
name := strings.TrimPrefix(f.Path, zonesPrefix)
|
||||||
zone, ok := strings.CutPrefix(name, zonePrefix)
|
zone, ok := strings.CutPrefix(name, zonePrefix)
|
||||||
@@ -132,6 +191,13 @@ func (r *Role) plan(rev core.Revision) ([]target, error) {
|
|||||||
if !haveConf || !haveOptions {
|
if !haveConf || !haveOptions {
|
||||||
return nil, fmt.Errorf("DNS revision must contain %s and %s", confFile, optionsFile)
|
return nil, fmt.Errorf("DNS revision must contain %s and %s", confFile, optionsFile)
|
||||||
}
|
}
|
||||||
|
if !haveKeys {
|
||||||
|
out = append(out, target{
|
||||||
|
file: bundle.File{Path: keysFile, Mode: keysMode},
|
||||||
|
data: []byte(noKeys),
|
||||||
|
dst: filepath.Join(r.cfg.ConfDir, keysFile),
|
||||||
|
})
|
||||||
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,8 +218,12 @@ func validZoneName(z string) bool {
|
|||||||
// fileStmt finds the zone file statements in ddi-suite.conf.
|
// fileStmt finds the zone file statements in ddi-suite.conf.
|
||||||
var fileStmt = regexp.MustCompile(`(?m)^\s*file\s+"([^"]*)"\s*;`)
|
var fileStmt = regexp.MustCompile(`(?m)^\s*file\s+"([^"]*)"\s*;`)
|
||||||
|
|
||||||
// checkZoneDir verifies that ddi-suite.conf names its zone files inside
|
// secondaryPath is the directory of the secondary zone files.
|
||||||
// the configured zone_dir and only files of this revision.
|
func (r *Role) secondaryPath() string { return path.Join(r.cfg.ZoneDir, secondaryDir) }
|
||||||
|
|
||||||
|
// checkZoneDir verifies that ddi-suite.conf names the files of primary
|
||||||
|
// zones inside the configured zone_dir and only files of this revision, and
|
||||||
|
// the files of secondary zones inside zone_dir/secondary.
|
||||||
func (r *Role) checkZoneDir(conf []byte, targets []target) error {
|
func (r *Role) checkZoneDir(conf []byte, targets []target) error {
|
||||||
zoneFiles := map[string]bool{}
|
zoneFiles := map[string]bool{}
|
||||||
for _, t := range targets {
|
for _, t := range targets {
|
||||||
@@ -163,18 +233,45 @@ func (r *Role) checkZoneDir(conf []byte, targets []target) error {
|
|||||||
}
|
}
|
||||||
for _, m := range fileStmt.FindAllSubmatch(conf, -1) {
|
for _, m := range fileStmt.FindAllSubmatch(conf, -1) {
|
||||||
p := string(m[1])
|
p := string(m[1])
|
||||||
if dir := path.Dir(p); dir != r.cfg.ZoneDir {
|
switch dir := path.Dir(p); dir {
|
||||||
|
case r.cfg.ZoneDir:
|
||||||
|
if !zoneFiles[path.Base(p)] {
|
||||||
|
return fmt.Errorf("%s references %q, which is not part of the revision", confFile, p)
|
||||||
|
}
|
||||||
|
case r.secondaryPath():
|
||||||
|
// Written by BIND after a zone transfer.
|
||||||
|
if z, ok := strings.CutPrefix(path.Base(p), zonePrefix); !ok || !validZoneName(z) {
|
||||||
|
return fmt.Errorf("%s references the secondary zone file %q (want db.<zone>)", confFile, p)
|
||||||
|
}
|
||||||
|
default:
|
||||||
return fmt.Errorf("%s places zone files in %q, but this agent's dns.zone_dir is %q: "+
|
return fmt.Errorf("%s places zone files in %q, but this agent's dns.zone_dir is %q: "+
|
||||||
"set the same zone directory in the server's generator settings and the agent configuration",
|
"set the same zone directory in the server's generator settings and the agent configuration",
|
||||||
confFile, dir, r.cfg.ZoneDir)
|
confFile, strings.TrimSuffix(dir, "/"+secondaryDir), r.cfg.ZoneDir)
|
||||||
}
|
|
||||||
if !zoneFiles[path.Base(p)] {
|
|
||||||
return fmt.Errorf("%s references %q, which is not part of the revision", confFile, p)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// secondaryZones returns the names of the secondary zones of the revision
|
||||||
|
// in Dir (from the file statements of its ddi-suite.conf).
|
||||||
|
func (r *Role) secondaryZones(rev core.Revision) []string {
|
||||||
|
conf, err := fsutil.ReadFile(filepath.Join(rev.Dir, confFile))
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var zones []string
|
||||||
|
for _, m := range fileStmt.FindAllSubmatch(conf, -1) {
|
||||||
|
p := string(m[1])
|
||||||
|
if path.Dir(p) != r.secondaryPath() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if z, ok := strings.CutPrefix(path.Base(p), zonePrefix); ok && validZoneName(z) {
|
||||||
|
zones = append(zones, z)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return zones
|
||||||
|
}
|
||||||
|
|
||||||
// Validate checks rev with named-checkconf (on a temporary named.conf that
|
// Validate checks rev with named-checkconf (on a temporary named.conf that
|
||||||
// includes the revision's files) and named-checkzone. Nothing live changes.
|
// includes the revision's files) and named-checkzone. Nothing live changes.
|
||||||
func (r *Role) Validate(ctx context.Context, rev core.Revision) error {
|
func (r *Role) Validate(ctx context.Context, rev core.Revision) error {
|
||||||
@@ -194,7 +291,16 @@ func (r *Role) Validate(ctx context.Context, rev core.Revision) error {
|
|||||||
if err := r.checkZoneDir(conf, targets); err != nil {
|
if err := r.checkZoneDir(conf, targets); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err := r.checkConf(ctx, rev.Dir); err != nil {
|
dyn, err := r.loadDynamic(rev, targets)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if dyn != nil {
|
||||||
|
if err := checkUpdateKeyKnown(rev, dyn.key); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := r.checkConf(ctx, rev); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
var errs []error
|
var errs []error
|
||||||
@@ -216,9 +322,11 @@ func (r *Role) Validate(ctx context.Context, rev core.Revision) error {
|
|||||||
return errors.Join(errs...)
|
return errors.Join(errs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// checkConf writes a temporary named.conf that includes the revision's two
|
// checkConf writes a temporary named.conf that includes the revision's
|
||||||
// files the way the distribution's named.conf does and checks it.
|
// files the way the distribution's named.conf does (the keys file, if the
|
||||||
func (r *Role) checkConf(ctx context.Context, revDir string) error {
|
// revision has one, before ddi-suite.conf) and checks it.
|
||||||
|
func (r *Role) checkConf(ctx context.Context, rev core.Revision) error {
|
||||||
|
revDir := rev.Dir
|
||||||
if strings.ContainsAny(revDir, "\"\\\n;") {
|
if strings.ContainsAny(revDir, "\"\\\n;") {
|
||||||
return fmt.Errorf("revision directory %q cannot be used in named.conf", revDir)
|
return fmt.Errorf("revision directory %q cannot be used in named.conf", revDir)
|
||||||
}
|
}
|
||||||
@@ -228,8 +336,12 @@ func (r *Role) checkConf(ctx context.Context, revDir string) error {
|
|||||||
}
|
}
|
||||||
defer func() { _ = os.RemoveAll(tmp) }()
|
defer func() { _ = os.RemoveAll(tmp) }()
|
||||||
slash := filepath.ToSlash
|
slash := filepath.ToSlash
|
||||||
named := fmt.Sprintf("options {\n\tdirectory %q;\n\tinclude %q;\n};\ninclude %q;\n",
|
keys := ""
|
||||||
slash(tmp), slash(filepath.Join(revDir, optionsFile)), slash(filepath.Join(revDir, confFile)))
|
if slices.ContainsFunc(rev.Files, func(f bundle.File) bool { return f.Path == keysFile }) {
|
||||||
|
keys = fmt.Sprintf("include %q;\n", slash(filepath.Join(revDir, keysFile)))
|
||||||
|
}
|
||||||
|
named := fmt.Sprintf("options {\n\tdirectory %q;\n\tinclude %q;\n};\n%sinclude %q;\n",
|
||||||
|
slash(tmp), slash(filepath.Join(revDir, optionsFile)), keys, slash(filepath.Join(revDir, confFile)))
|
||||||
nc := filepath.Join(tmp, "named.conf")
|
nc := filepath.Join(tmp, "named.conf")
|
||||||
if err := os.WriteFile(nc, []byte(named), 0o600); err != nil {
|
if err := os.WriteFile(nc, []byte(named), 0o600); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -240,19 +352,38 @@ func (r *Role) checkConf(ctx context.Context, revDir string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Activate installs rev and reloads BIND. See core.Role for the rules on
|
// Activate installs rev and reloads BIND, then applies the managed records
|
||||||
// CreateOnly files and removals. On failure the previous files are restored
|
// of dynamic zones (ADR 0026). See core.Role for the rules on CreateOnly
|
||||||
// (and BIND is reloaded again if it had been reloaded).
|
// files and removals. On failure the previous files are restored (and BIND
|
||||||
|
// is reloaded again if it had been reloaded); records already updated are
|
||||||
|
// restored by the core's rollback, which activates the previous revision.
|
||||||
func (r *Role) Activate(ctx context.Context, rev core.Revision, prev *core.Revision) (err error) {
|
func (r *Role) Activate(ctx context.Context, rev core.Revision, prev *core.Revision) (err error) {
|
||||||
targets, err := r.plan(rev)
|
targets, err := r.plan(rev)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
dyn, err := r.loadDynamic(rev, targets)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
var old []target
|
var old []target
|
||||||
|
var oldDyn *dynSet
|
||||||
if prev != nil {
|
if prev != nil {
|
||||||
// A previous revision that no longer fits the configuration only
|
// A previous revision that no longer fits the configuration only
|
||||||
// loses the removal of its stale files.
|
// loses the removal of its stale files and of its managed records.
|
||||||
old, _ = r.plan(*prev)
|
var perr error
|
||||||
|
if old, perr = r.plan(*prev); perr == nil {
|
||||||
|
if oldDyn, perr = r.loadDynamic(*prev, old); perr != nil {
|
||||||
|
r.log.Warn("previous revision has unusable dynamic records; none are deleted",
|
||||||
|
"revision", prev.Number, "error", perr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BIND writes transferred secondary zones there; it stays when the
|
||||||
|
// activation fails (it is empty or BIND's own).
|
||||||
|
if err := fsutil.MkdirLike(r.secondaryPath(), r.cfg.ZoneDir); err != nil {
|
||||||
|
return fmt.Errorf("secondary zone directory: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var backup fsutil.Backup
|
var backup fsutil.Backup
|
||||||
@@ -288,7 +419,7 @@ func (r *Role) Activate(ctx context.Context, rev core.Revision, prev *core.Revis
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
for _, w := range writes {
|
for _, w := range writes {
|
||||||
data, rerr := fsutil.ReadFile(w.src)
|
data, rerr := w.content()
|
||||||
if rerr != nil {
|
if rerr != nil {
|
||||||
return rerr
|
return rerr
|
||||||
}
|
}
|
||||||
@@ -310,7 +441,10 @@ func (r *Role) Activate(ctx context.Context, rev core.Revision, prev *core.Revis
|
|||||||
return fmt.Errorf("live configuration check failed, previous files restored: %w", cerr)
|
return fmt.Errorf("live configuration check failed, previous files restored: %w", cerr)
|
||||||
}
|
}
|
||||||
reloaded = true
|
reloaded = true
|
||||||
return r.reload(ctx)
|
if err := r.reload(ctx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return r.applyDynamic(ctx, rev, dyn, oldDyn, dynamicZones(targets))
|
||||||
}
|
}
|
||||||
|
|
||||||
// changes computes the files to write (zone files first, so that the
|
// changes computes the files to write (zone files first, so that the
|
||||||
|
|||||||
+214
-8
@@ -26,18 +26,45 @@ import (
|
|||||||
type fakeRunner struct {
|
type fakeRunner struct {
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
calls []string
|
calls []string
|
||||||
fn func(name string, args []string) ([]byte, error)
|
// inputs holds the stdin of every RunInput call, in order.
|
||||||
|
inputs []string
|
||||||
|
fn func(name string, args []string) ([]byte, error)
|
||||||
|
// fnInput answers RunInput calls if set (otherwise fn does).
|
||||||
|
fnInput func(input string, name string, args []string) ([]byte, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *fakeRunner) Run(_ context.Context, name string, args ...string) ([]byte, error) {
|
func (f *fakeRunner) Run(_ context.Context, name string, args ...string) ([]byte, error) {
|
||||||
|
return f.run(nil, name, args)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeRunner) RunInput(_ context.Context, input []byte, name string, args ...string) ([]byte, error) {
|
||||||
|
return f.run(input, name, args)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeRunner) Inputs() []string {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
return slices.Clone(f.inputs)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeRunner) run(input []byte, name string, args []string) ([]byte, error) {
|
||||||
f.mu.Lock()
|
f.mu.Lock()
|
||||||
f.calls = append(f.calls, strings.Join(append([]string{name}, args...), " "))
|
f.calls = append(f.calls, strings.Join(append([]string{name}, args...), " "))
|
||||||
fn := f.fn
|
if input != nil {
|
||||||
|
f.inputs = append(f.inputs, string(input))
|
||||||
|
}
|
||||||
|
fn, fnInput := f.fn, f.fnInput
|
||||||
f.mu.Unlock()
|
f.mu.Unlock()
|
||||||
if fn == nil {
|
var out []byte
|
||||||
|
var err error
|
||||||
|
switch {
|
||||||
|
case input != nil && fnInput != nil:
|
||||||
|
out, err = fnInput(string(input), name, args)
|
||||||
|
case fn != nil:
|
||||||
|
out, err = fn(name, args)
|
||||||
|
default:
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
out, err := fn(name, args)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Like command.Exec: the error quotes the output.
|
// Like command.Exec: the error quotes the output.
|
||||||
return out, &command.Error{Name: name, Args: args, Err: err, Output: out}
|
return out, &command.Error{Name: name, Args: args, Err: err, Output: out}
|
||||||
@@ -55,6 +82,7 @@ func (f *fakeRunner) Reset() {
|
|||||||
f.mu.Lock()
|
f.mu.Lock()
|
||||||
defer f.mu.Unlock()
|
defer f.mu.Unlock()
|
||||||
f.calls = nil
|
f.calls = nil
|
||||||
|
f.inputs = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type env struct {
|
type env struct {
|
||||||
@@ -92,15 +120,21 @@ func newEnv(t *testing.T) *env {
|
|||||||
|
|
||||||
// zone describes one zone of a fixture revision.
|
// zone describes one zone of a fixture revision.
|
||||||
type zone struct {
|
type zone struct {
|
||||||
name string
|
name string
|
||||||
dynamic bool
|
dynamic bool
|
||||||
extra string
|
secondary bool // no zone file; BIND transfers it
|
||||||
|
extra string
|
||||||
}
|
}
|
||||||
|
|
||||||
func confFor(zoneDir string, zones []zone) string {
|
func confFor(zoneDir string, zones []zone) string {
|
||||||
var b strings.Builder
|
var b strings.Builder
|
||||||
b.WriteString("// Generated by DDI Suite.\n")
|
b.WriteString("// Generated by DDI Suite.\n")
|
||||||
for _, z := range zones {
|
for _, z := range zones {
|
||||||
|
if z.secondary {
|
||||||
|
fmt.Fprintf(&b, "\nzone %q {\n type secondary;\n file \"%s/secondary/db.%s\";\n"+
|
||||||
|
" primaries { 192.0.2.1 key \"xfer\"; };\n notify no;\n};\n", z.name, zoneDir, z.name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
update := "none"
|
update := "none"
|
||||||
if z.dynamic {
|
if z.dynamic {
|
||||||
update = "any"
|
update = "any"
|
||||||
@@ -116,15 +150,30 @@ func zoneFile(name string, serial uint64, extra string) string {
|
|||||||
name, name, name, serial, name, extra)
|
name, name, name, serial, name, extra)
|
||||||
}
|
}
|
||||||
|
|
||||||
// revision writes a generator-like revision into a temporary directory.
|
// revision writes a generator-like revision (as before M5: without keys
|
||||||
|
// file) into a temporary directory.
|
||||||
func (e *env) revision(n uint64, zones []zone) core.Revision {
|
func (e *env) revision(n uint64, zones []zone) core.Revision {
|
||||||
|
e.t.Helper()
|
||||||
|
return e.revisionWithKeys(n, zones, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
const testKeys = "key \"xfer\" {\n algorithm hmac-sha256;\n secret \"eGZlcg==\";\n};\n"
|
||||||
|
|
||||||
|
// revisionWithKeys writes a revision with keys file (if keys is not empty).
|
||||||
|
func (e *env) revisionWithKeys(n uint64, zones []zone, keys string) core.Revision {
|
||||||
e.t.Helper()
|
e.t.Helper()
|
||||||
files := map[string]string{
|
files := map[string]string{
|
||||||
confFile: confFor(e.zoneDir, zones),
|
confFile: confFor(e.zoneDir, zones),
|
||||||
optionsFile: "recursion no;\nallow-transfer { none; };\n",
|
optionsFile: "recursion no;\nallow-transfer { none; };\n",
|
||||||
}
|
}
|
||||||
|
if keys != "" {
|
||||||
|
files[keysFile] = keys
|
||||||
|
}
|
||||||
createOnly := map[string]bool{}
|
createOnly := map[string]bool{}
|
||||||
for _, z := range zones {
|
for _, z := range zones {
|
||||||
|
if z.secondary {
|
||||||
|
continue
|
||||||
|
}
|
||||||
p := zonesPrefix + zonePrefix + z.name
|
p := zonesPrefix + zonePrefix + z.name
|
||||||
files[p] = zoneFile(z.name, n, z.extra)
|
files[p] = zoneFile(z.name, n, z.extra)
|
||||||
createOnly[p] = z.dynamic
|
createOnly[p] = z.dynamic
|
||||||
@@ -545,6 +594,160 @@ func TestActivateRemovesJournalWhenZoneBecomesManaged(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var clusterZones = []zone{
|
||||||
|
{name: "office.test"},
|
||||||
|
{name: "remote.test", secondary: true},
|
||||||
|
{name: "2.0.192.in-addr.arpa", secondary: true},
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateIncludesKeysBeforeConf(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
var namedConf string
|
||||||
|
e.run.fn = func(name string, args []string) ([]byte, error) {
|
||||||
|
if name == "named-checkconf" {
|
||||||
|
namedConf = readFile(t, args[len(args)-1])
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
rev := e.revisionWithKeys(1, clusterZones, testKeys)
|
||||||
|
if err := e.role.Validate(context.Background(), rev); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
keysInc := "include \"" + filepath.ToSlash(filepath.Join(rev.Dir, keysFile)) + "\";"
|
||||||
|
confInc := "include \"" + filepath.ToSlash(filepath.Join(rev.Dir, confFile)) + "\";"
|
||||||
|
ki, ci := strings.Index(namedConf, keysInc), strings.Index(namedConf, confInc)
|
||||||
|
if ki < 0 || ci < 0 || ki > ci || ki < strings.Index(namedConf, "};") {
|
||||||
|
t.Errorf("keys must be included at the top level before ddi-suite.conf:\n%s", namedConf)
|
||||||
|
}
|
||||||
|
// Only the primary zone has a zone file to check.
|
||||||
|
if calls := e.run.Calls(); len(calls) != 2 || !strings.Contains(calls[1], "office.test") {
|
||||||
|
t.Errorf("calls = %v", calls)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A revision without keys file (before M5) includes none.
|
||||||
|
rev = e.revision(2, sampleZones)
|
||||||
|
if err := e.role.Validate(context.Background(), rev); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if strings.Contains(namedConf, keysFile) {
|
||||||
|
t.Errorf("keys file included although the revision has none:\n%s", namedConf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateSecondaryZoneFiles(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
for name, c := range map[string]struct {
|
||||||
|
conf string
|
||||||
|
want string // "" means accepted
|
||||||
|
}{
|
||||||
|
"secondary file in zone_dir/secondary": {
|
||||||
|
conf: confFor(e.zoneDir, clusterZones),
|
||||||
|
},
|
||||||
|
"secondary file of another zone dir": {
|
||||||
|
conf: confFor("/srv/zones", []zone{{name: "remote.test", secondary: true}}),
|
||||||
|
want: "dns.zone_dir",
|
||||||
|
},
|
||||||
|
"secondary file with a bad name": {
|
||||||
|
conf: "zone \"x.test\" {\n type secondary;\n file \"" + e.zoneDir + "/secondary/x.test\";\n};\n",
|
||||||
|
want: "want db.<zone>",
|
||||||
|
},
|
||||||
|
"secondary directory below another directory": {
|
||||||
|
conf: "zone \"x.test\" {\n file \"" + e.zoneDir + "/secondary/a/db.x.test\";\n};\n",
|
||||||
|
want: "dns.zone_dir",
|
||||||
|
},
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
files := map[string]string{confFile: c.conf, optionsFile: "", keysFile: testKeys}
|
||||||
|
if strings.Contains(c.conf, "db.office.test") {
|
||||||
|
files["zones/db.office.test"] = zoneFile("office.test", 1, "")
|
||||||
|
}
|
||||||
|
err := e.role.Validate(context.Background(), writeRevision(t, 1, files, nil))
|
||||||
|
switch {
|
||||||
|
case c.want == "" && err != nil:
|
||||||
|
t.Fatalf("rejected: %v", err)
|
||||||
|
case c.want != "" && (err == nil || !strings.Contains(err.Error(), c.want)):
|
||||||
|
t.Fatalf("err = %v, want it to contain %q", err, c.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestActivateKeysAndSecondaryDirectory(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
e := newEnv(t)
|
||||||
|
if err := os.Chmod(e.zoneDir, 0o770); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
keysPath := filepath.Join(e.confDir, keysFile)
|
||||||
|
secDir := filepath.Join(e.zoneDir, "secondary")
|
||||||
|
|
||||||
|
// Before M5: a keys file without keys.
|
||||||
|
rev1 := e.revision(1, sampleZones)
|
||||||
|
if err := e.role.Activate(ctx, rev1, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := readFile(t, keysPath); got != noKeys {
|
||||||
|
t.Errorf("keys file = %q", got)
|
||||||
|
}
|
||||||
|
fi, err := os.Stat(secDir)
|
||||||
|
if err != nil || !fi.IsDir() || fi.Mode().Perm() != 0o770 {
|
||||||
|
t.Fatalf("secondary directory: %v %v", fi, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// BIND writes a transferred zone; the revision with keys replaces the
|
||||||
|
// placeholder and never touches the secondary directory.
|
||||||
|
transferred := filepath.Join(secDir, "db.remote.test")
|
||||||
|
if err := os.WriteFile(transferred, []byte("raw zone"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rev2 := e.revisionWithKeys(2, clusterZones, testKeys)
|
||||||
|
if err := e.role.Activate(ctx, rev2, &rev1); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := readFile(t, keysPath); got != testKeys {
|
||||||
|
t.Errorf("keys file = %q", got)
|
||||||
|
}
|
||||||
|
if fi, _ := os.Stat(keysPath); fi.Mode().Perm() != 0o640 {
|
||||||
|
t.Errorf("keys file mode %o", fi.Mode().Perm())
|
||||||
|
}
|
||||||
|
for _, z := range []string{"2.0.192.in-addr.arpa", "dyn.test"} {
|
||||||
|
if z == "dyn.test" {
|
||||||
|
if !exists(filepath.Join(e.zoneDir, "db."+z)) {
|
||||||
|
t.Error("create-only file removed")
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if exists(filepath.Join(e.zoneDir, "db."+z)) {
|
||||||
|
t.Errorf("zone file of %s (now secondary) still in zone_dir", z)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Back to a revision without keys (local rollback to an old revision):
|
||||||
|
// the keys file stays, without keys.
|
||||||
|
if err := e.role.Activate(ctx, rev1, &rev2); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := readFile(t, keysPath); got != noKeys {
|
||||||
|
t.Errorf("keys file after rollback = %q", got)
|
||||||
|
}
|
||||||
|
if got := readFile(t, transferred); got != "raw zone" {
|
||||||
|
t.Errorf("secondary zone file changed: %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Something else in the way of the secondary directory fails the
|
||||||
|
// activation before anything is written.
|
||||||
|
e2 := newEnv(t)
|
||||||
|
if err := os.WriteFile(filepath.Join(e2.zoneDir, "secondary"), nil, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := e2.role.Activate(ctx, e2.revision(1, sampleZones), nil); err == nil || !strings.Contains(err.Error(), "secondary zone directory") {
|
||||||
|
t.Fatalf("err = %v", err)
|
||||||
|
}
|
||||||
|
if exists(filepath.Join(e2.confDir, confFile)) {
|
||||||
|
t.Error("files written although the activation failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func snapshot(t *testing.T, e *env) map[string]string {
|
func snapshot(t *testing.T, e *env) map[string]string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
out := map[string]string{}
|
out := map[string]string{}
|
||||||
@@ -554,6 +757,9 @@ func snapshot(t *testing.T, e *env) map[string]string {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
for _, en := range entries {
|
for _, en := range entries {
|
||||||
|
if en.IsDir() {
|
||||||
|
continue // the secondary zone directory
|
||||||
|
}
|
||||||
out[filepath.Join(d, en.Name())] = readFile(t, filepath.Join(d, en.Name()))
|
out[filepath.Join(d, en.Name())] = readFile(t, filepath.Join(d, en.Name()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,651 @@
|
|||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package dns
|
||||||
|
|
||||||
|
// Records of dynamic zones (ADR 0026). BIND owns the content of a dynamic
|
||||||
|
// zone once its initial file exists, so the records DDI manages there are
|
||||||
|
// applied as RFC 2136 updates: a revision for a target that serves dynamic
|
||||||
|
// zones as primary carries dynamic-records.json (the managed records per
|
||||||
|
// zone) and ddi-suite-update.key (the TSIG key nsupdate signs with). Both
|
||||||
|
// stay in the revision directory; nothing is installed into conf_dir.
|
||||||
|
//
|
||||||
|
// After the reload, Activate sends per zone: deletes of exactly the records
|
||||||
|
// the previous revision managed and the new one does not, then adds of all
|
||||||
|
// records of the new revision (adding an existing record changes nothing).
|
||||||
|
// Records DDI never managed (domain controllers, other clients, manual
|
||||||
|
// updates) are never touched.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/netip"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.beugsiud.de/beug.k/DDI/agent/core"
|
||||||
|
"git.beugsiud.de/beug.k/DDI/agent/role/internal/fsutil"
|
||||||
|
"git.beugsiud.de/beug.k/DDI/internal/bundle"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Revision files of ADR 0026 (top level, never installed).
|
||||||
|
const (
|
||||||
|
updateKeyFile = "ddi-suite-update.key"
|
||||||
|
dynRecordsFile = "dynamic-records.json"
|
||||||
|
// dynRecordsVersion is the only format version understood.
|
||||||
|
dynRecordsVersion = 1
|
||||||
|
)
|
||||||
|
|
||||||
|
// Limits of the update files and of one update message.
|
||||||
|
const (
|
||||||
|
maxKeyFileSize = 16 << 10
|
||||||
|
maxRecordsSize = 64 << 20
|
||||||
|
// maxDataLen bounds the presentation form of one record's data.
|
||||||
|
maxDataLen = 8 << 10
|
||||||
|
// Updates are sent in batches of at most this many records or bytes of
|
||||||
|
// script text, so that one message stays well below the 64 KiB limit
|
||||||
|
// of DNS over TCP.
|
||||||
|
maxBatchRecords = 500
|
||||||
|
maxBatchBytes = 32 << 10
|
||||||
|
// nsupdateTimeout is passed to nsupdate -t (seconds per update).
|
||||||
|
nsupdateTimeout = "30"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Retry while a zone is not loaded yet right after rndc reconfig (BIND
|
||||||
|
// answers NOTAUTH or SERVFAIL until then).
|
||||||
|
const (
|
||||||
|
defaultUpdateWait = 10 * time.Second
|
||||||
|
defaultUpdateRetry = time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// dynRecord is one managed record in presentation form.
|
||||||
|
type dynRecord struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
TTL int64 `json:"ttl"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Data string `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// dynZone holds the managed records of one dynamic zone.
|
||||||
|
type dynZone struct {
|
||||||
|
Zone string `json:"zone"`
|
||||||
|
Records []dynRecord `json:"records"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// dynFile is the content of dynamic-records.json.
|
||||||
|
type dynFile struct {
|
||||||
|
Version int `json:"version"`
|
||||||
|
Key string `json:"key"`
|
||||||
|
Zones []dynZone `json:"zones"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// dynSet is the validated update data of one revision.
|
||||||
|
type dynSet struct {
|
||||||
|
key string // TSIG key name
|
||||||
|
keyFile string // path of the revision's key file
|
||||||
|
// zones maps the lowercase zone name to its records (validated, without
|
||||||
|
// duplicates, in file order).
|
||||||
|
zones map[string][]dynRecord
|
||||||
|
}
|
||||||
|
|
||||||
|
// identity returns a comparison key of r: names are case-insensitive, and
|
||||||
|
// so are the names in the data of PTR, CNAME, NS, MX and SRV records;
|
||||||
|
// addresses compare by value.
|
||||||
|
func (r dynRecord) identity() string {
|
||||||
|
data := r.Data
|
||||||
|
switch r.Type {
|
||||||
|
case "A", "AAAA":
|
||||||
|
if a, err := netip.ParseAddr(data); err == nil {
|
||||||
|
data = a.String()
|
||||||
|
}
|
||||||
|
case "PTR", "CNAME", "NS", "MX", "SRV":
|
||||||
|
data = strings.ToLower(data)
|
||||||
|
}
|
||||||
|
return strings.ToLower(r.Name) + " " + r.Type + " " + data
|
||||||
|
}
|
||||||
|
|
||||||
|
// dynamicZones returns the dynamic primary zones of a revision: zones whose
|
||||||
|
// file is create-only (the generator's initial file of a dynamic zone).
|
||||||
|
func dynamicZones(targets []target) map[string]bool {
|
||||||
|
zones := map[string]bool{}
|
||||||
|
for _, t := range targets {
|
||||||
|
if t.zone != "" && t.file.CreateOnly {
|
||||||
|
zones[strings.ToLower(t.zone)] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return zones
|
||||||
|
}
|
||||||
|
|
||||||
|
// isUpdateFile reports whether p is one of the revision files of ADR 0026.
|
||||||
|
func isUpdateFile(p string) bool { return p == updateKeyFile || p == dynRecordsFile }
|
||||||
|
|
||||||
|
// loadDynamic reads and validates the update files of rev. targets is the
|
||||||
|
// revision's plan. It returns nil if the revision has neither file.
|
||||||
|
func (r *Role) loadDynamic(rev core.Revision, targets []target) (*dynSet, error) {
|
||||||
|
var keyEntry, recEntry *bundle.File
|
||||||
|
for i, f := range rev.Files {
|
||||||
|
switch f.Path {
|
||||||
|
case updateKeyFile:
|
||||||
|
keyEntry = &rev.Files[i]
|
||||||
|
case dynRecordsFile:
|
||||||
|
recEntry = &rev.Files[i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case keyEntry == nil && recEntry == nil:
|
||||||
|
return nil, nil
|
||||||
|
case keyEntry == nil || recEntry == nil:
|
||||||
|
return nil, fmt.Errorf("DNS revision must contain both %s and %s or neither", updateKeyFile, dynRecordsFile)
|
||||||
|
case keyEntry.CreateOnly || recEntry.CreateOnly:
|
||||||
|
return nil, fmt.Errorf("%s and %s must not be create-only", updateKeyFile, dynRecordsFile)
|
||||||
|
}
|
||||||
|
keyPath := filepath.Join(rev.Dir, updateKeyFile)
|
||||||
|
if strings.ContainsAny(keyPath, "\x00\n") {
|
||||||
|
return nil, fmt.Errorf("revision directory %q cannot be passed to nsupdate", rev.Dir)
|
||||||
|
}
|
||||||
|
keyData, err := readLimited(keyPath, maxKeyFileSize)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: %w", updateKeyFile, err)
|
||||||
|
}
|
||||||
|
keyName, err := parseUpdateKey(keyData)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: %w", updateKeyFile, err)
|
||||||
|
}
|
||||||
|
recData, err := readLimited(filepath.Join(rev.Dir, dynRecordsFile), maxRecordsSize)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: %w", dynRecordsFile, err)
|
||||||
|
}
|
||||||
|
set, err := parseDynamicRecords(recData, dynamicZones(targets))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: %w", dynRecordsFile, err)
|
||||||
|
}
|
||||||
|
if set.key != keyName {
|
||||||
|
return nil, fmt.Errorf("%s names the key %q, but %s holds the key %q", dynRecordsFile, set.key, updateKeyFile, keyName)
|
||||||
|
}
|
||||||
|
set.keyFile = keyPath
|
||||||
|
return set, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkUpdateKeyKnown verifies that the revision's keys file defines the
|
||||||
|
// update key, so that named can verify the updates.
|
||||||
|
func checkUpdateKeyKnown(rev core.Revision, key string) error {
|
||||||
|
if !slices.ContainsFunc(rev.Files, func(f bundle.File) bool { return f.Path == keysFile }) {
|
||||||
|
return fmt.Errorf("%s requires the key %q in %s, which the revision lacks", dynRecordsFile, key, keysFile)
|
||||||
|
}
|
||||||
|
keys, err := fsutil.ReadFile(filepath.Join(rev.Dir, keysFile))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
stmt := regexp.MustCompile(`(?m)^\s*key\s+"` + regexp.QuoteMeta(key) + `"\s*\{`)
|
||||||
|
if !stmt.Match(keys) {
|
||||||
|
return fmt.Errorf("%s does not define the update key %q", keysFile, key)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readLimited(p string, limit int64) ([]byte, error) {
|
||||||
|
data, err := fsutil.ReadFile(p)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if int64(len(data)) > limit {
|
||||||
|
return nil, fmt.Errorf("larger than %d bytes", limit)
|
||||||
|
}
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// keyStmt matches the key statement of the update key file (named.conf
|
||||||
|
// syntax as written by the generator and tsig-keygen) after comments are
|
||||||
|
// removed. Group 1 is the name, the body is checked by parseKeyBody.
|
||||||
|
var keyStmt = regexp.MustCompile(`^\s*key\s+"([^"]*)"\s*\{([^{}"]*(?:"[^"]*"[^{}"]*)*)\}\s*;\s*$`)
|
||||||
|
|
||||||
|
// keyNameRE restricts TSIG key names to what the server allows plus dots.
|
||||||
|
var keyNameRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$`)
|
||||||
|
|
||||||
|
var tsigAlgorithms = []string{"hmac-md5", "hmac-sha1", "hmac-sha224", "hmac-sha256", "hmac-sha384", "hmac-sha512"}
|
||||||
|
|
||||||
|
// parseUpdateKey checks that data holds exactly one key statement with an
|
||||||
|
// HMAC algorithm and a base64 secret and returns the key name. Errors never
|
||||||
|
// quote the content (it is secret).
|
||||||
|
func parseUpdateKey(data []byte) (string, error) {
|
||||||
|
if bytes.ContainsAny(data, "\x00") {
|
||||||
|
return "", errors.New("invalid content")
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
for _, line := range strings.Split(string(data), "\n") {
|
||||||
|
t := strings.TrimSpace(line)
|
||||||
|
if t == "" || strings.HasPrefix(t, "//") || strings.HasPrefix(t, "#") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
b.WriteString(t)
|
||||||
|
b.WriteByte('\n')
|
||||||
|
}
|
||||||
|
m := keyStmt.FindStringSubmatch(b.String())
|
||||||
|
if m == nil {
|
||||||
|
return "", errors.New("must contain exactly one key statement (key \"<name>\" { algorithm ...; secret \"...\"; };) and only comments besides")
|
||||||
|
}
|
||||||
|
name := m[1]
|
||||||
|
if !keyNameRE.MatchString(name) {
|
||||||
|
return "", fmt.Errorf("invalid key name %q", name)
|
||||||
|
}
|
||||||
|
var alg, secret string
|
||||||
|
for _, s := range strings.Split(m[2], ";") {
|
||||||
|
f := strings.Fields(s)
|
||||||
|
switch {
|
||||||
|
case len(f) == 0:
|
||||||
|
continue
|
||||||
|
case len(f) == 2 && f[0] == "algorithm" && alg == "":
|
||||||
|
alg = f[1]
|
||||||
|
case len(f) == 2 && f[0] == "secret" && secret == "":
|
||||||
|
secret = f[1]
|
||||||
|
default:
|
||||||
|
return "", errors.New("the key statement must hold exactly one algorithm and one secret")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !slices.Contains(tsigAlgorithms, strings.ToLower(alg)) {
|
||||||
|
return "", errors.New("the key statement needs an HMAC algorithm")
|
||||||
|
}
|
||||||
|
raw, quoted := strings.CutPrefix(secret, `"`)
|
||||||
|
raw, closed := strings.CutSuffix(raw, `"`)
|
||||||
|
if !quoted || !closed || raw == "" {
|
||||||
|
return "", errors.New("the secret must be a quoted base64 string")
|
||||||
|
}
|
||||||
|
if _, err := base64.StdEncoding.DecodeString(raw); err != nil {
|
||||||
|
return "", errors.New("the secret is not valid base64")
|
||||||
|
}
|
||||||
|
return name, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseDynamicRecords decodes dynamic-records.json strictly and validates
|
||||||
|
// every field before it can reach an nsupdate script. dynamic holds the
|
||||||
|
// lowercase names of the revision's dynamic primary zones.
|
||||||
|
func parseDynamicRecords(data []byte, dynamic map[string]bool) (*dynSet, error) {
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(data))
|
||||||
|
dec.DisallowUnknownFields()
|
||||||
|
var f dynFile
|
||||||
|
if err := dec.Decode(&f); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid JSON: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
|
||||||
|
return nil, errors.New("invalid JSON: data after the object")
|
||||||
|
}
|
||||||
|
if f.Version != dynRecordsVersion {
|
||||||
|
return nil, fmt.Errorf("unsupported version %d (want %d)", f.Version, dynRecordsVersion)
|
||||||
|
}
|
||||||
|
if !keyNameRE.MatchString(f.Key) {
|
||||||
|
return nil, fmt.Errorf("invalid key name %q", f.Key)
|
||||||
|
}
|
||||||
|
set := &dynSet{key: f.Key, zones: map[string][]dynRecord{}}
|
||||||
|
for i, z := range f.Zones {
|
||||||
|
zone := strings.ToLower(strings.TrimSuffix(z.Zone, "."))
|
||||||
|
if !validZoneName(zone) || !validLabels(zone, false) {
|
||||||
|
return nil, fmt.Errorf("zones[%d]: invalid zone name %q", i, z.Zone)
|
||||||
|
}
|
||||||
|
if _, dup := set.zones[zone]; dup {
|
||||||
|
return nil, fmt.Errorf("zones[%d]: zone %s is listed twice", i, zone)
|
||||||
|
}
|
||||||
|
if !dynamic[zone] {
|
||||||
|
return nil, fmt.Errorf("zones[%d]: %s is not a dynamic primary zone of this revision", i, zone)
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
records := make([]dynRecord, 0, len(z.Records))
|
||||||
|
for j, rec := range z.Records {
|
||||||
|
if err := validateRecord(rec, zone); err != nil {
|
||||||
|
return nil, fmt.Errorf("zone %s, records[%d]: %w", zone, j, err)
|
||||||
|
}
|
||||||
|
if id := rec.identity(); !seen[id] {
|
||||||
|
seen[id] = true
|
||||||
|
records = append(records, rec)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
set.zones[zone] = records
|
||||||
|
}
|
||||||
|
return set, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateRecord checks one record of zone (lowercase, without trailing
|
||||||
|
// dot): an absolute owner name inside the zone, a TTL within RFC 2181, a
|
||||||
|
// supported type and data that is valid presentation form of that type on
|
||||||
|
// one line.
|
||||||
|
func validateRecord(r dynRecord, zone string) error {
|
||||||
|
if !validName(r.Name, true) {
|
||||||
|
return fmt.Errorf("invalid name %q (want an absolute name with trailing dot)", r.Name)
|
||||||
|
}
|
||||||
|
name := strings.ToLower(r.Name)
|
||||||
|
if name != zone+"." && !strings.HasSuffix(name, "."+zone+".") {
|
||||||
|
return fmt.Errorf("name %q is outside the zone %s", r.Name, zone)
|
||||||
|
}
|
||||||
|
if r.TTL < 0 || r.TTL > 1<<31-1 {
|
||||||
|
return fmt.Errorf("TTL %d is out of range", r.TTL)
|
||||||
|
}
|
||||||
|
if len(r.Data) == 0 || len(r.Data) > maxDataLen {
|
||||||
|
return fmt.Errorf("%s data is empty or too long", r.Type)
|
||||||
|
}
|
||||||
|
for i := 0; i < len(r.Data); i++ {
|
||||||
|
if c := r.Data[i]; c < 0x20 || c > 0x7e {
|
||||||
|
return fmt.Errorf("%s data contains a control or non-ASCII character", r.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
switch r.Type {
|
||||||
|
case "A":
|
||||||
|
err = checkAddr(r.Data, true)
|
||||||
|
case "AAAA":
|
||||||
|
err = checkAddr(r.Data, false)
|
||||||
|
case "PTR", "CNAME", "NS":
|
||||||
|
if !validName(r.Data, false) {
|
||||||
|
err = errors.New("want an absolute name with trailing dot")
|
||||||
|
}
|
||||||
|
case "MX":
|
||||||
|
err = checkFields(r.Data, 1, true)
|
||||||
|
case "SRV":
|
||||||
|
err = checkFields(r.Data, 3, true)
|
||||||
|
case "TXT":
|
||||||
|
err = checkTXT(r.Data)
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unsupported type %q (want A, AAAA, PTR, CNAME, MX, TXT, SRV or NS)", r.Type)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid %s data %q: %w", r.Type, r.Data, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkAddr(s string, v4 bool) error {
|
||||||
|
a, err := netip.ParseAddr(s)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
return errors.New("not an IP address")
|
||||||
|
case a.Zone() != "":
|
||||||
|
return errors.New("address with zone")
|
||||||
|
case v4 != a.Is4():
|
||||||
|
return errors.New("wrong address family")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkFields checks "<n1> ... <nk> <target>" with single spaces: k
|
||||||
|
// numbers 0-65535 and an absolute target name ("." if rootOK).
|
||||||
|
func checkFields(s string, numbers int, rootOK bool) error {
|
||||||
|
f := strings.Split(s, " ")
|
||||||
|
if len(f) != numbers+1 {
|
||||||
|
return fmt.Errorf("want %d numbers and a target, separated by single spaces", numbers)
|
||||||
|
}
|
||||||
|
for _, n := range f[:numbers] {
|
||||||
|
if n == "" || strings.Trim(n, "0123456789") != "" {
|
||||||
|
return fmt.Errorf("%q is not a number", n)
|
||||||
|
}
|
||||||
|
if _, err := strconv.ParseUint(n, 10, 16); err != nil {
|
||||||
|
return fmt.Errorf("%q is out of range", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if t := f[numbers]; (!rootOK || t != ".") && !validName(t, false) {
|
||||||
|
return errors.New("the target must be an absolute name with trailing dot")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkTXT accepts one or more quoted character-strings separated by single
|
||||||
|
// spaces, each at most 255 bytes long. Inside the quotes only printable
|
||||||
|
// ASCII is allowed, '"' and '\' only escaped, other escapes only as \DDD.
|
||||||
|
func checkTXT(s string) error {
|
||||||
|
i := 0
|
||||||
|
for {
|
||||||
|
if i >= len(s) || s[i] != '"' {
|
||||||
|
return errors.New("want quoted strings separated by single spaces")
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
n := 0
|
||||||
|
for {
|
||||||
|
if i >= len(s) {
|
||||||
|
return errors.New("unterminated string")
|
||||||
|
}
|
||||||
|
c := s[i]
|
||||||
|
if c == '"' {
|
||||||
|
i++
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if c == '\\' {
|
||||||
|
switch {
|
||||||
|
case i+1 < len(s) && (s[i+1] == '"' || s[i+1] == '\\'):
|
||||||
|
i += 2
|
||||||
|
case i+3 < len(s) && isDigit(s[i+1]) && isDigit(s[i+2]) && isDigit(s[i+3]):
|
||||||
|
if v, _ := strconv.Atoi(s[i+1 : i+4]); v > 255 {
|
||||||
|
return errors.New("escape out of range")
|
||||||
|
}
|
||||||
|
i += 4
|
||||||
|
default:
|
||||||
|
return errors.New(`only \", \\ and \DDD escapes are allowed`)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
if n > 255 {
|
||||||
|
return errors.New("string longer than 255 bytes")
|
||||||
|
}
|
||||||
|
if i == len(s) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if s[i] != ' ' {
|
||||||
|
return errors.New("want quoted strings separated by single spaces")
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isDigit(c byte) bool { return c >= '0' && c <= '9' }
|
||||||
|
|
||||||
|
// isNameChar reports whether c may appear in a label: letters, digits,
|
||||||
|
// '-' and '_' (service labels such as _ldap._tcp).
|
||||||
|
func isNameChar(c byte) bool {
|
||||||
|
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || isDigit(c) || c == '-' || c == '_'
|
||||||
|
}
|
||||||
|
|
||||||
|
// validName accepts an absolute domain name with trailing dot made of
|
||||||
|
// labels of letters, digits, '-' and '_' ("*" as the first label only for
|
||||||
|
// owner names).
|
||||||
|
func validName(s string, owner bool) bool {
|
||||||
|
n, ok := strings.CutSuffix(s, ".")
|
||||||
|
if !ok || n == "" || len(s) > 254 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return validLabels(n, owner)
|
||||||
|
}
|
||||||
|
|
||||||
|
// validLabels checks the labels of a name without trailing dot.
|
||||||
|
func validLabels(n string, wildcard bool) bool {
|
||||||
|
labels := strings.Split(n, ".")
|
||||||
|
for i, l := range labels {
|
||||||
|
if l == "" || len(l) > 63 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if l == "*" && wildcard && i == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for j := 0; j < len(l); j++ {
|
||||||
|
if !isNameChar(l[j]) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// zoneUpdate is the work for one zone.
|
||||||
|
type zoneUpdate struct {
|
||||||
|
zone string
|
||||||
|
deletes []dynRecord
|
||||||
|
adds []dynRecord
|
||||||
|
}
|
||||||
|
|
||||||
|
// planUpdates computes the updates from the previous set (may be nil) to
|
||||||
|
// cur. Zones that only the previous set lists lose its records if they are
|
||||||
|
// still dynamic primary zones of the new revision; otherwise BIND no longer
|
||||||
|
// serves them and they are skipped.
|
||||||
|
func planUpdates(cur, prev *dynSet, dynamic map[string]bool) []zoneUpdate {
|
||||||
|
zones := map[string]bool{}
|
||||||
|
if cur != nil {
|
||||||
|
for z := range cur.zones {
|
||||||
|
zones[z] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if prev != nil {
|
||||||
|
for z := range prev.zones {
|
||||||
|
if dynamic[z] {
|
||||||
|
zones[z] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
names := make([]string, 0, len(zones))
|
||||||
|
for z := range zones {
|
||||||
|
names = append(names, z)
|
||||||
|
}
|
||||||
|
slices.Sort(names)
|
||||||
|
var out []zoneUpdate
|
||||||
|
for _, z := range names {
|
||||||
|
u := zoneUpdate{zone: z}
|
||||||
|
keep := map[string]bool{}
|
||||||
|
if cur != nil {
|
||||||
|
u.adds = cur.zones[z]
|
||||||
|
for _, rec := range u.adds {
|
||||||
|
keep[rec.identity()] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if prev != nil {
|
||||||
|
for _, rec := range prev.zones[z] {
|
||||||
|
if !keep[rec.identity()] {
|
||||||
|
u.deletes = append(u.deletes, rec)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(u.adds) > 0 || len(u.deletes) > 0 {
|
||||||
|
out = append(out, u)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateScript renders the nsupdate input for u: deletes first, then adds,
|
||||||
|
// in batches (each with its own server, zone and send lines). Every field
|
||||||
|
// has been validated; a line break would still be refused here.
|
||||||
|
func updateScript(server netip.AddrPort, u zoneUpdate) (string, error) {
|
||||||
|
header := fmt.Sprintf("server %s %d\nzone %s.\n", server.Addr().String(), server.Port(), u.zone)
|
||||||
|
var b, batch strings.Builder
|
||||||
|
count := 0
|
||||||
|
flush := func() {
|
||||||
|
if count == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.WriteString(header)
|
||||||
|
b.WriteString(batch.String())
|
||||||
|
b.WriteString("send\n")
|
||||||
|
batch.Reset()
|
||||||
|
count = 0
|
||||||
|
}
|
||||||
|
add := func(line string) error {
|
||||||
|
if strings.ContainsAny(line, "\n\r\x00") {
|
||||||
|
return errors.New("record contains a line break")
|
||||||
|
}
|
||||||
|
if count >= maxBatchRecords || (count > 0 && batch.Len()+len(line) > maxBatchBytes) {
|
||||||
|
flush()
|
||||||
|
}
|
||||||
|
batch.WriteString(line)
|
||||||
|
batch.WriteByte('\n')
|
||||||
|
count++
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, r := range u.deletes {
|
||||||
|
if err := add(fmt.Sprintf("update delete %s %s %s", r.Name, r.Type, r.Data)); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, r := range u.adds {
|
||||||
|
if err := add(fmt.Sprintf("update add %s %d %s %s", r.Name, r.TTL, r.Type, r.Data)); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush()
|
||||||
|
return b.String(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// retryableUpdateError reports whether nsupdate failed because the zone is
|
||||||
|
// not (yet) loaded or the server did not answer.
|
||||||
|
func retryableUpdateError(out []byte) bool {
|
||||||
|
s := strings.ToLower(string(out))
|
||||||
|
for _, m := range []string{"notauth", "servfail", "communication with", "timed out", "connection refused"} {
|
||||||
|
if strings.Contains(s, m) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyDynamic sends the updates from prev to cur, one nsupdate run per
|
||||||
|
// zone. A failure is returned (Activate then restores the previous files;
|
||||||
|
// the core's rollback re-applies the previous revision's records).
|
||||||
|
func (r *Role) applyDynamic(ctx context.Context, rev core.Revision, cur, prev *dynSet, dynamic map[string]bool) error {
|
||||||
|
if cur == nil {
|
||||||
|
if prev != nil {
|
||||||
|
for z := range prev.zones {
|
||||||
|
if dynamic[z] {
|
||||||
|
r.log.Warn("revision has no update key: managed records of a dynamic zone stay as they are",
|
||||||
|
"revision", rev.Number, "zone", z)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
updates := planUpdates(cur, prev, dynamic)
|
||||||
|
if len(updates) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
server, err := netip.ParseAddrPort(r.cfg.DNSAddress)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("dns.dns_address: %w", err)
|
||||||
|
}
|
||||||
|
deadline := time.Now().Add(r.updateWait)
|
||||||
|
for _, u := range updates {
|
||||||
|
script, err := updateScript(server, u)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("zone %s: %w", u.zone, err)
|
||||||
|
}
|
||||||
|
if err := r.nsupdate(ctx, cur.keyFile, script, deadline); err != nil {
|
||||||
|
return fmt.Errorf("dynamic update of zone %s failed: %w", u.zone, err)
|
||||||
|
}
|
||||||
|
r.log.Info("managed records of a dynamic zone updated", "revision", rev.Number, "zone", u.zone,
|
||||||
|
"records", len(u.adds), "deleted", len(u.deletes))
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// nsupdate runs the script, retrying until deadline while the zone is not
|
||||||
|
// loaded yet. Adds and deletes of exact records are idempotent, so the
|
||||||
|
// whole script can be repeated.
|
||||||
|
func (r *Role) nsupdate(ctx context.Context, keyFile, script string, deadline time.Time) error {
|
||||||
|
for {
|
||||||
|
out, err := r.run.RunInput(ctx, []byte(script), r.cfg.Nsupdate, "-t", nsupdateTimeout, "-k", keyFile)
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !retryableUpdateError(out) || time.Now().Add(r.updateRetry).After(deadline) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
t := time.NewTimer(r.updateRetry)
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
t.Stop()
|
||||||
|
return errors.Join(err, ctx.Err())
|
||||||
|
case <-t.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,670 @@
|
|||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
package dns
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net/netip"
|
||||||
|
"path/filepath"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.beugsiud.de/beug.k/DDI/agent/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
testUpdateKeyName = "ddi-agent-update"
|
||||||
|
testUpdateSecret = "c2VjcmV0LW9mLXRoZS11cGRhdGUta2V5LTEyMzQ1Ng=="
|
||||||
|
)
|
||||||
|
|
||||||
|
// testUpdateKey is a key file as the generator writes it.
|
||||||
|
var testUpdateKey = "// Generated by DDI Suite. Do not edit: the DNS agent uses this key\n" +
|
||||||
|
"// for dynamic updates of the records DDI manages.\n\n" +
|
||||||
|
"key \"" + testUpdateKeyName + "\" {\n algorithm hmac-sha256;\n secret \"" + testUpdateSecret + "\";\n};\n"
|
||||||
|
|
||||||
|
func TestParseUpdateKey(t *testing.T) {
|
||||||
|
valid := map[string]string{
|
||||||
|
"generator": testUpdateKey,
|
||||||
|
"tsig-keygen": "key \"k1\" {\n\talgorithm hmac-sha512;\n\tsecret \"" + testUpdateSecret + "\";\n};\n",
|
||||||
|
"secret first": "# comment\nkey \"k.example\" { secret \"" + testUpdateSecret + "\"; algorithm HMAC-SHA256; };",
|
||||||
|
"one line, no nl": "key \"k\" { algorithm hmac-sha1; secret \"" + testUpdateSecret + "\"; };",
|
||||||
|
}
|
||||||
|
wantNames := map[string]string{"generator": testUpdateKeyName, "tsig-keygen": "k1", "secret first": "k.example", "one line, no nl": "k"}
|
||||||
|
for name, src := range valid {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
got, err := parseUpdateKey([]byte(src))
|
||||||
|
if err != nil || got != wantNames[name] {
|
||||||
|
t.Fatalf("parseUpdateKey = %q, %v", got, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
sec := `secret "` + testUpdateSecret + `";`
|
||||||
|
invalid := map[string]string{
|
||||||
|
"empty": "",
|
||||||
|
"comments only": "// nothing\n",
|
||||||
|
"two keys": `key "a" { algorithm hmac-sha256; ` + sec + ` }; key "b" { algorithm hmac-sha256; ` + sec + ` };`,
|
||||||
|
"no secret": `key "a" { algorithm hmac-sha256; };`,
|
||||||
|
"two secrets": `key "a" { algorithm hmac-sha256; ` + sec + sec + ` };`,
|
||||||
|
"no algorithm": `key "a" { ` + sec + ` };`,
|
||||||
|
"unknown alg": `key "a" { algorithm rsa; ` + sec + ` };`,
|
||||||
|
"bad base64": `key "a" { algorithm hmac-sha256; secret "not base64!"; };`,
|
||||||
|
"unquoted": `key "a" { algorithm hmac-sha256; secret ` + testUpdateSecret + `; };`,
|
||||||
|
"half quoted": `key "a" { algorithm hmac-sha256; secret ` + testUpdateSecret + `"; };`,
|
||||||
|
"unquoted name": `key a { algorithm hmac-sha256; ` + sec + ` };`,
|
||||||
|
"bad name": `key "a b" { algorithm hmac-sha256; ` + sec + ` };`,
|
||||||
|
"extra stmt": `key "a" { algorithm hmac-sha256; ` + sec + ` }; include "/etc/passwd";`,
|
||||||
|
"other clause": `key "a" { algorithm hmac-sha256; ` + sec + ` foo bar; };`,
|
||||||
|
"options": `options { directory "/tmp"; };`,
|
||||||
|
"inline comment": `key "a" { algorithm hmac-sha256; ` + sec + ` // x` + "\n};",
|
||||||
|
"nul": "key \"a\" { algorithm hmac-sha256; " + sec + " };\x00",
|
||||||
|
}
|
||||||
|
for name, src := range invalid {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
_, err := parseUpdateKey([]byte(src))
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected an error")
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), testUpdateSecret) {
|
||||||
|
t.Errorf("error quotes the secret: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// dynJSON renders a dynamic-records.json for the tests.
|
||||||
|
func dynJSON(t *testing.T, key string, zones map[string][]dynRecord) string {
|
||||||
|
t.Helper()
|
||||||
|
f := dynFile{Version: 1, Key: key, Zones: []dynZone{}}
|
||||||
|
names := make([]string, 0, len(zones))
|
||||||
|
for z := range zones {
|
||||||
|
names = append(names, z)
|
||||||
|
}
|
||||||
|
slices.Sort(names)
|
||||||
|
for _, z := range names {
|
||||||
|
recs := zones[z]
|
||||||
|
if recs == nil {
|
||||||
|
recs = []dynRecord{}
|
||||||
|
}
|
||||||
|
f.Zones = append(f.Zones, dynZone{Zone: z, Records: recs})
|
||||||
|
}
|
||||||
|
b, err := json.Marshal(f)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
var allTypes = []dynRecord{
|
||||||
|
{Name: "srv1.ad.example.org.", TTL: 3600, Type: "A", Data: "192.0.2.5"},
|
||||||
|
{Name: "srv1.ad.example.org.", TTL: 3600, Type: "AAAA", Data: "2001:db8::5"},
|
||||||
|
{Name: "5.ad.example.org.", TTL: 300, Type: "PTR", Data: "srv1.ad.example.org."},
|
||||||
|
{Name: "www.ad.example.org.", TTL: 300, Type: "CNAME", Data: "srv1.ad.example.org."},
|
||||||
|
{Name: "ad.example.org.", TTL: 300, Type: "MX", Data: "10 mail.example.org."},
|
||||||
|
{Name: "_dmarc.ad.example.org.", TTL: 300, Type: "TXT", Data: `"v=DMARC1; p=none" "a \"quoted\" \\ \010 x"`},
|
||||||
|
{Name: "_ldap._tcp.dc._msdcs.ad.example.org.", TTL: 600, Type: "SRV", Data: "0 100 389 dc1.ad.example.org."},
|
||||||
|
{Name: "sub.ad.example.org.", TTL: 0, Type: "NS", Data: "ns1.example.org."},
|
||||||
|
{Name: "*.wild.ad.example.org.", TTL: 60, Type: "A", Data: "192.0.2.6"},
|
||||||
|
{Name: "SRV1.AD.example.org.", TTL: 60, Type: "A", Data: "192.0.2.5"}, // duplicate (case)
|
||||||
|
{Name: "null.ad.example.org.", TTL: 60, Type: "MX", Data: "0 ."},
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseDynamicRecords(t *testing.T) {
|
||||||
|
dynamic := map[string]bool{"ad.example.org": true, "other.test": true}
|
||||||
|
src := dynJSON(t, "ddi-agent-update", map[string][]dynRecord{"ad.example.org": allTypes, "other.test": nil})
|
||||||
|
set, err := parseDynamicRecords([]byte(src), dynamic)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if set.key != "ddi-agent-update" || len(set.zones) != 2 || len(set.zones["other.test"]) != 0 {
|
||||||
|
t.Fatalf("set = %+v", set)
|
||||||
|
}
|
||||||
|
if got := len(set.zones["ad.example.org"]); got != len(allTypes)-1 {
|
||||||
|
t.Errorf("%d records, want %d (one duplicate dropped)", got, len(allTypes)-1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The zone may be written with a trailing dot and in upper case.
|
||||||
|
upper := strings.Replace(src, `"zone":"ad.example.org"`, `"zone":"AD.Example.org."`, 1)
|
||||||
|
if _, err := parseDynamicRecords([]byte(upper), dynamic); err != nil {
|
||||||
|
t.Errorf("zone with trailing dot: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseDynamicRecordsRejects(t *testing.T) {
|
||||||
|
dynamic := map[string]bool{"ad.example.org": true}
|
||||||
|
rec := func(name string, ttl int64, typ, data string) string {
|
||||||
|
b, _ := json.Marshal(dynRecord{Name: name, TTL: ttl, Type: typ, Data: data})
|
||||||
|
return `{"version":1,"key":"ddi-agent-update","zones":[{"zone":"ad.example.org","records":[` + string(b) + `]}]}`
|
||||||
|
}
|
||||||
|
const n = "srv1.ad.example.org."
|
||||||
|
cases := map[string]string{
|
||||||
|
"not JSON": `version: 1`,
|
||||||
|
"version 2": `{"version":2,"key":"k","zones":[]}`,
|
||||||
|
"no version": `{"key":"k","zones":[]}`,
|
||||||
|
"unknown field": `{"version":1,"key":"k","zones":[],"extra":true}`,
|
||||||
|
"unknown rec field": `{"version":1,"key":"k","zones":[{"zone":"ad.example.org","records":[{"name":"` + n + `","ttl":1,"type":"A","data":"192.0.2.1","class":"IN"}]}]}`,
|
||||||
|
"trailing data": `{"version":1,"key":"k","zones":[]} {}`,
|
||||||
|
"bad key name": `{"version":1,"key":"k\nsend","zones":[]}`,
|
||||||
|
"empty key name": `{"version":1,"key":"","zones":[]}`,
|
||||||
|
"zone not dynamic": `{"version":1,"key":"k","zones":[{"zone":"example.org","records":[]}]}`,
|
||||||
|
"zone twice": `{"version":1,"key":"k","zones":[{"zone":"ad.example.org","records":[]},{"zone":"ad.example.org.","records":[]}]}`,
|
||||||
|
"zone injection": `{"version":1,"key":"k","zones":[{"zone":"ad.example.org\nupdate delete ad.example.org. NS","records":[]}]}`,
|
||||||
|
"zone bad label": `{"version":1,"key":"k","zones":[{"zone":"ad..example.org","records":[]}]}`,
|
||||||
|
"ttl as string": `{"version":1,"key":"k","zones":[{"zone":"ad.example.org","records":[{"name":"` + n + `","ttl":"1","type":"A","data":"192.0.2.1"}]}]}`,
|
||||||
|
|
||||||
|
"relative name": rec("srv1", 60, "A", "192.0.2.1"),
|
||||||
|
"name outside zone": rec("srv1.example.org.", 60, "A", "192.0.2.1"),
|
||||||
|
"name suffix trick": rec("srv1.bad-ad.example.org.", 60, "A", "192.0.2.1"),
|
||||||
|
"name with newline": rec("srv1.ad.example.org.\nupdate delete ad.example.org. NS", 60, "A", "192.0.2.1"),
|
||||||
|
"name with space": rec("srv 1.ad.example.org.", 60, "A", "192.0.2.1"),
|
||||||
|
"name with semicolon": rec("srv1;.ad.example.org.", 60, "A", "192.0.2.1"),
|
||||||
|
"name with escape": rec(`srv\0461.ad.example.org.`, 60, "A", "192.0.2.1"),
|
||||||
|
"wildcard inside": rec("a.*.ad.example.org.", 60, "A", "192.0.2.1"),
|
||||||
|
"long label": rec(strings.Repeat("a", 64)+".ad.example.org.", 60, "A", "192.0.2.1"),
|
||||||
|
"empty label": rec("a..ad.example.org.", 60, "A", "192.0.2.1"),
|
||||||
|
"negative TTL": rec(n, -1, "A", "192.0.2.1"),
|
||||||
|
"TTL too large": rec(n, 1<<31, "A", "192.0.2.1"),
|
||||||
|
"type ANY": rec(n, 60, "ANY", "192.0.2.1"),
|
||||||
|
"type SOA": rec(n, 60, "SOA", "a. b. 1 2 3 4 5"),
|
||||||
|
"lowercase type": rec(n, 60, "a", "192.0.2.1"),
|
||||||
|
"type with data": rec(n, 60, "A 192.0.2.9", "192.0.2.1"),
|
||||||
|
"empty data": rec(n, 60, "A", ""),
|
||||||
|
"A newline injection": rec(n, 60, "A", "192.0.2.1\nsend\nupdate delete ad.example.org. NS"),
|
||||||
|
"A CR injection": rec(n, 60, "A", "192.0.2.1\rsend"),
|
||||||
|
"A semicolon": rec(n, 60, "A", "192.0.2.1;"),
|
||||||
|
"A with tab": rec(n, 60, "A", "192.0.2.1\t"),
|
||||||
|
"A is IPv6": rec(n, 60, "A", "2001:db8::1"),
|
||||||
|
"A not an address": rec(n, 60, "A", "srv1."),
|
||||||
|
"AAAA is IPv4": rec(n, 60, "AAAA", "192.0.2.1"),
|
||||||
|
"AAAA with zone": rec(n, 60, "AAAA", "fe80::1%eth0"),
|
||||||
|
"PTR relative": rec(n, 60, "PTR", "srv1"),
|
||||||
|
"CNAME two names": rec(n, 60, "CNAME", "a.example.org. b.example.org."),
|
||||||
|
"CNAME root": rec(n, 60, "CNAME", "."),
|
||||||
|
"NS non-ASCII": rec(n, 60, "NS", "nä.example.org."),
|
||||||
|
"MX no preference": rec(n, 60, "MX", "mail.example.org."),
|
||||||
|
"MX out of range": rec(n, 60, "MX", "70000 mail.example.org."),
|
||||||
|
"MX signed": rec(n, 60, "MX", "+10 mail.example.org."),
|
||||||
|
"MX double space": rec(n, 60, "MX", "10 mail.example.org."),
|
||||||
|
"MX extra field": rec(n, 60, "MX", "10 mail.example.org. x"),
|
||||||
|
"SRV too few": rec(n, 60, "SRV", "0 100 dc1.ad.example.org."),
|
||||||
|
"SRV relative": rec(n, 60, "SRV", "0 100 389 dc1"),
|
||||||
|
"TXT unquoted": rec(n, 60, "TXT", "v=spf1 -all"),
|
||||||
|
"TXT unterminated": rec(n, 60, "TXT", `"abc`),
|
||||||
|
"TXT trailing": rec(n, 60, "TXT", `"abc" x`),
|
||||||
|
"TXT trailing space": rec(n, 60, "TXT", `"abc" `),
|
||||||
|
"TXT newline": rec(n, 60, "TXT", "\"abc\nsend\""),
|
||||||
|
"TXT raw quote escape": rec(n, 60, "TXT", `"abc\"`),
|
||||||
|
"TXT letter escape": rec(n, 60, "TXT", `"a\nb"`),
|
||||||
|
"TXT short escape": rec(n, 60, "TXT", `"a\01"`),
|
||||||
|
"TXT escape > 255": rec(n, 60, "TXT", `"a\300"`),
|
||||||
|
"TXT too long": rec(n, 60, "TXT", `"`+strings.Repeat("a", 256)+`"`),
|
||||||
|
"TXT after string": rec(n, 60, "TXT", `"a";update delete ad.example.org. NS`),
|
||||||
|
"data too long": rec(n, 60, "TXT", strings.Repeat(`"`+strings.Repeat("a", 200)+`" `, 50)+`"x"`),
|
||||||
|
}
|
||||||
|
for name, src := range cases {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
if _, err := parseDynamicRecords([]byte(src), dynamic); err == nil {
|
||||||
|
t.Fatal("expected an error")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUpdateScript(t *testing.T) {
|
||||||
|
u := zoneUpdate{
|
||||||
|
zone: "ad.example.org",
|
||||||
|
deletes: []dynRecord{{Name: "old.ad.example.org.", TTL: 60, Type: "A", Data: "192.0.2.9"}},
|
||||||
|
adds: []dynRecord{
|
||||||
|
{Name: "srv1.ad.example.org.", TTL: 3600, Type: "A", Data: "192.0.2.5"},
|
||||||
|
{Name: "_dmarc.ad.example.org.", TTL: 300, Type: "TXT", Data: `"v=DMARC1; p=none"`},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
got, err := updateScript(netip.MustParseAddrPort("127.0.0.1:53"), u)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := "server 127.0.0.1 53\nzone ad.example.org.\n" +
|
||||||
|
"update delete old.ad.example.org. A 192.0.2.9\n" +
|
||||||
|
"update add srv1.ad.example.org. 3600 A 192.0.2.5\n" +
|
||||||
|
"update add _dmarc.ad.example.org. 300 TXT \"v=DMARC1; p=none\"\n" +
|
||||||
|
"send\n"
|
||||||
|
if got != want {
|
||||||
|
t.Errorf("script =\n%s\nwant\n%s", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
got, err = updateScript(netip.MustParseAddrPort("[::1]:5353"), zoneUpdate{zone: "z.test", adds: u.adds[:1]})
|
||||||
|
if err != nil || !strings.HasPrefix(got, "server ::1 5353\nzone z.test.\n") {
|
||||||
|
t.Errorf("IPv6 server: %q, %v", got, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Defense in depth: a line break never reaches the script.
|
||||||
|
bad := zoneUpdate{zone: "z.test", adds: []dynRecord{{Name: "a.z.test.", TTL: 1, Type: "A", Data: "192.0.2.1\nsend"}}}
|
||||||
|
if _, err := updateScript(netip.MustParseAddrPort("127.0.0.1:53"), bad); err == nil {
|
||||||
|
t.Error("line break accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUpdateScriptBatches(t *testing.T) {
|
||||||
|
var u zoneUpdate
|
||||||
|
u.zone = "big.test"
|
||||||
|
for i := range 1200 {
|
||||||
|
u.adds = append(u.adds, dynRecord{Name: fmt.Sprintf("h%d.big.test.", i), TTL: 60, Type: "A", Data: "192.0.2.1"})
|
||||||
|
}
|
||||||
|
u.deletes = []dynRecord{{Name: "gone.big.test.", TTL: 60, Type: "A", Data: "192.0.2.2"}}
|
||||||
|
got, err := updateScript(netip.MustParseAddrPort("127.0.0.1:53"), u)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
batches := strings.Split(strings.TrimSuffix(got, "send\n"), "send\n")
|
||||||
|
if len(batches) != 3 {
|
||||||
|
t.Fatalf("%d batches, want 3", len(batches))
|
||||||
|
}
|
||||||
|
total := 0
|
||||||
|
for i, b := range batches {
|
||||||
|
if !strings.HasPrefix(b, "server 127.0.0.1 53\nzone big.test.\n") {
|
||||||
|
t.Errorf("batch %d lacks server and zone: %.60q", i, b)
|
||||||
|
}
|
||||||
|
n := strings.Count(b, "\nupdate ")
|
||||||
|
if n > maxBatchRecords {
|
||||||
|
t.Errorf("batch %d has %d records", i, n)
|
||||||
|
}
|
||||||
|
total += n
|
||||||
|
}
|
||||||
|
if total != 1201 || !strings.Contains(batches[0], "update delete gone.big.test. A 192.0.2.2\n") {
|
||||||
|
t.Errorf("%d records in total; first batch starts %.120q", total, batches[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Long TXT records are cut by size, not count.
|
||||||
|
u = zoneUpdate{zone: "big.test"}
|
||||||
|
txt := `"` + strings.Repeat("x", 250) + `"`
|
||||||
|
for i := range 300 {
|
||||||
|
u.adds = append(u.adds, dynRecord{Name: fmt.Sprintf("t%d.big.test.", i), TTL: 60, Type: "TXT", Data: txt})
|
||||||
|
}
|
||||||
|
got, _ = updateScript(netip.MustParseAddrPort("127.0.0.1:53"), u)
|
||||||
|
for i, b := range strings.Split(got, "send\n") {
|
||||||
|
if len(b) > maxBatchBytes+512 {
|
||||||
|
t.Errorf("batch %d has %d bytes", i, len(b))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPlanUpdates(t *testing.T) {
|
||||||
|
a := func(name, ip string) dynRecord {
|
||||||
|
return dynRecord{Name: name + ".z.test.", TTL: 60, Type: "A", Data: ip}
|
||||||
|
}
|
||||||
|
prev := &dynSet{zones: map[string][]dynRecord{
|
||||||
|
"z.test": {a("one", "192.0.2.1"), a("two", "192.0.2.2"), a("Three", "192.0.2.3")},
|
||||||
|
"gone.test": {{Name: "x.gone.test.", TTL: 60, Type: "A", Data: "192.0.2.4"}},
|
||||||
|
"left.test": {{Name: "x.left.test.", TTL: 60, Type: "A", Data: "192.0.2.5"}},
|
||||||
|
}}
|
||||||
|
cur := &dynSet{zones: map[string][]dynRecord{
|
||||||
|
"z.test": {a("one", "192.0.2.1"), a("three", "192.0.2.3"), a("four", "192.0.2.4")},
|
||||||
|
"new.test": {{Name: "y.new.test.", TTL: 60, Type: "A", Data: "192.0.2.6"}},
|
||||||
|
}}
|
||||||
|
// gone.test is still a dynamic primary zone, left.test is not.
|
||||||
|
dynamic := map[string]bool{"z.test": true, "new.test": true, "gone.test": true}
|
||||||
|
got := planUpdates(cur, prev, dynamic)
|
||||||
|
if len(got) != 3 || got[0].zone != "gone.test" || got[1].zone != "new.test" || got[2].zone != "z.test" {
|
||||||
|
t.Fatalf("updates = %+v", got)
|
||||||
|
}
|
||||||
|
if len(got[0].adds) != 0 || len(got[0].deletes) != 1 {
|
||||||
|
t.Errorf("gone.test: %+v", got[0])
|
||||||
|
}
|
||||||
|
if len(got[1].adds) != 1 || len(got[1].deletes) != 0 {
|
||||||
|
t.Errorf("new.test: %+v", got[1])
|
||||||
|
}
|
||||||
|
// "Three" equals "three" (names are case-insensitive): only "two" goes.
|
||||||
|
if len(got[2].adds) != 3 || len(got[2].deletes) != 1 || got[2].deletes[0].Name != "two.z.test." {
|
||||||
|
t.Errorf("z.test: %+v", got[2])
|
||||||
|
}
|
||||||
|
|
||||||
|
if got := planUpdates(cur, nil, dynamic); len(got) != 2 {
|
||||||
|
t.Errorf("first revision: %+v", got)
|
||||||
|
}
|
||||||
|
empty := &dynSet{zones: map[string][]dynRecord{}}
|
||||||
|
if got := planUpdates(empty, empty, dynamic); len(got) != 0 {
|
||||||
|
t.Errorf("nothing to do: %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRecordIdentity(t *testing.T) {
|
||||||
|
same := [][2]dynRecord{
|
||||||
|
{{Name: "A.z.", Type: "AAAA", Data: "2001:DB8:0::1"}, {Name: "a.z.", Type: "AAAA", Data: "2001:db8::1"}},
|
||||||
|
{{Name: "a.z.", Type: "CNAME", Data: "B.z."}, {Name: "a.z.", Type: "CNAME", Data: "b.z."}},
|
||||||
|
}
|
||||||
|
for _, p := range same {
|
||||||
|
if p[0].identity() != p[1].identity() {
|
||||||
|
t.Errorf("%+v and %+v differ", p[0], p[1])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
txt1 := dynRecord{Name: "a.z.", Type: "TXT", Data: `"A"`}
|
||||||
|
txt2 := dynRecord{Name: "a.z.", Type: "TXT", Data: `"a"`}
|
||||||
|
if txt1.identity() == txt2.identity() {
|
||||||
|
t.Error("TXT data must compare case-sensitively")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRetryableUpdateError(t *testing.T) {
|
||||||
|
for out, want := range map[string]bool{
|
||||||
|
"update failed: NOTAUTH": true,
|
||||||
|
"update failed: SERVFAIL": true,
|
||||||
|
"; Communication with 127.0.0.1#53 failed: timed out": true,
|
||||||
|
"couldn't get address for 'x': not found": false,
|
||||||
|
"update failed: REFUSED": false,
|
||||||
|
"update failed: NOTZONE": false,
|
||||||
|
} {
|
||||||
|
if got := retryableUpdateError([]byte(out)); got != want {
|
||||||
|
t.Errorf("%q: %v, want %v", out, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Role tests (Unix paths) ---
|
||||||
|
|
||||||
|
const updateKeysConf = "key \"xfer\" {\n algorithm hmac-sha256;\n secret \"eGZlcg==\";\n};\n" +
|
||||||
|
"key \"" + testUpdateKeyName + "\" {\n algorithm hmac-sha256;\n secret \"" + testUpdateSecret + "\";\n};\n"
|
||||||
|
|
||||||
|
// dynRevision writes a revision with the dynamic zones in zones and the
|
||||||
|
// update files for records (nil records: no update files).
|
||||||
|
func (e *env) dynRevision(n uint64, zones []zone, records map[string][]dynRecord) revisionInfo {
|
||||||
|
e.t.Helper()
|
||||||
|
files := map[string]string{
|
||||||
|
confFile: confFor(e.zoneDir, zones),
|
||||||
|
optionsFile: "recursion no;\n",
|
||||||
|
keysFile: updateKeysConf,
|
||||||
|
}
|
||||||
|
createOnly := map[string]bool{}
|
||||||
|
for _, z := range zones {
|
||||||
|
p := zonesPrefix + zonePrefix + z.name
|
||||||
|
files[p] = zoneFile(z.name, n, z.extra)
|
||||||
|
createOnly[p] = z.dynamic
|
||||||
|
}
|
||||||
|
if records != nil {
|
||||||
|
files[updateKeyFile] = testUpdateKey
|
||||||
|
files[dynRecordsFile] = dynJSON(e.t, testUpdateKeyName, records)
|
||||||
|
}
|
||||||
|
r := writeRevision(e.t, n, files, createOnly)
|
||||||
|
return revisionInfo{Revision: r, keyFile: filepath.Join(r.Dir, updateKeyFile)}
|
||||||
|
}
|
||||||
|
|
||||||
|
type revisionInfo struct {
|
||||||
|
Revision core.Revision
|
||||||
|
keyFile string
|
||||||
|
}
|
||||||
|
|
||||||
|
var adZones = []zone{{name: "office.test"}, {name: "ad.office.test", dynamic: true}}
|
||||||
|
|
||||||
|
func adA(name, ip string) dynRecord {
|
||||||
|
return dynRecord{Name: name + ".ad.office.test.", TTL: 3600, Type: "A", Data: ip}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *env) nsupdateCalls() []string {
|
||||||
|
var out []string
|
||||||
|
for _, c := range e.run.Calls() {
|
||||||
|
if strings.HasPrefix(c, "nsupdate ") {
|
||||||
|
out = append(out, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidateDynamicRecords(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
e := newEnv(t)
|
||||||
|
recs := map[string][]dynRecord{"ad.office.test": {adA("srv1", "192.0.2.5")}}
|
||||||
|
if err := e.role.Validate(ctx, e.dynRevision(1, adZones, recs).Revision); err != nil {
|
||||||
|
t.Fatalf("valid revision rejected: %v", err)
|
||||||
|
}
|
||||||
|
if got := e.nsupdateCalls(); len(got) != 0 {
|
||||||
|
t.Errorf("Validate ran nsupdate: %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
for name, c := range map[string]struct {
|
||||||
|
mutate func(files map[string]string)
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
"only the key file": {func(f map[string]string) { delete(f, dynRecordsFile) }, "both"},
|
||||||
|
"only the records file": {func(f map[string]string) { delete(f, updateKeyFile) }, "both"},
|
||||||
|
"key name mismatch": {func(f map[string]string) {
|
||||||
|
f[updateKeyFile] = strings.Replace(f[updateKeyFile], testUpdateKeyName, "other-key", 1)
|
||||||
|
}, `holds the key "other-key"`},
|
||||||
|
"key unknown to named": {func(f map[string]string) {
|
||||||
|
f[keysFile] = "key \"xfer\" {\n algorithm hmac-sha256;\n secret \"eGZlcg==\";\n};\n"
|
||||||
|
}, "does not define the update key"},
|
||||||
|
"no keys file": {func(f map[string]string) { delete(f, keysFile) }, "which the revision lacks"},
|
||||||
|
"managed zone": {func(f map[string]string) {
|
||||||
|
f[dynRecordsFile] = dynJSON(t, testUpdateKeyName, map[string][]dynRecord{
|
||||||
|
"office.test": {{Name: "a.office.test.", TTL: 1, Type: "A", Data: "192.0.2.1"}}})
|
||||||
|
}, "not a dynamic primary zone"},
|
||||||
|
"injection": {func(f map[string]string) {
|
||||||
|
f[dynRecordsFile] = dynJSON(t, testUpdateKeyName, map[string][]dynRecord{
|
||||||
|
"ad.office.test": {adA("srv1", "192.0.2.5\nupdate delete ad.office.test. ANY")}})
|
||||||
|
}, "control or non-ASCII character"},
|
||||||
|
"bad key file": {func(f map[string]string) {
|
||||||
|
f[updateKeyFile] = "key \"" + testUpdateKeyName + "\" { algorithm hmac-sha256; };"
|
||||||
|
}, updateKeyFile},
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
files := map[string]string{
|
||||||
|
confFile: confFor(e.zoneDir, adZones),
|
||||||
|
optionsFile: "recursion no;\n",
|
||||||
|
keysFile: updateKeysConf,
|
||||||
|
updateKeyFile: testUpdateKey,
|
||||||
|
dynRecordsFile: dynJSON(t, testUpdateKeyName, recs),
|
||||||
|
}
|
||||||
|
createOnly := map[string]bool{}
|
||||||
|
for _, z := range adZones {
|
||||||
|
p := zonesPrefix + zonePrefix + z.name
|
||||||
|
files[p] = zoneFile(z.name, 2, "")
|
||||||
|
createOnly[p] = z.dynamic
|
||||||
|
}
|
||||||
|
c.mutate(files)
|
||||||
|
rev := writeRevision(t, 2, files, createOnly)
|
||||||
|
e.run.Reset()
|
||||||
|
err := e.role.Validate(ctx, rev)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), c.want) {
|
||||||
|
t.Fatalf("err = %v, want it to contain %q", err, c.want)
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), testUpdateSecret) {
|
||||||
|
t.Errorf("error quotes the secret: %v", err)
|
||||||
|
}
|
||||||
|
if e.run.Calls() != nil {
|
||||||
|
t.Errorf("programs ran for an invalid revision: %v", e.run.Calls())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestActivateAppliesDynamicRecords(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
e := newEnv(t)
|
||||||
|
|
||||||
|
// Revision 1: add only, after the reload; the update files stay in the
|
||||||
|
// revision directory.
|
||||||
|
recs1 := map[string][]dynRecord{"ad.office.test": {adA("srv1", "192.0.2.5"), adA("srv2", "192.0.2.6")}}
|
||||||
|
rev1 := e.dynRevision(1, adZones, recs1)
|
||||||
|
if err := e.role.Activate(ctx, rev1.Revision, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
calls := e.run.Calls()
|
||||||
|
wantCall := "nsupdate -t 30 -k " + rev1.keyFile
|
||||||
|
if len(calls) != 4 || calls[2] != "rndc -k /etc/bind/rndc.key reload" || calls[3] != wantCall {
|
||||||
|
t.Fatalf("calls = %v", calls)
|
||||||
|
}
|
||||||
|
want1 := "server 127.0.0.1 53\nzone ad.office.test.\n" +
|
||||||
|
"update add srv1.ad.office.test. 3600 A 192.0.2.5\nupdate add srv2.ad.office.test. 3600 A 192.0.2.6\nsend\n"
|
||||||
|
if in := e.run.Inputs(); len(in) != 1 || in[0] != want1 {
|
||||||
|
t.Fatalf("inputs = %q", in)
|
||||||
|
}
|
||||||
|
for _, f := range []string{updateKeyFile, dynRecordsFile} {
|
||||||
|
if exists(filepath.Join(e.confDir, f)) {
|
||||||
|
t.Errorf("%s was installed into conf_dir", f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revision 2 removes srv2 and adds srv3: exactly srv2 is deleted.
|
||||||
|
recs2 := map[string][]dynRecord{"ad.office.test": {adA("srv1", "192.0.2.5"), adA("srv3", "192.0.2.7")}}
|
||||||
|
rev2 := e.dynRevision(2, adZones, recs2)
|
||||||
|
e.run.Reset()
|
||||||
|
if err := e.role.Activate(ctx, rev2.Revision, &rev1.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want2 := "server 127.0.0.1 53\nzone ad.office.test.\nupdate delete srv2.ad.office.test. A 192.0.2.6\n" +
|
||||||
|
"update add srv1.ad.office.test. 3600 A 192.0.2.5\nupdate add srv3.ad.office.test. 3600 A 192.0.2.7\nsend\n"
|
||||||
|
if in := e.run.Inputs(); len(in) != 1 || in[0] != want2 {
|
||||||
|
t.Fatalf("inputs = %q", in)
|
||||||
|
}
|
||||||
|
if got := e.nsupdateCalls(); len(got) != 1 || got[0] != "nsupdate -t 30 -k "+rev2.keyFile {
|
||||||
|
t.Errorf("nsupdate must use the new revision's key: %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revision 3 lists the zone without records: all managed ones go.
|
||||||
|
rev3 := e.dynRevision(3, adZones, map[string][]dynRecord{"ad.office.test": nil})
|
||||||
|
e.run.Reset()
|
||||||
|
if err := e.role.Activate(ctx, rev3.Revision, &rev2.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want3 := "server 127.0.0.1 53\nzone ad.office.test.\nupdate delete srv1.ad.office.test. A 192.0.2.5\n" +
|
||||||
|
"update delete srv3.ad.office.test. A 192.0.2.7\nsend\n"
|
||||||
|
if in := e.run.Inputs(); len(in) != 1 || in[0] != want3 {
|
||||||
|
t.Fatalf("inputs = %q", in)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revision 4 drops the dynamic zone: BIND no longer serves it, nothing
|
||||||
|
// is sent.
|
||||||
|
rev4 := e.dynRevision(4, adZones[:1], nil)
|
||||||
|
e.run.Reset()
|
||||||
|
if err := e.role.Activate(ctx, rev4.Revision, &rev2.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := e.nsupdateCalls(); len(got) != 0 {
|
||||||
|
t.Errorf("nsupdate for a dropped zone: %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unchanged revision: everything is added again (idempotent), nothing
|
||||||
|
// deleted.
|
||||||
|
e.run.Reset()
|
||||||
|
if err := e.role.Activate(ctx, rev2.Revision, &rev2.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if in := e.run.Inputs(); len(in) != 1 || strings.Contains(in[0], "delete") {
|
||||||
|
t.Errorf("inputs = %q", in)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestActivateDynamicWithoutPreviousFiles(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
e := newEnv(t)
|
||||||
|
// The previous revision predates ADR 0026; its zone file is BIND's.
|
||||||
|
rev1 := e.dynRevision(1, adZones, nil)
|
||||||
|
if err := e.role.Activate(ctx, rev1.Revision, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(e.nsupdateCalls()) != 0 {
|
||||||
|
t.Fatalf("nsupdate without update files: %v", e.run.Calls())
|
||||||
|
}
|
||||||
|
rev2 := e.dynRevision(2, adZones, map[string][]dynRecord{"ad.office.test": {adA("srv1", "192.0.2.5")}})
|
||||||
|
e.run.Reset()
|
||||||
|
if err := e.role.Activate(ctx, rev2.Revision, &rev1.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if in := e.run.Inputs(); len(in) != 1 || strings.Contains(in[0], "delete") || !strings.Contains(in[0], "update add srv1") {
|
||||||
|
t.Errorf("inputs = %q", in)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestActivateDynamicFailureRestores(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
e := newEnv(t)
|
||||||
|
rev1 := e.dynRevision(1, adZones, map[string][]dynRecord{"ad.office.test": {adA("srv1", "192.0.2.5")}})
|
||||||
|
if err := e.role.Activate(ctx, rev1.Revision, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
before := snapshot(t, e)
|
||||||
|
|
||||||
|
zones2 := []zone{{name: "office.test", extra: "www IN A 192.0.2.10\n"}, {name: "ad.office.test", dynamic: true}}
|
||||||
|
rev2 := e.dynRevision(2, zones2, map[string][]dynRecord{"ad.office.test": {adA("srv2", "192.0.2.6")}})
|
||||||
|
e.run.Reset()
|
||||||
|
e.run.fnInput = func(string, string, []string) ([]byte, error) {
|
||||||
|
return []byte("update failed: REFUSED"), errors.New("exit status 2")
|
||||||
|
}
|
||||||
|
err := e.role.Activate(ctx, rev2.Revision, &rev1.Revision)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "REFUSED") || !strings.Contains(err.Error(), "ad.office.test") {
|
||||||
|
t.Fatalf("err = %v", err)
|
||||||
|
}
|
||||||
|
if strings.Contains(err.Error(), testUpdateSecret) {
|
||||||
|
t.Errorf("error quotes the secret: %v", err)
|
||||||
|
}
|
||||||
|
if got := snapshot(t, e); !mapsEqual(got, before) {
|
||||||
|
t.Errorf("files not restored")
|
||||||
|
}
|
||||||
|
calls := e.run.Calls()
|
||||||
|
// REFUSED is final: no retry; then BIND is reloaded with the old files.
|
||||||
|
if len(e.nsupdateCalls()) != 1 || len(calls) != 6 || calls[4] != "rndc -k /etc/bind/rndc.key reconfig" {
|
||||||
|
t.Errorf("calls = %v", calls)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The core's rollback activates revision 1 again with revision 2 as
|
||||||
|
// previous: srv2 is deleted, srv1 added.
|
||||||
|
e.run.fnInput = nil
|
||||||
|
e.run.Reset()
|
||||||
|
if err := e.role.Activate(ctx, rev1.Revision, &rev2.Revision); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := "server 127.0.0.1 53\nzone ad.office.test.\nupdate delete srv2.ad.office.test. A 192.0.2.6\n" +
|
||||||
|
"update add srv1.ad.office.test. 3600 A 192.0.2.5\nsend\n"
|
||||||
|
if in := e.run.Inputs(); len(in) != 1 || in[0] != want {
|
||||||
|
t.Errorf("rollback inputs = %q", in)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestActivateDynamicRetriesWhileZoneLoads(t *testing.T) {
|
||||||
|
ctx := context.Background()
|
||||||
|
e := newEnv(t)
|
||||||
|
e.role.updateRetry = time.Millisecond
|
||||||
|
attempts := 0
|
||||||
|
e.run.fnInput = func(string, string, []string) ([]byte, error) {
|
||||||
|
attempts++
|
||||||
|
if attempts < 3 {
|
||||||
|
return []byte("update failed: NOTAUTH"), errors.New("exit status 2")
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
rev := e.dynRevision(1, adZones, map[string][]dynRecord{"ad.office.test": {adA("srv1", "192.0.2.5")}})
|
||||||
|
if err := e.role.Activate(ctx, rev.Revision, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if attempts != 3 {
|
||||||
|
t.Errorf("%d attempts, want 3", attempts)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A zone that never loads fails after updateWait.
|
||||||
|
e.role.updateWait = 30 * time.Millisecond
|
||||||
|
e.run.fnInput = func(string, string, []string) ([]byte, error) {
|
||||||
|
return []byte("update failed: SERVFAIL"), errors.New("exit status 2")
|
||||||
|
}
|
||||||
|
e.run.Reset()
|
||||||
|
start := time.Now()
|
||||||
|
err := e.role.Activate(ctx, rev.Revision, &rev.Revision)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "SERVFAIL") {
|
||||||
|
t.Fatalf("err = %v", err)
|
||||||
|
}
|
||||||
|
if n := len(e.nsupdateCalls()); n < 2 || time.Since(start) > 5*time.Second {
|
||||||
|
t.Errorf("%d attempts in %s", n, time.Since(start))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewDecodesNsupdate(t *testing.T) {
|
||||||
|
if DefaultConfig().Nsupdate != "nsupdate" {
|
||||||
|
t.Error("default nsupdate program")
|
||||||
|
}
|
||||||
|
cfg := DefaultConfig()
|
||||||
|
cfg.Nsupdate = ""
|
||||||
|
if err := cfg.Validate(); err == nil || !strings.Contains(err.Error(), "dns.nsupdate") {
|
||||||
|
t.Errorf("empty nsupdate accepted: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
+63
-18
@@ -20,9 +20,15 @@ const maxParallelQueries = 8
|
|||||||
// revision number (the generator writes the revision as SOA serial).
|
// revision number (the generator writes the revision as SOA serial).
|
||||||
// Dynamic zones are not compared: BIND increments their serial on updates.
|
// Dynamic zones are not compared: BIND increments their serial on updates.
|
||||||
//
|
//
|
||||||
// State: Failed if rndc status fails or no zone serves the expected
|
// Secondary zones are queried too, any serial counts as loaded. They do not
|
||||||
// serial; Degraded if only some zones do or rndc status reports that the
|
// change the state: right after an activation a secondary zone may still
|
||||||
// last reload failed or is still in progress; OK otherwise.
|
// wait for its first transfer from a primary that has not got the revision
|
||||||
|
// yet, which must not roll the revision back. A zone that does not answer
|
||||||
|
// yet is reported as a degraded check "secondary zone <name>".
|
||||||
|
//
|
||||||
|
// State: Failed if rndc status fails or no managed zone serves the expected
|
||||||
|
// serial; Degraded if only some do or rndc status reports that the last
|
||||||
|
// reload failed or is still in progress; OK otherwise.
|
||||||
func (r *Role) Health(ctx context.Context, expected *core.Revision) core.Health {
|
func (r *Role) Health(ctx context.Context, expected *core.Revision) core.Health {
|
||||||
var h core.Health
|
var h core.Health
|
||||||
status := core.HealthCheck{Name: "rndc status", State: core.HealthOK}
|
status := core.HealthCheck{Name: "rndc status", State: core.HealthOK}
|
||||||
@@ -49,6 +55,12 @@ func (r *Role) Health(ctx context.Context, expected *core.Revision) core.Health
|
|||||||
}
|
}
|
||||||
zoneChecks := r.checkZones(ctx, zones, expected)
|
zoneChecks := r.checkZones(ctx, zones, expected)
|
||||||
h.Checks = append(h.Checks, zoneChecks...)
|
h.Checks = append(h.Checks, zoneChecks...)
|
||||||
|
var secondaries []string
|
||||||
|
if expected != nil {
|
||||||
|
secondaries = r.secondaryZones(*expected)
|
||||||
|
}
|
||||||
|
secondaryChecks := r.checkSecondaries(ctx, secondaries)
|
||||||
|
h.Checks = append(h.Checks, secondaryChecks...)
|
||||||
|
|
||||||
good := 0
|
good := 0
|
||||||
for _, c := range zoneChecks {
|
for _, c := range zoneChecks {
|
||||||
@@ -56,6 +68,12 @@ func (r *Role) Health(ctx context.Context, expected *core.Revision) core.Health
|
|||||||
good++
|
good++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
loaded := 0
|
||||||
|
for _, c := range secondaryChecks {
|
||||||
|
if c.State == core.HealthOK {
|
||||||
|
loaded++
|
||||||
|
}
|
||||||
|
}
|
||||||
switch {
|
switch {
|
||||||
case status.State == core.HealthFailed:
|
case status.State == core.HealthFailed:
|
||||||
h.State = core.HealthFailed
|
h.State = core.HealthFailed
|
||||||
@@ -76,15 +94,54 @@ func (r *Role) Health(ctx context.Context, expected *core.Revision) core.Health
|
|||||||
h.Message += fmt.Sprintf("; %d zones serve serial %d", len(zones), uint32(expected.Number)) //nolint:gosec // see above
|
h.Message += fmt.Sprintf("; %d zones serve serial %d", len(zones), uint32(expected.Number)) //nolint:gosec // see above
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if len(secondaries) > 0 && h.State != core.HealthFailed {
|
||||||
|
h.Message += fmt.Sprintf("; %d of %d secondary zones loaded", loaded, len(secondaries))
|
||||||
|
}
|
||||||
return h
|
return h
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// checkSecondaries queries the SOA of every secondary zone. A zone that
|
||||||
|
// does not answer authoritatively yet gets a degraded check; it does not
|
||||||
|
// count for the overall state (see Health).
|
||||||
|
func (r *Role) checkSecondaries(ctx context.Context, zones []string) []core.HealthCheck {
|
||||||
|
return r.querySOAs(ctx, zones, func(z string, serial uint32, err error) core.HealthCheck {
|
||||||
|
c := core.HealthCheck{Name: "secondary zone " + z, State: core.HealthOK, Message: fmt.Sprintf("serial %d", serial)}
|
||||||
|
if err != nil {
|
||||||
|
c.State = core.HealthDegraded
|
||||||
|
c.Message = "not loaded yet, waiting for a zone transfer (SOA query: " + err.Error() + ")"
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkZones queries the SOA of every managed zone, whose serial must be
|
||||||
|
// the revision number.
|
||||||
func (r *Role) checkZones(ctx context.Context, zones []string, expected *core.Revision) []core.HealthCheck {
|
func (r *Role) checkZones(ctx context.Context, zones []string, expected *core.Revision) []core.HealthCheck {
|
||||||
checks := make([]core.HealthCheck, len(zones))
|
|
||||||
if len(zones) == 0 {
|
if len(zones) == 0 {
|
||||||
return checks
|
return make([]core.HealthCheck, 0)
|
||||||
}
|
}
|
||||||
want := uint32(expected.Number) //nolint:gosec // serials are revision numbers < 2^32 (ADR 0021)
|
want := uint32(expected.Number) //nolint:gosec // serials are revision numbers < 2^32 (ADR 0021)
|
||||||
|
return r.querySOAs(ctx, zones, func(z string, serial uint32, err error) core.HealthCheck {
|
||||||
|
c := core.HealthCheck{Name: "zone " + z}
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
c.State = core.HealthFailed
|
||||||
|
c.Message = "SOA query: " + err.Error()
|
||||||
|
case serial != want:
|
||||||
|
c.State = core.HealthFailed
|
||||||
|
c.Message = fmt.Sprintf("serial %d, expected %d", serial, want)
|
||||||
|
default:
|
||||||
|
c.State = core.HealthOK
|
||||||
|
c.Message = fmt.Sprintf("serial %d", serial)
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// querySOAs queries the SOA of every zone in parallel (bounded) and turns
|
||||||
|
// each answer into a check with eval.
|
||||||
|
func (r *Role) querySOAs(ctx context.Context, zones []string, eval func(zone string, serial uint32, err error) core.HealthCheck) []core.HealthCheck {
|
||||||
|
checks := make([]core.HealthCheck, len(zones))
|
||||||
sem := make(chan struct{}, maxParallelQueries)
|
sem := make(chan struct{}, maxParallelQueries)
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
for i, z := range zones {
|
for i, z := range zones {
|
||||||
@@ -92,20 +149,8 @@ func (r *Role) checkZones(ctx context.Context, zones []string, expected *core.Re
|
|||||||
sem <- struct{}{}
|
sem <- struct{}{}
|
||||||
go func() {
|
go func() {
|
||||||
defer func() { <-sem; wg.Done() }()
|
defer func() { <-sem; wg.Done() }()
|
||||||
c := core.HealthCheck{Name: "zone " + z}
|
|
||||||
serial, err := querySOA(ctx, r.dial, r.cfg.DNSAddress, z)
|
serial, err := querySOA(ctx, r.dial, r.cfg.DNSAddress, z)
|
||||||
switch {
|
checks[i] = eval(z, serial, err)
|
||||||
case err != nil:
|
|
||||||
c.State = core.HealthFailed
|
|
||||||
c.Message = "SOA query: " + err.Error()
|
|
||||||
case serial != want:
|
|
||||||
c.State = core.HealthFailed
|
|
||||||
c.Message = fmt.Sprintf("serial %d, expected %d", serial, want)
|
|
||||||
default:
|
|
||||||
c.State = core.HealthOK
|
|
||||||
c.Message = fmt.Sprintf("serial %d", serial)
|
|
||||||
}
|
|
||||||
checks[i] = c
|
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
|
|||||||
@@ -218,6 +218,49 @@ func TestHealthStates(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestHealthSecondaryZones(t *testing.T) {
|
||||||
|
e, f := healthEnv(t)
|
||||||
|
rev := e.revisionWithKeys(7, clusterZones, testKeys)
|
||||||
|
f.set("office.test", 7)
|
||||||
|
f.set("remote.test", 3) // any serial: the primary decides
|
||||||
|
|
||||||
|
// 2.0.192.in-addr.arpa has not been transferred yet: reported, but the
|
||||||
|
// state stays OK, so the revision is not rolled back.
|
||||||
|
h := e.role.Health(context.Background(), &rev)
|
||||||
|
if h.State != core.HealthOK || !strings.Contains(h.Message, "1 of 2 secondary zones loaded") {
|
||||||
|
t.Fatalf("health = %+v", h)
|
||||||
|
}
|
||||||
|
checks := map[string]core.HealthCheck{}
|
||||||
|
for _, c := range h.Checks {
|
||||||
|
checks[c.Name] = c
|
||||||
|
}
|
||||||
|
if c := checks["secondary zone remote.test"]; c.State != core.HealthOK || c.Message != "serial 3" {
|
||||||
|
t.Errorf("loaded secondary: %+v", c)
|
||||||
|
}
|
||||||
|
if c := checks["secondary zone 2.0.192.in-addr.arpa"]; c.State != core.HealthDegraded || !strings.Contains(c.Message, "waiting for a zone transfer") {
|
||||||
|
t.Errorf("missing secondary: %+v", c)
|
||||||
|
}
|
||||||
|
if c := checks["zone office.test"]; c.State != core.HealthOK {
|
||||||
|
t.Errorf("primary zone: %+v", c)
|
||||||
|
}
|
||||||
|
if len(h.Checks) != 4 {
|
||||||
|
t.Errorf("checks = %+v", h.Checks)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A member that serves only secondary zones is healthy while waiting.
|
||||||
|
rev = e.revisionWithKeys(8, clusterZones[1:], testKeys)
|
||||||
|
if h := e.role.Health(context.Background(), &rev); h.State != core.HealthOK || !strings.Contains(h.Message, "1 of 2") {
|
||||||
|
t.Errorf("secondary only: %+v", h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The primary zone still decides.
|
||||||
|
f.set("office.test", 6)
|
||||||
|
rev = e.revisionWithKeys(7, clusterZones, testKeys)
|
||||||
|
if h := e.role.Health(context.Background(), &rev); h.State != core.HealthFailed || strings.Contains(h.Message, "secondary") {
|
||||||
|
t.Errorf("stale primary zone: %+v", h)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestHealthWithoutRevision(t *testing.T) {
|
func TestHealthWithoutRevision(t *testing.T) {
|
||||||
e, _ := healthEnv(t)
|
e, _ := healthEnv(t)
|
||||||
if h := e.role.Health(context.Background(), nil); h.State != core.HealthOK || len(h.Checks) != 1 {
|
if h := e.role.Health(context.Background(), nil); h.State != core.HealthOK || len(h.Checks) != 1 {
|
||||||
|
|||||||
@@ -0,0 +1,203 @@
|
|||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
|
||||||
|
//go:build integration
|
||||||
|
|
||||||
|
package integration
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
const updateKeyName = "ddi-agent-update"
|
||||||
|
|
||||||
|
// dynRecord mirrors a record of dynamic-records.json (ADR 0026).
|
||||||
|
type dynRecord struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
TTL int `json:"ttl"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Data string `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func tsigSecret(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
b := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return base64.StdEncoding.EncodeToString(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func keyStmt(name, secret string) string {
|
||||||
|
return fmt.Sprintf("key %q {\n algorithm hmac-sha256;\n secret %q;\n};\n", name, secret)
|
||||||
|
}
|
||||||
|
|
||||||
|
// dynamicRevision renders a revision with the managed zone office.test and
|
||||||
|
// the dynamic zone ad.office.test whose updates need the key
|
||||||
|
// ddi-agent-update (the agent) or dc (a "domain controller"). records nil
|
||||||
|
// means no update files.
|
||||||
|
func dynamicRevision(t *testing.T, serial uint64, keysConf, updateKey string, records []dynRecord) (map[string]string, []string) {
|
||||||
|
t.Helper()
|
||||||
|
office := dnsZone{name: "office.test", records: "ns1 IN A 192.0.2.53\nwww IN A 192.0.2.10\n"}
|
||||||
|
ad := dnsZone{name: "ad.office.test", dynamic: true}
|
||||||
|
files, createOnly := dnsRevision([]dnsZone{office, ad}, serial, defaultOptions)
|
||||||
|
acl := `acl "ddi-update-ad.office.test" { 127.0.0.1/32; };`
|
||||||
|
if !strings.Contains(files["ddi-suite.conf"], acl) {
|
||||||
|
t.Fatalf("fixture changed: no update ACL in\n%s", files["ddi-suite.conf"])
|
||||||
|
}
|
||||||
|
files["ddi-suite.conf"] = strings.Replace(files["ddi-suite.conf"], acl,
|
||||||
|
`acl "ddi-update-ad.office.test" { key "`+updateKeyName+`"; key "dc"; };`, 1)
|
||||||
|
files["ddi-suite-keys.conf"] = "// Generated by DDI Suite (test fixture).\n\n" + keysConf
|
||||||
|
if records != nil {
|
||||||
|
files["ddi-suite-update.key"] = "// Generated by DDI Suite (test fixture).\n\n" + updateKey
|
||||||
|
doc := map[string]any{"version": 1, "key": updateKeyName,
|
||||||
|
"zones": []any{map[string]any{"zone": "ad.office.test", "records": records}}}
|
||||||
|
data, err := json.Marshal(doc)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
files["dynamic-records.json"] = string(data)
|
||||||
|
}
|
||||||
|
return files, createOnly
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDNSDynamicRecords(t *testing.T) {
|
||||||
|
driver := driverBinary(t)
|
||||||
|
for _, image := range images("DDI_BIND_IMAGES", "internetsystemsconsortium/bind9:9.18 internetsystemsconsortium/bind9:9.20") {
|
||||||
|
t.Run(image, func(t *testing.T) { testDNSDynamicRecords(t, image, driver) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testDNSDynamicRecords(t *testing.T, image string, driver []byte) {
|
||||||
|
agentSecret, dcSecret := tsigSecret(t), tsigSecret(t)
|
||||||
|
agentKey := keyStmt(updateKeyName, agentSecret)
|
||||||
|
keysConf := agentKey + keyStmt("dc", dcSecret)
|
||||||
|
a := func(name, ip string) dynRecord {
|
||||||
|
return dynRecord{Name: name + ".ad.office.test.", TTL: 3600, Type: "A", Data: ip}
|
||||||
|
}
|
||||||
|
srv := dynRecord{Name: "_ldap._tcp.dc._msdcs.ad.office.test.", TTL: 600, Type: "SRV", Data: "0 100 389 dc1.ad.office.test."}
|
||||||
|
txt := dynRecord{Name: "_dmarc.ad.office.test.", TTL: 300, Type: "TXT", Data: `"v=DMARC1; p=none"`}
|
||||||
|
|
||||||
|
tr := newTree(t)
|
||||||
|
tr.file("/etc/bind/named.conf", []byte(namedConf), 0o644)
|
||||||
|
tr.file("/etc/bind/rndc.key", rndcKey(t), 0o640)
|
||||||
|
tr.file(bindConfDir+"/ddi-suite.conf", []byte("// bootstrap\n"), 0o640)
|
||||||
|
tr.file(bindConfDir+"/ddi-suite-keys.conf", []byte("// bootstrap\n"), 0o640)
|
||||||
|
tr.file(bindConfDir+"/ddi-suite-options.conf", []byte("// bootstrap\n"), 0o640)
|
||||||
|
tr.file(driverPath, driver, 0o755)
|
||||||
|
tr.file(dnsConfig, []byte(dnsAgentConfig), 0o644)
|
||||||
|
|
||||||
|
// Revision 1 creates the dynamic zone (its initial file has no managed
|
||||||
|
// records: they come by dynamic update).
|
||||||
|
files1, co1 := dynamicRevision(t, 1, keysConf, agentKey, []dynRecord{a("srv1", "192.0.2.5"), a("srv2", "192.0.2.6"), srv, txt})
|
||||||
|
rev1 := tr.revision("dyn1", 1, files1, co1...)
|
||||||
|
// Revision 2 drops srv2 and adds srv3.
|
||||||
|
files2, co2 := dynamicRevision(t, 2, keysConf, agentKey, []dynRecord{a("srv1", "192.0.2.5"), a("srv3", "192.0.2.7"), srv, txt})
|
||||||
|
rev2 := tr.revision("dyn2", 2, files2, co2...)
|
||||||
|
// Revision 3 gives named another secret for the update key than
|
||||||
|
// nsupdate uses: the updates fail and the revision is rolled back.
|
||||||
|
files3, co3 := dynamicRevision(t, 3, keyStmt(updateKeyName, tsigSecret(t))+keyStmt("dc", dcSecret), agentKey,
|
||||||
|
[]dynRecord{a("srv1", "192.0.2.5"), a("srv4", "192.0.2.8")})
|
||||||
|
rev3 := tr.revision("dyn3", 3, files3, co3...)
|
||||||
|
// Revision 4 still serves the zone but manages no records in it.
|
||||||
|
files4, co4 := dynamicRevision(t, 4, keysConf, agentKey, []dynRecord{})
|
||||||
|
rev4 := tr.revision("dyn4", 4, files4, co4...)
|
||||||
|
|
||||||
|
c := startContainer(t, image, tr, bindScript)
|
||||||
|
for _, prog := range []string{"nsupdate", "dig"} {
|
||||||
|
if _, all, ok := c.exec("sh", "-c", "command -v "+prog); !ok {
|
||||||
|
t.Fatalf("%s is missing in %s: %s", prog, image, all)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if r := c.driver("dns", dnsConfig, "wait"); r.Error != "" {
|
||||||
|
t.Fatalf("named did not start: %+v", r)
|
||||||
|
}
|
||||||
|
dig := func(name, typ string) []string {
|
||||||
|
t.Helper()
|
||||||
|
out, all, ok := c.exec("dig", "@127.0.0.1", "+short", "+time=2", "+tries=2", name, typ)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("dig %s %s: %s", name, typ, all)
|
||||||
|
}
|
||||||
|
var res []string
|
||||||
|
for _, l := range strings.Split(strings.TrimSpace(out), "\n") {
|
||||||
|
if l = strings.TrimSpace(l); l != "" {
|
||||||
|
res = append(res, l)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
slices.Sort(res)
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
expect := func(name, typ string, want ...string) {
|
||||||
|
t.Helper()
|
||||||
|
slices.Sort(want)
|
||||||
|
if got := dig(name, typ); !slices.Equal(got, want) {
|
||||||
|
t.Errorf("%s %s = %q, want %q", name, typ, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
r := c.driver("dns", dnsConfig, "apply", rev1)
|
||||||
|
if r.Outcome != "succeeded" {
|
||||||
|
t.Fatalf("revision 1: %+v %+v", r, r.Health)
|
||||||
|
}
|
||||||
|
expect("srv1.ad.office.test", "A", "192.0.2.5")
|
||||||
|
expect("srv2.ad.office.test", "A", "192.0.2.6")
|
||||||
|
expect("_ldap._tcp.dc._msdcs.ad.office.test", "SRV", "0 100 389 dc1.ad.office.test.")
|
||||||
|
expect("_dmarc.ad.office.test", "TXT", `"v=DMARC1; p=none"`)
|
||||||
|
for _, f := range []string{"ddi-suite-update.key", "dynamic-records.json"} {
|
||||||
|
if c.exists(bindConfDir + "/" + f) {
|
||||||
|
t.Errorf("%s was installed into conf_dir", f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if dyn := c.cat(bindZoneDir + "/db.ad.office.test"); strings.Contains(dyn, "srv1") {
|
||||||
|
t.Errorf("initial file of the dynamic zone already has srv1:\n%s", dyn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A domain controller registers itself and adds a second address to a
|
||||||
|
// managed name.
|
||||||
|
// printf expands the \n escapes of its format argument.
|
||||||
|
update := `server 127.0.0.1\nzone ad.office.test\n` +
|
||||||
|
`update add dc1.ad.office.test. 300 A 192.0.2.20\n` +
|
||||||
|
`update add srv2.ad.office.test. 300 A 192.0.2.99\nsend\n`
|
||||||
|
if _, all, ok := c.exec("sh", "-c", `printf "$1" | nsupdate -y "$2"`, "sh", update, "hmac-sha256:dc:"+dcSecret); !ok {
|
||||||
|
t.Fatalf("third-party update failed: %s", all)
|
||||||
|
}
|
||||||
|
expect("srv2.ad.office.test", "A", "192.0.2.6", "192.0.2.99")
|
||||||
|
|
||||||
|
r = c.driver("dns", dnsConfig, "apply", rev2, rev1)
|
||||||
|
if r.Outcome != "succeeded" {
|
||||||
|
t.Fatalf("revision 2: %+v %+v", r, r.Health)
|
||||||
|
}
|
||||||
|
expect("srv1.ad.office.test", "A", "192.0.2.5")
|
||||||
|
expect("srv2.ad.office.test", "A", "192.0.2.99") // only DDI's address is gone
|
||||||
|
expect("srv3.ad.office.test", "A", "192.0.2.7")
|
||||||
|
expect("dc1.ad.office.test", "A", "192.0.2.20")
|
||||||
|
expect("_dmarc.ad.office.test", "TXT", `"v=DMARC1; p=none"`)
|
||||||
|
|
||||||
|
t.Run("failed update rolls back", func(t *testing.T) {
|
||||||
|
r := c.driver("dns", dnsConfig, "apply", rev3, rev2)
|
||||||
|
if r.Outcome != "rolled_back" || !strings.Contains(r.Error, "dynamic update of zone ad.office.test") {
|
||||||
|
t.Fatalf("got %+v", r)
|
||||||
|
}
|
||||||
|
if got := c.cat(bindConfDir + "/ddi-suite-keys.conf"); !strings.Contains(got, agentSecret) {
|
||||||
|
t.Error("keys file not restored")
|
||||||
|
}
|
||||||
|
expect("srv4.ad.office.test", "A")
|
||||||
|
expect("srv3.ad.office.test", "A", "192.0.2.7")
|
||||||
|
})
|
||||||
|
|
||||||
|
r = c.driver("dns", dnsConfig, "apply", rev4, rev2)
|
||||||
|
if r.Outcome != "succeeded" {
|
||||||
|
t.Fatalf("revision 4: %+v %+v", r, r.Health)
|
||||||
|
}
|
||||||
|
expect("srv1.ad.office.test", "A")
|
||||||
|
expect("srv3.ad.office.test", "A")
|
||||||
|
expect("_ldap._tcp.dc._msdcs.ad.office.test", "SRV")
|
||||||
|
expect("_dmarc.ad.office.test", "TXT")
|
||||||
|
expect("srv2.ad.office.test", "A", "192.0.2.99")
|
||||||
|
expect("dc1.ad.office.test", "A", "192.0.2.20")
|
||||||
|
}
|
||||||
@@ -35,6 +35,7 @@ options {
|
|||||||
notify no;
|
notify no;
|
||||||
include "` + bindConfDir + `/ddi-suite-options.conf";
|
include "` + bindConfDir + `/ddi-suite-options.conf";
|
||||||
};
|
};
|
||||||
|
include "` + bindConfDir + `/ddi-suite-keys.conf";
|
||||||
include "` + bindConfDir + `/ddi-suite.conf";
|
include "` + bindConfDir + `/ddi-suite.conf";
|
||||||
`
|
`
|
||||||
|
|
||||||
@@ -75,7 +76,10 @@ func rndcKey(t *testing.T) []byte {
|
|||||||
type dnsZone struct {
|
type dnsZone struct {
|
||||||
name string
|
name string
|
||||||
dynamic bool
|
dynamic bool
|
||||||
records string
|
// secondary zones transfer from 192.0.2.1 (unreachable) with the key
|
||||||
|
// "xfer"; they have no zone file.
|
||||||
|
secondary bool
|
||||||
|
records string
|
||||||
}
|
}
|
||||||
|
|
||||||
// dnsRevision renders generator-like files (see the server's bindgen
|
// dnsRevision renders generator-like files (see the server's bindgen
|
||||||
@@ -91,6 +95,11 @@ func dnsRevision(zones []dnsZone, serial uint64, options string) (map[string]str
|
|||||||
files := map[string]string{"ddi-suite-options.conf": "// Generated by DDI Suite (test fixture).\n\n" + options}
|
files := map[string]string{"ddi-suite-options.conf": "// Generated by DDI Suite (test fixture).\n\n" + options}
|
||||||
var createOnly []string
|
var createOnly []string
|
||||||
for _, z := range zones {
|
for _, z := range zones {
|
||||||
|
if z.secondary {
|
||||||
|
fmt.Fprintf(&conf, "\nzone %q {\n type secondary;\n file \"%s/secondary/db.%s\";\n"+
|
||||||
|
" primaries { 192.0.2.1 key \"xfer\"; };\n notify no;\n};\n", z.name, bindZoneDir, z.name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
update := "none"
|
update := "none"
|
||||||
if z.dynamic {
|
if z.dynamic {
|
||||||
update = fmt.Sprintf("%q", "ddi-update-"+z.name)
|
update = fmt.Sprintf("%q", "ddi-update-"+z.name)
|
||||||
@@ -128,6 +137,7 @@ func testDNSRole(t *testing.T, image string, driver []byte) {
|
|||||||
tr.file("/etc/bind/named.conf", []byte(namedConf), 0o644)
|
tr.file("/etc/bind/named.conf", []byte(namedConf), 0o644)
|
||||||
tr.file("/etc/bind/rndc.key", rndcKey(t), 0o640)
|
tr.file("/etc/bind/rndc.key", rndcKey(t), 0o640)
|
||||||
tr.file(bindConfDir+"/ddi-suite.conf", []byte("// bootstrap\n"), 0o640)
|
tr.file(bindConfDir+"/ddi-suite.conf", []byte("// bootstrap\n"), 0o640)
|
||||||
|
tr.file(bindConfDir+"/ddi-suite-keys.conf", []byte("// bootstrap\n"), 0o640)
|
||||||
tr.file(bindConfDir+"/ddi-suite-options.conf", []byte("// bootstrap\n"), 0o640)
|
tr.file(bindConfDir+"/ddi-suite-options.conf", []byte("// bootstrap\n"), 0o640)
|
||||||
tr.file(driverPath, driver, 0o755)
|
tr.file(driverPath, driver, 0o755)
|
||||||
tr.file(dnsConfig, []byte(dnsAgentConfig), 0o644)
|
tr.file(dnsConfig, []byte(dnsAgentConfig), 0o644)
|
||||||
@@ -157,6 +167,14 @@ func testDNSRole(t *testing.T, image string, driver []byte) {
|
|||||||
stale, coS := dnsRevision([]dnsZone{office2, dynamic2}, 99, defaultOptions)
|
stale, coS := dnsRevision([]dnsZone{office2, dynamic2}, 99, defaultOptions)
|
||||||
revStale := tr.revision("stale", 5, stale, coS...)
|
revStale := tr.revision("stale", 5, stale, coS...)
|
||||||
|
|
||||||
|
// Revision 6 (M5) has TSIG keys and a secondary zone whose primary is
|
||||||
|
// unreachable.
|
||||||
|
keys := "// Generated by DDI Suite (test fixture).\n\nkey \"xfer\" {\n algorithm hmac-sha256;\n secret \"" +
|
||||||
|
base64.StdEncoding.EncodeToString([]byte("xfer-secret-of-the-test-cluster!")) + "\";\n};\n"
|
||||||
|
clusterFiles, coC := dnsRevision([]dnsZone{office2, dynamic2, {name: "remote.test", secondary: true}}, 6, defaultOptions)
|
||||||
|
clusterFiles["ddi-suite-keys.conf"] = keys
|
||||||
|
revCluster := tr.revision("cluster", 6, clusterFiles, coC...)
|
||||||
|
|
||||||
c := startContainer(t, image, tr, bindScript)
|
c := startContainer(t, image, tr, bindScript)
|
||||||
if r := c.driver("dns", dnsConfig, "wait"); r.Error != "" {
|
if r := c.driver("dns", dnsConfig, "wait"); r.Error != "" {
|
||||||
t.Fatalf("named did not start: %+v", r)
|
t.Fatalf("named did not start: %+v", r)
|
||||||
@@ -177,6 +195,9 @@ func testDNSRole(t *testing.T, image string, driver []byte) {
|
|||||||
if !c.exists(bindZoneDir + "/db.2.0.192.in-addr.arpa") {
|
if !c.exists(bindZoneDir + "/db.2.0.192.in-addr.arpa") {
|
||||||
t.Fatal("reverse zone file missing after revision 1")
|
t.Fatal("reverse zone file missing after revision 1")
|
||||||
}
|
}
|
||||||
|
if got := c.cat(bindConfDir + "/ddi-suite-keys.conf"); !strings.Contains(got, "No TSIG keys") {
|
||||||
|
t.Errorf("revision without keys file: keys file is\n%s", got)
|
||||||
|
}
|
||||||
|
|
||||||
r = c.driver("dns", dnsConfig, "apply", rev2, rev1)
|
r = c.driver("dns", dnsConfig, "apply", rev2, rev1)
|
||||||
if r.Outcome != "succeeded" {
|
if r.Outcome != "succeeded" {
|
||||||
@@ -221,7 +242,31 @@ func testDNSRole(t *testing.T, image string, driver []byte) {
|
|||||||
|
|
||||||
r = c.driver("dns", dnsConfig, "health", rev2)
|
r = c.driver("dns", dnsConfig, "health", rev2)
|
||||||
if r.Health == nil || r.Health.State != core.HealthOK {
|
if r.Health == nil || r.Health.State != core.HealthOK {
|
||||||
t.Fatalf("final health: %+v", r.Health)
|
t.Fatalf("health of revision 2: %+v", r.Health)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The secondary zone waits for its transfer without failing the
|
||||||
|
// deployment; BIND reads the keys; the secondary directory belongs to
|
||||||
|
// bind like zone_dir.
|
||||||
|
r = c.driver("dns", dnsConfig, "apply", revCluster, rev2)
|
||||||
|
if r.Outcome != "succeeded" {
|
||||||
|
t.Fatalf("revision with keys and a secondary zone: %+v %+v", r, r.Health)
|
||||||
|
}
|
||||||
|
assertZones(t, r.Health, 1)
|
||||||
|
waiting := false
|
||||||
|
for _, ch := range r.Health.Checks {
|
||||||
|
if ch.Name == "secondary zone remote.test" && ch.State == core.HealthDegraded {
|
||||||
|
waiting = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !waiting {
|
||||||
|
t.Errorf("no degraded check for the secondary zone: %+v", r.Health.Checks)
|
||||||
|
}
|
||||||
|
if got := c.cat(bindConfDir + "/ddi-suite-keys.conf"); got != keys {
|
||||||
|
t.Errorf("keys file:\n%s", got)
|
||||||
|
}
|
||||||
|
if out, all, ok := c.exec("stat", "-c", "%U:%G %a", bindZoneDir+"/secondary"); !ok || strings.TrimSpace(out) != "bind:bind 750" {
|
||||||
|
t.Errorf("secondary directory: %q %s", out, all)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ import (
|
|||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"time"
|
"time"
|
||||||
@@ -78,6 +79,9 @@ func run(args []string, stdout, stderr io.Writer) int {
|
|||||||
_, _ = fmt.Fprintln(stderr, err)
|
_, _ = fmt.Fprintln(stderr, err)
|
||||||
return 2
|
return 2
|
||||||
}
|
}
|
||||||
|
if ls, ok := role.(core.LogSetter); ok {
|
||||||
|
ls.SetLogger(slog.New(slog.NewTextHandler(stderr, nil)))
|
||||||
|
}
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
|
|||||||
@@ -30,15 +30,30 @@ type Runner interface {
|
|||||||
Run(ctx context.Context, name string, args ...string) ([]byte, error)
|
Run(ctx context.Context, name string, args ...string) ([]byte, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// InputRunner is a Runner that can also feed data to the program's
|
||||||
|
// standard input (e.g. an nsupdate script).
|
||||||
|
type InputRunner interface {
|
||||||
|
Runner
|
||||||
|
RunInput(ctx context.Context, input []byte, name string, args ...string) ([]byte, error)
|
||||||
|
}
|
||||||
|
|
||||||
// Exec runs programs on the host. Timeout bounds every run (0 means only
|
// Exec runs programs on the host. Timeout bounds every run (0 means only
|
||||||
// the context bounds it).
|
// the context bounds it).
|
||||||
type Exec struct {
|
type Exec struct {
|
||||||
Timeout time.Duration
|
Timeout time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var _ InputRunner = Exec{}
|
||||||
|
|
||||||
// Run implements Runner. A non-zero exit status, a timeout or a missing
|
// Run implements Runner. A non-zero exit status, a timeout or a missing
|
||||||
// program yields an *Error that quotes the (truncated) output.
|
// program yields an *Error that quotes the (truncated) output.
|
||||||
func (e Exec) Run(ctx context.Context, name string, args ...string) ([]byte, error) {
|
func (e Exec) Run(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||||
|
return e.RunInput(ctx, nil, name, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunInput implements InputRunner: like Run, with input on the program's
|
||||||
|
// standard input (nil means none). Errors never quote the input.
|
||||||
|
func (e Exec) RunInput(ctx context.Context, input []byte, name string, args ...string) ([]byte, error) {
|
||||||
if e.Timeout > 0 {
|
if e.Timeout > 0 {
|
||||||
var cancel context.CancelFunc
|
var cancel context.CancelFunc
|
||||||
ctx, cancel = context.WithTimeout(ctx, e.Timeout)
|
ctx, cancel = context.WithTimeout(ctx, e.Timeout)
|
||||||
@@ -48,6 +63,9 @@ func (e Exec) Run(ctx context.Context, name string, args ...string) ([]byte, err
|
|||||||
cmd := exec.CommandContext(ctx, name, args...) //nolint:gosec // programs come from the agent configuration, no shell is involved
|
cmd := exec.CommandContext(ctx, name, args...) //nolint:gosec // programs come from the agent configuration, no shell is involved
|
||||||
cmd.Stdout = &out
|
cmd.Stdout = &out
|
||||||
cmd.Stderr = &out
|
cmd.Stderr = &out
|
||||||
|
if input != nil {
|
||||||
|
cmd.Stdin = bytes.NewReader(input)
|
||||||
|
}
|
||||||
// Do not wait forever for grandchildren that keep the pipes open.
|
// Do not wait forever for grandchildren that keep the pipes open.
|
||||||
cmd.WaitDelay = 5 * time.Second
|
cmd.WaitDelay = 5 * time.Second
|
||||||
err := cmd.Run()
|
err := cmd.Run()
|
||||||
|
|||||||
@@ -39,6 +39,20 @@ func TestFailingProgramQuotesOutput(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRunInputFeedsStdin(t *testing.T) {
|
||||||
|
sh, err := exec.LookPath("sh")
|
||||||
|
if err != nil {
|
||||||
|
t.Skip("sh not available")
|
||||||
|
}
|
||||||
|
out, err := Exec{Timeout: 10 * time.Second}.RunInput(context.Background(), []byte("line one\nline two\n"), sh, "-c", "wc -l")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(string(out)) != "2" {
|
||||||
|
t.Errorf("output = %q, want 2 lines counted", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestTimeout(t *testing.T) {
|
func TestTimeout(t *testing.T) {
|
||||||
sh, err := exec.LookPath("sh")
|
sh, err := exec.LookPath("sh")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -114,6 +114,43 @@ func Same(path string, data []byte, mode fs.FileMode) bool {
|
|||||||
return err == nil && bytes.Equal(cur, data)
|
return err == nil && bytes.Equal(cur, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MkdirLike creates the directory path unless it exists, with the
|
||||||
|
// permission bits and (when running as root) the owner of the existing
|
||||||
|
// directory ref, so that the service that owns ref can write there too.
|
||||||
|
// An existing directory is left as it is; anything else at path is an
|
||||||
|
// error.
|
||||||
|
func MkdirLike(path, ref string) error {
|
||||||
|
fi, err := os.Lstat(path)
|
||||||
|
switch {
|
||||||
|
case err == nil && fi.IsDir():
|
||||||
|
return nil
|
||||||
|
case err == nil:
|
||||||
|
return fmt.Errorf("%s exists and is not a directory", path)
|
||||||
|
case !errors.Is(err, fs.ErrNotExist):
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
rfi, err := os.Stat(ref)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !rfi.IsDir() {
|
||||||
|
return fmt.Errorf("%s is not a directory", ref)
|
||||||
|
}
|
||||||
|
if err := os.Mkdir(path, rfi.Mode().Perm()); err != nil {
|
||||||
|
return fmt.Errorf("create %s: %w", path, err)
|
||||||
|
}
|
||||||
|
// The umask may have removed bits.
|
||||||
|
if err := os.Chmod(path, rfi.Mode().Perm()); err != nil {
|
||||||
|
return fmt.Errorf("chmod %s: %w", path, err)
|
||||||
|
}
|
||||||
|
if o, ok := ownerOf(ref); ok {
|
||||||
|
if err := chownPath(path, o); err != nil {
|
||||||
|
return fmt.Errorf("chown %s: %w", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SyncDir(filepath.Dir(path))
|
||||||
|
}
|
||||||
|
|
||||||
// RequireDir returns an error unless path is an existing directory.
|
// RequireDir returns an error unless path is an existing directory.
|
||||||
func RequireDir(path string) error {
|
func RequireDir(path string) error {
|
||||||
fi, err := os.Stat(path)
|
fi, err := os.Stat(path)
|
||||||
|
|||||||
@@ -13,5 +13,7 @@ func ownerOf(string) (Owner, bool) { return Owner{}, false }
|
|||||||
|
|
||||||
func chown(*os.File, Owner) error { return nil }
|
func chown(*os.File, Owner) error { return nil }
|
||||||
|
|
||||||
|
func chownPath(string, Owner) error { return nil }
|
||||||
|
|
||||||
// SyncDir is a no-op on systems without directory sync.
|
// SyncDir is a no-op on systems without directory sync.
|
||||||
func SyncDir(string) error { return nil }
|
func SyncDir(string) error { return nil }
|
||||||
|
|||||||
@@ -117,6 +117,51 @@ func TestSame(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestMkdirLike(t *testing.T) {
|
||||||
|
ref := filepath.Join(t.TempDir(), "zones")
|
||||||
|
if err := os.Mkdir(ref, 0o750); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Chmod(ref, 0o770); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
sub := filepath.Join(ref, "secondary")
|
||||||
|
if err := MkdirLike(sub, ref); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
fi, err := os.Stat(sub)
|
||||||
|
if err != nil || !fi.IsDir() {
|
||||||
|
t.Fatalf("not created: %v", err)
|
||||||
|
}
|
||||||
|
if runtime.GOOS != "windows" && fi.Mode().Perm() != 0o770 {
|
||||||
|
t.Errorf("mode = %o, want 770", fi.Mode().Perm())
|
||||||
|
}
|
||||||
|
// Existing directories stay as they are (content included).
|
||||||
|
if err := os.WriteFile(filepath.Join(sub, "db.x"), []byte("x"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := MkdirLike(sub, ref); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(sub, "db.x")); err != nil {
|
||||||
|
t.Error("content of the existing directory changed")
|
||||||
|
}
|
||||||
|
// A file in the way and a missing reference are errors.
|
||||||
|
file := filepath.Join(ref, "file")
|
||||||
|
if err := os.WriteFile(file, nil, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if MkdirLike(file, ref) == nil {
|
||||||
|
t.Error("file accepted as directory")
|
||||||
|
}
|
||||||
|
if MkdirLike(filepath.Join(ref, "other"), filepath.Join(ref, "missing")) == nil {
|
||||||
|
t.Error("missing reference accepted")
|
||||||
|
}
|
||||||
|
if MkdirLike(filepath.Join(ref, "other"), file) == nil {
|
||||||
|
t.Error("file accepted as reference")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestRequireDir(t *testing.T) {
|
func TestRequireDir(t *testing.T) {
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
if err := RequireDir(dir); err != nil {
|
if err := RequireDir(dir); err != nil {
|
||||||
|
|||||||
@@ -30,6 +30,14 @@ func chown(f *os.File, owner Owner) error {
|
|||||||
return f.Chown(owner.UID, owner.GID)
|
return f.Chown(owner.UID, owner.GID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// chownPath is chown for a path (not following a final symbolic link).
|
||||||
|
func chownPath(path string, owner Owner) error {
|
||||||
|
if !owner.Valid || os.Geteuid() != 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return os.Lchown(path, owner.UID, owner.GID)
|
||||||
|
}
|
||||||
|
|
||||||
// SyncDir flushes directory entries (renames, removals) to disk.
|
// SyncDir flushes directory entries (renames, removals) to disk.
|
||||||
func SyncDir(dir string) error {
|
func SyncDir(dir string) error {
|
||||||
d, err := os.Open(dir) //nolint:gosec // dir is a configured directory of the role
|
d, err := os.Open(dir) //nolint:gosec // dir is a configured directory of the role
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
|
//
|
||||||
|
// Seed for the development environment: no TSIG keys yet. From M5 on, the
|
||||||
|
// DNS agent writes the keys of the revision here (ADR 0023).
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
// SPDX-License-Identifier: Apache-2.0
|
// SPDX-License-Identifier: Apache-2.0
|
||||||
//
|
//
|
||||||
// Development BIND configuration. On managed hosts the distribution's
|
// Development BIND configuration. On managed hosts the distribution's
|
||||||
// named.conf only needs the include line below; everything else under
|
// named.conf only needs the include lines below (the keys before the
|
||||||
// /etc/bind/ddi-suite is written by the DNS agent (ADR 0004).
|
// zones); everything else under /etc/bind/ddi-suite is written by the DNS
|
||||||
|
// agent (ADR 0004, ADR 0023).
|
||||||
|
|
||||||
options {
|
options {
|
||||||
directory "/var/cache/bind";
|
directory "/var/cache/bind";
|
||||||
@@ -15,4 +16,5 @@ options {
|
|||||||
dnssec-validation no;
|
dnssec-validation no;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
include "/etc/bind/ddi-suite/ddi-suite-keys.conf";
|
||||||
include "/etc/bind/ddi-suite/ddi-suite.conf";
|
include "/etc/bind/ddi-suite/ddi-suite.conf";
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
# Template of the nfpm configuration of the .deb and .rpm packages (ADR 0024),
|
||||||
|
# shared by all binaries. scripts/build-packages.sh replaces the placeholders
|
||||||
|
# (at-sign NAME at-sign) per binary and architecture (ADR 0018: no product
|
||||||
|
# names in this file). The
|
||||||
|
# packages contain only the binary, its systemd unit and the license text;
|
||||||
|
# configuration, users and services are set up by the installer.
|
||||||
|
name: "@PKG_NAME@"
|
||||||
|
arch: "@PKG_ARCH@"
|
||||||
|
platform: linux
|
||||||
|
version: "@PKG_VERSION@"
|
||||||
|
version_schema: semver
|
||||||
|
release: "1"
|
||||||
|
section: net
|
||||||
|
priority: optional
|
||||||
|
maintainer: "@PKG_MAINTAINER@"
|
||||||
|
vendor: "@PKG_VENDOR@"
|
||||||
|
homepage: "@PKG_HOMEPAGE@"
|
||||||
|
license: "@PKG_LICENSE@"
|
||||||
|
description: "@PKG_DESCRIPTION@"
|
||||||
|
|
||||||
|
contents:
|
||||||
|
- src: "@PKG_SRC_DIR@/binary"
|
||||||
|
dst: "/usr/bin/@PKG_NAME@"
|
||||||
|
file_info:
|
||||||
|
mode: 0755
|
||||||
|
- src: "@PKG_SRC_DIR@/unit.service"
|
||||||
|
dst: "/usr/lib/systemd/system/@PKG_NAME@.service"
|
||||||
|
file_info:
|
||||||
|
mode: 0644
|
||||||
|
- src: "@PKG_SRC_DIR@/LICENSE"
|
||||||
|
dst: "/usr/share/doc/@PKG_NAME@/LICENSE"
|
||||||
|
file_info:
|
||||||
|
mode: 0644
|
||||||
|
|
||||||
|
scripts:
|
||||||
|
postinstall: "@PKG_SCRIPTS_DIR@/postinstall.sh"
|
||||||
|
postremove: "@PKG_SCRIPTS_DIR@/postremove.sh"
|
||||||
Executable
+9
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
# Package hook (deb postinst, rpm %post): make systemd see the new or
|
||||||
|
# updated unit. Enabling and starting services is left to the installer.
|
||||||
|
if [ -d /run/systemd/system ]; then
|
||||||
|
systemctl daemon-reload >/dev/null 2>&1 || true
|
||||||
|
fi
|
||||||
|
exit 0
|
||||||
Executable
+9
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
# Package hook (deb postrm, rpm %postun): make systemd forget the removed
|
||||||
|
# unit. Stopping and disabling services is left to the installer.
|
||||||
|
if [ -d /run/systemd/system ]; then
|
||||||
|
systemctl daemon-reload >/dev/null 2>&1 || true
|
||||||
|
fi
|
||||||
|
exit 0
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
# Template of the dhcp agent unit (ADR 0018, 0024). Placeholders (at-sign NAME at-sign)
|
||||||
|
# are replaced by scripts/render-units.sh. The
|
||||||
|
# installer sets User= and Group= to the Kea DHCPv4 user in a drop-in
|
||||||
|
# (10-user.conf): the agent runs with the rights of the service it manages.
|
||||||
|
[Unit]
|
||||||
|
Description=@DISPLAY_NAME@ dhcp agent (Kea DHCPv4)
|
||||||
|
Documentation=https://git.beugsiud.de/beug.k/DDI
|
||||||
|
Wants=network-online.target
|
||||||
|
After=network-online.target isc-kea-dhcp4-server.service kea-dhcp4.service kea-dhcp4-server.service
|
||||||
|
# Enabled by the installer right away; starts once the agent is enrolled
|
||||||
|
# (`enroll` as root starts it directly).
|
||||||
|
ConditionPathExists=/var/lib/@PRODUCT@/agent-dhcp/identity/agent.json
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
ExecStart=@BINDIR@/@BIN_AGENT_DHCP@ run
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5s
|
||||||
|
StateDirectory=@PRODUCT@/agent-dhcp
|
||||||
|
StateDirectoryMode=0700
|
||||||
|
UMask=0027
|
||||||
|
ReadWritePaths=-/etc/kea -/run/kea
|
||||||
|
|
||||||
|
# Hardening (ADR 0024).
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=yes
|
||||||
|
PrivateTmp=yes
|
||||||
|
PrivateDevices=yes
|
||||||
|
ProtectKernelTunables=yes
|
||||||
|
ProtectKernelModules=yes
|
||||||
|
ProtectKernelLogs=yes
|
||||||
|
ProtectControlGroups=yes
|
||||||
|
ProtectClock=yes
|
||||||
|
ProtectHostname=yes
|
||||||
|
# AF_NETLINK: "kea-dhcp4 -t" (validation) detects the interfaces via netlink.
|
||||||
|
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
|
||||||
|
RestrictNamespaces=yes
|
||||||
|
RestrictRealtime=yes
|
||||||
|
RestrictSUIDSGID=yes
|
||||||
|
LockPersonality=yes
|
||||||
|
MemoryDenyWriteExecute=yes
|
||||||
|
SystemCallArchitectures=native
|
||||||
|
SystemCallFilter=@system-service
|
||||||
|
CapabilityBoundingSet=
|
||||||
|
AmbientCapabilities=
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
# Template of the dns agent unit (ADR 0018, 0024). Placeholders (at-sign NAME at-sign)
|
||||||
|
# are replaced by scripts/render-units.sh. The
|
||||||
|
# installer sets User= and Group= to the BIND (named) user in a drop-in
|
||||||
|
# (10-user.conf): the agent runs with the rights of the service it manages.
|
||||||
|
[Unit]
|
||||||
|
Description=@DISPLAY_NAME@ dns agent (BIND (named))
|
||||||
|
Documentation=https://git.beugsiud.de/beug.k/DDI
|
||||||
|
Wants=network-online.target
|
||||||
|
After=network-online.target named.service bind9.service
|
||||||
|
# Enabled by the installer right away; starts once the agent is enrolled
|
||||||
|
# (`enroll` as root starts it directly).
|
||||||
|
ConditionPathExists=/var/lib/@PRODUCT@/agent-dns/identity/agent.json
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
ExecStart=@BINDIR@/@BIN_AGENT_DNS@ run
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5s
|
||||||
|
StateDirectory=@PRODUCT@/agent-dns
|
||||||
|
StateDirectoryMode=0700
|
||||||
|
UMask=0027
|
||||||
|
ReadWritePaths=-/etc/bind/@PRODUCT@ -/etc/named/@PRODUCT@ -/var/lib/bind/@PRODUCT@
|
||||||
|
|
||||||
|
# Hardening (ADR 0024).
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=yes
|
||||||
|
PrivateTmp=yes
|
||||||
|
PrivateDevices=yes
|
||||||
|
ProtectKernelTunables=yes
|
||||||
|
ProtectKernelModules=yes
|
||||||
|
ProtectKernelLogs=yes
|
||||||
|
ProtectControlGroups=yes
|
||||||
|
ProtectClock=yes
|
||||||
|
ProtectHostname=yes
|
||||||
|
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
|
||||||
|
RestrictNamespaces=yes
|
||||||
|
RestrictRealtime=yes
|
||||||
|
RestrictSUIDSGID=yes
|
||||||
|
LockPersonality=yes
|
||||||
|
MemoryDenyWriteExecute=yes
|
||||||
|
SystemCallArchitectures=native
|
||||||
|
SystemCallFilter=@system-service
|
||||||
|
CapabilityBoundingSet=
|
||||||
|
AmbientCapabilities=
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
# Template of the management server unit (ADR 0018, 0024). Placeholders
|
||||||
|
# (at-sign NAME at-sign) are replaced by scripts/render-units.sh.
|
||||||
|
[Unit]
|
||||||
|
Description=@DISPLAY_NAME@ management server
|
||||||
|
Documentation=https://git.beugsiud.de/beug.k/DDI
|
||||||
|
Wants=network-online.target
|
||||||
|
After=network-online.target postgresql.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=@PRODUCT@
|
||||||
|
Group=@PRODUCT@
|
||||||
|
Environment=@ENV_PREFIX@CONFIG_FILE=@CONFIG_DIR@/server.yaml
|
||||||
|
ExecStart=@BINDIR@/@BIN_SERVER@ serve
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5s
|
||||||
|
StateDirectory=@PRODUCT@/server
|
||||||
|
StateDirectoryMode=0750
|
||||||
|
UMask=0027
|
||||||
|
|
||||||
|
# Hardening (ADR 0024).
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=yes
|
||||||
|
PrivateTmp=yes
|
||||||
|
PrivateDevices=yes
|
||||||
|
ProtectKernelTunables=yes
|
||||||
|
ProtectKernelModules=yes
|
||||||
|
ProtectKernelLogs=yes
|
||||||
|
ProtectControlGroups=yes
|
||||||
|
ProtectClock=yes
|
||||||
|
ProtectHostname=yes
|
||||||
|
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
|
||||||
|
RestrictNamespaces=yes
|
||||||
|
RestrictRealtime=yes
|
||||||
|
RestrictSUIDSGID=yes
|
||||||
|
LockPersonality=yes
|
||||||
|
MemoryDenyWriteExecute=yes
|
||||||
|
SystemCallArchitectures=native
|
||||||
|
SystemCallFilter=@system-service
|
||||||
|
# Only for the address check (ping): raw ICMP sockets where unprivileged
|
||||||
|
# ICMP sockets are not permitted (ADR 0025), like /bin/ping.
|
||||||
|
CapabilityBoundingSet=CAP_NET_RAW
|
||||||
|
AmbientCapabilities=CAP_NET_RAW
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
# Active Directory mit dynamischen Zonen
|
||||||
|
|
||||||
|
Diese Anleitung beschreibt, wie die DNS-Zonen einer Active-Directory-Domäne (AD) auf den von der DDI Suite verwalteten BIND-Servern liegen. Grundlage sind [ADR 0023](adr/0023-cluster-und-zonen-m5.md) und [ADR 0026](adr/0026-eintraege-in-dynamischen-zonen.md).
|
||||||
|
|
||||||
|
## Grundsatz
|
||||||
|
|
||||||
|
Domain Controller (DC) registrieren ihre Einträge selbst per **RFC-2136-Update** (dynamisches DNS): A-Records der DCs, SRV-Records für LDAP, Kerberos und den globalen Katalog sowie die Einträge unter `_msdcs`. Die Zone der AD-Domäne muss deshalb eine **dynamische Zone** sein. Bei dynamischen Zonen gilt:
|
||||||
|
|
||||||
|
- Der DNS-Agent legt die Zone in BIND an und schreibt **nur beim ersten Mal** eine Anfangsdatei. Danach gehören Zonendatei und Journal BIND; die DDI Suite überschreibt sie nie.
|
||||||
|
- Die Records, die die DDI Suite für die Zone kennt – A/AAAA/PTR aus der Adresstabelle und die in der Oberfläche angelegten Records der Zone –, trägt der DNS-Agent auf dem Primary bei jeder Revision **per dynamischem Update** ein (`nsupdate` mit dem Systemschlüssel `ddi-agent-update`). Was in DDI gelöscht oder geändert wurde, entfernt er dabei genau als diesen Record. Records anderer Herkunft (von den DCs, von Clients, per Hand) fasst er nie an.
|
||||||
|
- Ändert oder löscht jemand einen von DDI verwalteten Record direkt in BIND, stellt die nächste Revision den Stand aus DDI wieder her.
|
||||||
|
- Updates werden nur von den eingetragenen Quellen angenommen: IP-Adressen bzw. Netze (`allow_update`), TSIG-Schlüssel der Zone und der Systemschlüssel des Agents.
|
||||||
|
|
||||||
|
**Nicht unterstützt (Version 1):** GSS-TSIG (Kerberos-gesicherte „sichere“ Updates, wie sie AD-integrierte Microsoft-DNS-Server verwenden). Updates werden daher über die IP-Adressen der DCs oder über TSIG abgesichert.
|
||||||
|
|
||||||
|
## Einrichtung
|
||||||
|
|
||||||
|
1. **Zone anlegen** (*Zonen → Neue Zone*): Name der AD-Domäne, z. B. `ad.example.com`, Modus **dynamisch**, DNS-Cluster wählen.
|
||||||
|
2. **Update-Quellen** eintragen: die IP-Adressen aller Domain Controller als `/32` bzw. `/128`, z. B. `192.0.2.10/32` und `192.0.2.11/32`. Keine ganzen Client-Netze eintragen – sonst kann jeder Rechner darin Einträge der Domäne überschreiben.
|
||||||
|
3. **`_msdcs`:** Die Einträge unter `_msdcs.ad.example.com` gehören in **dieselbe** dynamische Zone. Eine eigene Zone `_msdcs.…` ist nicht nötig (und wird nicht abgeleitet); die DCs legen die Records darin selbst an.
|
||||||
|
4. **Reverse-Zonen:** Sollen DCs oder Clients auch PTR-Records eintragen, die betroffene Reverse-Zone ebenfalls als dynamische Zone anlegen (z. B. `2.0.192.in-addr.arpa`) und dieselben Update-Quellen eintragen. Die PTR-Records der Adresstabelle hält der Agent darin ebenso aktuell. Reverse-Zonen, in die niemand außer DDI schreibt, bleiben besser `managed`.
|
||||||
|
5. **Revision erzeugen und ausrollen.** Der Primary des Clusters nimmt die Updates an, die Secondaries erhalten die Änderungen per NOTIFY und IXFR. Mit der ersten dynamischen Zone legt der Server den Systemschlüssel `ddi-agent-update` an; er steht in der Liste der TSIG-Schlüssel, lässt sich rotieren, aber nicht löschen.
|
||||||
|
6. **Windows-Seite:** Auf den DCs als DNS-Server die Adressen der BIND-Server eintragen. In den DNS-Einstellungen der Netzwerkkarte „Adressen dieser Verbindung in DNS registrieren“ aktiv lassen. Die DCs schicken Updates an den Server aus dem SOA-Record (MNAME) der Zone; das ist der Primary des Clusters (bzw. `primary_ns`).
|
||||||
|
|
||||||
|
Prüfen lässt sich die Registrierung nach einem Neustart des Dienstes „Netlogon“ auf einem DC (`nltest /dsregdns`) mit:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
dig @<primary> SRV _ldap._tcp.dc._msdcs.ad.example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
## Bestehende Windows-DNS-Zone nach DDI
|
||||||
|
|
||||||
|
So zieht eine AD-integrierte Zone eines Windows-DNS-Servers auf die BIND-Server der DDI Suite um. Beispiel: Domäne `ad.example.com`, DCs `192.0.2.10` und `192.0.2.11`, BIND-Primary `192.0.2.53`.
|
||||||
|
|
||||||
|
1. **Bestand sichern:** Auf einem DC die Zone exportieren, z. B. `dnscmd /zoneexport ad.example.com ad.example.com.dns` (Datei unter `%SystemRoot%\System32\dns`) oder `Get-DnsServerResourceRecord -ZoneName ad.example.com | Export-Csv records.csv`. Die Liste dient als Vorlage und zum Vergleich.
|
||||||
|
2. **Zone in DDI anlegen:** *Zonen → Neue Zone*, Name `ad.example.com`, Modus **dynamisch**, DNS-Cluster wählen, unter `allow_update` die Adressen aller DCs als `/32` bzw. `/128`. Gibt es unter Windows eine eigene Zone `_msdcs.ad.example.com` (Standard für die Stammdomäne einer Gesamtstruktur), entfällt sie: Ihre Records landen in der dynamischen Zone `ad.example.com`. Reverse-Zonen bei Bedarf ebenso dynamisch anlegen (Einrichtung, Punkt 4).
|
||||||
|
3. **Übrige Einträge übernehmen:** Mitgliedsserver, Drucker und andere feste Adressen aus dem Export als Einträge der Adresstabelle importieren (CSV-Import in ein Netz mit der Domain `ad.example.com`; DDI erzeugt dann A und PTR) oder, wenn sie zu keinem verwalteten Netz gehören, als Records der Zone anlegen. Die Einträge der DCs selbst (A, SRV, `_msdcs`) nicht übernehmen – die DCs tragen sie gleich selbst ein.
|
||||||
|
4. **Ausrollen** und prüfen, dass BIND die Zone bedient: `dig @192.0.2.53 SOA ad.example.com` und für einen übernommenen Eintrag `dig @192.0.2.53 A server1.ad.example.com`.
|
||||||
|
5. **DCs umstellen:** Auf jedem DC in den Einstellungen der Netzwerkkarte die BIND-Server als DNS-Server eintragen (der DC selbst bzw. `127.0.0.1` nicht mehr an erster Stelle). Die DCs schicken ihre Updates an den Server aus dem SOA-Record (MNAME) der Zone, also den Primary des Clusters. Alternativ behalten die DCs ihren eigenen DNS-Server, wenn dieser die Zone nicht mehr selbst hält, sondern per bedingter Weiterleitung an die BIND-Server verweist: Dann finden sie den Primary über den SOA-Record und schicken ihm die Updates direkt.
|
||||||
|
6. **Neu registrieren lassen**, auf jedem DC:
|
||||||
|
|
||||||
|
```bat
|
||||||
|
ipconfig /registerdns
|
||||||
|
nltest /dsregdns
|
||||||
|
```
|
||||||
|
|
||||||
|
`nltest /dsregdns` trägt die SRV-Records des DC-Locators neu ein; gleichwertig ist ein Neustart des Dienstes „Netlogon“ (`net stop netlogon && net start netlogon`). Die vollständige Liste der Records, die Netlogon registrieren will, steht in `%SystemRoot%\System32\config\netlogon.dns`.
|
||||||
|
7. **Prüfen:**
|
||||||
|
|
||||||
|
```sh
|
||||||
|
dig @192.0.2.53 SRV _ldap._tcp.dc._msdcs.ad.example.com
|
||||||
|
dig @192.0.2.53 SRV _kerberos._tcp.ad.example.com
|
||||||
|
dig @192.0.2.53 A dc1.ad.example.com
|
||||||
|
```
|
||||||
|
|
||||||
|
Auf einem DC zusätzlich `dcdiag /test:RegisterInDNS /DnsDomain:<domain>` (`dcdiag /test:dns` taugt nur, solange der Windows-DNS-Server noch läuft, siehe [Prüfen nach der Umstellung](#prüfen-nach-der-umstellung)). Fehlen Records, im Log des Primary (`named`) nach `update … denied` suchen: Meist passt die Quelladresse des DCs nicht zu `allow_update`.
|
||||||
|
8. **Clients umstellen:** Die DNS-Server der Clients auf die BIND-Server setzen – in DDI über die DNS-Server der Netze (DHCP-Option 6), bei festen Adressen per Hand oder Gruppenrichtlinie. Den Windows-DNS-Server mit der alten Zone erst abschalten bzw. die Zone dort löschen, wenn alle Leases erneuert sind; bis dahin beide Seiten vergleichen.
|
||||||
|
|
||||||
|
**Folgen ohne GSS-TSIG:** „Sichere“ Updates (GSS-TSIG/Kerberos) beherrscht BIND hier nicht. Updates sind nur über die Quelladresse (und TSIG, das Windows nicht kann) abgesichert; wer im Netz eine DC-Adresse fälschen kann, kann Einträge der Domäne ändern – die DCs deshalb in ein eigenes, gefiltertes Netz. Windows-Clients können sich nicht selbst registrieren (ihre Updates werden abgelehnt, solange ihre Netze nicht in `allow_update` stehen, und das sollen sie nicht); ihre Namen kommen aus der Adresstabelle. Namen dynamischer DHCP-Clients wären Aufgabe von Kea-DDNS (noch nicht umgesetzt). Ein Aufräumen veralteter Einträge (Scavenging) gibt es nicht.
|
||||||
|
|
||||||
|
## Updates mit TSIG
|
||||||
|
|
||||||
|
Statt über IP-Adressen lassen sich Updates mit einem TSIG-Schlüssel absichern, etwa für DHCP-Server, Skripte oder `nsupdate`:
|
||||||
|
|
||||||
|
1. *TSIG-Schlüssel → Neuer Schlüssel* (Algorithmus `hmac-sha256`).
|
||||||
|
2. In der dynamischen Zone den Schlüssel unter „Update-Schlüssel“ auswählen.
|
||||||
|
3. Geheimnis anzeigen (nur Administratoren, wird protokolliert) und beim Client hinterlegen, z. B. für `nsupdate`:
|
||||||
|
|
||||||
|
```text
|
||||||
|
key "updater.ad.example.com" {
|
||||||
|
algorithm hmac-sha256;
|
||||||
|
secret "<Geheimnis>";
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
```sh
|
||||||
|
nsupdate -k updater.key <<EOF
|
||||||
|
server <primary>
|
||||||
|
zone ad.example.com
|
||||||
|
update add host1.ad.example.com. 3600 A 192.0.2.50
|
||||||
|
send
|
||||||
|
EOF
|
||||||
|
```
|
||||||
|
|
||||||
|
Microsoft-Clients und -DCs beherrschen TSIG nicht; für sie bleibt nur die Freigabe per IP-Adresse.
|
||||||
|
|
||||||
|
## Hinweise
|
||||||
|
|
||||||
|
- Wird eine dynamische Zone gelöscht oder einem anderen Cluster zugeordnet, entfernt der Agent den Zonenblock aus der Konfiguration, löscht aber Zonendatei und Journal nicht. Die Daten liegen weiter im Zonenverzeichnis des Servers.
|
||||||
|
- Eine Zone von `managed` auf `dynamic` umzustellen ist möglich: Die vorhandene Zonendatei bleibt bestehen und wird ab dann von BIND gepflegt. Der umgekehrte Weg verwirft alle per Update angelegten Records.
|
||||||
|
- Scavenging (Aufräumen veralteter dynamischer Einträge) übernimmt BIND nicht; veraltete Records müssen per `nsupdate` entfernt werden.
|
||||||
|
- MX-Records einer dynamischen Zone, deren Ziel in der Zone liegt, brauchen dort einen A- oder AAAA-Record: Sonst lehnt BIND das Update des Agents ab (Prüfung `check-integrity`), und das Ausrollen der Revision scheitert.
|
||||||
|
|
||||||
|
## Skript für die Domain Controller
|
||||||
|
|
||||||
|
[`tools/windows/Set-DcDnsToDdi.ps1`](../tools/windows/Set-DcDnsToDdi.ps1) stellt einen DC (auch Server Core, Windows PowerShell 5.1) auf die BIND-Server um: prüft die Zone auf dem DDI-Server, setzt die DNS-Server der Netzwerkkarte, macht auf Wunsch eine DHCP-Adresse statisch (`-MakeStatic`), stoppt und deaktiviert den Windows-DNS-Server, registriert A-Record und Locator-Records neu (`ipconfig /registerdns`, `nltest /dsregdns`) und wartet, bis A-, SRV- und `_msdcs`-Einträge am DDI-Server antworten. Vorher die Adresse des DCs als Update-Quelle der Zone eintragen und ausrollen.
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\Set-DcDnsToDdi.ps1 -DnsServer 10.10.10.151 -WhatIf # nur anzeigen
|
||||||
|
.\Set-DcDnsToDdi.ps1 -DnsServer 10.10.10.151 -MakeStatic -StartIsmServ -Sync
|
||||||
|
```
|
||||||
|
|
||||||
|
## Fehlersuche: `dcdiag /test:dns` meldet fehlende Einträge
|
||||||
|
|
||||||
|
- **A-Record des DCs da, SRV-Records fehlen:** Den A-Record trägt der DNS-Client ein (`ipconfig /registerdns`), die SRV-Records, den `<GUID>._msdcs`-CNAME, `gc._msdcs` und `DomainDnsZones` trägt **Netlogon** ein. Lief `nltest /dsregdns` (oder der Start von Netlogon), bevor die Update-Quellen stimmten, versucht Netlogon es erst Stunden später erneut. Abhilfe auf jedem DC: `nltest /dsregdns` oder `net stop netlogon && net start netlogon`, dann `dcdiag /test:dns` wiederholen.
|
||||||
|
- **`gc._msdcs` oder andere A-Records unter `_msdcs` fehlen:** BIND prüft in Primary-Zonen Hostnamen (`check-names`) und lehnt Unterstriche ab. Seit v0.9.1 erzeugt DDI für dynamische Zonen `check-names ignore;`; ältere Versionen nach dem Update neu ausrollen.
|
||||||
|
- **Updates werden abgelehnt:** Windows schickt Updates an den Server aus dem SOA der Zone (Primary). `nslookup -type=SOA <domain> <dns-server>` muss den BIND-Primary nennen, und dessen Name muss auflösen (z. B. als Eintrag in der Adresstabelle). Die Adressen der DCs müssen unter *Update-Quellen* der Zone stehen. Im Log von BIND (`journalctl -u named` bzw. `-u bind9`) steht bei jeder Ablehnung die Quell-IP (`update … denied`).
|
||||||
|
- **„invalid DNS server“ / keine Internet-Namen:** DDI betreibt BIND standardmäßig rein autoritativ. Zeigen DCs oder Clients ausschließlich auf BIND, unter *DNS/DHCP-Einstellungen* Rekursion einschalten, die eigenen Netze unter „Rekursion erlaubt für“ eintragen und Forwarder angeben (z. B. Router oder Resolver des Providers).
|
||||||
|
- **Domain Controller mit DHCP-Adresse:** dcdiag warnt zu Recht; DCs sollten ihre IP fest im Betriebssystem eingetragen haben.
|
||||||
|
- **„Broken delegated domain _msdcs“:** BIND führt `_msdcs` in der Zone selbst, ohne Delegation. Die Meldung stammt aus den Daten eines noch laufenden Windows-DNS-Servers (auf dem DC, auf dem dcdiag läuft); sie verschwindet, sobald dort der Dienst gestoppt ist. Eine eigene Zone `_msdcs.<domain>` in DDI ist nicht nötig – sie würde die vorhandenen `_msdcs`-Einträge der Hauptzone verdecken.
|
||||||
|
|
||||||
|
## Prüfen nach der Umstellung
|
||||||
|
|
||||||
|
`dcdiag /test:dns` setzt einen Windows-DNS-Server auf dem DC voraus. Ist dieser gestoppt, meldet der Test „DNS service is stopped“ bzw. „no DNS RPC connectivity“ und überspringt den Rest; mit BIND bleibt er daher rot. Ebenso erzeugt dcdiag selbst DCOM-Fehler (Ereignis 10028) im Systemprotokoll, weil es die DNS-Server per Microsoft-RPC verwalten will. Aussagekräftig sind stattdessen:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
dcdiag /test:RegisterInDNS /DnsDomain:ad.example.com # darf der DC seine Einträge registrieren?
|
||||||
|
nltest /dsgetdc:ad.example.com /force # DC-Locator
|
||||||
|
dcdiag # Standardtests ohne DNS-Test
|
||||||
|
repadmin /replsummary
|
||||||
|
```
|
||||||
|
|
||||||
|
Scheitern dabei *Advertising* und *NetLogons* (Freigabe `NETLOGON` fehlt, `SysvolReady` = 0), liegt das nicht an DNS, sondern an der SYSVOL-Replikation (DFSR). Konnten die DCs sich vor der Umstellung lange nicht erreichen, steht ein DC oft im Zustand 5 mit Ereignis 4012 (`MaxOfflineTimeInDays` überschritten) und der andere wartet mit 4612/4614 auf die Erstsynchronisation. Abhilfe ist eine autoritative SYSVOL-Synchronisation vom DC mit der gültigen Kopie (Microsoft KB 2218556). Zustand abfragen:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
Get-CimInstance -Namespace root\microsoftdfs -ClassName DfsrReplicatedFolderInfo | Select-Object ReplicatedFolderName,State # 4 = normal
|
||||||
|
```
|
||||||
|
|
||||||
|
Auf Server Core fehlt `dfsrdiag`; statt `dfsrdiag pollad` genügt `Restart-Service DFSR`.
|
||||||
+26
-6
@@ -23,8 +23,10 @@ Sitzungen enden nach 12 Stunden oder nach 1 Stunde Inaktivität (konfigurierbar)
|
|||||||
|
|
||||||
| Recht | Viewer | Operator | Admin |
|
| Recht | Viewer | Operator | Admin |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Netze, Adressen, Lizenzstatus ansehen, exportieren, eigene Filter | ✓ | ✓ | ✓ |
|
| Netze, Adressen, Zonen, Records, Cluster, TSIG-Schlüssel (ohne Geheimnis), Lizenzstatus ansehen, exportieren, eigene Filter | ✓ | ✓ | ✓ |
|
||||||
| Netze und Adressen ändern, Import | | ✓ | ✓ |
|
| Netze, Adressen, Zonen und Records ändern, Import | | ✓ | ✓ |
|
||||||
|
| Revisionen erzeugen, ausrollen, zurückrollen | | ✓ | ✓ |
|
||||||
|
| Cluster und TSIG-Schlüssel verwalten, Geheimnis eines Schlüssels anzeigen, Agents, Generator-Einstellungen | | | ✓ |
|
||||||
| Benutzer, SSO, Lizenz verwalten, Audit-Log | | | ✓ |
|
| Benutzer, SSO, Lizenz verwalten, Audit-Log | | | ✓ |
|
||||||
|
|
||||||
`GET /auth/session` liefert die effektiven Rechte (`permissions`).
|
`GET /auth/session` liefert die effektiven Rechte (`permissions`).
|
||||||
@@ -49,15 +51,15 @@ Fehler sind Problem-Dokumente nach RFC 9457 (`application/problem+json`):
|
|||||||
- `problems` listet Feldfehler mit eigenem `code`, optional `field` und `params`.
|
- `problems` listet Feldfehler mit eigenem `code`, optional `field` und `params`.
|
||||||
- `request_id` entspricht dem Header `X-Request-ID` und findet sich in den Server-Logs wieder.
|
- `request_id` entspricht dem Header `X-Request-ID` und findet sich in den Server-Logs wieder.
|
||||||
|
|
||||||
Wichtige Statuscodes: `401` (nicht angemeldet, `mfa_required`), `403` (`forbidden`, `csrf`, `license_read_only`, `password_change_required`), `404`, `409` (Konflikt, z. B. `network_overlap`, `version_conflict`), `422` (Validierung), `429` (zu viele Anmeldeversuche, mit `Retry-After`).
|
Wichtige Statuscodes: `401` (nicht angemeldet, `mfa_required`), `403` (`forbidden`, `csrf`, `license_read_only`, `license_limit`, `license_feature`, `password_change_required`), `404`, `409` (Konflikt, z. B. `network_overlap`, `version_conflict`), `422` (Validierung), `429` (zu viele Anmeldeversuche, mit `Retry-After`).
|
||||||
|
|
||||||
## Schreibschutz durch die Lizenz
|
## Schreibschutz durch die Lizenz
|
||||||
|
|
||||||
Ist der Server schreibgeschützt (siehe [LICENSING.md](LICENSING.md)), antworten alle ändernden Endpunkte mit `403 license_read_only`. Lesen, Export, Anmeldung, eigene Filter und die Lizenzverwaltung bleiben erlaubt.
|
Ist der Server schreibgeschützt (siehe [LICENSING.md](LICENSING.md)), antworten alle ändernden Endpunkte mit `403 license_read_only`. Lesen, Export, Anmeldung, eigene Filter und die Lizenzverwaltung bleiben erlaubt. Überschreitet eine Änderung ein Limit der Lizenz (Adressen, Agents), antwortet der Server mit `403 license_limit` (Parameter `kind`, `limit`); braucht sie eine nicht freigeschaltete Funktion, mit `403 license_feature` (Parameter `feature`, ADR 0027).
|
||||||
|
|
||||||
## Gleichzeitige Änderungen
|
## Gleichzeitige Änderungen
|
||||||
|
|
||||||
Netze und Adressen tragen eine `version`. Änderungen (`PUT`) müssen die gelesene Version mitsenden; hat jemand anderes inzwischen geändert, antwortet der Server mit `409 version_conflict`.
|
Netze, Adressen, Cluster, TSIG-Schlüssel, Zonen und Records tragen eine `version`. Änderungen (`PUT`) müssen die gelesene Version mitsenden; hat jemand anderes inzwischen geändert, antwortet der Server mit `409 version_conflict`.
|
||||||
|
|
||||||
## Adresstabelle
|
## Adresstabelle
|
||||||
|
|
||||||
@@ -72,7 +74,25 @@ Netze und Adressen tragen eine `version`. Änderungen (`PUT`) müssen die gelese
|
|||||||
|
|
||||||
Die Antwort enthält `items` und `total`. `GET /addresses/export` akzeptiert dieselben Filter und liefert CSV.
|
Die Antwort enthält `items` und `total`. `GET /addresses/export` akzeptiert dieselben Filter und liefert CSV.
|
||||||
|
|
||||||
`POST /addresses/preview` beschreibt vorab die Auswirkungen einer Änderung auf DNS und DHCP (z. B. `dhcp.add_reservation`). Massenänderungen (`/addresses/bulk`) und CSV-Import (`/addresses/import`, mit `dry_run=true` zur Prüfung) gelten ganz oder gar nicht; Probleme werden pro Adresse bzw. Zeile gemeldet.
|
`POST /addresses/preview` beschreibt vorab die Auswirkungen einer Änderung auf DNS und DHCP (z. B. `dhcp.add_reservation`). Massenänderungen (`/addresses/bulk`) und CSV-Import (`/addresses/import`, mit `dry_run=true` zur Prüfung) gelten ganz oder gar nicht; Probleme werden pro Adresse bzw. Zeile gemeldet. `/addresses/bulk` kennt außerdem `set_description`, `regenerate_hostnames` (neue Zufallsnamen für `dynamic`-Einträge) und `dry_run`: Dann ändert sich nichts, die Antwort meldet Probleme und unter `effects` die zusammengefassten Auswirkungen (Codes wie bei der Vorschau, Parameter `count`; kommt ein Code nur einmal vor, stehen seine Parameter dabei).
|
||||||
|
|
||||||
|
## DHCP-Bereiche und IP-Listen (ADR 0025)
|
||||||
|
|
||||||
|
Ein Netz hat keine Pools mehr; sein DHCP-Bereich besteht aus den `dynamic`-Einträgen. `Network.pools` ist eine abgeleitete, schreibgeschützte Liste der zusammenhängenden Bereiche; `NetworkRequest` kennt kein `pools`. `dynamic`-Einträge ohne Hostnamen erhalten einen Namen `dyn-` + 8 Zeichen `[a-z0-9]`. `Address.lease_hostname` ist der Name, den der DHCP-Client zuletzt gemeldet hat; er wirkt nicht auf DNS.
|
||||||
|
|
||||||
|
- `GET /networks/{id}/ips?offset&limit&filter=all|free|used` (Recht `ipam.read`, `limit` bis 1024, Standard 256): jede Adresse des Netzes in Adressreihenfolge mit Zustand `free`, `network`, `broadcast`, `gateway` oder `used` (dann mit `address`). `all` und `free` nur für IPv4-Netze bis /16, sonst `422 network_too_large`.
|
||||||
|
- `POST /networks/{id}/range` (Recht `ipam.write`): `{"start", "end", "action": "assign"|"clear", "type", "types", "dry_run"}`. `assign` legt für jede freie Adresse des Bereichs einen Eintrag vom Typ `dynamic`, `static` oder `reserved` an (Netz-, Broadcast- und Gateway-Adresse sowie belegte Adressen zählen als `skipped`); `clear` löscht die Einträge der Typen `types` (Standard `dynamic` und `reserved`). Höchstens 65.536 Adressen, ein Audit-Eintrag `network.range_assign` bzw. `network.range_clear` je Aufruf. Fehlercodes: `range_invalid`, `range_outside_network`, `range_too_large`, `invalid_type`; Regelverstöße der Einträge (z. B. `dhcp_disabled`) als `validation_failed`.
|
||||||
|
- `POST /addresses/check` (Recht `ipam.read`, 1–100 IDs): je Eintrag Ping (unprivilegiertes ICMP-Echo, Status `reachable`, `unreachable` oder `unavailable` mit Grund) und für Einträge mit DNS-Namen die Vorwärts- und Rückwärtsauflösung bei den autoritativen Servern der Zone (Status `ok`, `missing`, `mismatch`, `error`, mit befragtem Server und Antworten). Unbekannte IDs: `404 not_found`.
|
||||||
|
|
||||||
|
## Geheimnisse
|
||||||
|
|
||||||
|
TSIG-Schlüssel und HA-Passwörter erzeugt der Server selbst ([ADR 0023](adr/0023-cluster-und-zonen-m5.md)). Die API liefert sie nur an einer Stelle aus: `GET /tsig-keys/{id}/secret` (Recht `settings.admin`, jeder Abruf steht im Audit-Log – ohne das Geheimnis). Dateien mit Schlüsselmaterial erscheinen in Vorschau, Revision, Diff und offenen Änderungen mit `secret: true` und leerem Inhalt; Diffs nennen für sie nur den Status. Das HA-Passwort eines DHCP-Clusters wird nie angezeigt.
|
||||||
|
|
||||||
|
Der Systemschlüssel `ddi-agent-update` ([ADR 0026](adr/0026-eintraege-in-dynamischen-zonen.md)) entsteht mit der ersten dynamischen Zone und steht mit `system: true` in `GET /tsig-keys`. Mit ihm gleichen die DNS-Agents die von DDI verwalteten Records dynamischer Zonen ab (Dateien `ddi-suite-update.key`, geheim, und `dynamic-records.json`). Er lässt sich rotieren, aber nicht löschen (`409 key_system`); sein Name ist reserviert (`409 key_exists`).
|
||||||
|
|
||||||
|
## Ziele von Revisionen
|
||||||
|
|
||||||
|
Dateien in Vorschau, Revision und Diff tragen ein `target`: leer für die Standardgruppe (Agents ohne Cluster), sonst die Agent-ID eines Cluster-Mitglieds. `targets` beschreibt die Ziele mit Rolle, Cluster und Mitgliedsrolle zum Zeitpunkt der Revision. Ein Agent erhält die Dateien seines Ziels, wenn die Revision eines hat, sonst die der Standardgruppe.
|
||||||
|
|
||||||
## Betriebsendpunkte
|
## Betriebsendpunkte
|
||||||
|
|
||||||
|
|||||||
+25
-11
@@ -61,7 +61,7 @@ server/internal/config YAML-Datei + Umgebungsvariablen
|
|||||||
server/internal/httpserver Listener, Health, Middleware (Request-ID, Log, Header, Recover)
|
server/internal/httpserver Listener, Health, Middleware (Request-ID, Log, Header, Recover)
|
||||||
server/internal/httpapi REST-API: Routentabelle, Sitzung/CSRF/Rechte/Schreibschutz, OIDC-Flow
|
server/internal/httpapi REST-API: Routentabelle, Sitzung/CSRF/Rechte/Schreibschutz, OIDC-Flow
|
||||||
server/internal/service Anwendungsfälle; jede Änderung schreibt ihr Audit in derselben Transaktion
|
server/internal/service Anwendungsfälle; jede Änderung schreibt ihr Audit in derselben Transaktion
|
||||||
server/internal/ipam Fachlogik Netze/Pools/Adressen (rein): Validierung, effektive Pools,
|
server/internal/ipam Fachlogik Netze/DHCP-Bereiche/Adressen (rein): Validierung, effektive Pools,
|
||||||
Auslastung, Adresskarte, Änderungsvorschau
|
Auslastung, Adresskarte, Änderungsvorschau
|
||||||
server/internal/auth Argon2id, TOTP, Tokens, Rate-Limiter, Rollen und Rechte
|
server/internal/auth Argon2id, TOTP, Tokens, Rate-Limiter, Rollen und Rechte
|
||||||
server/internal/license LicenseProvider, KeygenProvider, Lizenzdateien, Zustandsautomat, Manager
|
server/internal/license LicenseProvider, KeygenProvider, Lizenzdateien, Zustandsautomat, Manager
|
||||||
@@ -70,6 +70,8 @@ server/internal/store PostgreSQL-Repositories (pgx), Migrationen (goose
|
|||||||
server/internal/configgen reine Generatoren für BIND und Kea (derive, bindgen, keagen)
|
server/internal/configgen reine Generatoren für BIND und Kea (derive, bindgen, keagen)
|
||||||
server/internal/agentapi gRPC-Dienst für Agents (Enrollment, Stream, Bundles, Leases), mTLS-Prüfung
|
server/internal/agentapi gRPC-Dienst für Agents (Enrollment, Stream, Bundles, Leases), mTLS-Prüfung
|
||||||
server/internal/agenthub offene Agent-Streams: Push neuer Revisionen, Trennen beim Sperren
|
server/internal/agenthub offene Agent-Streams: Push neuer Revisionen, Trennen beim Sperren
|
||||||
|
server/internal/events Ereignisbus für Live-Aktualisierungen (SSE unter /api/v1/events)
|
||||||
|
server/internal/textdiff Zeilen-Diff (Myers) im Unified-Format für Revisionen
|
||||||
server/internal/pki Agent-CA, Bundle-Signaturschlüssel, Zertifikate ausstellen und prüfen
|
server/internal/pki Agent-CA, Bundle-Signaturschlüssel, Zertifikate ausstellen und prüfen
|
||||||
internal/bundle Bundle-Manifest, Signatur und Prüfung (Ed25519), von Server und Agent genutzt
|
internal/bundle Bundle-Manifest, Signatur und Prüfung (Ed25519), von Server und Agent genutzt
|
||||||
internal/agentpki Agent-ID im Zertifikat, CA-Fingerprint, TLS-Einstellungen der Agents
|
internal/agentpki Agent-ID im Zertifikat, CA-Fingerprint, TLS-Einstellungen der Agents
|
||||||
@@ -81,7 +83,7 @@ Fachlogik (`ipam`, `auth`, `license`) kennt weder HTTP noch SQL. `service` orche
|
|||||||
|
|
||||||
### 3.2 Datenmodell (Kern)
|
### 3.2 Datenmodell (Kern)
|
||||||
|
|
||||||
Umgesetzt in M1 (`server/internal/store/migrations`): `app_settings` (u. a. Installationszeitpunkt, OIDC mit verschlüsseltem Secret), `users`, `sessions` (nur Token-Hash), `audit_log`, `networks`, `dhcp_pools`, `addresses` (Typen `static`, `reserved`, `manual_dhcp`, `dynamic`), `saved_filters`, `license_state` (verschlüsselt).
|
Umgesetzt in M1 (`server/internal/store/migrations`): `app_settings` (u. a. Installationszeitpunkt, OIDC mit verschlüsseltem Secret), `users`, `sessions` (nur Token-Hash), `audit_log`, `networks`, `dhcp_pools` (bis Migration 00006), `addresses` (Typen `static`, `reserved`, `manual_dhcp`, `dynamic`), `saved_filters`, `license_state` (verschlüsselt).
|
||||||
|
|
||||||
Die Datenbank erzwingt die Kernregeln selbst:
|
Die Datenbank erzwingt die Kernregeln selbst:
|
||||||
|
|
||||||
@@ -90,11 +92,20 @@ Die Datenbank erzwingt die Kernregeln selbst:
|
|||||||
- IP eindeutig je Netz, Name (FQDN) eindeutig je Zone für Einträge mit DNS-Records
|
- IP eindeutig je Netz, Name (FQDN) eindeutig je Zone für Einträge mit DNS-Records
|
||||||
- Adresse liegt im Netz (Trigger), Host-Adresse statt Präfix
|
- Adresse liegt im Netz (Trigger), Host-Adresse statt Präfix
|
||||||
|
|
||||||
Optimistisches Sperren über `version`; alle Änderungen an Pools und Adressen eines Netzes sperren die Netzzeile und sind dadurch serialisiert.
|
Optimistisches Sperren über `version`; alle Änderungen an den Adressen eines Netzes sperren die Netzzeile und sind dadurch serialisiert.
|
||||||
|
|
||||||
M3 (Migration 00003): `agents`, `enrollment_tokens`, `pki_keys` (verschlüsselt), `config_revisions` und `config_revision_files` (unveränderlich per Trigger), `deployments`, `dhcp_leases`; Einzelheiten in [ADR 0021](adr/0021-agent-strecke-m3.md). Ab M4/M5 folgen `pending_change` (Entwürfe), `zone` (`forward`/`reverse`, Modus `managed`/`dynamic`), `record` und `cluster` (`dns`/`dhcp`).
|
M3 (Migration 00003): `agents`, `enrollment_tokens`, `pki_keys` (verschlüsselt), `config_revisions` und `config_revision_files` (unveränderlich per Trigger), `deployments`, `dhcp_leases`; Einzelheiten in [ADR 0021](adr/0021-agent-strecke-m3.md). M4 (Migration 00004): `agents.target_revision`, offene Push-Deployments, `config_revisions.source` (Generator-Eingabe für Rollbacks); Entwürfe ergeben sich aus Audit-Log und Konfigurationsvergleich ([ADR 0022](adr/0022-ausrollen-pull-push-m4.md)), eine eigene `pending_change`-Tabelle entfällt. Ab M5 folgen `zone` (`forward`/`reverse`, Modus `managed`/`dynamic`), `record` und `cluster` (`dns`/`dhcp`).
|
||||||
|
|
||||||
**Pools und feste Adressen:** Pools sind Bereichsdefinitionen. Gateway sowie `static`-, `reserved`- und `manual_dhcp`-Einträge werden aus dem **effektiven** Pool ausgeschnitten (`ipam.EffectivePools`); `dynamic`-Einträge müssen innerhalb eines Pools liegen. Damit gilt die Vorgabe „statische Adressen außerhalb der Pools“ für das, was Kea tatsächlich vergibt, ohne dass Pools manuell zerlegt werden müssen.
|
**DHCP pro Adresse ([ADR 0025](adr/0025-dhcp-pro-adresse-pruefungen-ui.md), Migration 00006):** Pools werden nicht mehr gepflegt; `dhcp_pools` entfällt. Der DHCP-Bereich eines Netzes mit `dhcp_enabled` ist die Menge seiner `dynamic`-Einträge (nur IPv4, nicht die Gateway-Adresse); jede ununterbrochene Folge davon wird ein Kea-Pool (`ipam.Ranges`, in der API als abgeleitetes `Network.pools`). Damit liegen `static`-, `reserved`- und `manual_dhcp`-Einträge automatisch außerhalb dessen, was Kea vergibt.
|
||||||
|
|
||||||
|
| Typ | DHCP | DNS (A/AAAA, PTR) |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `static` | nein | ja |
|
||||||
|
| `reserved` | nein (gesperrt) | nein |
|
||||||
|
| `manual_dhcp` | Reservierung MAC → IP | ja |
|
||||||
|
| `dynamic` | IP gehört zum DHCP-Bereich (ohne MAC) | ja (ab Generator-Eingabe Version 3) |
|
||||||
|
|
||||||
|
`dynamic`-Einträge ohne Hostnamen erhalten beim Anlegen (Formular, CSV, Bereichsoperation, Typwechsel, Massenänderung) einen zufälligen Namen `dyn-` + 8 Zeichen `[a-z0-9]`; der eindeutige FQDN-Index umfasst `static`, `manual_dhcp` und `dynamic`. Leases ändern nur vorhandene Einträge (Lease-Felder, vom Client gemeldeter Name in `lease_hostname`, bei `dynamic` die MAC), nie den Hostnamen, und legen keine Einträge an. Bereichsoperationen (`POST /networks/{id}/range`) legen bzw. löschen bis zu 65.536 Einträge in einer Anweisung mit einem Audit-Eintrag.
|
||||||
|
|
||||||
### 3.3 Änderungsfluss
|
### 3.3 Änderungsfluss
|
||||||
|
|
||||||
@@ -149,11 +160,11 @@ type Role interface { // wie wird sie angewendet?
|
|||||||
|
|
||||||
### 4.3 DNS-Rolle
|
### 4.3 DNS-Rolle
|
||||||
|
|
||||||
Eine generierte Include-Datei plus Zonendateien der managed Zonen. Dynamische Zonen werden angelegt, aber deren Daten nie überschrieben. Primary/Secondary mit NOTIFY und TSIG-gesichertem AXFR/IXFR (M5). Details: [0004](adr/0004-dns-engine-bind9.md).
|
Eine generierte Include-Datei plus Zonendateien der managed Zonen. Dynamische Zonen werden angelegt, aber deren Daten nie überschrieben; die Records, die DDI darin verwaltet (Adresstabelle, Records der Zone), gleicht der DNS-Agent per `nsupdate` mit dem Systemschlüssel `ddi-agent-update` ab ([0026](adr/0026-eintraege-in-dynamischen-zonen.md)). Primary/Secondary mit NOTIFY und TSIG-gesichertem AXFR/IXFR (M5). Details: [0004](adr/0004-dns-engine-bind9.md).
|
||||||
|
|
||||||
### 4.4 DHCP-Rolle
|
### 4.4 DHCP-Rolle
|
||||||
|
|
||||||
Vollständige `kea-dhcp4.conf`, Pools um `static`/`reserved` herum aufgeteilt, Reservierungen aus `manual_dhcp`. Leases über `lease_cmds` (`lease4-get-page`), daraus Änderungsereignisse an den Server. HA über `libdhcp_ha.so` (M5). Nur frei verfügbare Kea-Bestandteile ([0005](adr/0005-dhcp-engine-kea.md)).
|
Vollständige `kea-dhcp4.conf`, Pools aus den Folgen von `dynamic`-Einträgen (ADR 0025), Reservierungen aus `manual_dhcp`. Leases über `lease_cmds` (`lease4-get-page`), daraus Änderungsereignisse an den Server. HA über `libdhcp_ha.so` (M5). Nur frei verfügbare Kea-Bestandteile ([0005](adr/0005-dhcp-engine-kea.md)).
|
||||||
|
|
||||||
## 5. Kommunikation und Sicherheit
|
## 5. Kommunikation und Sicherheit
|
||||||
|
|
||||||
@@ -165,7 +176,7 @@ Vollständige `kea-dhcp4.conf`, Pools um `static`/`reserved` herum aufgeteilt, R
|
|||||||
| DNS | Clients → BIND | 53/udp+tcp | – |
|
| DNS | Clients → BIND | 53/udp+tcp | – |
|
||||||
| Zonentransfer | Secondary ↔ Primary | 53/tcp | TSIG |
|
| Zonentransfer | Secondary ↔ Primary | 53/tcp | TSIG |
|
||||||
| DHCP | Clients/Relays → Kea | 67/udp (Antwort 68/udp) | – |
|
| DHCP | Clients/Relays → Kea | 67/udp (Antwort 68/udp) | – |
|
||||||
| Kea-HA | Kea ↔ Kea | konfigurierbar | TLS empfohlen (M5) |
|
| Kea-HA | Kea ↔ Kea | 8001/tcp (`ha_port`) | HTTP mit Basic-Auth, noch ohne TLS (siehe [SECURITY.md](SECURITY.md#6-was-nicht-geschützt-ist)) |
|
||||||
|
|
||||||
Vertrauenskette und Schlüssel:
|
Vertrauenskette und Schlüssel:
|
||||||
|
|
||||||
@@ -173,7 +184,7 @@ Vertrauenskette und Schlüssel:
|
|||||||
- **CA-Schlüssel** signiert Server- und Agent-Zertifikate ([0008](adr/0008-interne-ca-enrollment.md)).
|
- **CA-Schlüssel** signiert Server- und Agent-Zertifikate ([0008](adr/0008-interne-ca-enrollment.md)).
|
||||||
- **Bundle-Signaturschlüssel** (Ed25519, getrennt von der CA) signiert Konfigurationen ([0009](adr/0009-signierte-config-bundles.md)).
|
- **Bundle-Signaturschlüssel** (Ed25519, getrennt von der CA) signiert Konfigurationen ([0009](adr/0009-signierte-config-bundles.md)).
|
||||||
|
|
||||||
Bedrohungsmodell und Härtung folgen in `docs/SECURITY.md` (M6).
|
Bedrohungsmodell, Schlüsselverwaltung und Härtung: [SECURITY.md](SECURITY.md). Betrieb (Sicherung, Upgrade, Rotation, Fehlersuche): [OPERATIONS.md](OPERATIONS.md). Ports, Versionen und gemessene Richtwerte: [SYSTEM-REQUIREMENTS.md](SYSTEM-REQUIREMENTS.md).
|
||||||
|
|
||||||
## 6. Dateisystem auf den Zielsystemen
|
## 6. Dateisystem auf den Zielsystemen
|
||||||
|
|
||||||
@@ -199,14 +210,17 @@ Server und Agents lesen eine YAML-Datei (Server: Pfad aus `DDI_CONFIG_FILE`, Bei
|
|||||||
| `DDI_LOG_LEVEL`, `DDI_LOG_FORMAT` | Logging |
|
| `DDI_LOG_LEVEL`, `DDI_LOG_FORMAT` | Logging |
|
||||||
| `DDI_SESSION_LIFETIME`, `DDI_SESSION_IDLE_TIMEOUT` | Sitzungen |
|
| `DDI_SESSION_LIFETIME`, `DDI_SESSION_IDLE_TIMEOUT` | Sitzungen |
|
||||||
| `DDI_LICENSE_GRACE_PERIOD`, `KEYGEN_URL`, `KEYGEN_PRODUCT_ID` | Lizenz (siehe [LICENSING.md](LICENSING.md)) |
|
| `DDI_LICENSE_GRACE_PERIOD`, `KEYGEN_URL`, `KEYGEN_PRODUCT_ID` | Lizenz (siehe [LICENSING.md](LICENSING.md)) |
|
||||||
|
| `DDI_RETENTION_AUDIT_DAYS`, `DDI_RETENTION_REVISIONS_KEEP` | Aufbewahrung (`retention.audit_days`, `retention.revisions_keep`; 0 = alles behalten) |
|
||||||
|
|
||||||
`KEYGEN_ACCOUNT_ID` und `KEYGEN_PUBLIC_KEY` gelten nur für Builds ohne eingebettete Werte (Entwicklung). Dauerangaben verstehen Go-Notation und Tage (`14d`).
|
`KEYGEN_ACCOUNT_ID` und `KEYGEN_PUBLIC_KEY` gelten nur für Builds ohne eingebettete Werte (Entwicklung). Dauerangaben verstehen Go-Notation und Tage (`14d`).
|
||||||
|
|
||||||
|
**Aufbewahrung** ([0024](adr/0024-auslieferung-installer-m6.md)): Ist `retention.audit_days` oder `retention.revisions_keep` gesetzt, räumt der Server fünf Minuten nach dem Start und danach täglich auf. Gelöscht werden Audit-Einträge, die älter als die angegebene Zahl Tage sind, und Revisionen jenseits der neuesten `revisions_keep` (samt Dateien). Nie gelöscht werden die neueste Revision, Revisionen, die ein Agent anwendet, als letzte funktionierende kennt oder als Ziel hat, und Revisionen mit offenen Deployments. Ein Aufräumlauf, der etwas löscht, schreibt den Audit-Eintrag `retention.cleanup` mit den Anzahlen.
|
||||||
|
|
||||||
## 8. Build, CI und Auslieferung
|
## 8. Build, CI und Auslieferung
|
||||||
|
|
||||||
- `Makefile` als Einstieg: `build`, `test`, `lint`, `fmt`, `generate`, `web`, `dev-up`/`dev-down`, `release`.
|
- `Makefile` als Einstieg: `build`, `test`, `lint`, `fmt`, `generate`, `web`, `dev-up`/`dev-down`, `release`.
|
||||||
- CI: Gitea Actions unter `.gitea/workflows/` ([0003](adr/0003-git-host-gitea-actions.md)). Geprüft werden Go (Format, `vet`, `golangci-lint`, Tests, `govulncheck`), Protobuf (`buf lint`, generierter Code aktuell), Web (ESLint, Typecheck, Build, Tests, `npm audit`), Shell (`shellcheck`), SPDX-Header und die Entwicklungsumgebung (Compose-Smoke-Test).
|
- CI: Gitea Actions unter `.gitea/workflows/` ([0003](adr/0003-git-host-gitea-actions.md)). Geprüft werden Go (Format, `vet`, `golangci-lint`, Tests, `govulncheck`), Protobuf (`buf lint`, generierter Code aktuell), Web (ESLint, Typecheck, Build, Tests, `npm audit`), Shell (`shellcheck`), SPDX-Header und die Entwicklungsumgebung (Compose-Smoke-Test).
|
||||||
- Release bei Tag `v*`: Binaries für `linux/amd64` und `linux/arm64`, Tarballs, `SHA256SUMS`, Upload an das Gitea-Release.
|
- Release bei Tag `v*`: Binaries für `linux/amd64` und `linux/arm64`, Tarballs, `.deb`/`.rpm` (nfpm), `SHA256SUMS` und – mit Secret `RELEASE_SIGNING_KEY` – die Ed25519-Signatur `SHA256SUMS.sig`, Upload an das Gitea-Release ([RELEASE.md](RELEASE.md)).
|
||||||
- Installer `scripts/install.sh` (M6) lädt die Artefakte und prüft die Prüfsummen.
|
- Installer `scripts/install.sh` (M6) lädt die Artefakte und prüft die Prüfsummen.
|
||||||
|
|
||||||
## 9. Entwicklungsumgebung
|
## 9. Entwicklungsumgebung
|
||||||
@@ -215,7 +229,7 @@ Server und Agents lesen eine YAML-Datei (Server: Pfad aus `DDI_CONFIG_FILE`, Bei
|
|||||||
|
|
||||||
## 10. Skalierung
|
## 10. Skalierung
|
||||||
|
|
||||||
Zielgröße der ersten Version sind bis ca. 50 Agents und einige zehntausend Adressen. Damit es nach oben nicht verbaut ist, gilt:
|
Zielgröße der ersten Version sind bis ca. 50 Agents und einige zehntausend Adressen. Gemessene Werte für 5.000 und 50.000 Adressen stehen in [SYSTEM-REQUIREMENTS.md](SYSTEM-REQUIREMENTS.md#4-messungen). Damit es nach oben nicht verbaut ist, gilt:
|
||||||
|
|
||||||
- Tabellen werden serverseitig paginiert und gefiltert. Indizes auf `ip`, `mac`, `hostname`.
|
- Tabellen werden serverseitig paginiert und gefiltert. Indizes auf `ip`, `mac`, `hostname`.
|
||||||
- Revisionen speichern strukturierte Daten plus Artefakte. Die Aufbewahrung ist konfigurierbar.
|
- Revisionen speichern strukturierte Daten plus Artefakte. Die Aufbewahrung ist konfigurierbar.
|
||||||
|
|||||||
+159
@@ -0,0 +1,159 @@
|
|||||||
|
# Installation
|
||||||
|
|
||||||
|
`scripts/install.sh` richtet die drei Rollen der DDI-Suite auf einem Linux-Host ein: den **Management-Server** (`server`), den **DNS-Agent mit BIND** (`agent-dns`) und den **DHCP-Agent mit Kea** (`agent-dhcp`). Die Rollen lassen sich beliebig auf Hosts verteilen oder kombinieren. Entscheidungen dazu: [ADR 0024](adr/0024-auslieferung-installer-m6.md).
|
||||||
|
|
||||||
|
## Voraussetzungen
|
||||||
|
|
||||||
|
| | |
|
||||||
|
| --- | --- |
|
||||||
|
| Systeme | Debian 12 und 13, Ubuntu 22.04 und 24.04 LTS, Rocky Linux/AlmaLinux/RHEL 9 |
|
||||||
|
| Architekturen | amd64 (x86_64), arm64 (aarch64, z. B. Raspberry Pi 4/5 mit 64-Bit-System) |
|
||||||
|
| Rechte | root (`sudo`) |
|
||||||
|
| Init-System | systemd |
|
||||||
|
| Netz | Zugriff auf die Paketquellen der Distribution, auf `git.beugsiud.de` (Release-Artefakte) und für `agent-dhcp` auf `dl.cloudsmith.io` (ISC-Kea-Pakete); der Server prüft `https://license.beugsiud.de` (nur Warnung) |
|
||||||
|
| Zeit | synchronisierte Uhr (NTP), sonst warnt der Installer |
|
||||||
|
|
||||||
|
Richtwerte stehen in `docs/SYSTEM-REQUIREMENTS.md`; der Installer prüft vorab (Abschnitt 3 dort, Schwellen als Variablen oben im Skript). Mehrere Rollen auf einem Host: RAM und Platte addieren sich, bei CPU zählt das Maximum.
|
||||||
|
|
||||||
|
| Prüfung | Warnung | Abbruch |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| CPU-Kerne | Server < 2 | – |
|
||||||
|
| RAM | Server < 3,5 GiB, je Agent < 900 MiB | Server < 1,8 GiB, je Agent < 450 MiB |
|
||||||
|
| Freier Platz im Dateisystem von `/var/lib` | Server < 20 GiB, je Agent < 5 GiB | Server < 4 GiB, je Agent < 1 GiB |
|
||||||
|
| Freier Platz für `/usr/local/bin` | – | < 200 MiB |
|
||||||
|
| Ports | 8001/tcp (Kea-HA) belegt; 53 nur von systemd-resolved auf 127.0.0.53 belegt | 8443/8444 belegt (nicht vom Server), 53 belegt (nicht von `named`), 67/udp belegt (nicht von `kea-dhcp4`) |
|
||||||
|
| Versionen | BIND < 9.18, Kea < 3.0 (keine HA) | PostgreSQL < 13, Kea < 2.6 |
|
||||||
|
| Netz | Lizenzserver nicht erreichbar (Server), Agent-API des Servers nicht erreichbar (Agents mit `--server`) | ISC-Repository nicht erreichbar (`--kea-source isc`) |
|
||||||
|
| Zeit | Uhr nicht per NTP synchronisiert | – |
|
||||||
|
|
||||||
|
`--force` macht aus jedem Abbruch eine Warnung; nicht unterstützte Systeme und Architekturen bleiben ein Abbruch.
|
||||||
|
|
||||||
|
## Herunterladen, prüfen, ausführen
|
||||||
|
|
||||||
|
Das Skript bitte **nicht** per `curl … | sudo bash` ausführen, sondern erst herunterladen und lesen:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -fsSLO https://git.beugsiud.de/beug.k/DDI/raw/branch/main/scripts/install.sh
|
||||||
|
less install.sh # ansehen, was es tut
|
||||||
|
chmod +x install.sh
|
||||||
|
sudo ./install.sh --role server --dry-run # zeigt nur, was passieren würde
|
||||||
|
sudo ./install.sh --role server
|
||||||
|
```
|
||||||
|
|
||||||
|
Für eine feste Version das Skript aus dem Tag statt aus `main` laden, z. B. `https://git.beugsiud.de/beug.k/DDI/raw/tag/v0.7.0/scripts/install.sh`, und `--version v0.7.0` angeben.
|
||||||
|
|
||||||
|
Ohne `--version` installiert das Skript das neueste Release (`/api/v1/repos/beug.k/DDI/releases/latest`). Es lädt die Tarballs der gewählten Rollen und `SHA256SUMS` von `https://git.beugsiud.de/beug.k/DDI/releases/download/<tag>/` und prüft jede Prüfsumme. Ist im Skript ein öffentlicher Signaturschlüssel hinterlegt (`RELEASE_PUBLIC_KEY_PEM`), muss außerdem die Ed25519-Signatur `SHA256SUMS.sig` gültig sein; solange die Releases nicht signiert werden, weist das Skript darauf hin, dass nur die Prüfsummen geprüft wurden.
|
||||||
|
|
||||||
|
## Typischer Ablauf
|
||||||
|
|
||||||
|
1. **Server installieren:**
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo ./install.sh --role server --public-url https://ddi.example.org:8443
|
||||||
|
```
|
||||||
|
|
||||||
|
Am Ende stehen die URL der Oberfläche und ein **einmaliges Administrator-Passwort** (Benutzer `admin`). Es steht nur auf dem Bildschirm, nicht im Log, und muss bei der ersten Anmeldung geändert werden. Interaktiv fragt der Installer nach einem Lizenzschlüssel (optional, Eingabe auch später in der Oberfläche möglich).
|
||||||
|
|
||||||
|
2. **Agent registrieren:** In der Oberfläche unter *Agents* ein Enrollment-Token für die Rolle anlegen. Die Oberfläche zeigt zwei gleichwertige Befehle: den Installer-Aufruf für einen neuen Host und `ddi-agent-dns enroll --server <host>:8444 --token <token> --ca-hash sha256:<hex>` für einen Host, auf dem der Agent schon installiert ist. Auf einem neuen Host:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo ./install.sh --role agent-dns --server ddi.example.org:8444 \
|
||||||
|
--token <token> --ca-hash sha256:<hex>
|
||||||
|
```
|
||||||
|
|
||||||
|
Für den DHCP-Agent entsprechend `--role agent-dhcp` mit einem Token der Rolle `dhcp`. Pro Aufruf wird genau ein Agent registriert.
|
||||||
|
|
||||||
|
**Ohne Token** wird der Agent installiert und sein Dienst eingeschaltet; systemd startet ihn erst, wenn eine Identität vorhanden ist (`ConditionPathExists`). Registrieren lässt er sich danach auf zwei Wegen: den Installer erneut mit `--server --token --ca-hash` aufrufen oder den `enroll`-Befehl aus der Oberfläche **als root** ausführen. Dieser übergibt die Identität an den Dienstbenutzer (`bind` bzw. `_kea`) und startet den Dienst (`systemctl enable --now`; mit `--no-start` nicht). Ein Agent, der mit einer älteren Version von Hand registriert wurde und nicht läuft, wird durch `install.sh --upgrade` repariert.
|
||||||
|
|
||||||
|
3. **Prüfen:** In der Oberfläche erscheinen die Agents als verbunden; nach dem ersten Ausrollen liefern BIND und Kea die Konfiguration.
|
||||||
|
|
||||||
|
Alle drei Rollen auf einem Host: `sudo ./install.sh --role server,agent-dns,agent-dhcp`, danach die Agents wie in Schritt 2 registrieren (Server-Adresse ist der eigene Hostname).
|
||||||
|
|
||||||
|
## Optionen
|
||||||
|
|
||||||
|
| Option | Bedeutung |
|
||||||
|
| --- | --- |
|
||||||
|
| `--role <rolle>` | `server`, `agent-dns`, `agent-dhcp`; mehrfach oder mit Komma getrennt |
|
||||||
|
| `--version <tag>` | Release, Standard: neuestes |
|
||||||
|
| `--from-dir <verzeichnis>` | Release-Artefakte (Tarballs, `SHA256SUMS`, ggf. `SHA256SUMS.sig`) aus einem Verzeichnis statt Download (offline, Tests) |
|
||||||
|
| `--git-token <token>` | Zugriffstoken, falls Releases eine Anmeldung brauchen (alternativ `DDI_GIT_TOKEN`); wird nie geloggt |
|
||||||
|
| `--server <host:port>`, `--token <token>`, `--ca-hash sha256:<hex>` | Registrierung eines Agents (Werte aus dem Enrollment-Befehl der Oberfläche) |
|
||||||
|
| `--server-name <name>` | TLS-Name des Servers, falls er vom Host in `--server` abweicht (steht dann im Befehl der Oberfläche) |
|
||||||
|
| `--kea-source isc\|distro` | Kea aus dem ISC-Repository (Standard, Kea 3.x mit HA) oder aus der Distribution (ohne HA, siehe unten) |
|
||||||
|
| `--public-url <url>` | URL der Oberfläche, Standard `https://<fqdn>:8443`; ihr Hostname ist auch die Agent-API-Adresse (`<host>:8444`) |
|
||||||
|
| `--tls-cert <datei>`, `--tls-key <datei>` | eigenes Zertifikat (PEM, mit Kette) und Schlüssel; ohne erzeugt der Installer ein selbstsigniertes Zertifikat |
|
||||||
|
| `--license-key-file <datei>` | Lizenzschlüssel aktivieren; Fehler (ungültig, Lizenzserver nicht erreichbar) sind nur Warnungen |
|
||||||
|
| `--upgrade` | Binaries und Units ersetzen, Dienste neu starten |
|
||||||
|
| `--uninstall` | Rollen entfernen, Konfiguration und Daten bleiben |
|
||||||
|
| `--purge` | mit `--uninstall`: auch Konfiguration, Daten, Datenbank, Schlüssel und Dienstbenutzer löschen |
|
||||||
|
| `--dry-run` | nur anzeigen, nichts ändern |
|
||||||
|
| `--non-interactive` | nie nachfragen (zum Ändern ist dann `--yes` nötig) |
|
||||||
|
| `--yes` | Rückfrage mit Ja beantworten |
|
||||||
|
| `--force` | Vorabprüfung nur warnen lassen |
|
||||||
|
|
||||||
|
Umgebung: `DDI_RELEASE_BASE_URL` ersetzt die Download-Adresse (`<tag>` darin wird durch die Version ersetzt; ohne `<tag>` ist es das Verzeichnis der Artefakte), `DDI_GIT_TOKEN`.
|
||||||
|
|
||||||
|
## Was wird wo installiert
|
||||||
|
|
||||||
|
Gemeinsam für alle Rollen:
|
||||||
|
|
||||||
|
| Pfad | Inhalt |
|
||||||
|
| --- | --- |
|
||||||
|
| `/usr/local/bin/ddi-server`, `ddi-agent-dns`, `ddi-agent-dhcp` | Binaries |
|
||||||
|
| `/etc/systemd/system/<binary>.service` | systemd-Units (gehärtet, siehe ADR 0024) |
|
||||||
|
| `/etc/ddi-suite/` | Konfiguration (Verzeichnis 0755, Dateien einzeln geschützt) |
|
||||||
|
| `/var/lib/ddi-suite/` | Zustand (`server/`, `agent-dns/`, `agent-dhcp/`) |
|
||||||
|
| `/var/log/ddi-suite/install.log` | Protokoll des Installers (ohne Tokens, Schlüssel und Passwörter) |
|
||||||
|
| `/usr/local/share/doc/ddi-suite/` | Lizenztexte |
|
||||||
|
|
||||||
|
**Server**
|
||||||
|
|
||||||
|
| | |
|
||||||
|
| --- | --- |
|
||||||
|
| Pakete | PostgreSQL der Distribution (Debian/Ubuntu `postgresql`, EL9 `postgresql-server` aus dem Modul-Stream ≥ 15, höchster verfügbarer), `openssl`, `curl` |
|
||||||
|
| Benutzer | Systembenutzer `ddi-suite` |
|
||||||
|
| Datenbank | Rolle und Datenbank `ddi-suite`, Anmeldung per Peer-Authentifizierung über den Unix-Socket (kein Passwort) |
|
||||||
|
| `/etc/ddi-suite/server.yaml` | Konfiguration (0640 root:ddi-suite) |
|
||||||
|
| `/etc/ddi-suite/master.key` | Master-Key (0400 ddi-suite) – **sichern**, ohne ihn sind verschlüsselte Daten verloren |
|
||||||
|
| `/etc/ddi-suite/tls/` | TLS-Zertifikat und Schlüssel der Oberfläche |
|
||||||
|
| Ports | 8443/tcp (Oberfläche, API), 8444/tcp (Agent-API) |
|
||||||
|
|
||||||
|
**DNS-Agent** (läuft als BIND-Benutzer `bind` bzw. `named`)
|
||||||
|
|
||||||
|
| | Debian/Ubuntu | EL9 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Pakete | `bind9`, `bind9-utils`, `bind9-dnsutils` | `bind9.18`, `bind9.18-utils` (sonst `bind`, Warnung unter 9.18) |
|
||||||
|
| BIND-Konfiguration | `/etc/bind/named.conf`, `named.conf.options` | `/etc/named.conf` |
|
||||||
|
| Dateien des Agents | `/etc/bind/ddi-suite/` | `/etc/named/ddi-suite/` |
|
||||||
|
| Zonendateien | `/var/lib/bind/ddi-suite/` (inkl. `secondary/`) | ebenso, SELinux-Typ `named_cache_t` |
|
||||||
|
| Agent-Konfiguration | `/etc/ddi-suite/agent-dns.yaml` | ebenso |
|
||||||
|
|
||||||
|
Der Installer fügt in `named.conf` einen markierten Block ein (`// BEGIN ddi-suite …` bis `// END ddi-suite …`), der `ddi-suite-keys.conf` und `ddi-suite.conf` einbindet, und im `options`-Block einen zweiten mit `ddi-suite-options.conf`. Anweisungen der Distribution, die der Generator selbst setzt (`recursion`, `allow-recursion`, `forwarders`, `allow-transfer`), sowie `listen-on`, `listen-on-v6` und `allow-query`, die BIND auf localhost beschränken (Standard auf EL9), werden mit dem Präfix `//ddi-suite-disabled: ` auskommentiert. Beim Deinstallieren werden die Blöcke entfernt und die Zeilen wiederhergestellt. Danach prüft `named-checkconf` die Konfiguration; scheitert sie, stellt der Installer die Originale wieder her.
|
||||||
|
|
||||||
|
**DHCP-Agent** (läuft als Kea-Benutzer `_kea` bzw. `kea`)
|
||||||
|
|
||||||
|
| | |
|
||||||
|
| --- | --- |
|
||||||
|
| Pakete | `isc-kea-dhcp4`, `isc-kea-hooks` aus dem ISC-Repository `isc/kea-3-2` (Cloudsmith). Der Schlüssel des Repositorys wird nur mit dem Fingerabdruck `360D0B03DFE219DB0F9FEA4C720DD962343B440F` akzeptiert. Auf EL9 wird zusätzlich EPEL aktiviert (die ISC-Pakete brauchen `log4cplus`). |
|
||||||
|
| Dienst | `isc-kea-dhcp4-server` (Debian/Ubuntu) bzw. `kea-dhcp4` (EL9) |
|
||||||
|
| Drop-in `/etc/systemd/system/<kea-unit>.service.d/10-ddi-suite.conf` | setzt `KEA_CONTROL_SOCKET_DIR=/run/kea`: Die ISC-Pakete sind mit `/var/run/kea` übersetzt und vergleichen Pfade wörtlich, der Generator verwendet `/run/kea`. Dieselbe Variable bekommt der DHCP-Agent (für `kea-dhcp4 -t`). |
|
||||||
|
| `/etc/kea/kea-dhcp4.conf` | Startkonfiguration ohne Subnetze mit Control-Socket `/run/kea/kea4-ctrl-socket`, Lease-Datei `/var/lib/kea/kea-leases4.csv` und Hook `lease_cmds`; das Original bleibt als `kea-dhcp4.conf.ddi-suite-orig` erhalten. Der Agent überschreibt die Datei mit jeder Revision. |
|
||||||
|
| HA-Dateien | `/etc/kea/ddi-suite-ha-user`, `ddi-suite-ha-password` (schreibt der Agent, wenn ein HA-Cluster konfiguriert ist) |
|
||||||
|
| Agent-Konfiguration | `/etc/ddi-suite/agent-dhcp.yaml` |
|
||||||
|
|
||||||
|
Mit `--kea-source distro` kommt Kea aus der Distribution (Debian 12: 2.2, Debian 13: 2.6, Ubuntu 22.04: 2.0, Ubuntu 24.04: 2.4). Diese Versionen können keine HA mit Dateien für Benutzer und Passwort; außerdem schreibt der Generator Hook-Bibliotheken ohne Pfad, was erst Kea 3.x auflöst. Der Weg ist für Hosts ohne Zugang zu Cloudsmith gedacht und nicht Teil der CI-Tests.
|
||||||
|
|
||||||
|
Die Agents laufen nicht als root, sondern als Benutzer des Dienstes, den sie verwalten (Drop-in `/etc/systemd/system/<binary>.service.d/10-user.conf`). Zonen-Verzeichnis, Kea-Konfiguration und Pfade entsprechen den Standard-Einstellungen des Generators auf dem Server; deshalb lassen sich Agents verschiedener Distributionen in einem Cluster mischen.
|
||||||
|
|
||||||
|
## Erneut ausführen, Upgrade, Deinstallation
|
||||||
|
|
||||||
|
- **Erneut ausführen** ist sicher: Vorhandene Konfiguration, Master-Key, Datenbank und Agent-Identität werden nie überschrieben. Ein zweiter Lauf mit denselben Optionen meldet `nothing to change (0 changes)`. Weicht ein installiertes Binary vom Release ab, bleibt es mit einer Warnung stehen.
|
||||||
|
- **Upgrade:** `sudo ./install.sh --upgrade` (ohne `--role` für alle installierten Rollen, optional `--version`). Ersetzt Binaries und Units, startet die Dienste neu; Datenbankmigrationen laufen beim Serverstart. Vorher Datenbank und `/etc/ddi-suite/master.key` sichern.
|
||||||
|
- **Deinstallation:** `sudo ./install.sh --uninstall` stoppt und entfernt Dienste, Units und Binaries und nimmt die Einbindung aus `named.conf` heraus. Konfiguration, Zustand, Zonendateien, Kea-Konfiguration, Datenbank und Master-Key bleiben erhalten; BIND, Kea und PostgreSQL laufen weiter.
|
||||||
|
- **Vollständig entfernen:** `sudo ./install.sh --uninstall --purge` löscht zusätzlich `/etc/ddi-suite`, `/var/lib/ddi-suite`, die Datenbank `ddi-suite` samt Rolle, den Benutzer `ddi-suite`, die Zonendateien, die Dateien des DNS-Agents unter `/etc/bind` bzw. `/etc/named` und stellt die ursprüngliche `kea-dhcp4.conf` wieder her. Das geht auch nach einem einfachen `--uninstall`. Pakete und das ISC-Repository bleiben installiert.
|
||||||
|
|
||||||
|
## Fehlerfälle
|
||||||
|
|
||||||
|
- Bricht ein Lauf ab, entfernt der Installer die in diesem Lauf angelegten Dateien, Verzeichnisse, Benutzer und die neu angelegte Datenbank und stellt geänderte Dateien wieder her; installierte Pakete bleiben. Details stehen in `/var/log/ddi-suite/install.log`.
|
||||||
|
- Dienste: `systemctl status ddi-server ddi-agent-dns ddi-agent-dhcp`, Logs mit `journalctl -u <dienst>`, Zustand eines Agents mit `sudo -u bind ddi-agent-dns status` (bzw. als `_kea`/`kea` für `ddi-agent-dhcp`).
|
||||||
|
- Ein selbstsigniertes Zertifikat lässt sich später ersetzen: Dateien in `/etc/ddi-suite/tls/` austauschen (Schlüssel 0640 root:ddi-suite) und `systemctl restart ddi-server`.
|
||||||
+39
-2
@@ -43,16 +43,53 @@ Das Skript legt an (und verwendet beim erneuten Aufruf wieder):
|
|||||||
- täglicher Heartbeat; ein Server, der sich einen Tag nicht meldet, wird freigegeben und beim nächsten Kontakt automatisch neu aktiviert
|
- täglicher Heartbeat; ein Server, der sich einen Tag nicht meldet, wird freigegeben und beim nächsten Kontakt automatisch neu aktiviert
|
||||||
- Laufzeit ein Jahr
|
- Laufzeit ein Jahr
|
||||||
- Standardlimits in den Metadaten: `maxAgents: 10`, `maxAddresses: 5000`
|
- Standardlimits in den Metadaten: `maxAgents: 10`, `maxAddresses: 5000`
|
||||||
|
- **Entitlements** für die Funktionen (siehe unten): `DDI_CLUSTER`, `DDI_KEA_HA`, `DDI_DYNAMIC_ZONES`, `DDI_SSO`
|
||||||
|
|
||||||
Die ausgegebene Produkt-ID wird beim Server als `KEYGEN_PRODUCT_ID` eingetragen.
|
Die ausgegebene Produkt-ID wird beim Server als `KEYGEN_PRODUCT_ID` eingetragen.
|
||||||
|
|
||||||
|
## Limits und Funktionen
|
||||||
|
|
||||||
|
| In Keygen | Name/Code | Wirkung |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Lizenz-Metadaten | `maxAddresses` | Höchstzahl der Einträge der Adresstabelle (alle Netze zusammen) |
|
||||||
|
| Lizenz-Metadaten | `maxAgents` | Höchstzahl registrierter Agents (DNS und DHCP zusammen, gesperrte zählen nicht) |
|
||||||
|
| Entitlement | `DDI_CLUSTER` | DNS- und DHCP-Cluster |
|
||||||
|
| Entitlement | `DDI_KEA_HA` | Kea-HA: DHCP-Cluster mit Primary und Secondary (braucht zusätzlich `DDI_CLUSTER`) |
|
||||||
|
| Entitlement | `DDI_DYNAMIC_ZONES` | dynamische Zonen (Updates per RFC 2136, z. B. Active Directory) |
|
||||||
|
| Entitlement | `DDI_SSO` | Anmeldung per Single Sign-On (OIDC) |
|
||||||
|
|
||||||
|
- Fehlt ein Metadatum, gilt dafür keine Grenze. Die Schreibweise muss genau stimmen.
|
||||||
|
- In der **Testphase** ist alles freigeschaltet und unbegrenzt.
|
||||||
|
- Ohne eine Funktion lässt sie sich nicht **neu** in Gebrauch nehmen (kein neuer Cluster, kein neues Mitglied, kein neues HA-Paar, keine neue dynamische Zone, SSO nicht einschaltbar). **Was schon besteht, läuft weiter** und bleibt bearbeitbar – eine Lizenzänderung schaltet weder DNS/DHCP noch den Zugang ab ([ADR 0027](adr/0027-funktionen-per-entitlement-agent-limit.md)).
|
||||||
|
- Am Agent-Limit lassen sich keine Registrierungs-Tokens mehr erzeugen, und Registrierungen werden abgelehnt. Bestehende Agents laufen weiter. Für eine Neuregistrierung (`enroll --force`) den alten Agent vorher sperren oder löschen.
|
||||||
|
- Die Seite **Lizenz** zeigt Nutzung, Limits und welche Funktionen freigeschaltet sind; gesperrte Bedienelemente sind in der Oberfläche deaktiviert.
|
||||||
|
|
||||||
## Lizenz ausstellen
|
## Lizenz ausstellen
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
tools/keygen-setup/keygen-setup.sh create-license --name "Kunde GmbH" --max-agents 20 --max-addresses 20000
|
tools/keygen-setup/keygen-setup.sh create-license --name "Kunde GmbH" --max-agents 20 --max-addresses 20000 \
|
||||||
|
--features DDI_CLUSTER,DDI_KEA_HA,DDI_DYNAMIC_ZONES,DDI_SSO # oder --features all
|
||||||
```
|
```
|
||||||
|
|
||||||
Ausgegeben werden Lizenz-ID und **Lizenzschlüssel**. Limits pro Lizenz stehen in deren Metadaten (`maxAgents`, `maxAddresses`); Feature-Freischaltungen erfolgen über Keygen-Entitlements.
|
Ausgegeben werden Lizenz-ID, **Lizenzschlüssel** und die zugeordneten Funktionen. Limits pro Lizenz stehen in deren Metadaten (`maxAgents`, `maxAddresses`), Funktionen als Entitlements der Lizenz.
|
||||||
|
|
||||||
|
Funktionen einer bestehenden Lizenz ändern:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
tools/keygen-setup/keygen-setup.sh features --license <LIZENZ-ID> # anzeigen
|
||||||
|
tools/keygen-setup/keygen-setup.sh features --license <LIZENZ-ID> --add DDI_SSO --remove DDI_KEA_HA
|
||||||
|
```
|
||||||
|
|
||||||
|
Limits einer bestehenden Lizenz ändern (Keygen ersetzt `metadata` vollständig, also beide Werte angeben):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
curl -sS -X PATCH "https://license.beugsiud.de/v1/accounts/<ACCOUNT-ID>/licenses/<LIZENZ-ID>" \
|
||||||
|
-H "Authorization: Bearer $KEYGEN_ADMIN_TOKEN" \
|
||||||
|
-H "Content-Type: application/vnd.api+json" -H "Accept: application/vnd.api+json" \
|
||||||
|
-d '{"data":{"type":"licenses","attributes":{"metadata":{"maxAgents":20,"maxAddresses":20000}}}}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Der Server übernimmt Änderungen bei der nächsten Prüfung (stündlich) oder sofort mit **Lizenz → Jetzt prüfen**. Offline-Lizenzdateien enthalten die Entitlements zum Zeitpunkt des Exports; nach einer Änderung neu exportieren.
|
||||||
|
|
||||||
Der Administrator trägt den Schlüssel in der Oberfläche unter **Lizenz → Lizenzschlüssel eintragen** ein. Der Server prüft ihn, aktiviert sich selbst als Maschine (Fingerprint aus der Machine-ID, nicht die Machine-ID selbst) und meldet sich danach regelmäßig.
|
Der Administrator trägt den Schlüssel in der Oberfläche unter **Lizenz → Lizenzschlüssel eintragen** ein. Der Server prüft ihn, aktiviert sich selbst als Maschine (Fingerprint aus der Machine-ID, nicht die Machine-ID selbst) und meldet sich danach regelmäßig.
|
||||||
|
|
||||||
|
|||||||
+123
-28
@@ -6,7 +6,7 @@ Neue Einträge oben im Abschnitt „Verlauf“ ergänzen und den Abschnitt „St
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Stand (2026-10-13, nach M3)
|
## Stand (2026-10-18, nach ADR 0027)
|
||||||
|
|
||||||
| Meilenstein | Status | Tag |
|
| Meilenstein | Status | Tag |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -14,39 +14,48 @@ Neue Einträge oben im Abschnitt „Verlauf“ ergänzen und den Abschnitt „St
|
|||||||
| M1 Server-Kern | fertig, CI grün | `v0.2.0` |
|
| M1 Server-Kern | fertig, CI grün | `v0.2.0` |
|
||||||
| M2 Config-Generator | fertig, CI grün | `v0.3.0` |
|
| M2 Config-Generator | fertig, CI grün | `v0.3.0` |
|
||||||
| M3 Agent verwaltet | fertig, CI grün | `v0.4.0` |
|
| M3 Agent verwaltet | fertig, CI grün | `v0.4.0` |
|
||||||
| M4 Pull und Push | **als Nächstes** | – |
|
| M4 Pull und Push | fertig, CI grün | `v0.5.0` |
|
||||||
| M5–M6 | offen | – |
|
| M5 Cluster und Zonen | fertig, CI grün | `v0.6.0` |
|
||||||
|
| M6 Auslieferung | fertig, CI grün | `v0.7.0` |
|
||||||
|
| Anpassungen nach Rückmeldung (ADR 0025: DHCP pro Adresse, DNS für dynamische Einträge, Bereichs-/Massenänderungen, Prüfung, neue Oberfläche) | fertig | `v0.8.0` |
|
||||||
|
| Korrekturen aus dem Betrieb: Prüfung mit Raw-ICMP und DNS-Agents (`v0.8.1`), von Hand registrierte Agents als Dienst (`v0.8.2`) | fertig | `v0.8.1`, `v0.8.2` |
|
||||||
|
| Einträge in dynamischen Zonen per `nsupdate` (ADR 0026), AD-Zone in DDI | fertig | `v0.9.0` |
|
||||||
|
| `check-names ignore` für dynamische Zonen (AD-Records unter `_msdcs`), DC-Umstellungsskript | fertig | `v0.9.1` |
|
||||||
|
| Funktionen per Entitlement (Cluster, Kea-HA, dynamische Zonen, SSO), Agent-Limit (ADR 0027) | fertig | `v0.10.0` |
|
||||||
|
| M7 (Standalone, DHCPv6, DNSSEC, Discovery) | nur Schnittstellen vorbereitet (Brief §12) | – |
|
||||||
|
|
||||||
Branch `main`, alles gepusht nach `https://git.beugsiud.de/beug.k/DDI`. Release `v0.1.0` mit Artefakten auf Gitea veröffentlicht; `v0.2.0` ebenso über den Release-Workflow.
|
Branch `main`, alles gepusht nach `https://git.beugsiud.de/beug.k/DDI`. Releases mit Artefakten über den Release-Workflow.
|
||||||
|
|
||||||
### Nächster Schritt: M4 (Pull und Push)
|
### Nächster Schritt: Abnahme auf echten Maschinen (Brief §14)
|
||||||
|
|
||||||
Laut Brief: Betriebsmodi pro Agent (`auto_pull`/`manual`, Feld `mode` existiert schon), „Jetzt ausrollen“ aus dem UI (Push über den bestehenden Stream, `ApplyRevisionCommand` mit Deployment-ID), Entwürfe (`pending_change`, „X Änderungen warten auf Ausrollen“), Diff-Ansicht zwischen Revisionen, Deployment-Status live (statt 5-s-Polling: Server-Sent Events oder WebSocket aus dem Agent-Hub), Rollback über das UI (neue Revision mit altem Inhalt, ADR 0009). Vorarbeit aus M3: `agenthub` kennt alle offenen Streams, der Agent behandelt jedes Kommando als expliziten Push.
|
M0–M6 sind umgesetzt. Was die CI nicht abdecken kann, steht noch aus:
|
||||||
|
|
||||||
|
1. **Release-Signatur einrichten** (nur du): Schlüsselpaar erzeugen, Secret `RELEASE_SIGNING_KEY` in Gitea setzen und den öffentlichen Schlüssel in `scripts/install.sh` (`RELEASE_PUBLIC_KEY_PEM`) eintragen – Anleitung in [RELEASE.md](RELEASE.md). Bis dahin prüft der Installer nur `SHA256SUMS` und warnt.
|
||||||
|
2. **Abnahme nach Brief §14** auf drei VMs (Debian 12 Server, je eine VM für DNS- und DHCP-Agent): Installation nach [INSTALL.md](INSTALL.md), echter Keygen-Lizenzschlüssel (Punkt 1 unten), Oberfläche im Browser durchklicken (Punkt 2), DHCP mit echtem Client (Lease → Adresstabelle → `manual_dhcp`), Lizenz sperren/Keygen unerreichbar (Lesemodus nach Karenzzeit, DNS/DHCP laufen weiter).
|
||||||
|
3. Danach bewusst entscheiden, welche offenen Punkte vor einem `v1.0.0` nötig sind (z. B. HA mit TLS, Kea-DDNS, Neuverschlüsselung beim Master-Key-Wechsel).
|
||||||
|
|
||||||
### Offene Punkte
|
### Offene Punkte
|
||||||
|
|
||||||
1. **Live-Test mit echter Keygen-Lizenz nur teilweise.** Am 2026-10-13 mit einem echten Schlüssel geprüft (Schlüssel nur in der Umgebung, nirgends gespeichert): Antwortsignatur mit dem eingebetteten Public Key gültig, Lizenz `ACTIVE`, `maxMachines` 1, Policy verlangt Fingerprint-Scope, unbekannter Fingerprint ergibt `NO_MACHINE` (darauf folgt im Server die Aktivierung). Die Aktivierung selbst wurde bewusst nicht ausgelöst, weil sie den einzigen Maschinenplatz belegt; offen ist also der volle Ablauf im Server. Ablauf: `tools/keygen-setup/keygen-setup.sh setup` (Admin-Token nur als Umgebungsvariable), Produkt-ID als `KEYGEN_PRODUCT_ID` setzen, `create-license`, Schlüssel in der Oberfläche eintragen. Zu beobachten: Aktivierung (`POST /machines` mit `License`-Auth), Entitlements, Heartbeat, Revalidierung. Das Skript selbst ist gegen die Instanz noch nie gelaufen (Produkt-Attribut `code`, Policy-Attribute ggf. an die CE-Version anpassen).
|
1. **Keygen live geprüft (2026-10-13), aber noch nicht mit dem Go-Code selbst.** Die Aufruffolge des `KeygenProvider` wurde per Skript mit echtem Schlüssel nachgespielt (alle Antworten signiert und gültig; `validate-key` → `NO_MACHINES`, Aktivierung 201, erneut 422 `FINGERPRINT_TAKEN`, Validierung `VALID`, Entitlements `DDI_Networks`, Heartbeat 200, Deaktivierung 204). **Offen:** der Go-Code selbst gegen die echte Instanz, z. B. bei der Abnahme mit `ddi-server license set-key` oder per Live-Test in der CI mit Gitea-Secret. `tools/keygen-setup/keygen-setup.sh` ist nie gegen die Instanz gelaufen.
|
||||||
2. **Oberfläche nie im echten Browser bedient.** Abgesichert nur durch Vitest-Komponententests und den CI-Smoke-Test des Release-Binaries (Auslieferung von `index.html`/Assets). Beim ersten Durchklicken (`make dev-up`, `make dev-admin`, `make run-server`, `cd web && npm run dev`) auf Layout-Fehler und Abläufe achten.
|
2. **Oberfläche nie im echten Browser bedient** (inzwischen viele Dialoge: Cluster, Zonen, Records, TSIG). Abgesichert durch Vitest und Smoke-Tests. Bei der Abnahme auf Layout-Fehler und Abläufe achten.
|
||||||
3. **Frontend-Bundle groß** (~600 KB, 182 KB gzip). Code-Splitting nach Seiten (React `lazy`) einplanen.
|
3. **Frontend-Bundle:** Seiten werden nachgeladen; der Hauptteil ist noch 481 KB (154 KB gzip). Weiter verkleinern: Vendor-Split, Sprachdateien nachladen.
|
||||||
4. **Service-Schicht ohne eigene Abdeckungszahl:** Sie wird über die API-Tests geprüft; für einen Nachweis `go test -coverpkg=./server/... ./server/internal/httpapi` verwenden.
|
4. **Service-Schicht ohne eigene Abdeckungszahl:** Nachweis mit `go test -coverpkg=./server/... ./server/internal/httpapi`.
|
||||||
5. **GitHub-Rate-Limit in der CI:** `setup-go`/`setup-node` holen Manifeste von GitHub (60 Anfragen/Stunde je IP, ohne Token). Bisher nur Warnungen mit Fallback. Falls Jobs daran scheitern: Go/Node in `scripts/ci/install-tools.sh` selbst mit Prüfsumme installieren.
|
5. **GitHub-Rate-Limit in der CI:** `setup-go`/`setup-node` holen Manifeste von GitHub. Falls Jobs scheitern: Go/Node in `scripts/ci/install-tools.sh` selbst mit Prüfsumme installieren.
|
||||||
6. **TanStack Table 9 und React Router 8** sind erschienen; bewusst auf Table 8 / Router 7 geblieben. Upgrade später als eigener Schritt.
|
6. **TanStack Table 9 und React Router 8** sind erschienen; bewusst auf Table 8 / Router 7 geblieben.
|
||||||
7. **Leases werden noch nicht in die Adresstabelle übernommen** (`addresses.lease_state`/`last_seen`), nur unter **Leases** angezeigt. Gehört zu M5 („automatische Erfassung dynamischer Leases“). Der End-to-End-Test prüft Leases nicht; abgedeckt sind sie durch Rollen-Integrationstest (`lease4-add` → `Leases`), Agent-Kern- und Server-Tests.
|
7. **Kea-HA:** nur mit Kea ≥ 3.0; Zugangsdaten aus Dateien; HA-Verbindung per HTTP mit Basic-Auth **ohne TLS**. Beide Peers melden dieselben Leases (harmlos).
|
||||||
8. **Rollback senkt die SOA-Seriennummer** (Serial = Revision). Ohne Secondaries (M3) egal; mit Primary/Secondary (M5) muss ein Rollback eine neue Revision erzeugen (ADR 0009 sieht das für UI-Rollbacks schon vor) oder die Seriennummer anders ableiten. Der lokale Rollback im Agent bleibt davon betroffen.
|
8. **SOA-Seriennummer bei lokalem Rollback:** Rollt der Agent auf dem Primary lokal zurück, sinkt die Seriennummer dort; Secondaries behalten bis zur nächsten Revision die höhere (ADR 0023).
|
||||||
9. **Zertifikatserneuerung mit verlorener Antwort:** Erhält der Agent die neue Antwort nicht, gilt beim Server schon die neue Seriennummer; der Agent muss neu registriert werden. Selten, aber in `OPERATIONS.md` (M6) beschreiben.
|
9. **Kea `config-reload` liest die Datei, mit der Kea gestartet wurde.** Der Installer setzt die Pfade passend; wer Kea von Hand umkonfiguriert, siehe `OPERATIONS.md` §10.3.
|
||||||
10. **Kea `config-reload` liest die Datei, mit der Kea gestartet wurde.** Weicht `dhcp.config_file` des Agents davon ab, meldet der Reload Erfolg mit alter Konfiguration; nur der Dateivergleich im Health-Check fällt auf. Installer (M6) muss Pfade, Hook-Verzeichnis (Kea 3.x: einkompiliert) und Socket-Verzeichnis (Modus 0750) passend setzen.
|
10. **Server-Tests mit Zeitbezug:** Agent-Kern- und Agent-API-Tests nutzen kurze Intervalle. Bei sporadischen CI-Fehlern zuerst an Timing denken (so auch der AXFR-Integrationstest, behoben durch Start-Reihenfolge).
|
||||||
11. **Server-Tests mit Zeitbezug:** Agent-Kern- und Agent-API-Tests nutzen kurze Intervalle (50 ms bis 15 s). Bei sporadischen CI-Fehlern dort zuerst an Timing denken.
|
11. **Nicht umgesetzt aus dem Brief (optional bzw. später):** Kea-DDNS für Namen dynamischer Leases (§5.2, optional); GSS-TSIG; Bindung eines Enrollment-Tokens an einen Cluster (ADR 0008).
|
||||||
|
12. **Cluster-Kleinigkeiten:** Löschen eines Agents entfernt ihn ohne eigenen Audit-Eintrag aus seinem Cluster; Secondary kann direkt nach dem Ausrollen kurz `tsig indicates error` melden (NOTIFY holt die Zonen danach).
|
||||||
### Erledigt: M2 (Config-Generator) – ursprünglicher Plan
|
13. **Aus den Messungen:** `GET /addresses` ohne Netzfilter braucht bei 50.000 Einträgen 110–240 ms. Jede Revision speichert alle Dateien voll (50.000 Adressen: 4,6 MiB) – Aufbewahrung (`retention.revisions_keep`) empfehlen bzw. später deduplizieren. Nicht gemessen: Speicher der Agents, 50 verbundene Agents, viele gleichzeitige Benutzer, Kea mit HA.
|
||||||
|
14. **Schlüsselrotation unvollständig:** kein Neuverschlüsseln vorhandener Werte beim Master-Key-Wechsel; keine Rotation für Agent-CA, Bundle-Schlüssel und HA-Passwort (nur Neuanlage des Clusters). Beschrieben in `OPERATIONS.md`/`SECURITY.md`.
|
||||||
Laut Brief §7 und [ADR 0014](adr/0014-konfigurationserzeugung.md):
|
15. **Installer, nicht in der CI geprüft:** `--kea-source distro` (Hooks ohne Pfad), AppArmor/SELinux im erzwingenden Modus (Container setzen sie nicht durch), echte Downloads vom Gitea-Release (die CI nutzt `--from-dir`). EL9 braucht EPEL für Kea von ISC.
|
||||||
|
16. **Zertifikatserneuerung mit verlorener Antwort:** Agent muss neu registriert werden (`enroll --force`), beschrieben in `OPERATIONS.md` §8.2.
|
||||||
- Paket `server/internal/configgen`: reine Funktionen `Render(input) → Artefakte`, keine DB/Uhr/Zufall im Generator, deterministische Ausgabe.
|
17. **Messwerte nach ADR 0025 neu erheben:** Die Zahlen in `SYSTEM-REQUIREMENTS.md` stammen von vor dem Wechsel zu DHCP pro Adresse (eine voll dynamische /16 sind jetzt 65.521 Einträge mit DNS-Namen). Benchmark-Workflow `bench` erneut laufen lassen. Die IP-Liste eines Netzes blättert in 256er-Seiten statt zu virtualisieren.
|
||||||
- Kea: typisierte Go-Structs → `encoding/json`; Subnetze, **effektive Pools** (`ipam.EffectivePools` existiert schon), Reservierungen aus `manual_dhcp`, Optionen (Router, DNS, NTP, Domain, Suchdomänen), Lease-Zeiten, `lease_cmds`-Hook, Unix-Control-Socket. Nur freie Bestandteile ([ADR 0005](adr/0005-dhcp-engine-kea.md)).
|
18. **ADR 0026, Restpunkte:** MX-Records in dynamischen Zonen, deren Ziel in der Zone keine Adresse hat, lassen das Update der ganzen Zone scheitern (`check-integrity`; Aktivieren schlägt fehl, Rollback) – eine Warnung des Generators fehlt noch. Schlägt die erste Revision mit den neuen Dateien fehl und rollt der Agent auf eine ältere ohne sie zurück, bleiben schon eingetragene Records stehen (sie stehen ohnehin in der Adresstabelle). Sehr große Zonen werden in Transaktionen zu je 500 Records abgeglichen.
|
||||||
- BIND: eigene Writer für die Include-Datei und Zonendateien der managed Zonen, A/PTR aus `static`/`manual_dhcp`, Reverse-Zonen ableiten, SOA-Serial = Revisionsnummer, strikte Validierung/Escaping (TXT in ≤255-Byte-Strings). Kein `text/template`.
|
19. **Integrationstest `TestBINDDynamicUpdates` übersprungen:** Sein Container (named + nsupdate per Shell-Helfer im selben Container) endet in der CI nach ~30 s ohne jede Ausgabe (Läufe 116–122; auch `docker logs` leer). Der Ablauf ist durch `TestDNSDynamicRecords` (echter Agent-Code gegen BIND 9.18/9.20) und den End-to-End-Test abgedeckt. Ursache klären (lokal mit Docker nachstellen) und Test wieder einschalten.
|
||||||
- Golden-Files unter `testdata/` mit `-update`-Flag, Fuzz-Tests für Validierer.
|
20. **Sporadisch beobachtet (Lauf 125, Installationstest Debian 12, Upgrade-Schritt):** BIND 9.18 lud die geänderte Reverse-Zone nach `rndc reload` nicht innerhalb der 30 s des Health-Checks (Seriennummer blieb 1); der Agent rollte korrekt zurück. Mit gleichem Code vorher und auf den anderen Systemen grün. Falls es wiederkehrt: prüfen, ob der Agent zonenweise `rndc reload <zone>` nutzen sollte bzw. ob Dateizeitstempel (Sekundenauflösung) eine Rolle spielen.
|
||||||
- Integrationstests in `/test` gegen echte Container: `named-checkconf -z`/`named-checkzone` und `kea-dhcp4 -t`. In der CI laufen Container nur im Job mit Docker-Zugriff (Muster: Compose-Job; **keine Bind-Mounts**, Dateien per Build-Kontext oder `docker cp` in die Container bringen).
|
|
||||||
- Für M2 fehlen noch Tabellen für Zonen/Records/Cluster/Revisionen (Migration `00002_…`); Zonenverwaltung im UI ist M5, M2 kann Zonen aus `networks.domain` ableiten.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -75,6 +84,15 @@ Auf dem ersten Arbeitsplatz (verwalteter Windows-Rechner) blockiert eine Defende
|
|||||||
- Werkzeuge lagen portabel in `%LOCALAPPDATA%\ddi-tools` (Go, Node, golangci-lint, shellcheck, buf, jq) mit `GOTMPDIR` dort.
|
- Werkzeuge lagen portabel in `%LOCALAPPDATA%\ddi-tools` (Go, Node, golangci-lint, shellcheck, buf, jq) mit `GOTMPDIR` dort.
|
||||||
- Die Regel nicht umgehen. Auf einem Linux-Rechner (oder mit Ausnahme durch die IT) gilt nichts davon: `make ci` läuft dort komplett.
|
- Die Regel nicht umgehen. Auf einem Linux-Rechner (oder mit Ausnahme durch die IT) gilt nichts davon: `make ci` läuft dort komplett.
|
||||||
|
|
||||||
|
### Zweiter Windows-Rechner (BRLN-WKS1, ab M5)
|
||||||
|
|
||||||
|
Keine ASR-Sperre: Go-Tests laufen, auch mit Datenbank. Weiterhin kein Docker, kein `make`, kein `sudo` (WSL-Ubuntu 26.04 ist vorhanden, aber leer). Integrations- und End-to-End-Tests laufen daher nur in der CI.
|
||||||
|
|
||||||
|
- Werkzeuge portabel unter `%LOCALAPPDATA%\ddi-tools` (`go`, `node`, `bin/` mit golangci-lint, shellcheck, buf, jq) und **PostgreSQL 17.10** (`pgsql/`, Daten in `pgdata/`, Port 55432, Anmeldung ohne Passwort).
|
||||||
|
- In Git-Bash vor Go-Befehlen: `T=$(cygpath -u "$LOCALAPPDATA/ddi-tools"); export PATH="$T/go/bin:$T/node:$T/bin:$PATH" GOTOOLCHAIN=local GOTMPDIR="$(cygpath -w $T/tmp)"`.
|
||||||
|
- Datenbank starten: `"$T/pgsql/bin/pg_ctl" -D "$T/pgdata" -o "-p 55432 -c listen_addresses=127.0.0.1" -l "$T/pg.log" start`, dann `DDI_TEST_DATABASE_URL="postgres://ddi@127.0.0.1:55432/ddi?sslmode=disable" DDI_REQUIRE_DB_TESTS=1`.
|
||||||
|
- Die Unit-Tests der Agent-Rollen werden unter Windows übersprungen (Unix-Pfade). Lint zusätzlich für Linux: `GOOS=linux golangci-lint run --build-tags integration ./...`.
|
||||||
|
|
||||||
### Nützliche Befehle
|
### Nützliche Befehle
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -118,6 +136,83 @@ Datenbanktests brauchen `DDI_TEST_DATABASE_URL` (z. B. `postgres://ddi:ddi-dev-o
|
|||||||
|
|
||||||
## Verlauf
|
## Verlauf
|
||||||
|
|
||||||
|
### 2026-10-18 – Funktionen per Entitlement, Agent-Limit (ADR 0027, `v0.10.0`)
|
||||||
|
|
||||||
|
- **Anlass:** Der Nutzer will Cluster, Kea-HA, SSO und dynamische Zonen getrennt lizenzieren und Agents zählen. Bis dahin wurden Entitlements nur angezeigt und `maxAgents` nie geprüft (nur `maxAddresses`); `usage.agents` war immer 0.
|
||||||
|
- **Umsetzung:** `license.Manager.HasFeature` (Testphase: alles), Prüfungen im Service nur dort, wo eine Funktion neu in Gebrauch kommt (Cluster anlegen/Mitglied hinzufügen, DHCP-Cluster wird HA-Paar, Zone wird dynamisch, SSO wird eingeschaltet); Bestand bleibt bearbeitbar. `maxAgents` bei Token-Erzeugung und Registrierung (Advisory-Lock, gesperrte Agents zählen nicht). API: `403 license_feature`, `available_features`. Oberfläche: Funktionsübersicht auf der Lizenzseite, deaktivierte Bedienelemente mit Hinweis. `keygen-setup.sh`: Entitlements anlegen, `--features`, Befehl `features`.
|
||||||
|
- **Werkzeug:** Auf BRLN-WKS1 fehlte `link.exe` in der Go-Installation (`go test` scheiterte mit „no such tool link“); aus dem offiziellen Archiv `go1.27.2.windows-amd64.zip` (SHA-256 gegen go.dev geprüft) wiederhergestellt.
|
||||||
|
- **Für den Nutzer:** Seine Installation läuft in der Testphase (alles frei). Seine Lizenz in Keygen braucht vor dem Eintragen die Entitlements (`keygen-setup.sh setup`, dann `features --license … --add all`), sonst kann er z. B. keine weitere dynamische Zone anlegen (die vorhandene AD-Zone bliebe aber nutzbar).
|
||||||
|
|
||||||
|
### 2026-10-18 – AD-Umstellung beim Nutzer (`v0.9.1`, DC-Skript)
|
||||||
|
|
||||||
|
- **v0.9.1:** BIND lehnte die Registrierung von `gc._msdcs.<domain>` (A-Record mit Unterstrich im Namen) ab, weil Primary-Zonen standardmäßig Hostnamen prüfen (`check-names`). Dynamische Zonen erhalten jetzt `check-names ignore;`; der End-to-End-Test trägt `gc._msdcs` per `nsupdate` ein.
|
||||||
|
- **`tools/windows/Set-DcDnsToDdi.ps1`:** stellt einen DC (auch Server Core) auf die BIND-Server um und prüft danach A-, SRV- und `_msdcs`-Einträge am DDI-Server. Beim Nutzer für DC2 benutzt.
|
||||||
|
- **Lehren aus der Umstellung (in `ACTIVE-DIRECTORY.md` übernommen):** `dcdiag /test:dns` ist mit BIND immer rot (setzt den Windows-DNS-Dienst voraus) und erzeugt selbst DCOM-Fehler; stattdessen `dcdiag /test:RegisterInDNS`, `nltest /dsgetdc`, `dcdiag`, `repadmin`. „Broken delegated domain _msdcs“ kam vom noch laufenden Windows-DNS-Dienst auf DC2, nicht aus BIND. Eine eigene Zone `_msdcs.<domain>` ist unnötig (DDI lehnt Unterstriche in Zonennamen ab; das zu ändern wäre nur für Fälle wie `_domainkey` interessant). Der Rest (Advertising/NetLogons) war ein SYSVOL-Problem: DC1 im DFSR-Zustand 5 (Ereignis 4012, `MaxOfflineTimeInDays`), DC2 wartend (4612) – behoben per autoritativer SYSVOL-Synchronisation von DC1. Auf Server Core fehlt `dfsrdiag`; `Restart-Service DFSR` ersetzt `pollad`.
|
||||||
|
- **Beim Nutzer noch offen:** feste IPs der DCs (`-MakeStatic`), Rekursion/Forwarder auf BIND für Internet-Namen, RODC `dbrlnvl-rodc1t` nicht erreichbar (Fehler 58), `dcdiag-test-record` in der Zone.
|
||||||
|
|
||||||
|
### 2026-10-17 – Rückmeldungen aus dem Betrieb (`v0.8.1`, `v0.8.2`) und AD-Zone in DDI (`v0.9.0`)
|
||||||
|
|
||||||
|
- **v0.8.1, Adressprüfung auf dem echten Server:** Ping meldete „socket: permission denied“ (unprivilegierte ICMP-Sockets nicht erlaubt, `ping_group_range`), DNS fragte nur den System-Resolver. Jetzt Rückfall auf einen Raw-Socket mit `CAP_NET_RAW` (einzige Capability der Server-Unit), DNS-Agents ohne Cluster als Server der Standardgruppe, eigene Frist je Server, Hinweise im Ergebnis (`system_resolver`, `not_deployed` – per Audit-IDs, nicht per Zeitstempel, weil Server- und Datenbankuhr abweichen können). End-to-End- und Installationstest prüfen die Prüfung ausdrücklich.
|
||||||
|
- **v0.8.2, von Hand registrierte Agents:** Ohne Token installiert und dann mit dem `enroll`-Befehl der Oberfläche (als root) registriert, lief der DNS-Agent nie als Dienst (Unit nicht eingeschaltet, Identität gehörte root). Jetzt: Unit immer eingeschaltet mit `ConditionPathExists`, `enroll` als root übergibt die Dateien an den Dienstbenutzer (`os.Root` gegen Symlink-Tricks) und startet den Dienst, `--upgrade` repariert; die Oberfläche zeigt zusätzlich den Installer-Befehl. Der Installationstest spielt diesen Weg auf allen fünf Systemen nach.
|
||||||
|
- **CI-Lehre:** `named -g` schreibt schon beim Start „running as: named …“; auf „running“ zu warten endet sofort. Auf die Zeile warten, die mit „ running“ endet (alle Zonen geladen). Außerdem kann die per `docker start -a` angehängte Ausgabe abreißen – bei Fehlern `docker logs` lesen.
|
||||||
|
- **Umstieg von einer Windows-Domäne:** Der Nutzer will die AD-Zone in DDI betreiben. Einen Export seiner bisherigen DHCP-Zuordnungen (UniFi-Format) habe ich ins Importformat umgebaut (`local/import/`, git-ignoriert; 51 Reservierungen, 11 dynamische Leases, doppelte Hostnamen mit MAC-Endung eindeutig gemacht) und gegen einen lokalen Server per Probelauf geprüft.
|
||||||
|
|
||||||
|
### 2026-10-17 – Einträge in dynamischen Zonen, Generator und Server (ADR 0026)
|
||||||
|
|
||||||
|
- **Anlass:** In der dynamischen Zone `ddi-test.ad.beugsiud.de` fehlten neue Adressen, weil Records dort nur in die Anfangsdatei gingen. Nach [ADR 0026](adr/0026-eintraege-in-dynamischen-zonen.md) gleicht künftig der DNS-Agent die von DDI verwalteten Records per `nsupdate` ab; Generator/Server und Agent-Seite parallel in zwei Worktrees.
|
||||||
|
- **Generator:** `configgen.SourceVersion` 4 mit `Source.UpdateKeyID`, `DNSConfig.UpdateKey`; Ziele mit dynamischer Primary-Zone erhalten den Schlüssel in der Update-ACL sowie `ddi-suite-update.key` (geheim) und `dynamic-records.json` (Format in den Präzisierungen der ADR). Eingaben bis Version 3 und Ziele ohne dynamische Primary-Zone erzeugen byte-gleich; neue Golden-Files `dynamic-update`, geänderte `dynamic-keys`.
|
||||||
|
- **Server:** Migration 00007 (`tsig_keys.system`), Systemschlüssel `ddi-agent-update` beim Anlegen/Ändern einer dynamischen Zone und beim Start, nicht löschbar (`key_system`), Name reserviert (`key_exists`), `system` in der API. Die Adressprüfung meldet `dynamic_zone` nicht mehr.
|
||||||
|
- **Integrationstest** `TestBINDDynamicUpdates`: `named` mit den Anfangsdateien der Vorgänger-Revision, Abgleich per `nsupdate -k` aus `dynamic-records.json` (kleiner Go-Helfer statt Agent), Prüfung mit `dig`, Löschen genau eines Records neben einem fremden am selben Namen, unsigniertes Update von 127.0.0.1 abgelehnt. Lokal nur kompiliert (`go vet -tags integration`), läuft in der CI.
|
||||||
|
- **Gelernt:** `named` lehnt mit `check-integrity` ein Update ab, das einen MX auf einen Namen der Zone ohne Adresse hinzufügt – die Transaktion der ganzen Zone scheitert. `nsupdate -k` liest eine Datei im `named.conf`-Format über den Rückfall für Session-Keys, auch wenn sie auf `.key` endet.
|
||||||
|
|
||||||
|
### 2026-10-17 – Anpassungen nach Rückmeldung (`v0.8.0`)
|
||||||
|
|
||||||
|
- **Rückmeldung des Nutzers** nach M6: Netze aufklappbar mit allen IPs; DHCP pro IP statt Pools; Oberfläche wirkt generiert; Massenänderungen; Prüfung per Ping und DNS; Zufallsname für dynamische Einträge; DNS auch für dynamische Einträge. Umgesetzt nach [ADR 0025](adr/0025-dhcp-pro-adresse-pruefungen-ui.md) mit zwei Agents (Server/Generator, Web); beide brachen einmal am Sitzungslimit ab.
|
||||||
|
- **Modell:** `dynamic` = IP im DHCP-Bereich ohne MAC, jetzt mit A/PTR; Kea-Pools entstehen aus zusammenhängenden `dynamic`-IPs (`ipam.Ranges`). Migration 00006 wandelt Pools in Einträge um (Zufallsnamen `dyn-` + 8 Zeichen), entfernt `dhcp_pools`, neue Spalte `lease_hostname`. `configgen.SourceVersion` 3: ältere gespeicherte Eingaben erzeugen weiterhin byte-gleich (kein DNS für `dynamic`).
|
||||||
|
- **Entscheidung (ohne Rückfrage, im Bericht an den Nutzer genannt):** Der DNS-Name gehört dem Eintrag; eine Lease ändert ihn nicht, sonst entstünde nach jeder Vergabe eine Konfigurationsänderung. Den vom Client gemeldeten Namen zeigt `lease_hostname`, per Klick übernehmbar. Client-Namen automatisch in DNS wäre Kea-DDNS (offener Punkt 11).
|
||||||
|
- **Neue Endpunkte:** `GET /networks/{id}/ips`, `POST /networks/{id}/range` (assign/clear, Probelauf), `POST /addresses/check` (Ping über unprivilegierte ICMP-Sockets, unter Windows „nicht verfügbar“; DNS direkt an die zuständigen Server mit eigenem kleinen Client, weil der Go-Resolver `/etc/hosts` liest), Massenänderung mit `dry_run`, `set_description`, `regenerate_hostnames`.
|
||||||
|
- **Oberfläche:** Erstmals im echten Browser angesehen (Edge per `playwright-core` aus einem Scratch-Verzeichnis, lokaler Server mit portabler PostgreSQL). Neu: Seitenleiste in Gruppen, volle Breite, dichte Tabellen, Typ-Kürzel statt Auswahlliste je Zeile, Hilfe als „?“-Popover, eine Hauptschaltfläche je Seite; aufklappbare Netze mit IP-Liste, Umschalt-Klick-Auswahl, Bereichs-, Massen- und Prüfdialog.
|
||||||
|
- **Lehre:** Befehle mit `| tail` verschlucken den Exit-Code (ein Push und ein Lint-Lauf scheinbar erfolgreich). Prüfungen vor Commit/Push ohne Pipe ausführen oder `set -o pipefail` setzen.
|
||||||
|
|
||||||
|
|
||||||
|
### 2026-10-16 – M6 Auslieferung (`v0.7.0`)
|
||||||
|
|
||||||
|
- Verträge vorab: [ADR 0024](adr/0024-auslieferung-installer-m6.md), gehärtete Unit-Vorlagen `deploy/systemd/*.service.in`, `scripts/render-units.sh`. Vorher per Probe-Workflow auf einem Wegwerf-Branch geprüft, dass die CI-Runner privilegierte systemd-Container starten können (Debian, Ubuntu, Rocky) und Netz zu Paketquellen, Gitea und Keygen haben. Dann drei Agents (Installer, Release/Server, Messungen/Doku); alle brachen mehrfach am Sitzungslimit ab und liefen nach `SendMessage` weiter. Installer- und Mess-Agent durften für CI-Läufe je einen eigenen Remote-Branch pushen (`m6-installer`, `m6-bench`, danach gelöscht).
|
||||||
|
- **Installer** `scripts/install.sh`: Rollen `server`, `agent-dns`, `agent-dhcp` auf Debian 12/13, Ubuntu 22.04/24.04, EL9; Vorabprüfung nach `SYSTEM-REQUIREMENTS.md` §3; Prüfsummen und (sobald eingerichtet) Ed25519-Signatur; PostgreSQL mit Peer-Authentifizierung (kein DB-Passwort); Agents laufen als Benutzer ihres Dienstes (`bind`/`named`, `_kea`/`kea`), ohne root; Kea 3.2 aus dem ISC-Repository (EL9 braucht EPEL); markierte Blöcke in `named.conf`, kollidierende Distributionsoptionen umkehrbar auskommentiert; idempotent, `--upgrade`, `--uninstall [--purge]`, `--dry-run`, Aufräumen bei Abbruch. Neu `docs/INSTALL.md`.
|
||||||
|
- **Installationstest** (Workflow `install`, Lauf 101): je System ein privilegierter systemd-Container, alle Rollen installieren, Agents per Token registrieren, Revision ausrollen, `dig` und Kea-Reservierung prüfen, Hardening und Nicht-root-Prozesse prüfen, zweiter Lauf ohne Änderungen, Upgrade auf eine zweite Version, Deinstallation mit und ohne `--purge`. Auf allen fünf Systemen grün.
|
||||||
|
- **Release/Server:** `ddi-server license set-key` (stdin, Exit-Codes 0–4), Aufbewahrung (`retention.audit_days`, `retention.revisions_keep`, täglich, nie benutzte Revisionen), `.deb`/`.rpm` mit nfpm, Signatur `SHA256SUMS.sig` im Release-Workflow (Secret `RELEASE_SIGNING_KEY`, Anleitung `docs/RELEASE.md`), Namensprüfung `scripts/check-brand.sh` (ADR 0018).
|
||||||
|
- **Von den Tests gefunden:** ISC-Kea vergleicht den Socket-Pfad wörtlich mit dem einkompilierten `/var/run/kea` (Lösung: `KEA_CONTROL_SOCKET_DIR=/run/kea` per Drop-in); `kea-dhcp4 -t` braucht Netlink in der Agent-Unit; Rocky-`named.conf` beschränkt `listen-on`/`allow-query` auf localhost; der Server lehnt einen gruppenlesbaren Master-Key ab (ADR korrigiert: 0400); der CSV-Import war mit ~300 Zeilen/s zu langsam für die 50.000-Zeilen-Grenze (jetzt ~1.100/s); der AXFR-Integrationstest war wackelig (Secondary startete vor dem Primary).
|
||||||
|
- **CI-Lehren:** Ein Runner hatte für das Standard-Build-Netz von Docker kein ausgehendes Netz – Images mit `--network host` bauen. Die CI-Runner haben nur ~1,9 GB freien Platz; der Installationstest prüft deshalb erst, dass die Vorabprüfung abbricht, und nutzt dann `--force`.
|
||||||
|
|
||||||
|
### 2026-10-15 – M6 Messungen, Betriebs- und Sicherheitsdoku
|
||||||
|
|
||||||
|
- Benchmark `test/bench/` (`make bench`, Workflow `bench`, nur `workflow_dispatch`): Server mit PostgreSQL 17, synthetische Daten (5.000 und 50.000 Einträge) per CSV-Import über die API; BIND 9.20 mit `dnsperf` und Kea 3.2.1 mit `perfdhcp` auf den Dateien aus `GET /config/preview`. Ergebnisse (Lauf 93, Runner 4 vCPU Skylake, 7,7 GiB) in `SYSTEM-REQUIREMENTS.md`; neu `OPERATIONS.md`, `SECURITY.md`.
|
||||||
|
- Kernzahlen 50.000 Einträge: Server 33–194 MiB RSS (Spitze 235 MiB durch Argon2id), PostgreSQL 128 MiB, DB 72 MiB, Revision 2,8 s und 4,6 MiB, BIND 57 MiB und 50–70k QPS, Kea 42 MiB und 750–1.000 DORA/s.
|
||||||
|
- **CI-Lehren:** `perfdhcp` ist nicht im Kea-Image, das ISC-Repository muss erst eingerichtet werden (`setup.alpine.sh` von Cloudsmith); `dnsperf` gibt es nicht in Alpine stable; `deb.debian.org:80` war vom Runner zeitweise nicht erreichbar (Rückfall auf HTTPS mit abgeschalteter Peer-Prüfung, Pakete bleiben signaturgeprüft). `perfdhcp` braucht für Relay-Betrieb eine Subnetzauswahl per `relay.ip-addresses`, die das IPAM-Modell noch nicht kennt (im Benchmark per `jq` ergänzt). Beschreibung-only-Änderungen erzeugen keine neue Revision (byte-gleiche Ausgabe). Durchsätze schwanken auf dem geteilten Runner um bis zu 30 %.
|
||||||
|
|
||||||
|
### 2026-10-14 – M5 Cluster und Zonen (`v0.6.0`)
|
||||||
|
|
||||||
|
- Neuer Rechner (siehe Arbeitsumgebung). Verträge vorab: [ADR 0023](adr/0023-cluster-und-zonen-m5.md), Generator-Modell (Ziele pro Cluster-Mitglied, geheime Artefakte, `Source` Version 2), OpenAPI für Cluster, TSIG-Schlüssel, Zonen und Records. Dann drei Agents in Worktrees (Generator + Agent-Rollen, Server, Web). Server und Generator brachen einmal am Sitzungslimit ab und liefen nach `SendMessage` weiter. Der Server-Agent arbeitete bis zum Zusammenführen gegen eine Übergangslösung (`derive_shim.go`), die beim Merge entfiel.
|
||||||
|
- **Kernentscheidung:** Revisionen bleiben global (Nummer = SOA-Seriennummer), ihre Dateien tragen ein **Ziel** (`''` = Standardgruppe ohne Cluster, sonst Agent-ID). Ohne Cluster verhält sich alles wie in M4 (`TestM4Compatibility`: byte-gleich bis auf die neue Schlüsseldatei).
|
||||||
|
- **Geheimnisse:** TSIG-Schlüssel und HA-Zugangsdaten stehen nur in geheimen Dateien (`ddi-suite-keys.conf`, `ddi-suite-ha-user`, `ddi-suite-ha-password`), versiegelt in der Datenbank, in der API nie sichtbar (`secret: true`, auch im Diff), im signierten Bundle im Klartext. Die gespeicherte Generator-Eingabe enthält keine Geheimnisse; sie liegen versiegelt in `config_revisions.secrets` für Rollbacks.
|
||||||
|
- **Server:** Migration 00005 (Rollen über zusammengesetzte Fremdschlüssel erzwungen), CRUD mit Audit und Rechten, Bundle-Auswahl pro Agent, Lease-Übernahme als `dynamic`-Einträge mit Ereignis `addresses`.
|
||||||
|
- **Generator:** Primary mit `notify explicit`/`also-notify`/`allow-transfer` per Schlüssel, Secondaries mit `primaries … key`, dynamische Zonen mit Schlüsseln in der Update-ACL, Records mit CNAME-Konfliktprüfung, Kea-HA über einen authentifizierten HTTP-Control-Socket. Nachträglich: Pool-Teilung bei Load-Balancing (Kea verlangt getrennte Pools, `HA_primary`/`HA_secondary`), Kopf der Schlüsseldatei ohne Revisionsnummer (sonst stünde sie in jedem Diff).
|
||||||
|
- **Web:** Seiten für Cluster, TSIG-Schlüssel, Zonen und Records, Gruppierung von Revisionen/Diffs nach Ziel, Code-Splitting.
|
||||||
|
- **Von der CI gefunden:** Kea 3.2 lehnt Klartext-Benutzernamen in der HTTP-Authentifizierung ab (`use of clear text 'user' is NOT SECURE`) → Benutzer und Passwort aus Dateien (`user-file`, `basic-auth-user-file`). Der Zonentransfer per TSIG lief im ersten End-to-End-Lauf sofort.
|
||||||
|
- **Ergebnis:** alle 8 CI-Jobs grün (Lauf 75), End-to-End-Test mit allen M5-Schritten bestanden.
|
||||||
|
- **End-to-End erweitert:** zweiter BIND als Secondary, zweiter Kea als HA-Partner; Prüfung von Transfer, Records, dynamischen Updates per IP und per TSIG (inkl. abgelehntem Update), Erhalt dynamischer Records über Revisionen, HA-Zustand `hot-standby` über den authentifizierten Socket (ohne Anmeldung 401) und Lease-Übernahme.
|
||||||
|
- Neu: `docs/ACTIVE-DIRECTORY.md`.
|
||||||
|
|
||||||
|
### 2026-10-13 – M4 Pull und Push (`v0.5.0`)
|
||||||
|
|
||||||
|
- Gleiches Vorgehen wie M3: Verträge vorab ([ADR 0022](adr/0022-ausrollen-pull-push-m4.md), OpenAPI, Proto-Feld `GetDesiredStateResponse.deployment_id`, Paket `server/internal/textdiff` mit Myers-Diff), dann drei Agents in Worktrees (Server, Web, Agent-Kern + E2E). Alle drei brachen einmal am Sitzungslimit ab und liefen nach `SendMessage` weiter.
|
||||||
|
- **Server:** Migration 00004 (`agents.target_revision`, Deployment-Ergebnisse `pending`/`superseded`, `requested_by`, `config_revisions.source` mit der Generator-Eingabe), Betriebsmodi, Push mit offenen Deployments (erneut gesendet beim Verbinden, beim Polling über `deployment_id`), Rollback durch erneutes Rendern der gespeicherten Eingabe mit neuer Nummer, Diff, offene Änderungen (Audit seit der Revision + Konfigurationsvergleich), Ereignisbus `server/internal/events` und `GET /events` (SSE, Schreib-Deadline wird je Nachricht verschoben), `Tx.AfterCommit` für Ereignisse erst nach dem Commit.
|
||||||
|
- **Agent-Kern:** Push über Polling, jede Push-ID nur einmal anwenden (letzte 20 in `state.json`), endgültig abgelehnte Berichte verwerfen statt die Warteschlange zu blockieren.
|
||||||
|
- **Web:** Live-Aktualisierung per `EventSource` mit Polling als Rückfall, Hinweis „N Änderungen warten auf Ausrollen“, Diff-Ansicht, „Jetzt ausrollen“, Rollback, Moduswechsel.
|
||||||
|
- **Entscheidung:** Pushes gehen nie unter die aktive Revision eines Agents (Replay-Schutz, ADR 0009); dafür gibt es den Rollback. Präzisierungen des Servers stehen als Abschnitt in ADR 0022.
|
||||||
|
- **E2E erweitert:** offene Änderungen, `manual`-Agent bleibt stehen bis zum Push, Push-Deployment `succeeded`, Diff, Rollback auf Revision 1 (Namen verschwinden, Seriennummer steigt), SSE-Ereignis. Erster Lauf scheiterte nur am Testskript selbst: jeder Schritt meldete sich neu an und lief in die Login-Ratenbegrenzung (Sitzung wird jetzt wiederverwendet).
|
||||||
|
- **Keygen live:** siehe Offene Punkte (Ablauf per Skript mit echter Lizenz vollständig geprüft).
|
||||||
|
|
||||||
### 2026-10-13 – M3 Agent verwaltet (`v0.4.0`)
|
### 2026-10-13 – M3 Agent verwaltet (`v0.4.0`)
|
||||||
|
|
||||||
- **Vorgehen:** zuerst die Verträge selbst festgelegt und committet (`internal/bundle`: Manifest, Ed25519-Signatur, Pfadregeln; `internal/agentpki`: Agent-ID als URI-SAN, CA-Fingerprint, TLS; `agent/core/role.go`: Rollen-Schnittstelle; OpenAPI für Agents/Tokens/Revisionen/Deployments/Leases; [ADR 0021](adr/0021-agent-strecke-m3.md)). Dann drei Agents parallel in **eigenen Git-Worktrees** (`.claude/worktrees/`, git-ignoriert): Server, Agent-Kern, BIND/Kea-Rollen; jeder committet auf seinem Branch, Zusammenführen per `git merge`. Ging konfliktfrei. Die Web-Oberfläche habe ich parallel gegen die Spec gebaut.
|
- **Vorgehen:** zuerst die Verträge selbst festgelegt und committet (`internal/bundle`: Manifest, Ed25519-Signatur, Pfadregeln; `internal/agentpki`: Agent-ID als URI-SAN, CA-Fingerprint, TLS; `agent/core/role.go`: Rollen-Schnittstelle; OpenAPI für Agents/Tokens/Revisionen/Deployments/Leases; [ADR 0021](adr/0021-agent-strecke-m3.md)). Dann drei Agents parallel in **eigenen Git-Worktrees** (`.claude/worktrees/`, git-ignoriert): Server, Agent-Kern, BIND/Kea-Rollen; jeder committet auf seinem Branch, Zusammenführen per `git merge`. Ging konfliktfrei. Die Web-Oberfläche habe ich parallel gegen die Spec gebaut.
|
||||||
|
|||||||
@@ -0,0 +1,250 @@
|
|||||||
|
# Betrieb
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt den laufenden Betrieb der DDI-Suite: Dienste, Logs, Überwachung, Sicherung, Wiederherstellung, Upgrade, Schlüssel- und Zertifikatspflege, Cluster und Fehlersuche. Installation: [INSTALL.md](INSTALL.md). Voraussetzungen, Ports und Größen: [SYSTEM-REQUIREMENTS.md](SYSTEM-REQUIREMENTS.md). Sicherheitsmodell: [SECURITY.md](SECURITY.md).
|
||||||
|
|
||||||
|
Namen und Pfade sind die Standardwerte der zentralen Benennung ([ADR 0018](adr/0018-zentrale-benennung.md)); wer umbenennt, ersetzt `ddi-suite`, `ddi-server`, `ddi-agent-dns` und `ddi-agent-dhcp` entsprechend.
|
||||||
|
|
||||||
|
## 1. Dienste und Dateien
|
||||||
|
|
||||||
|
| Rolle | systemd-Unit | Benutzer | Konfiguration | Zustand |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| Management-Server | `ddi-server.service` | `ddi-suite` | `/etc/ddi-suite/server.yaml`, `/etc/ddi-suite/master.key` | PostgreSQL-Datenbank `ddi-suite`, `/var/lib/ddi-suite/server` |
|
||||||
|
| DNS-Agent | `ddi-agent-dns.service` | BIND-Benutzer (`bind` bzw. `named`) | `/etc/ddi-suite/agent-dns.yaml` | `/var/lib/ddi-suite/agent-dns` (Identität, Revisionen, Zustand) |
|
||||||
|
| DHCP-Agent | `ddi-agent-dhcp.service` | Kea-Benutzer (`_kea` bzw. `kea`) | `/etc/ddi-suite/agent-dhcp.yaml` | `/var/lib/ddi-suite/agent-dhcp` |
|
||||||
|
| BIND | `named.service` bzw. `bind9.service` | Distribution | `named.conf` mit Includes aus `/etc/bind/ddi-suite` bzw. `/etc/named/ddi-suite` | Zonen in `/var/lib/bind/ddi-suite` (inkl. `secondary/`) |
|
||||||
|
| Kea DHCPv4 | `isc-kea-dhcp4-server.service` (ISC-Pakete auf Debian/Ubuntu) bzw. `kea-dhcp4.service` (ISC-Pakete auf EL) | Kea-Paket | `/etc/kea/kea-dhcp4.conf` (vom Agent geschrieben; das Original liegt als `kea-dhcp4.conf.ddi-suite-orig` daneben) | Leases in `/var/lib/kea/kea-leases4.csv` |
|
||||||
|
|
||||||
|
Die Agents schreiben ausschließlich die Dateien, die der Server erzeugt (Include-Dateien, Zonendateien, `kea-dhcp4.conf`, Schlüssel- und HA-Dateien). `named.conf` selbst gehört dem Administrator; der Installer fügt dort nur markierte Blöcke ein (`// BEGIN ddi-suite …` bis `// END ddi-suite …`: `ddi-suite-keys.conf` vor `ddi-suite.conf` auf oberster Ebene, `ddi-suite-options.conf` innerhalb von `options`). Optionen der Distribution, die der Generator selbst setzt (`recursion`, `allow-recursion`, `forwarders`, `allow-transfer`, auf localhost beschränkte `listen-on`/`allow-query`), kommentiert er mit dem Präfix `//ddi-suite-disabled: ` aus; `--uninstall` stellt sie wieder her. Innerhalb der Blöcke nichts von Hand ändern.
|
||||||
|
|
||||||
|
Weitere Dateien des Installers:
|
||||||
|
|
||||||
|
- Benutzer der Agents per Drop-in `/etc/systemd/system/ddi-agent-<rolle>.service.d/10-user.conf`; Kea erhält das Drop-in `…/<kea-unit>.service.d/10-ddi-suite.conf` mit `KEA_CONTROL_SOCKET_DIR=/run/kea` (die ISC-Pakete sind mit `/var/run/kea` gebaut und vergleichen Pfade wörtlich; die Variable hält den Standardpfad der Generator-Einstellungen gültig). Der DHCP-Agent bekommt dieselbe Variable.
|
||||||
|
- Installer-Log `/var/log/ddi-suite/install.log`, Zertifikat der Weboberfläche `/etc/ddi-suite/tls/server.{crt,key}` (selbstsigniert, falls keines angegeben wurde; eigenes ablegen und `systemctl restart ddi-server`).
|
||||||
|
- EL9: Kea aus dem ISC-Repository braucht `log4cplus` aus **EPEL**; EPEL für Kea-Updates aktiviert lassen.
|
||||||
|
|
||||||
|
Übliche Befehle:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
systemctl status ddi-server ddi-agent-dns ddi-agent-dhcp
|
||||||
|
systemctl restart ddi-server # führt beim Start offene Migrationen aus
|
||||||
|
sudo -u bind ddi-agent-dns status --config /etc/ddi-suite/agent-dns.yaml # Identität, Revisionen, letztes Ergebnis
|
||||||
|
ddi-server version
|
||||||
|
```
|
||||||
|
|
||||||
|
`ddi-agent-<rolle> status` zeigt Agent-ID, Server, Ablauf des Zertifikats (und ab wann es erneuert wird), CA-Fingerprint, angewendete und letzte funktionierende Revision, die lokal gehaltenen Revisionen (die letzten 10) und eine zuletzt abgelehnte Revision.
|
||||||
|
|
||||||
|
## 2. Logs
|
||||||
|
|
||||||
|
- Alle Dienste schreiben nach **journald**: `journalctl -u ddi-server -f`, `journalctl -u ddi-agent-dns --since today`.
|
||||||
|
- Server und Agents loggen standardmäßig **JSON** (eine Zeile je Ereignis), Stufe `info`. Umstellen in der YAML-Datei (`log: {level: debug, format: text}`) oder beim Server per `DDI_LOG_LEVEL`/`DDI_LOG_FORMAT`.
|
||||||
|
- **Korrelations-ID:** Jede HTTP-Anfrage erhält eine `request_id` (aus einem gültigen `X-Request-ID`-Header übernommen oder neu erzeugt), die in jeder Logzeile dieser Anfrage, im Antwort-Header `X-Request-ID` und im Audit-Eintrag (`request_id`) steht. Fehlermeldungen der Oberfläche nennen sie; damit findet man die Logzeilen: `journalctl -u ddi-server -o cat | grep '"request_id":"<id>"'`.
|
||||||
|
- Deployments erscheinen im Server-Log und im Agent-Log mit Revisionsnummer, Agent-ID und Deployment-ID.
|
||||||
|
- Geheimnisse (Passwörter, Tokens, Schlüssel, Lizenzschlüssel) werden nie geloggt, auch nicht im Installer-Log `/var/log/ddi-suite/install.log`.
|
||||||
|
- BIND und Kea loggen wie von der Distribution eingerichtet (journald bzw. Syslog).
|
||||||
|
|
||||||
|
## 3. Überwachung
|
||||||
|
|
||||||
|
| Endpunkt | Zweck |
|
||||||
|
| --- | --- |
|
||||||
|
| `GET /healthz` | Lebt der Prozess? Immer `{"status":"ok"}`, ohne Abhängigkeiten. Für Neustart-Logik. |
|
||||||
|
| `GET /readyz` | Kann der Server arbeiten? Prüft die Datenbank (`{"status":"ok","checks":{"database":"ok"}}`, sonst HTTP 503). Für Load-Balancer und Monitoring. |
|
||||||
|
| `GET /metrics` | Prometheus-Metriken, u. a. `ddi_http_requests_total`, `ddi_http_request_duration_seconds`, `ddi_agents_connected{role}`, `ddi_license_writable`, `ddi_build_info`, dazu Go- und Prozessmetriken. Ohne Anmeldung – per Firewall oder Reverse-Proxy auf das Monitoring beschränken. |
|
||||||
|
|
||||||
|
Empfohlene Alarme:
|
||||||
|
|
||||||
|
- `/readyz` nicht 200 über mehrere Minuten.
|
||||||
|
- `ddi_agents_connected` kleiner als die Zahl der Agents (ein Agent ohne Stream arbeitet im Polling weiter, meldet aber ggf. ein Problem).
|
||||||
|
- `ddi_license_writable == 0` (Lesemodus, siehe §10.6).
|
||||||
|
- In der Oberfläche bzw. `GET /api/v1/agents`: Health-Zustand ungleich `ok`, angewendete Revision ≠ Soll-Revision über längere Zeit, Deployments mit Ergebnis `rejected`, `rolled_back` oder `failed`.
|
||||||
|
- Auf den Agent-Hosts zusätzlich BIND und Kea selbst überwachen (DNS-Abfrage, DHCP-Dienststatus); die Datenebene läuft auch ohne Server und Agent weiter.
|
||||||
|
- Zeitsynchronisation auf allen Hosts (Zertifikate, TSIG und Lizenzprüfung brauchen korrekte Uhren).
|
||||||
|
|
||||||
|
## 4. Sicherung
|
||||||
|
|
||||||
|
Was gesichert werden muss:
|
||||||
|
|
||||||
|
| Was | Wo | Wie oft | Hinweis |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| **Datenbank** | PostgreSQL `ddi-suite` | täglich, vor jedem Upgrade | Enthält alle Fachdaten, Revisionen, Audit-Log und – versiegelt – CA, Bundle-Schlüssel, TSIG-Schlüssel, HA-Passwörter, Lizenzzustand. |
|
||||||
|
| **Master-Key** | `/etc/ddi-suite/master.key` | einmalig und nach jeder Änderung | **Ohne ihn ist die Datenbank nur teilweise brauchbar** (§5). Getrennt von der Datenbanksicherung aufbewahren (z. B. Passwortsafe, Tresor). |
|
||||||
|
| **Server-Konfiguration** | `/etc/ddi-suite/` (`server.yaml`, TLS-Zertifikat und -Schlüssel) | nach Änderungen | |
|
||||||
|
| **Agent-Identität** (optional) | `/var/lib/ddi-suite/agent-<rolle>/identity/` | nach dem Enrollment | Erspart nach einer Neuinstallation des Agent-Hosts das erneute Registrieren. Ohne Sicherung: neu registrieren (§8.2). |
|
||||||
|
| BIND-/Kea-Grunddateien | `named.conf`, `rndc.key`, Kea-Leases | nach Bedarf | Generierte Dateien muss man nicht sichern, der Server liefert sie neu. Leases (`kea-leases4.csv`) sichern, wenn laufende Vergaben eine Neuinstallation überstehen sollen. |
|
||||||
|
|
||||||
|
Datenbank sichern (als root auf dem Server, Peer-Authentifizierung):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo -u postgres pg_dump --format=custom --file=/var/backups/ddi-suite-$(date +%F).dump ddi-suite
|
||||||
|
```
|
||||||
|
|
||||||
|
Der Dump enthält keine Klartext-Geheimnisse, aber IPAM-Daten und Passwort-Hashes: verschlüsselt ablegen. Ein Dump im laufenden Betrieb ist konsistent (eine Transaktion); der Server muss dafür nicht angehalten werden.
|
||||||
|
|
||||||
|
## 5. Wiederherstellung
|
||||||
|
|
||||||
|
1. Server installieren wie in [INSTALL.md](INSTALL.md) beschrieben, **ohne** ihn zu starten (bzw. danach `systemctl stop ddi-server`).
|
||||||
|
2. Den gesicherten **Master-Key** nach `/etc/ddi-suite/master.key` legen (Eigentümer `ddi-suite`, Modus 0400) und die gesicherte `server.yaml` zurückspielen.
|
||||||
|
3. Datenbank leeren und zurückspielen:
|
||||||
|
```sh
|
||||||
|
sudo -u postgres dropdb ddi-suite && sudo -u postgres createdb -O ddi-suite ddi-suite
|
||||||
|
sudo -u postgres pg_restore --role=ddi-suite --no-owner --dbname=ddi-suite /var/backups/ddi-suite-<datum>.dump
|
||||||
|
```
|
||||||
|
4. `systemctl start ddi-server`. Neuere Server-Versionen migrieren das Schema beim Start.
|
||||||
|
5. Agents verbinden sich von selbst wieder: CA und Bundle-Schlüssel stammen aus der Sicherung, ihre Zertifikate bleiben gültig. Agents, die seit der Sicherung ihr Zertifikat erneuert haben, kennt der Server nur mit der alten Seriennummer: Sie werden abgewiesen und müssen neu registriert werden (§8.2). Ebenso Agents, die erst nach der Sicherung registriert wurden.
|
||||||
|
6. Liegt die Sicherung hinter der höchsten Revision, die Agents schon angewendet haben, lehnen sie ältere Nummern ab (Replay-Schutz). Abhilfe: so lange neue Revisionen erzeugen bzw. einen Rollback auf den gewünschten Stand ausführen, bis die Nummer über der höchsten angewendeten liegt; die Oberfläche zeigt die angewendete Revision je Agent.
|
||||||
|
|
||||||
|
**Master-Key verloren = Geheimnisse verloren.** Ohne den passenden Master-Key startet der Server nicht. Ein neuer Master-Key macht die versiegelten Werte nicht wieder lesbar. Der einzige Weg ist ein Neuaufbau der Geheimnisse: neuer Master-Key, Einträge in `pki_keys` löschen (der Server erzeugt CA und Bundle-Schlüssel beim Start neu), alle Agents neu registrieren, alle TSIG-Schlüssel neu anlegen bzw. erneuern, DHCP-Cluster neu anlegen (HA-Passwort), OIDC-Secret neu eintragen, TOTP für alle Benutzer neu einrichten, Lizenz neu eintragen. Die IPAM-Daten bleiben erhalten. Bis dahin laufen DNS und DHCP mit ihrer letzten Konfiguration weiter.
|
||||||
|
|
||||||
|
## 6. Upgrade
|
||||||
|
|
||||||
|
- **Server:** `sudo ./install.sh --upgrade --role server [--version <tag>]` ersetzt Binary und Unit und startet den Dienst neu (Details in [INSTALL.md](INSTALL.md)). Datenbankmigrationen laufen beim Start automatisch (`database.auto_migrate`, Standard an); manuell mit `ddi-server migrate`. Vorher die Datenbank sichern (§4) – Migrationen werden nicht automatisch zurückgenommen; ein Downgrade heißt: alte Version installieren und die Sicherung zurückspielen.
|
||||||
|
- **Upgrade auf DHCP pro Adresse ([ADR 0025](adr/0025-dhcp-pro-adresse-pruefungen-ui.md), Migration 00006):** Jede freie Adresse eines bisherigen Pools wird ein `dynamic`-Eintrag mit Zufallsnamen `dyn-…` (ohne Netz-, Broadcast- und Gateway-Adresse); bisher namenlose `dynamic`-Einträge erhalten einen Zufallsnamen, kollidierende Lease-Namen wandern nach `lease_hostname`. Große Pools werden zu vielen Zeilen (ein /16-Pool: rund 65.000) und zählen gegen das Adresslimit der Lizenz. Die nächste Revision enthält für alle diese Einträge A- und PTR-Records; die Kea-Pools bleiben gleich. Ältere gespeicherte Revisionen werden beim Rollback unverändert erzeugt (ohne Records für `dynamic`).
|
||||||
|
- **Agents:** `sudo ./install.sh --upgrade --role agent-dns` bzw. `agent-dhcp` auf jedem Agent-Host. Identität und Revisionen bleiben erhalten. Während des Neustarts läuft BIND bzw. Kea unverändert weiter.
|
||||||
|
- **Reihenfolge:** erst der Server, dann die Agents. Das gRPC-Protokoll wird nur rückwärtskompatibel erweitert (neue Felder, keine geänderten Bedeutungen); ein Server bedient Agents der Vorversion. Agents, die neuer als der Server sind, werden nicht unterstützt. Die Versionen aller Agents zeigt die Agent-Liste.
|
||||||
|
- **BIND/Kea:** Pakete der Distribution bzw. des ISC-Repositorys wie gewohnt aktualisieren. Nach einem Wechsel der Kea-Hauptversion (z. B. 2.6 → 3.x) mit einer neuen Revision prüfen, dass `kea-dhcp4 -t` die Konfiguration akzeptiert (der Agent tut das bei jedem Ausrollen).
|
||||||
|
- **Releases prüfen:** Der Installer prüft `SHA256SUMS` und die Signatur ([RELEASE.md](RELEASE.md)). Von Hand: `sha256sum -c SHA256SUMS` und `scripts/sign-release.sh verify SHA256SUMS SHA256SUMS.sig release-signing.pub.pem`.
|
||||||
|
- **Pakete:** Wer statt der Tarballs die `.deb`-/`.rpm`-Pakete des Releases nutzt (`apt install ./ddi-server_<version>-1_amd64.deb` bzw. `dnf install ./ddi-server-<version>-1.x86_64.rpm`), aktualisiert damit nur Binary (`/usr/bin`) und Unit; die Pakete legen keine Benutzer oder Konfiguration an und starten nichts. Eingerichtet wird weiterhin mit dem Installer, danach `systemctl restart ddi-server`.
|
||||||
|
|
||||||
|
## 7. Aufbewahrung (Retention)
|
||||||
|
|
||||||
|
Audit-Log und Revisionen wachsen mit jeder Änderung (Messwerte in [SYSTEM-REQUIREMENTS.md §7](SYSTEM-REQUIREMENTS.md#7-plattenplatz-planung)). Standardmäßig wird nichts gelöscht. In `server.yaml`:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
retention:
|
||||||
|
audit_days: 365 # Audit-Einträge älter als 365 Tage löschen (0 = unbegrenzt, Standard)
|
||||||
|
revisions_keep: 200 # nur die neuesten 200 Revisionen behalten (0 = alle, Standard)
|
||||||
|
```
|
||||||
|
|
||||||
|
Der Server räumt auf, sobald einer der beiden Werte gesetzt ist (auch per Umgebung: `DDI_RETENTION_AUDIT_DAYS`, `DDI_RETENTION_REVISIONS_KEEP`): fünf Minuten nach dem Start und danach alle 24 Stunden, in einer Transaktion, auch im Lizenz-Lesemodus. Gelöscht werden Audit-Einträge, die älter als `audit_days` Tage sind (höchstens 36.500), und Revisionen jenseits der neuesten `revisions_keep` samt ihren Dateien. **Nie gelöscht** werden die neueste Revision, jede Revision, die ein Agent anwendet, als letzte funktionierende kennt oder als Soll-Revision hat, und Revisionen mit offenen (`pending`) Deployments. Deployments selbst bleiben erhalten (sie nennen nur die Nummer). Hat ein Lauf etwas gelöscht, schreibt er den Audit-Eintrag `retention.cleanup` mit den Anzahlen und den gelöschten Revisionsnummern.
|
||||||
|
|
||||||
|
Folgen: Ein Rollback auf eine gelöschte Revision und ein Diff gegen eine gelöschte Vorgängerin sind nicht mehr möglich (`not_found`). Wer das Audit-Log länger braucht als die Aufbewahrung, exportiert es vorher (`GET /api/v1/audit/export`, Seite **Audit**). Nach großen Löschläufen gibt PostgreSQL den Platz erst durch `VACUUM` an die Tabelle zurück (Autovacuum erledigt das), an das Dateisystem erst durch `VACUUM FULL`.
|
||||||
|
|
||||||
|
## 8. Schlüssel und Zertifikate
|
||||||
|
|
||||||
|
### 8.1 Agent-Zertifikate
|
||||||
|
|
||||||
|
Agent-Zertifikate laufen 14 Tage und werden automatisch ab der Hälfte der Laufzeit über die bestehende Verbindung erneuert (neuer Schlüssel). Ein Agent, der länger offline war, darf sein abgelaufenes Zertifikat bis 30 Tage nach Ablauf noch für die Erneuerung benutzen. Danach ist ein neues Enrollment nötig.
|
||||||
|
|
||||||
|
Das Serverzertifikat des Agent-Ports stellt der Server bei jedem Start neu aus; es muss nicht gepflegt werden. Das Zertifikat der Weboberfläche (`http.tls_cert_file`) erneuert der Administrator selbst (eigenes oder ACME-Zertifikat ablegen, `systemctl restart ddi-server`).
|
||||||
|
|
||||||
|
### 8.2 Erneuerung mit verlorener Antwort, Neuregistrierung
|
||||||
|
|
||||||
|
Der Server speichert je Agent nur die Seriennummer des **aktuellen** Zertifikats. Geht die Antwort auf eine Erneuerung verloren (Verbindungsabbruch genau in diesem Moment, Absturz vor dem Speichern), gilt beim Server schon das neue Zertifikat, der Agent hat aber nur das alte. Der Agent wird dann abgewiesen (Log: Zertifikat unbekannt bzw. ersetzt) und muss **neu registriert** werden. Ebenso nach mehr als 30 Tagen offline, nach einer Wiederherstellung des Servers aus einer älteren Sicherung (§5) oder nach Verlust des Zustandsverzeichnisses.
|
||||||
|
|
||||||
|
Neu registrieren:
|
||||||
|
|
||||||
|
1. In der Oberfläche den alten Agent **löschen** (er verlässt dabei seinen Cluster) und ein neues Enrollment-Token für die Rolle erzeugen.
|
||||||
|
2. Auf dem Agent-Host:
|
||||||
|
```sh
|
||||||
|
sudo -u bind ddi-agent-dns enroll --config /etc/ddi-suite/agent-dns.yaml --force \
|
||||||
|
--server <host:8444> --token <token> --ca-hash sha256:<hex>
|
||||||
|
systemctl restart ddi-agent-dns
|
||||||
|
```
|
||||||
|
(`--force` ersetzt die vorhandene Identität; der Befehl steht ohne `--force` fertig in der Oberfläche.)
|
||||||
|
3. Den neuen Agent ggf. wieder seinem Cluster zuordnen und eine Revision ausrollen. Die zuletzt angewendete Revisionsnummer bleibt im Zustand erhalten.
|
||||||
|
|
||||||
|
Während der ganzen Zeit läuft BIND bzw. Kea mit der letzten Konfiguration weiter.
|
||||||
|
|
||||||
|
### 8.3 Master-Key-Rotation
|
||||||
|
|
||||||
|
Die Master-Key-Datei kann mehrere Schlüssel enthalten (`<id> <base64>` je Zeile); der erste verschlüsselt, alle entschlüsseln.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
systemctl stop ddi-server
|
||||||
|
cp -a /etc/ddi-suite/master.key /root/master.key.bak
|
||||||
|
ddi-server gen-master-key --out /tmp/new.key --id k2 # neue Datei mit einem Schlüssel
|
||||||
|
# Zeile "k2 …" aus /tmp/new.key als ERSTE Schlüsselzeile in master.key einfügen, alte Zeile darunter lassen
|
||||||
|
shred -u /tmp/new.key
|
||||||
|
chown ddi-suite /etc/ddi-suite/master.key && chmod 0400 /etc/ddi-suite/master.key
|
||||||
|
systemctl start ddi-server
|
||||||
|
```
|
||||||
|
|
||||||
|
Neue und geänderte Geheimnisse werden ab dann mit `k2` versiegelt; vorhandene bleiben mit dem alten Schlüssel lesbar. Ein Werkzeug, das alle vorhandenen Werte neu verschlüsselt, gibt es noch nicht (ADR 0015 sieht es vor). Die alte Zeile darf deshalb **nicht** entfernt werden, solange Werte unter ihr liegen; wer sie loswerden will, erneuert die betroffenen Geheimnisse (TSIG-Schlüssel rotieren, OIDC-Secret neu eintragen, TOTP neu einrichten …). CA und Bundle-Schlüssel lassen sich nicht neu versiegeln, ohne sie neu zu erzeugen (§5). Beide Schlüsselzeilen gehören in die Sicherung.
|
||||||
|
|
||||||
|
Der Server startet nur, wenn die Datei weder für die Gruppe noch für andere lesbar ist (Modus 0400 oder 0600).
|
||||||
|
|
||||||
|
### 8.4 TSIG-Schlüssel und HA-Passwort
|
||||||
|
|
||||||
|
- **TSIG:** Seite **TSIG-Schlüssel** → „Erneuern“ (bzw. `POST /api/v1/tsig-keys/{id}/rotate`), danach eine Revision ausrollen. Das gilt auch für den Transferschlüssel eines DNS-Clusters. Direkt nach dem Ausrollen kann ein Secondary kurz `tsig indicates error` melden, wenn er den neuen Schlüssel vor dem Primary aktiviert; NOTIFY holt den Transfer danach nach (§10.4). Externe Clients mit dem Schlüssel (`nsupdate`, DHCP-Server von Domain Controllern) mit dem neuen Geheimnis versorgen (Admins: „Geheimnis anzeigen“, wird auditiert).
|
||||||
|
- **HA-Passwort:** wird beim Anlegen eines DHCP-Clusters erzeugt; es gibt keinen Erneuern-Knopf. Zum Erneuern den Cluster neu anlegen (§9). Benutzer und Passwort stehen auf den Kea-Hosts nur in `ddi-suite-ha-user` und `ddi-suite-ha-password` neben der Kea-Konfiguration, weil Kea 3.x Klartext-Zugangsdaten in der Konfiguration ablehnt.
|
||||||
|
- **`rndc`-Schlüssel:** `rndc-confgen -a`, BIND neu starten; die Agent-Konfiguration verweist per `rndc_args` auf die Schlüsseldatei.
|
||||||
|
|
||||||
|
## 9. Cluster-Mitglieder hinzufügen und entfernen
|
||||||
|
|
||||||
|
**DNS (Primary + Secondaries):**
|
||||||
|
|
||||||
|
- *Secondary hinzufügen:* Agent auf dem neuen Host installieren und registrieren, in der Oberfläche dem Cluster als `secondary` mit der Adresse hinzufügen, über die er den Primary erreicht. Revision ausrollen. Der Primary erhält ihn in `also-notify`, der Secondary holt alle Zonen per AXFR. Firewall: 53/tcp und 53/udp zwischen beiden.
|
||||||
|
- *Secondary entfernen:* aus dem Cluster entfernen, ausrollen, danach Agent löschen oder deinstallieren. Ein entfernter, noch laufender Agent erhält wieder die Konfiguration der Standardgruppe (alle Zonen ohne Cluster als Primary) – deshalb erst entfernen, dann den Dienst stoppen.
|
||||||
|
- *Primary wechseln:* neuen Primary als `primary` eintragen und den alten im selben Schritt zum `secondary` machen oder entfernen (es gibt genau einen Primary), ausrollen. Dynamische Zonen: deren Daten liegen nur beim bisherigen Primary (Journal); vor dem Wechsel per AXFR auf dem neuen Primary bereitstellen oder nach dem Wechsel neu befüllen lassen (Domain Controller registrieren ihre Records erneut).
|
||||||
|
|
||||||
|
**DHCP (Kea-HA):**
|
||||||
|
|
||||||
|
- *Zweiten Server hinzufügen:* Agent registrieren, dem Cluster als `secondary` mit der Adresse des HA-Listeners hinzufügen (Port `ha_port`, Standard 8001), ausrollen. Beide Peers synchronisieren die Leases und gehen in `hot-standby` (bzw. `load-balancing`). Voraussetzung Kea ≥ 3.0 auf beiden.
|
||||||
|
- *Server entfernen:* aus dem Cluster entfernen und ausrollen; der verbleibende arbeitet als Einzelserver. Dann den Agent löschen und Kea stoppen.
|
||||||
|
- *HA-Passwort erneuern:* Mitglieder entfernen, Cluster löschen, neu anlegen, Netze bzw. Standardcluster neu zuordnen, ausrollen.
|
||||||
|
|
||||||
|
Clusteränderungen wirken wie alle Änderungen erst mit der nächsten Revision und erscheinen vorher unter „Änderungen warten auf Ausrollen“.
|
||||||
|
|
||||||
|
## 10. Fehlersuche
|
||||||
|
|
||||||
|
### 10.1 Agent lehnt eine Revision ab
|
||||||
|
|
||||||
|
Deployment-Ergebnis `rejected` (Prüfung gescheitert, nichts aktiviert) oder `rolled_back` (aktiviert, Health-Check gescheitert, vorige Revision wiederhergestellt). Die Meldung steht beim Deployment in der Oberfläche und im Agent-Log.
|
||||||
|
|
||||||
|
- Häufige Ursachen: Pfade der Generator-Einstellungen passen nicht zur Agent-Konfiguration (`zone_dir`, `control_socket` – der Agent lehnt dann ausdrücklich ab), `named.conf` bindet die Includes nicht oder in falscher Reihenfolge ein, Rechte auf `zone_dir`/`secondary/`, fehlender Kea-Hook (Kea 3.x lädt Hooks nur aus dem eingebauten Verzeichnis), BIND-Optionen der Distribution kollidieren mit generierten Optionen (`recursion`, `allow-transfer` …).
|
||||||
|
- Eine abgelehnte Revision wird **nicht** automatisch erneut versucht. Nach der Korrektur eine neue Revision erzeugen oder dieselbe Revision per „Jetzt ausrollen“ erneut pushen.
|
||||||
|
- Prüfen von Hand auf dem Agent-Host: `named-checkconf -z /etc/bind/named.conf`, `kea-dhcp4 -t /etc/kea/kea-dhcp4.conf`.
|
||||||
|
|
||||||
|
### 10.2 Rollback
|
||||||
|
|
||||||
|
- **Über die Oberfläche:** Revisionen → ältere Revision → „Zurückrollen“ erzeugt eine **neue** Revision mit dem Inhalt der alten (höhere Nummer, also auch höhere SOA-Seriennummer). `auto_pull`-Agents übernehmen sie sofort, `manual`-Agents nach „Jetzt ausrollen“.
|
||||||
|
- **Automatisch im Agent:** Scheitert der Health-Check, stellt der Agent die letzte funktionierende Revision wieder her. Auf einem DNS-Primary sinkt dabei die Seriennummer; Secondaries behalten die höhere, bis die nächste Revision kommt. Die nächste Revision aus der Oberfläche behebt das.
|
||||||
|
- Revisionen ältere als M4 (ohne gespeicherte Generator-Eingabe) und Revisionen, deren Geheimnisse fehlen, lassen sich nicht zurückrollen (`rollback_unavailable`).
|
||||||
|
|
||||||
|
### 10.3 Kea übernimmt die neue Konfiguration nicht (`config-reload`)
|
||||||
|
|
||||||
|
Kea liest bei `config-reload` die Datei, **mit der es gestartet wurde**. Zeigt `dhcp.config_file` des Agents auf eine andere Datei, meldet der Reload Erfolg, Kea arbeitet aber mit der alten Konfiguration weiter; nur der Dateivergleich im Health-Check des Agents fällt auf („Konfiguration weicht ab“). Abhilfe: `config_file` des Agents auf die Datei setzen, die die Kea-Unit mit `-c` übergibt (Standard `/etc/kea/kea-dhcp4.conf`), und Kea neu starten.
|
||||||
|
|
||||||
|
Verwandte Punkte: Der Control-Socket muss in Keas Socket-Verzeichnis liegen (`/run/kea`, Modus 0750, Umgebungsvariable `KEA_CONTROL_SOCKET_DIR`), die Lease-Datei in Keas Datenverzeichnis; die Generator-Einstellungen (`control_socket`, `lease_file`, `ha_password_file`) müssen zu den Pfaden auf den Hosts passen.
|
||||||
|
|
||||||
|
### 10.4 Secondary überträgt keine Zonen
|
||||||
|
|
||||||
|
- `journalctl -u named` auf dem Secondary: `tsig indicates error` bzw. `BADKEY`/`BADSIG` heißt, Primary und Secondary haben unterschiedliche Schlüssel. Direkt nach einer Schlüsseländerung normal (der Secondary war schneller); NOTIFY löst den Transfer wieder aus. Bleibt es dabei: prüfen, dass beide Agents dieselbe Revision anwenden (Oberfläche), und `rndc retransfer <zone>` auf dem Secondary.
|
||||||
|
- `BADTIME`: Uhren gehen auseinander (TSIG erlaubt 5 Minuten) → NTP prüfen.
|
||||||
|
- `connection refused`/Timeout: 53/tcp vom Secondary zum Primary freigeben; die Adressen der Mitglieder im Cluster müssen die sein, unter denen sich die Server gegenseitig erreichen.
|
||||||
|
- `refused` beim Transfer: Der Primary kennt den Secondary nicht (Cluster nicht ausgerollt) oder der Schlüssel fehlt in `allow-transfer`.
|
||||||
|
- Eine noch nicht übertragene Zone zeigt der Health-Check als „eingeschränkt“, nicht als Fehler.
|
||||||
|
|
||||||
|
### 10.5 Agent nicht verbunden
|
||||||
|
|
||||||
|
- `ddi-agent-<rolle> status`: Ist das Zertifikat abgelaufen? Stimmt die Serveradresse?
|
||||||
|
- Netz: Agent → Server 8444/tcp ausgehend. Ein Proxy, der TLS aufbricht, verhindert mTLS.
|
||||||
|
- Log „certificate … unknown/replaced/revoked“: neu registrieren (§8.2).
|
||||||
|
- Der Agent fällt bei Störungen des Streams auf Polling zurück; „verbunden“ zeigt nur den Stream.
|
||||||
|
|
||||||
|
### 10.6 Lizenz: Lesemodus
|
||||||
|
|
||||||
|
Im Zustand `read_only` (Testzeitraum abgelaufen, Lizenz abgelaufen oder gesperrt, Keygen länger als die Karenzzeit nicht erreichbar) lehnt der Server alle Änderungen und das Ausrollen ab; Lesen, Export und die Lizenzverwaltung bleiben möglich, Agents sperren und löschen ebenfalls. **DNS und DHCP laufen unverändert weiter**, Agents holen weiterhin ihre Soll-Revision. Abhilfe: Lizenzschlüssel eintragen bzw. erneuern (Seite **Lizenz** oder auf dem Server `ddi-server license set-key <schluessel.txt`: liest den Schlüssel von stdin, gibt Status, Ablauf und Grenzen aus, nie den Schlüssel; Exit-Code 0 aktiviert, 2 Eingabe leer, zu lang oder mehrzeilig, 3 Schlüssel abgelehnt, 4 Lizenzserver nicht erreichbar oder Antwort nicht vertrauenswürdig, 1 sonstiger Fehler; bei 3 und 4 wird nichts gespeichert), Erreichbarkeit von `https://license.beugsiud.de` (443/tcp ausgehend) prüfen, in isolierten Netzen eine Offline-Lizenzdatei importieren. Einzelheiten: [LICENSING.md](LICENSING.md).
|
||||||
|
|
||||||
|
### 10.7 Prüfung „Ping/DNS“ meldet „nicht verfügbar“ oder Fehler
|
||||||
|
|
||||||
|
Die Prüfung einzelner Einträge (`POST /addresses/check`, ADR 0025) läuft vom Server aus:
|
||||||
|
|
||||||
|
- **Ping `unavailable`:** Der Server versucht zuerst unprivilegierte ICMP-Sockets (`net.ipv4.ping_group_range`), dann einen Raw-Socket mit `CAP_NET_RAW` aus seiner systemd-Unit. „Nicht verfügbar“ heißt, beides ging nicht: Unit älter als v0.8.1 (`install.sh --upgrade`), die Capability in einem Container nicht vorhanden (z. B. LXC ohne `CAP_NET_RAW`) oder der Server läuft nicht unter Linux. Abhilfe ohne Capability: `sysctl -w net.ipv4.ping_group_range="0 2147483647"` und dauerhaft in `/etc/sysctl.d/`. „Nicht verfügbar“ sagt nichts über den Host aus.
|
||||||
|
- **Ping `unreachable`:** keine Antwort innerhalb von zwei Versuchen à 1 s – Host aus oder ICMP auf dem Weg (Firewall) gesperrt.
|
||||||
|
- **DNS `error` oder `missing`:** Gefragt werden die Mitglieder des DNS-Clusters der Zone (Primary zuerst), sonst die Nameserver-Adressen aus den Generator-Einstellungen, bei Zonen ohne Cluster außerdem die DNS-Agents unter der Adresse ihrer letzten Verbindung, erst dann der Resolver des Servers („system“). Der Server braucht 53/udp und 53/tcp zu ihnen. Die Hinweise unter dem Ergebnis nennen die häufigsten Gründe für „fehlt“: nur der Resolver des Servers wurde gefragt, oder die Änderung ist **noch nicht ausgerollt**. In **dynamischen Zonen** (z. B. einer Active-Directory-Domäne) trägt der DNS-Agent die Einträge der Adresstabelle beim Ausrollen per `nsupdate` ein ([ADR 0026](adr/0026-eintraege-in-dynamischen-zonen.md)); fehlt dort etwas, zuerst den Bericht des Agents zur Revision ansehen. `mismatch` heißt, der DNS-Server antwortet anders als die Adresstabelle.
|
||||||
|
|
||||||
|
### 10.8 Weitere Hinweise
|
||||||
|
|
||||||
|
- Server startet nicht, „master key file … must not be accessible by group or others“: `chmod 0400 /etc/ddi-suite/master.key`.
|
||||||
|
- Server startet nicht, „decryption failed“: falscher Master-Key zur Datenbank (§5).
|
||||||
|
- CSV-Import: rund 1.100 Zeilen pro Sekunde (gemessen, [SYSTEM-REQUIREMENTS.md §4](SYSTEM-REQUIREMENTS.md#4-messungen)); eine Datei an der Grenze von 50.000 Zeilen braucht knapp eine Minute. Die Anfrage hat dafür eine eigene Frist von 10 Minuten (statt der allgemeinen 60 s).
|
||||||
|
- Login gesperrt (HTTP 429): Ratenbegrenzung, nach einer Minute wieder ein Versuch. Ein vergessenes Admin-Passwort setzt ein anderer Admin zurück (Benutzer → Passwort zurücksetzen). `ddi-server bootstrap-admin` funktioniert nur, solange es noch keinen Benutzer gibt; deshalb immer mindestens zwei Administratoren oder OIDC-Zugang einrichten.
|
||||||
|
|
||||||
|
### 10.9 Einträge in dynamischen Zonen (ADR 0026)
|
||||||
|
|
||||||
|
Die von DDI verwalteten Einträge einer dynamischen Zone (Adresstabelle und Records der Zone) trägt der DNS-Agent auf dem Primary nach dem Neuladen von BIND per dynamischem Update ein: `nsupdate -k` mit dem Systemschlüssel `ddi-agent-update` aus der Revision, an `dns_address` der Agent-Konfiguration. Er löscht ausschließlich Einträge, die die vorige Revision verwaltet hat und die neue nicht mehr enthält; Einträge der Domain Controller, anderer Clients oder von Hand bleiben unberührt. Secondaries erhalten die Änderungen per NOTIFY/IXFR.
|
||||||
|
|
||||||
|
- `nsupdate` muss auf dem Primary vorhanden sein (Debian/Ubuntu: `bind9-dnsutils`, EL9: `bind-utils`; der Installer richtet beides ein). Programmname oder Pfad: Option `dns.nsupdate` in `agent-dns.yaml` (Standard `nsupdate`).
|
||||||
|
- Agent-Log: „managed records of a dynamic zone updated“ mit `zone`, `records` (Anzahl der verwalteten Einträge) und `deleted`.
|
||||||
|
- Scheitert ein Update, scheitert das Aktivieren, und der Agent rollt auf die vorige Revision zurück, die ihren eigenen Stand wieder einträgt. `REFUSED` heißt meist, dass der Schlüssel in der Update-ACL der Zone fehlt; `NOTAUTH` mit `BADSIG`/`BADKEY` im BIND-Log, dass BIND einen anderen Schlüssel kennt. Direkt nach dem Anlegen einer Zone wartet der Agent bis zu 10 s, bis BIND sie geladen hat.
|
||||||
|
- Einen verwalteten Eintrag, den jemand von Hand ändert oder löscht, setzt die nächste Revision auf den Stand von DDI zurück.
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# Release
|
||||||
|
|
||||||
|
Wie ein Release gebaut, signiert und veröffentlicht wird ([ADR 0003](adr/0003-git-host-gitea-actions.md), [ADR 0024](adr/0024-auslieferung-installer-m6.md)).
|
||||||
|
|
||||||
|
## Ablauf
|
||||||
|
|
||||||
|
1. Meilenstein fertig, CI auf `main` grün.
|
||||||
|
2. Tag setzen und pushen: `git tag -a v0.7.0 -m "M6 Auslieferung" && git push origin v0.7.0`.
|
||||||
|
3. Der Workflow `.gitea/workflows/release.yml` baut mit `make release PACKAGES=1 VERSION=<tag>`:
|
||||||
|
- Tarballs `<binary>_<tag>_linux_<arch>.tar.gz` für `amd64` und `arm64`,
|
||||||
|
- Pakete `<binary>_<version>-1_<arch>.deb` und `<binary>-<version>-1.<arch>.rpm` (nfpm, siehe unten),
|
||||||
|
- `SHA256SUMS` über Tarballs und Pakete,
|
||||||
|
- `SHA256SUMS.sig`, falls das Secret `RELEASE_SIGNING_KEY` gesetzt ist.
|
||||||
|
4. `scripts/release-upload.sh` legt das Gitea-Release an (Tags mit `-` werden als Vorabversion markiert) und lädt alle Dateien aus `dist/` hoch; vorhandene Dateien gleichen Namens werden ersetzt, der Workflow kann also erneut laufen.
|
||||||
|
|
||||||
|
Lokal: `make release` (nur Tarballs), `make release PACKAGES=1` bzw. nach `make release` ein `make packages` (braucht `nfpm`), `make sign-release RELEASE_SIGNING_KEY_FILE=<pfad>`.
|
||||||
|
|
||||||
|
## Pakete (`.deb`, `.rpm`)
|
||||||
|
|
||||||
|
`scripts/build-packages.sh` nimmt die Binaries aus den Tarballs in `dist/` (dieselben Dateien, keine zweite Übersetzung) und baut je Binary und Architektur ein `.deb` und ein `.rpm` mit [nfpm](https://nfpm.goreleaser.com). nfpm wird in der CI von `scripts/ci/install-tools.sh` in einer festen Version mit Prüfsumme installiert (`NFPM_VERSION`); lokal genügt ein `nfpm` im `PATH` oder `make packages NFPM=/pfad/zu/nfpm`.
|
||||||
|
|
||||||
|
| Paket | Inhalt |
|
||||||
|
| --- | --- |
|
||||||
|
| Name = Binary-Name (`BIN_SERVER`, `BIN_AGENT_DNS`, `BIN_AGENT_DHCP` aus dem Makefile) | `/usr/bin/<binary>` (0755) |
|
||||||
|
| | `/usr/lib/systemd/system/<binary>.service` (aus `deploy/systemd/*.service.in`, gerendert mit `/usr/bin`) |
|
||||||
|
| | `/usr/share/doc/<binary>/LICENSE` (Server proprietär, Agents Apache-2.0) |
|
||||||
|
|
||||||
|
- Paketversion: Tag ohne `v` (`v0.7.0` → `0.7.0`, Release `1`); Builds ohne Versions-Tag erhalten `0.0.0-dev.<beschreibung>`.
|
||||||
|
- Die Pakete enthalten **keine** Konfiguration, legen keine Benutzer an und starten nichts. Die Paket-Skripte rufen nur `systemctl daemon-reload` auf. Eingerichtet wird mit `scripts/install.sh`.
|
||||||
|
- Konfiguration: Vorlage `deploy/nfpm/package.yaml.in` mit Platzhaltern (ADR 0018). `PKG_MAINTAINER`, `PKG_VENDOR` und `PKG_HOMEPAGE` lassen sich per Umgebung überschreiben.
|
||||||
|
|
||||||
|
## Signatur
|
||||||
|
|
||||||
|
`SHA256SUMS.sig` ist eine Ed25519-Signatur (64 Byte, binär) über `SHA256SUMS`, erzeugt mit `openssl pkeyutl -sign -rawin`. Weil `SHA256SUMS` alle Artefakte abdeckt, genügt eine Signatur. Der Installer prüft sie mit dem öffentlichen Schlüssel aus seinem Variablenblock.
|
||||||
|
|
||||||
|
### Schlüsselpaar erzeugen (einmalig, offline)
|
||||||
|
|
||||||
|
```sh
|
||||||
|
umask 077
|
||||||
|
openssl genpkey -algorithm ed25519 -out release-signing.pem # privat
|
||||||
|
openssl pkey -in release-signing.pem -pubout -out release-signing.pub.pem
|
||||||
|
```
|
||||||
|
|
||||||
|
Der private Schlüssel gehört in einen Passwortmanager bzw. auf einen Offline-Datenträger, nicht ins Repository. Wer ihn hat, kann Releases signieren, die jeder Installer annimmt.
|
||||||
|
|
||||||
|
### Gitea-Secret setzen
|
||||||
|
|
||||||
|
Repository → Einstellungen → Actions → Secrets → **Secret hinzufügen**: Name `RELEASE_SIGNING_KEY`, Wert = kompletter Inhalt von `release-signing.pem` (einschließlich der Zeilen `-----BEGIN PRIVATE KEY-----`/`-----END PRIVATE KEY-----`).
|
||||||
|
|
||||||
|
Der Workflow schreibt den Schlüssel nur für die Dauer des Signierens in eine Datei mit Modus 0600 (`umask 077`) und löscht sie danach; er wird nie ausgegeben. Ohne Secret entsteht kein `SHA256SUMS.sig`, der Workflow warnt.
|
||||||
|
|
||||||
|
### Öffentlichen Schlüssel in den Installer eintragen
|
||||||
|
|
||||||
|
In `scripts/install.sh` im Variablenblock (zwischen `# --- names (ADR 0018) ---` und `# --- end names ---`) den Inhalt von `release-signing.pub.pem` als `RELEASE_PUBLIC_KEY_PEM` eintragen:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
RELEASE_PUBLIC_KEY_PEM="-----BEGIN PUBLIC KEY-----
|
||||||
|
MCowBQYDK2VwAyEA…
|
||||||
|
-----END PUBLIC KEY-----"
|
||||||
|
```
|
||||||
|
|
||||||
|
Ist der Schlüssel gesetzt, bricht der Installer bei fehlender oder ungültiger Signatur ab; ohne Schlüssel prüft er nur die Prüfsummen und weist darauf hin. Der Release-Workflow prüft die frische Signatur mit dem Schlüssel aus `scripts/install.sh`, damit ein falsch eingetragener Schlüssel schon beim Release auffällt.
|
||||||
|
|
||||||
|
### Prüfen von Hand
|
||||||
|
|
||||||
|
```sh
|
||||||
|
scripts/sign-release.sh verify SHA256SUMS SHA256SUMS.sig release-signing.pub.pem
|
||||||
|
# entspricht
|
||||||
|
openssl pkeyutl -verify -pubin -inkey release-signing.pub.pem -rawin -in SHA256SUMS -sigfile SHA256SUMS.sig
|
||||||
|
sha256sum -c SHA256SUMS
|
||||||
|
```
|
||||||
|
|
||||||
|
Die CI (Job „Release build (dry run)“) erzeugt bei jedem Lauf einen Wegwerf-Schlüssel und prüft Signieren, Verifizieren sowie die Ablehnung einer veränderten Datei und eines fremden Schlüssels (`scripts/sign-release.sh selftest`).
|
||||||
|
|
||||||
|
### Schlüsselwechsel
|
||||||
|
|
||||||
|
Neues Schlüsselpaar erzeugen, Secret ersetzen, öffentlichen Schlüssel in `scripts/install.sh` tauschen, neues Release taggen. Bereits verteilte Installer-Skripte kennen nur den alten Schlüssel und lehnen Releases mit dem neuen ab; sie müssen durch das Skript des neuen Releases ersetzt werden.
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
# Sicherheit
|
||||||
|
|
||||||
|
Dieses Dokument beschreibt das Bedrohungsmodell der DDI-Suite, die Verwaltung der Schlüssel, ihre Rotation, Härtungshinweise und – ebenso wichtig – was das System **nicht** schützt. Grundlage sind Brief §8 und §9 sowie die ADRs [0007](adr/0007-server-agent-grpc-mtls.md), [0008](adr/0008-interne-ca-enrollment.md), [0009](adr/0009-signierte-config-bundles.md), [0015](adr/0015-geheimnisse-verschluesselt.md), [0016](adr/0016-lizenzierung-keygen.md), [0020](adr/0020-authentifizierung-sitzungen.md), [0023](adr/0023-cluster-und-zonen-m5.md) und [0024](adr/0024-auslieferung-installer-m6.md). Betrieb und Abläufe stehen in [OPERATIONS.md](OPERATIONS.md), Voraussetzungen und Ports in [SYSTEM-REQUIREMENTS.md](SYSTEM-REQUIREMENTS.md).
|
||||||
|
|
||||||
|
Namen und Pfade (`ddi-suite`, `/etc/ddi-suite`, `ddi-server` …) sind die Standardwerte der zentralen Benennung ([ADR 0018](adr/0018-zentrale-benennung.md)).
|
||||||
|
|
||||||
|
## 1. Schutzgüter
|
||||||
|
|
||||||
|
| Schutzgut | Warum schützenswert | Wo es liegt |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| **Datenebene** (DNS-Antworten, DHCP-Vergabe) | Wer sie verfälscht, lenkt Clients um oder legt das Netz lahm. | BIND und Kea auf den Agent-Hosts |
|
||||||
|
| **Soll-Konfiguration** (Revisionen) | Wer sie fälscht, steuert alle DNS- und DHCP-Server. | PostgreSQL, signierte Bundles |
|
||||||
|
| **Master-Key** | Entschlüsselt alle Geheimnisse in der Datenbank. | `/etc/ddi-suite/master.key` (nur Server) |
|
||||||
|
| **Agent-CA-Schlüssel** | Stellt Agent- und Serverzertifikate aus. | Datenbank, mit dem Master-Key versiegelt |
|
||||||
|
| **Bundle-Signaturschlüssel** (Ed25519) | Unterschreibt jede Konfiguration, der ein Agent vertraut. | Datenbank, versiegelt |
|
||||||
|
| **TSIG-Schlüssel, HA-Zugangsdaten** | Erlauben Zonentransfers, dynamische Updates, Steuerung des Kea-Partners. | Datenbank (versiegelt), Bundles, Dateien auf den Agent-Hosts |
|
||||||
|
| **Benutzerkonten, Sitzungen, TOTP-, OIDC-Secret** | Zugang zur Verwaltung. | Datenbank (Passwörter als Argon2id-Hash, Sitzungen als SHA-256-Hash, TOTP- und OIDC-Secret versiegelt) |
|
||||||
|
| **Agent-Identität** (privater Schlüssel, Zertifikat) | Erlaubt, sich gegenüber dem Server als dieser Agent auszugeben. | `/var/lib/ddi-suite/agent-<rolle>/identity/` (Modus 0700) |
|
||||||
|
| **IPAM-Daten, Audit-Log** | Inventar des Netzes, Nachvollziehbarkeit. | Datenbank |
|
||||||
|
| **Lizenzstatus** | Wirtschaftliches Interesse des Herstellers (Soft-Control, §9). | Datenbank (versiegelt) |
|
||||||
|
|
||||||
|
## 2. Vertrauensgrenzen
|
||||||
|
|
||||||
|
```
|
||||||
|
Browser ──HTTPS 8443──▶ Management-Server ──Unix-Socket──▶ PostgreSQL
|
||||||
|
│ ▲
|
||||||
|
│ └── HTTPS 443 ausgehend ──▶ Keygen (Lizenz)
|
||||||
|
│
|
||||||
|
gRPC/mTLS 8444 ◀─┘ (Agent verbindet sich ausgehend)
|
||||||
|
│
|
||||||
|
┌──────────┴───────────┐
|
||||||
|
▼ ▼
|
||||||
|
DNS-Agent ──rndc 127.0.0.1──▶ BIND DHCP-Agent ──Unix-Socket──▶ Kea
|
||||||
|
│ 53/tcp TSIG ▲ │ HTTP+Basic-Auth (HA, ohne TLS)
|
||||||
|
▼ │ ▼
|
||||||
|
Secondary ────────┘ Kea-Partner
|
||||||
|
```
|
||||||
|
|
||||||
|
| Grenze | Angreifer könnte … | Schutz |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| **Browser ↔ Server** | Sitzungen stehlen, Anfragen fälschen (CSRF), Skripte einschleusen (XSS), Passwörter raten. | TLS ≥ 1.2, HSTS, Content-Security-Policy, `X-Frame-Options: DENY`; Sitzungscookie `Secure`, `HttpOnly`, `SameSite=Lax`; CSRF-Token pro Sitzung plus `Origin`/`Sec-Fetch-Site`-Prüfung; Login-Ratenbegrenzung pro IP und Benutzer; Argon2id; optional TOTP; OIDC mit PKCE, `state`, `nonce`; RBAC pro Route (Viewer, Operator, Admin). |
|
||||||
|
| **Server ↔ Agent** | Sich als Server ausgeben, als Agent ausgeben, Konfiguration fälschen oder alte wieder einspielen. | TLS 1.3 mit gegenseitigen Zertifikaten der internen CA. Enrollment nur mit Einmal-Token (24 h, in der DB nur als Hash) und vorab bekanntem CA-Fingerprint (`--ca-hash`). Agent-Zertifikate 14 Tage, der Server akzeptiert nur die **aktuelle** Seriennummer je Agent und prüft die Sperre bei jedem Aufruf. Bundles sind mit einem **eigenen** Ed25519-Schlüssel signiert (nicht der CA); der Agent wendet nur Revisionen an, die größer als die zuletzt angewendete sind. |
|
||||||
|
| **Agent ↔ Daemon** | Über den Steuerkanal BIND/Kea umkonfigurieren. | `rndc` nur auf 127.0.0.1 mit Schlüssel; Kea-Control-Socket als Unix-Socket in einem Verzeichnis mit Modus 0750. Der Agent läuft als Benutzer des Dienstes (`bind`/`named` bzw. `_kea`/`kea`), nicht als root. Jede Konfiguration wird vor dem Aktivieren geprüft (`named-checkconf -z`, `named-checkzone`, `kea-dhcp4 -t`). |
|
||||||
|
| **Primary ↔ Secondary (DNS)** | Zonen abziehen, gefälschte Zonen unterschieben. | `allow-transfer` nur mit dem TSIG-Transferschlüssel des Clusters (`hmac-sha256`), NOTIFY nur an die Secondaries, Secondaries holen nur mit diesem Schlüssel. |
|
||||||
|
| **Kea ↔ Kea (HA)** | HA-Befehle senden, Leases manipulieren. | HTTP mit Basic-Auth; Benutzer und Passwort je Cluster zufällig erzeugt, nur in Dateien (Modus 0640). **Ohne TLS** – siehe Abschnitt 6. |
|
||||||
|
| **Server ↔ Keygen** | Lizenzantworten fälschen. | HTTPS, jede Antwort mit Ed25519 signiert (Account-Schlüssel beim Build eingebettet), Digest, Request-Target, Datum ≤ 5 min, `nonce` bei der Validierung. |
|
||||||
|
| **Server ↔ PostgreSQL** | Datenbank lesen oder ändern. | Installer: Peer-Authentifizierung über den Unix-Socket, kein Passwort, kein TCP nötig. Geheimnisse sind zusätzlich mit dem Master-Key versiegelt (AES-256-GCM, Zeilenkontext als Associated Data). |
|
||||||
|
| **Installer ↔ Release-Server** | Manipulierte Binaries ausliefern. | `SHA256SUMS` und, falls der öffentliche Schlüssel im Installer gesetzt ist, die Ed25519-Signatur `SHA256SUMS.sig` (Abschnitt 7). |
|
||||||
|
|
||||||
|
## 3. Bedrohungen und ihre Folgen
|
||||||
|
|
||||||
|
| Ereignis | Folge | Begrenzung |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Server-Host kompromittiert (root oder Dienstbenutzer) | **Vollständige Kontrolle:** Master-Key und Datenbank geben alle Geheimnisse frei, der Bundle-Schlüssel signiert beliebige Konfigurationen für alle Agents. | Server isoliert betreiben, Zugang streng begrenzen (Abschnitt 5). Agents prüfen jede Konfiguration syntaktisch, fremde Dateipfade sind im Bundle-Format ausgeschlossen. |
|
||||||
|
| Datenbank oder Backup gestohlen (ohne Master-Key) | IPAM-Daten und Audit-Log lesbar, Geheimnisse nicht; Passwort-Hashes (Argon2id) offline angreifbar; Sitzungen nicht übernehmbar (nur Hashes). | Backups verschlüsselt und getrennt vom Master-Key aufbewahren. |
|
||||||
|
| Master-Key gestohlen (ohne Datenbank) | Für sich wertlos. | Getrennte Aufbewahrung. |
|
||||||
|
| Agent-Host kompromittiert | Der Angreifer kontrolliert diesen DNS- bzw. DHCP-Dienst, kennt dessen TSIG- bzw. HA-Geheimnisse und kann sich als dieser Agent beim Server melden (Status, Leases). Andere Agents und der Server sind nicht betroffen; gefälschte Lease-Meldungen erzeugen höchstens `dynamic`-Einträge. | Agent in der Oberfläche **sperren** (wirkt sofort), Transferschlüssel des Clusters und betroffene TSIG-Schlüssel rotieren. |
|
||||||
|
| Enrollment-Token abgefangen | Wer es vor dem rechtmäßigen Agent nutzt, registriert einen eigenen Agent dieser Rolle und erhält deren Konfiguration samt Geheimnissen. | Kurze Laufzeit, einmalig; nur über vertrauliche Kanäle weitergeben; unbekannte Agents in der Oberfläche prüfen und sperren. |
|
||||||
|
| Transportweg Agent ↔ Server manipuliert | Ohne CA-Schlüssel kein gültiges Serverzertifikat, ohne Bundle-Schlüssel keine gültige Konfiguration. | – |
|
||||||
|
| Administratorkonto übernommen | Volle Verwaltung, Ausrollen beliebiger (gültiger) Konfiguration. | TOTP oder OIDC mit MFA, Audit-Log prüfen, Sitzungen per Passwortwechsel beenden. |
|
||||||
|
|
||||||
|
## 4. Schlüsselverwaltung
|
||||||
|
|
||||||
|
| Schlüssel | Erzeugt von | Liegt | Schutz | Rotation |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| **Master-Key** (AES-256, Datei mit Schlüssel-ID) | `ddi-server gen-master-key` (Installer) | `/etc/ddi-suite/master.key` | Der Server startet nur, wenn die Datei **weder für Gruppe noch für andere** lesbar ist (Modus 0400 oder 0600, Eigentümer Dienstbenutzer). Nie in der Datenbank. | Teilweise, siehe 4.1 |
|
||||||
|
| **Agent-CA** (ECDSA P-256, 10 Jahre) | Server beim ersten Start | Datenbank, versiegelt | Master-Key | Nicht umgesetzt (ADR 0008/0021); bei Kompromittierung neue Installation der PKI, siehe 4.2 |
|
||||||
|
| **Serverzertifikat Agent-Port** (1 Jahr) | Server bei **jedem Start** aus der CA | nur im Speicher | – | Automatisch bei jedem Neustart |
|
||||||
|
| **Agent-Zertifikate** (ECDSA P-256, 14 Tage) | Agent erzeugt Schlüssel und CSR, Server signiert | `/var/lib/ddi-suite/agent-<rolle>/identity/` | Modus 0700, Dienstbenutzer | Automatisch ab halber Laufzeit, neuer Schlüssel |
|
||||||
|
| **Bundle-Signaturschlüssel** (Ed25519) | Server beim ersten Start | Datenbank, versiegelt; öffentlicher Teil bei jedem Agent | Master-Key | Vorgesehen (neuer Schlüssel vom alten signiert, ADR 0009), **nicht umgesetzt** |
|
||||||
|
| **TSIG-Schlüssel** (`hmac-sha256/384/512`) | Server (Zufall, Länge = Hash-Länge) | Datenbank versiegelt, im Bundle, auf den DNS-Hosts in `ddi-suite-keys.conf` (0640) | Master-Key; API zeigt sie nur Admins über `GET /tsig-keys/{id}/secret` (auditiert) | `POST /tsig-keys/{id}/rotate`, siehe 4.3 |
|
||||||
|
| **HA-Zugangsdaten** (Benutzer + Passwort je DHCP-Cluster) | Server beim Anlegen des Clusters | Datenbank versiegelt, im Bundle, auf den Kea-Hosts in `ddi-suite-ha-user`/`ddi-suite-ha-password` (0640) | Master-Key; nie in der API | Kein eigener Befehl, siehe 4.3 |
|
||||||
|
| **`rndc`-Schlüssel** | Paket bzw. Installer (`rndc-confgen`) | `/etc/bind/rndc.key` | Distribution (0640 root:bind) | `rndc-confgen -a` erneut, BIND neu starten |
|
||||||
|
| **Sitzungen** | Server (256 Bit Zufall) | Cookie; in der DB nur SHA-256 | – | Laufzeit 12 h, Leerlauf 1 h; Logout und Passwortwechsel beenden sie |
|
||||||
|
| **TOTP-Secret, OIDC-Client-Secret** | Benutzer bzw. Administrator | Datenbank, versiegelt | Master-Key | TOTP ab- und wieder einschalten; OIDC-Secret beim Identity-Provider erneuern und in der Oberfläche eintragen |
|
||||||
|
| **Enrollment-Token** | Administrator in der Oberfläche | in der DB nur SHA-256 | einmalig, 24 h | Unbenutzte Tokens löschen |
|
||||||
|
| **Release-Signaturschlüssel** (Ed25519) | Hersteller | Secret `RELEASE_SIGNING_KEY` der CI | nur der Release-Workflow; privater Schlüssel offline | Neues Paar, Secret ersetzen, öffentlichen Schlüssel in `scripts/install.sh` tauschen; ältere Installer lehnen Releases mit dem neuen Schlüssel ab ([RELEASE.md](RELEASE.md#schlüsselwechsel)) |
|
||||||
|
|
||||||
|
### 4.1 Master-Key
|
||||||
|
|
||||||
|
Die Datei enthält eine Zeile `<schlüssel-id> <base64>` je Schlüssel. Der **erste** Schlüssel verschlüsselt, alle Schlüssel entschlüsseln; jeder Chiffretext trägt die ID seines Schlüssels.
|
||||||
|
|
||||||
|
Umgesetzt ist damit: einen neuen Schlüssel als erste Zeile eintragen und den Server neu starten. Neue und geänderte Geheimnisse werden ab dann mit dem neuen Schlüssel versiegelt, bestehende bleiben mit dem alten lesbar. **Nicht umgesetzt** ist das Neuverschlüsseln aller bestehenden Werte; der alte Schlüssel darf deshalb nicht entfernt werden. Ein gestohlener alter Master-Key bleibt damit gefährlich, solange Werte unter ihm liegen. Ablauf und Grenzen: [OPERATIONS.md §8](OPERATIONS.md#8-schlüssel-und-zertifikate).
|
||||||
|
|
||||||
|
**Master-Key verloren = Geheimnisse verloren.** Ohne ihn lassen sich CA, Bundle-Schlüssel, TSIG-Schlüssel, HA-Passwörter, TOTP- und OIDC-Secret nicht mehr entschlüsseln; der Server startet mit falschem Schlüssel nicht. Er gehört in jedes Backup – getrennt von der Datenbanksicherung aufbewahrt.
|
||||||
|
|
||||||
|
### 4.2 Agent-CA und Bundle-Schlüssel
|
||||||
|
|
||||||
|
Beide werden beim ersten Start erzeugt und haben keine Rotationsfunktion. Ist einer von beiden kompromittiert (praktisch nur zusammen mit Datenbank **und** Master-Key, also mit dem Server-Host), bleibt nur der Neuaufbau: neue Server-Installation mit neuer Datenbank oder gezieltes Entfernen der Schlüssel in `pki_keys` (Server erzeugt neue beim Start), anschließend alle Agents neu registrieren. Die Datenebene läuft während dessen mit der letzten Konfiguration weiter.
|
||||||
|
|
||||||
|
### 4.3 TSIG und HA
|
||||||
|
|
||||||
|
- **TSIG-Schlüssel** (auch der Transferschlüssel eines Clusters) werden mit „Erneuern“ bzw. `POST /tsig-keys/{id}/rotate` neu erzeugt; wirksam mit der nächsten Revision. Primary und Secondaries aktivieren sie nicht exakt gleichzeitig, kurz kann ein Secondary `tsig indicates error` melden, NOTIFY holt den Transfer danach nach. Clients, die per `nsupdate` mit dem Schlüssel aktualisieren (z. B. DHCP-Server von Domain Controllern), müssen das neue Geheimnis erhalten.
|
||||||
|
- **HA-Zugangsdaten** werden beim Anlegen des DHCP-Clusters erzeugt; eine Erneuerung per Knopf gibt es nicht. Wer sie erneuern muss, legt den Cluster neu an (Mitglieder entfernen, Cluster löschen, neu anlegen, Netze zuordnen, ausrollen). Kea arbeitet in dieser Zeit als Einzelserver weiter.
|
||||||
|
|
||||||
|
## 5. Härtung
|
||||||
|
|
||||||
|
### Systemdienste (ADR 0024)
|
||||||
|
|
||||||
|
- **Eigene Benutzer:** Server als `ddi-suite`; DNS-Agent als BIND-Benutzer (`bind`/`named`), DHCP-Agent als Kea-Benutzer (`_kea`/`kea`). Ein kompromittierter Agent hat damit die Rechte des Dienstes, den er ohnehin konfiguriert – nicht mehr. Kein Dienst läuft als root.
|
||||||
|
- **systemd-Hardening** in allen Units: `NoNewPrivileges`, `ProtectSystem=strict` mit gezielten `ReadWritePaths`, `ProtectHome`, `PrivateTmp`, `PrivateDevices`, `ProtectKernel*`, `ProtectControlGroups`, `ProtectClock`, `ProtectHostname`, `RestrictAddressFamilies`, `RestrictNamespaces`, `RestrictSUIDSGID`, `LockPersonality`, `MemoryDenyWriteExecute`, `SystemCallFilter=@system-service`, leere `CapabilityBoundingSet`, `UMask=0027`. Prüfen mit `systemd-analyze security ddi-server`.
|
||||||
|
- **Dateirechte:** `/etc/ddi-suite/server.yaml` 0640 root:ddi-suite, `master.key` 0400 (Eigentümer `ddi-suite`), Agent-Identität 0700, geheime BIND/Kea-Dateien 0640, Kea-Socket-Verzeichnis 0750.
|
||||||
|
|
||||||
|
### Netzwerk
|
||||||
|
|
||||||
|
- Ports und Richtungen: [SYSTEM-REQUIREMENTS.md §5](SYSTEM-REQUIREMENTS.md#5-netzwerk). Auf Agent-Hosts muss für den Server **kein** Port offen sein.
|
||||||
|
- Port 8443 nur aus den Verwaltungsnetzen erreichbar machen, Port 8444 nur aus den Netzen der Agents. `/metrics` liegt am selben Listener wie die Oberfläche und ist ohne Anmeldung abrufbar: per Reverse-Proxy oder Firewall auf das Monitoring beschränken.
|
||||||
|
- Ein eigenes TLS-Zertifikat (`--tls-cert`/`--tls-key`) statt des selbstsignierten verwenden; TLS ≥ 1.2 ist fest eingestellt (Agent-Port TLS 1.3).
|
||||||
|
- HA-Verkehr zwischen den Kea-Partnern über ein eigenes, nicht von Clients erreichbares Netz (VLAN) oder einen Tunnel (WireGuard, IPsec) führen.
|
||||||
|
- BIND: Rekursion ist standardmäßig aus (rein autoritativ). Wer Rekursion einschaltet, begrenzt `allow-recursion` auf die eigenen Netze.
|
||||||
|
|
||||||
|
### PostgreSQL
|
||||||
|
|
||||||
|
- Der Installer richtet **Peer-Authentifizierung über den Unix-Socket** ein: kein Datenbankpasswort, kein offener TCP-Port. `listen_addresses` kann auf `localhost` bleiben.
|
||||||
|
- Wer eine entfernte Datenbank nutzt: TLS (`sslmode=verify-full`) und `database.url_file` mit Modus 0640, damit das Passwort nicht in der Hauptkonfiguration steht.
|
||||||
|
|
||||||
|
### Konten
|
||||||
|
|
||||||
|
- Das erste Admin-Passwort ist einmalig und muss geändert werden. Für Administratoren TOTP aktivieren oder OIDC mit MFA beim Identity-Provider verwenden.
|
||||||
|
- Rollen sparsam vergeben: Viewer für Leser, Operator für das Tagesgeschäft, Admin nur für Benutzer, Lizenz, OIDC, Cluster und Schlüssel.
|
||||||
|
|
||||||
|
### Lieferkette
|
||||||
|
|
||||||
|
- Go- und npm-Abhängigkeiten sind gepinnt, die CI prüft mit `govulncheck` und `npm audit`; externe Actions sind per Commit-SHA gepinnt.
|
||||||
|
- Reproduzierbarer Release-Build (`-trimpath`, feste Build-Zeit aus dem Commit), statische Binaries (`CGO_ENABLED=0`).
|
||||||
|
|
||||||
|
## 6. Was nicht geschützt ist
|
||||||
|
|
||||||
|
- **Kea-HA ohne TLS.** Die HA-Verbindung nutzt HTTP mit Basic-Auth. Wer den Verkehr zwischen den Partnern mitlesen kann, sieht die Zugangsdaten und kann danach HA-Befehle an beide senden (z. B. Leases ändern, Zustand umschalten). Abhilfe bis zur TLS-Unterstützung: getrenntes Netz oder Tunnel (Abschnitt 5).
|
||||||
|
- **Dynamische Updates per IP-Adresse.** `allow_update` mit Adressen vertraut der Absenderadresse eines UDP-Pakets; im selben Netz lässt sie sich fälschen. Wo möglich TSIG verwenden, IP-Freigaben auf einzelne Adressen (/32) der Domain Controller beschränken.
|
||||||
|
- **GSS-TSIG** (Kerberos-gesicherte Updates von Active Directory) wird nicht unterstützt ([ACTIVE-DIRECTORY.md](ACTIVE-DIRECTORY.md)).
|
||||||
|
- **DHCP selbst ist nicht authentifiziert.** Gefälschte DHCP-Server, Adress-Erschöpfung durch viele MAC-Adressen und MAC-Spoofing gegen Reservierungen lassen sich nur im Netz verhindern (DHCP-Snooping, Port-Security, 802.1X).
|
||||||
|
- **Keine DNSSEC-Signierung** der Zonen (für M7 vorgesehen); Antworten von BIND sind nicht signiert.
|
||||||
|
- **Geheimnisse liegen auf den Agent-Hosts im Klartext** (TSIG-Schlüssel in `ddi-suite-keys.conf`, HA-Zugangsdaten), weil BIND und Kea sie so brauchen. Geschützt nur durch Dateirechte.
|
||||||
|
- **Keine Rotation** von Agent-CA und Bundle-Schlüssel, kein Neuverschlüsseln mit neuem Master-Key (Abschnitt 4).
|
||||||
|
- **Login-Ratenbegrenzung im Speicher** des Servers: Ein Neustart setzt sie zurück. Sie ersetzt keine starken Passwörter oder MFA.
|
||||||
|
- **Server-Host = Vertrauensanker.** Wer ihn kontrolliert, kontrolliert alle verwalteten DNS- und DHCP-Server (Abschnitt 3).
|
||||||
|
- **Audit-Log ist nicht manipulationssicher** gegen Datenbank-Administratoren; wer revisionssichere Protokolle braucht, exportiert es regelmäßig (`GET /audit/export`) in ein getrenntes System.
|
||||||
|
|
||||||
|
## 7. Release-Signatur
|
||||||
|
|
||||||
|
Jedes Release enthält `SHA256SUMS` über alle Tarballs und Pakete (`.deb`, `.rpm`); ist im Release-Workflow das Secret `RELEASE_SIGNING_KEY` gesetzt, zusätzlich `SHA256SUMS.sig`, eine binäre Ed25519-Signatur (64 Byte) über `SHA256SUMS`. Weil `SHA256SUMS` alle Artefakte abdeckt, sichert diese eine Signatur auch die Pakete. Der private Schlüssel gehört offline aufbewahrt; wer ihn hat, kann Releases signieren, die jeder Installer annimmt. Prüfen von Hand: `scripts/sign-release.sh verify SHA256SUMS SHA256SUMS.sig release-signing.pub.pem`, danach `sha256sum -c SHA256SUMS`. Der Installer enthält den zugehörigen öffentlichen Schlüssel im Variablenblock: Ist er gesetzt, muss die Signatur gültig sein, sonst bricht er ab; ist er leer, prüft er nur die Prüfsummen und weist darauf hin. Manuelle Prüfung und Schlüsselverwaltung: [RELEASE.md](RELEASE.md).
|
||||||
|
|
||||||
|
Den Installer selbst vor dem Ausführen herunterladen und lesen, **nicht** per `curl | sudo bash` starten ([INSTALL.md](INSTALL.md)).
|
||||||
|
|
||||||
|
## 8. Lizenzprüfung ist ein Soft-Control
|
||||||
|
|
||||||
|
Der Management-Server prüft seine Lizenz gegen Keygen, verifiziert jede Antwort mit dem beim Build eingebetteten öffentlichen Schlüssel und lässt sich nicht per Konfiguration auf einen anderen Lizenzserver umlenken ([LICENSING.md](LICENSING.md)). Das verhindert das **bequeme** Umgehen über Konfiguration, gefälschte Antworten oder einen Proxy.
|
||||||
|
|
||||||
|
Es ist aber **keine technische Garantie**: Wer die Software auf eigener Hardware betreibt, kann das Binary verändern, die Prüfung entfernen oder die Uhr verstellen. Eine Lizenzprüfung in selbst gehosteter Software ist eine vertragliche und organisatorische Maßnahme mit technischer Unterstützung, kein Kopierschutz. Unabhängig davon gilt: Die Lizenz beeinträchtigt **nie** die Datenebene – Agents prüfen keine Lizenz, DNS und DHCP laufen bei abgelaufener Lizenz unverändert weiter.
|
||||||
|
|
||||||
|
## 9. Schwachstellen melden
|
||||||
|
|
||||||
|
Sicherheitsprobleme bitte nicht als öffentliches Issue, sondern direkt an den Betreiber des Repositorys melden (Kontakt im Gitea-Profil von `beug.k`).
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
# Systemvoraussetzungen
|
||||||
|
|
||||||
|
Dieses Dokument nennt Betriebssysteme, Software-Versionen, Browser, Größen je Rolle, Netzwerkports und Plattenbedarf der DDI-Suite. Die Richtwerte stützen sich auf **Messungen** (Abschnitt 4); was geschätzt ist, steht ausdrücklich dabei. Der Installer prüft die Mindestwerte aus Abschnitt 3 vor der Installation. Installation: [INSTALL.md](INSTALL.md), Betrieb: [OPERATIONS.md](OPERATIONS.md), Sicherheit: [SECURITY.md](SECURITY.md).
|
||||||
|
|
||||||
|
## 1. Betriebssysteme und Architekturen
|
||||||
|
|
||||||
|
| System | Versionen | Architekturen |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Debian | 12 (bookworm), 13 (trixie) | `amd64`, `arm64` |
|
||||||
|
| Ubuntu LTS | 22.04, 24.04 | `amd64`, `arm64` |
|
||||||
|
| RHEL-Familie (Rocky Linux, AlmaLinux, RHEL) | 9 | `x86_64`, `aarch64` |
|
||||||
|
|
||||||
|
Erkennung über `/etc/os-release` und `uname -m`. Andere Systeme lehnt der Installer ab. Die Binaries sind statisch gebaut (`CGO_ENABLED=0`) und laufen auch auf anderen Linux-Systemen, dort aber ohne Installer und ohne Unterstützung. Erforderlich ist systemd (die Units nutzen Härtungsoptionen ab systemd 249).
|
||||||
|
|
||||||
|
Alle drei Rollen (`server`, `agent-dns`, `agent-dhcp`) dürfen auf einem Host liegen; die Mindestwerte addieren sich dann (Abschnitt 3).
|
||||||
|
|
||||||
|
## 2. Software
|
||||||
|
|
||||||
|
| Komponente | Unterstützt | In der CI getestet | Quelle bei der Installation |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| PostgreSQL (nur Server) | ≥ 13 | 17.11 | Paket der Distribution (Debian 12: 15, Debian 13: 17, Ubuntu 22.04: 14, Ubuntu 24.04: 16, EL9: Modul-Stream ≥ 15) |
|
||||||
|
| BIND 9 (DNS-Agent) | ≥ 9.18 | 9.18, 9.20 | Paket der Distribution (`bind9`; EL9: `bind9.18`) |
|
||||||
|
| Kea DHCPv4 mit HA (DHCP-Agent) | 3.x | 3.2.1 | ISC-Repository `isc/kea-3-2` (Standard, `--kea-source isc`) |
|
||||||
|
| Kea DHCPv4 ohne HA | 2.6 | 2.6.5 | Paket der Distribution mit `--kea-source distro` |
|
||||||
|
| systemd | ≥ 249 | – | Distribution |
|
||||||
|
|
||||||
|
- **Kea-HA braucht Kea ≥ 3.0**: Der HA-Partner wird über einen authentifizierten HTTP-Control-Socket angesprochen, Zugangsdaten nur aus Dateien (ADR 0023). Die Distributionen liefern Kea 2.0–2.6; deshalb installiert der Installer standardmäßig aus dem ISC-Repository. Kea-Versionen vor 2.6 sind nicht getestet.
|
||||||
|
- Genutzt werden nur frei verfügbare Kea-Hooks: `libdhcp_lease_cmds.so` und `libdhcp_ha.so`.
|
||||||
|
- Agents brauchen keine Datenbank; ihr Zustand liegt in Dateien.
|
||||||
|
|
||||||
|
### Browser
|
||||||
|
|
||||||
|
Die Weboberfläche nutzt aktuelles JavaScript (ES2023). Unterstützt sind die jeweils aktuellen Versionen (letzte zwei Hauptversionen) von **Firefox**, **Chrome**, **Edge** und **Safari**, auf Desktop und Tablet. Ältere Browser und Internet Explorer werden nicht unterstützt. Cookies müssen erlaubt sein (Sitzungscookie); JavaScript ist Pflicht.
|
||||||
|
|
||||||
|
## 3. Richtwerte je Rolle
|
||||||
|
|
||||||
|
Größenklassen wie im Auftrag: **klein** bis ca. 5.000 Adressen und 10 Agents, **mittel** bis ca. 50.000 Adressen und 50 Agents. „Gemessen“ bedeutet: aus den Messungen in Abschnitt 4 abgeleitet, mit Reserve für Betriebssystem, Spitzen und Wachstum. Die Reserve ist bewusst groß, weil die Messung nur Datenmengen, keine parallelen Benutzer und keine 50 verbundenen Agents abbildet.
|
||||||
|
|
||||||
|
| Rolle | Klein | Mittel | Grundlage |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Management-Server inkl. PostgreSQL | 2 vCPU, **2 GB** RAM (4 GB empfohlen), 20 GB SSD | 4 vCPU, **4 GB** RAM (8 GB empfohlen), 50 GB SSD | gemessen: Server 30–195 MiB RSS, Spitze 235 MiB (Anmeldungen mit Argon2id: 64 MiB je gleichzeitiger Anmeldung); PostgreSQL 65–130 MiB; Datenbank 15 bzw. 72 MiB. Platte: Revisionen und Audit-Log wachsen (Abschnitt 7). CPU: Listenabfragen über 50.000 Einträge brauchen 40–240 ms je Anfrage (eine Abfrage = ein Kern), mehrere Benutzer gleichzeitig profitieren von 4 Kernen. |
|
||||||
|
| DNS-Agent + BIND | 1 vCPU, **512 MB** RAM (1 GB empfohlen), 5 GB | 2 vCPU, **1 GB** RAM (2 GB empfohlen), 10 GB | gemessen: `named` 22–27 MiB (9.000 Records) bzw. 57–61 MiB (90.000 Records, 657 Zonen); 50.000–70.000 Abfragen/s mit 1,0–1,4 Kernen. Agent geschätzt 20–40 MiB. |
|
||||||
|
| DHCP-Agent + Kea | 1 vCPU, **512 MB** RAM (1 GB empfohlen), 5 GB | 2 vCPU, **1 GB** RAM (2 GB empfohlen), 10 GB | gemessen: `kea-dhcp4` 20–35 MiB (1.000 Reservierungen) bzw. 42–58 MiB (10.000 Reservierungen, bis 50.000 Leases); 750–1.000 DORA/s mit rund einem Kern. Agent geschätzt 20–40 MiB. |
|
||||||
|
|
||||||
|
Gegenüber den Ausgangswerten des Auftrags (Server 4 GB / 8–16 GB, DNS 1 GB / 2–4 GB, DHCP 1 GB / 2 GB) zeigen die Messungen deutlich geringeren Speicherbedarf; die Mindestwerte sind entsprechend gesenkt, die Empfehlungen bleiben nahe am Auftrag, um Reserve für Wachstum, Logs, Paketupdates und Lastspitzen zu lassen. **SSD** ist für den Server empfohlen (PostgreSQL), für Agents auf einem Raspberry Pi Pflicht (Abschnitt 6).
|
||||||
|
|
||||||
|
### Vorabprüfung des Installers
|
||||||
|
|
||||||
|
Der Installer (`scripts/install.sh`, ADR 0024) prüft vor der Installation diese Werte. **Warnung**: Hinweis, Installation läuft weiter (mit `--non-interactive` ohne Rückfrage). **Abbruch**: Installation stoppt; mit `--force` wird daraus eine Warnung (außer bei Betriebssystem und Architektur).
|
||||||
|
|
||||||
|
| Prüfung | Rolle | Warnung, wenn | Abbruch, wenn |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Betriebssystem | alle | – | nicht in Abschnitt 1 (auch mit `--force`) |
|
||||||
|
| Architektur (`uname -m`) | alle | – | nicht `x86_64`/`amd64` oder `aarch64`/`arm64` (auch mit `--force`) |
|
||||||
|
| CPU-Kerne (`nproc`) | `server` | < 2 | – |
|
||||||
|
| | `agent-dns`, `agent-dhcp` | – | – |
|
||||||
|
| Arbeitsspeicher (`MemTotal`) | `server` | < 3,5 GiB | < 1,8 GiB |
|
||||||
|
| | `agent-dns` | < 900 MiB | < 450 MiB |
|
||||||
|
| | `agent-dhcp` | < 900 MiB | < 450 MiB |
|
||||||
|
| Freier Platz im Dateisystem von `/var/lib` | `server` | < 20 GiB | < 4 GiB |
|
||||||
|
| | `agent-dns` | < 5 GiB | < 1 GiB |
|
||||||
|
| | `agent-dhcp` | < 5 GiB | < 1 GiB |
|
||||||
|
| Freier Platz im Dateisystem von `/usr/local/bin` bzw. `/usr/bin` | alle | – | < 200 MiB |
|
||||||
|
| Zeitsynchronisation (`timedatectl show -p NTPSynchronized`, aktiver `chronyd`/`systemd-timesyncd`/`ntpd`) | alle | nicht synchronisiert oder kein Zeitdienst aktiv | – |
|
||||||
|
| Port 8443/tcp, 8444/tcp frei (`ss -ltn`) | `server` | – | von einem anderen Prozess belegt (bei `--upgrade` vom eigenen Dienst erlaubt) |
|
||||||
|
| Port 53/udp+tcp frei | `agent-dns` | nur `systemd-resolved` auf 127.0.0.53 | von einem anderen Prozess als `named` belegt |
|
||||||
|
| Port 67/udp frei | `agent-dhcp` | – | von einem anderen Prozess als `kea-dhcp4` belegt (z. B. `dnsmasq`, `isc-dhcp-server`) |
|
||||||
|
| Port 8001/tcp frei (Kea-HA, Standard `ha_port`) | `agent-dhcp` | belegt | – |
|
||||||
|
| PostgreSQL-Version des Pakets | `server` | – | < 13 |
|
||||||
|
| BIND-Version des Pakets | `agent-dns` | < 9.18 | – |
|
||||||
|
| Kea-Version | `agent-dhcp` | < 3.0 (kein HA möglich) | < 2.6 |
|
||||||
|
| ISC-Repository erreichbar (443/tcp, nur `--kea-source isc`) | `agent-dhcp` | – | nicht erreichbar (Hinweis auf `--kea-source distro`) |
|
||||||
|
| Lizenzserver `https://license.beugsiud.de` erreichbar | `server` | nicht erreichbar | – |
|
||||||
|
| Agent-Port des Servers erreichbar (`--server`) | `agent-dns`, `agent-dhcp` | nicht erreichbar | – |
|
||||||
|
|
||||||
|
Mehrere Rollen auf einem Host: Speicher- und Plattengrenzen werden **addiert** (z. B. `server` + `agent-dns` + `agent-dhcp`: Warnung unter 5,3 GiB RAM bzw. 30 GiB Platte, Abbruch unter 2,7 GiB bzw. 6 GiB), für CPU gilt der höchste Wert. Die Grenzen liegen etwas unter den Nennwerten (4 GB, 2 GB, 1 GB, 512 MB), weil der Kernel einen Teil des Speichers für sich behält und `MemTotal` deshalb kleiner ist.
|
||||||
|
|
||||||
|
## 4. Messungen
|
||||||
|
|
||||||
|
**Gemessen** mit dem Benchmark in [`test/bench/`](../test/bench/) (`make bench`, Workflow `bench` in [`.gitea/workflows/bench.yml`](../.gitea/workflows/bench.yml)) auf dem CI-Runner. Maßgeblich ist Lauf 93 vom 15.10.2026 (Commit `f5f6ceb`); wo ein früherer Lauf (82 vom 14.10.2026, Commit `9c61d31`, gleiche Hardware) deutlich abwich, ist die Spanne beider Läufe angegeben. Der CSV-Import stammt aus Lauf 95 vom 15.10.2026 (Commit `7ea66d9`, nach der Beschleunigung des Imports). Alle Dienste liefen gleichzeitig als Container auf einem Docker-Host:
|
||||||
|
|
||||||
|
| Hardware des Runners | |
|
||||||
|
| --- | --- |
|
||||||
|
| CPU | Intel Xeon (Skylake, IBRS), virtualisiert |
|
||||||
|
| Kerne (`nproc`) | 4 |
|
||||||
|
| RAM | 7,7 GiB |
|
||||||
|
| Kernel / Docker | 5.15.0-130-generic / 29.1.4 |
|
||||||
|
|
||||||
|
Der Docker-Daemon kann mit anderen CI-Jobs geteilt sein, und Lastgenerator und Dienst teilen sich dieselben 4 Kerne; zwischen den beiden Läufen schwankten die Durchsätze von BIND und Kea deshalb um bis zu 30 %. Die Werte sind daher eher **untere Grenzen** dessen, was auf dedizierter Hardware möglich ist.
|
||||||
|
|
||||||
|
### Methode
|
||||||
|
|
||||||
|
- **Daten** (`test/bench/datagen.sh`): je 1.000 Einträge in /21-Netzen `10.x.y.0/21` (70 % `static`, 20 % `manual_dhcp` mit MAC, 10 % `reserved`; DHCP-Pool in der oberen Hälfte jedes Netzes), alle Namen in der Zone `bench.test`. Datensatz *klein*: 5 Netze, 5.000 Einträge; *mittel*: 50 Netze, 50.000 Einträge. Zusätzlich ein DHCP-Netz `10.200.0.0/16` mit einem Pool über fast das ganze /16 für `perfdhcp`.
|
||||||
|
- **Server** (Build wie im Release, PostgreSQL 17.11 mit den Standardwerten des offiziellen Images): Import über `POST /api/v1/addresses/import` in Dateien zu 5.000 Zeilen, danach Messung von Speicher (`VmRSS`/`VmHWM` des Prozesses, `docker stats` für PostgreSQL), Datenbank- und Tabellengrößen, `POST /revisions` (Dauer, Tabellenwachstum und gespeicherte, komprimierte Größe), `GET /config/preview`, `GET /config/pending`, 20 Wiederholungen je Filter von `GET /addresses?limit=100` (Median und 95. Perzentil), 50 Umbenennungen per `PUT /addresses/{id}` mit Wachstum des Audit-Logs, danach eine weitere Revision.
|
||||||
|
- **BIND 9.20**: Die Dateien aus `GET /config/preview` (unverändert) in einem BIND-Container, `named` neu gestartet; Ladezeit aus dem BIND-Log („starting BIND“ bis „all zones loaded“). `dnsperf` (Debian-Paket) in einem eigenen Container: 15 s mit 16 Clients und bis zu 500 offenen Abfragen (A und PTR existierender Namen, 10 % NXDOMAIN), dann 15 s mit festen 5.000 Abfragen/s.
|
||||||
|
- **Kea 3.2.1**: `kea-dhcp4.conf` aus `GET /config/preview`; einzige Änderung: Das /16-Testnetz erhält die Adresse des `perfdhcp`-Containers als Relay (`relay.ip-addresses`), weil Relay-Adressen noch nicht im IPAM-Modell stehen. `perfdhcp` (ISC-Paket) sendet als Relay per Unicast, je 10 s mit 50.000 simulierten Clients bei steigender Rate; spätere Läufe verlängern teils bestehende Leases. CPU aus `/proc/<pid>/stat` (100 % = ein Kern).
|
||||||
|
|
||||||
|
### Ergebnisse: Management-Server
|
||||||
|
|
||||||
|
| Messgröße | 5.000 Einträge | 50.000 Einträge |
|
||||||
|
| --- | ---: | ---: |
|
||||||
|
| Netze / Adresseinträge | 6 / 5.000 | 51 / 50.000 |
|
||||||
|
| CSV-Import über die API | 4,4 s (1.130 Einträge/s) | 41 s für 45.000 neue (1.090 Einträge/s) |
|
||||||
|
| Server-RSS nach dem Import / Höchstwert | 29 / 235 MiB | 33 / 235 MiB |
|
||||||
|
| Server-RSS am Ende (nach Vorschau, Revisionen) | 37–53 MiB | 137–194 MiB |
|
||||||
|
| PostgreSQL-Container (Speicher) | 67 MiB | 128 MiB |
|
||||||
|
| Datenbankgröße nach dem Import | 15 MiB | 72 MiB |
|
||||||
|
| davon Tabelle `addresses` inkl. Indizes | 2,1 MiB | 20 MiB |
|
||||||
|
| davon Audit-Log (ein Eintrag je importierter Adresse) | 4,3 MiB (5.010 Einträge) | 42 MiB (50.107 Einträge) |
|
||||||
|
| `POST /revisions` | 0,29–0,34 s | 2,8–2,9 s |
|
||||||
|
| Speicher je Revision: Tabellenwachstum / gespeicherte Daten | 0,7 / 0,5 MiB | 4,6 / 4,2 MiB |
|
||||||
|
| Erzeugte Dateien: DNS-Dateien / Gesamtgröße | 300 / 0,8 MiB | 660 / 7,0 MiB |
|
||||||
|
| `GET /config/preview` | 0,09 s | 0,62 s |
|
||||||
|
| `GET /config/pending` | 0,08 s | 0,71–0,89 s |
|
||||||
|
| `GET /addresses?limit=100` ohne Filter (Median / p95) | 13 / 14 ms | 110 / 120 ms |
|
||||||
|
| … mit `network_id` (ein Netz) | 5 / 7 ms | 5 / 7 ms |
|
||||||
|
| … mit `type=manual_dhcp` | 7 / 8 ms | 40 / 50 ms |
|
||||||
|
| … Suche nach Hostname-Präfix (`q=h3-12`) | 14 / 17 ms | 115 / 135 ms |
|
||||||
|
| … Suche nach MAC-Präfix | 16 / 23 ms | 131 / 145 ms |
|
||||||
|
| … sortiert nach Hostname, letzte Seite | 20 / 33 ms | 204 / 236 ms |
|
||||||
|
| `PUT /addresses/{id}` (Mittel aus 50) | 5,0 ms | 5,8 ms |
|
||||||
|
| Audit-Wachstum je Änderung | 1,5 KiB | 1,6 KiB |
|
||||||
|
|
||||||
|
Der Höchstwert des Server-Speichers (235 MiB) stammt von den Anmeldungen (Argon2id mit 64 MiB je Hashberechnung), nicht von der Datenmenge. Jede Revision speichert alle erzeugten Dateien vollständig (komprimiert): Eine Revision nach 50 Änderungen ist so groß wie die erste.
|
||||||
|
|
||||||
|
### Ergebnisse: BIND 9.20
|
||||||
|
|
||||||
|
| Messgröße | 5.000 Einträge | 50.000 Einträge |
|
||||||
|
| --- | ---: | ---: |
|
||||||
|
| Zonen / A- und PTR-Records | 297 / 9.001 | 657 / 90.001 |
|
||||||
|
| Zonendateien | 0,6 MiB | 5,4 MiB |
|
||||||
|
| Start bis alle Zonen geladen | 0,07–0,08 s | 0,35–0,43 s |
|
||||||
|
| `named`-RSS nach dem Laden / nach den Läufen | 22 / 27 MiB | 57 / 61 MiB |
|
||||||
|
| `dnsperf` maximal: Abfragen/s (Lauf 93 / Lauf 82) | 68.200 / 69.400 | 51.600 / 72.000 |
|
||||||
|
| … mittlere Latenz / verloren | 2,2 ms / 0,08 % | 2,2–3,2 ms / 0,1 % |
|
||||||
|
| … CPU von `named` | 126–141 % | 104–141 % |
|
||||||
|
| `dnsperf` bei 5.000 Abfragen/s: mittlere Latenz | 0,2 ms | 0,2–0,7 ms |
|
||||||
|
|
||||||
|
Die Zonenzahl enthält 256 leere Reverse-Zonen des /16-Testnetzes. Der Durchsatz hängt kaum von der Zonengröße ab; die Grenze setzen die geteilten 4 Kerne, die Schwankung zwischen den Läufen kommt vom geteilten Runner.
|
||||||
|
|
||||||
|
### Ergebnisse: Kea 3.2.1
|
||||||
|
|
||||||
|
| Messgröße | 5.000 Einträge | 50.000 Einträge |
|
||||||
|
| --- | ---: | ---: |
|
||||||
|
| Subnetze / Reservierungen | 6 / 1.000 | 51 / 10.000 |
|
||||||
|
| `kea-dhcp4 -t` (Prüfung beim Ausrollen) | 0,08–0,13 s | 0,36–0,39 s |
|
||||||
|
| Start bis `DHCP4_STARTED` | 0,06–0,07 s | 0,48–0,58 s |
|
||||||
|
| `kea-dhcp4`-RSS nach dem Start | 20 MiB | 42 MiB |
|
||||||
|
|
||||||
|
Lauf 93, Werte je Zelle „klein / mittel“:
|
||||||
|
|
||||||
|
| `perfdhcp`-Rate (Ziel) | DORA/s erreicht | Verluste Discover-Offer | mittlere Verzögerung Request-Ack | CPU Kea | RSS Kea | Lease-Datei kumuliert |
|
||||||
|
| ---: | ---: | ---: | ---: | ---: | ---: | ---: |
|
||||||
|
| 250/s | 250 / 250 | 0 % / 0 % | 0,8 / 1,8 ms | 29 / 31 % | 22 / 44 MiB | 0,2 MiB |
|
||||||
|
| 500/s | 500 / 500 | 0 % / 0 % | 0,8 / 1,5 ms | 56 / 61 % | 24 / 46 MiB | 0,4 MiB |
|
||||||
|
| 750/s | 750 / 717 | 0 % / 2,6 % | 1,7 / 6,9 ms | 83 / 89 % | 26 / 47 MiB | 0,6 MiB |
|
||||||
|
| 1.000/s | 1.000 / 795 | 0 % / 12,7 % | 2,2 / 20 ms | 117 / 112 % | 28 / 48 MiB | 0,8 MiB |
|
||||||
|
| 1.500/s | 1.050 / 781 | 17 % / 29 % | 24 / 26 ms | 153 / 137 % | 31 / 49 MiB | 1,0 MiB |
|
||||||
|
| 2.000/s | 917 / 690 | 33 % / 42 % | 21 / 22 ms | 171 / 141 % | 33 / 51 MiB | 1,3 MiB |
|
||||||
|
| 4.000/s | 503 / 284 | 65 % / 74 % | 15 / 20 ms | 165 / 116 % | 36 / 50 MiB | 1,5 MiB |
|
||||||
|
|
||||||
|
In Lauf 82 erreichte Kea bei 1.000/s mit beiden Datensätzen 987 DORA/s (Verluste unter 1 %), bei 2.000/s rund 880 DORA/s.
|
||||||
|
|
||||||
|
**Ergebnis:** Auf 4 geteilten Kernen bedient Kea mit der erzeugten Konfiguration **750–1.000 vollständige Vergaben pro Sekunde** ohne nennenswerte Verluste; mit 10.000 Reservierungen eher am unteren Ende. Darüber bricht der Durchsatz ein (Kea verwirft unter Überlast Pakete; Lastgenerator und Kea konkurrieren um dieselben Kerne). Zum Vergleich: 10.000 Clients mit einer Lease-Zeit von einer Stunde erneuern im Mittel rund 6 Leases pro Sekunde, ein gleichzeitiger Neustart aller 10.000 Clients dauert bei 750/s etwa 15 s. Die Lease-Datei wächst um rund 85 Byte je Vergabe oder Verlängerung und wird von Kea stündlich verdichtet (`lfc-interval` 3600 s).
|
||||||
|
|
||||||
|
### Was nicht gemessen wurde (geschätzt)
|
||||||
|
|
||||||
|
- Speicher der **Agents** selbst (Go-Prozess, geschätzt 20–40 MiB je Agent) und des Servers mit **50 verbundenen Agents** (je Agent ein gRPC-Stream; geschätzt wenige MiB zusätzlich).
|
||||||
|
- **Parallele Benutzer** der Oberfläche; die Latenzen oben gelten für eine Anfrage zur Zeit.
|
||||||
|
- **Kea-HA** (zwei Partner): Jede Vergabe wird zusätzlich an den Partner gemeldet; die Rate sinkt nach Kea-Handbuch spürbar. Mit HA ist von deutlich weniger als den gemessenen 750–1.000 DORA/s auszugehen.
|
||||||
|
- Speichermedium: Die Messung lief auf dem Speicher des Runners (vermutlich SSD). Auf SD-Karten sind PostgreSQL und die Kea-Lease-Datei deutlich langsamer.
|
||||||
|
|
||||||
|
## 5. Netzwerk
|
||||||
|
|
||||||
|
| Verbindung | Richtung | Port | Pflicht |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Weboberfläche und REST-API | Browser → Server | 8443/tcp (HTTPS) | ja |
|
||||||
|
| Agent-Protokoll (gRPC, mTLS) | **Agent → Server** (ausgehend vom Agent) | 8444/tcp | ja; auf dem Agent-Host muss kein Port für den Server offen sein |
|
||||||
|
| DNS-Abfragen | Clients → BIND | 53/udp und 53/tcp | DNS-Agent |
|
||||||
|
| NOTIFY | Primary → Secondaries | 53/udp (und tcp) | DNS-Cluster |
|
||||||
|
| Zonentransfer (AXFR/IXFR, TSIG) | Secondary → Primary | 53/tcp | DNS-Cluster |
|
||||||
|
| Dynamische Updates (RFC 2136) | Domain Controller/Clients → Primary | 53/udp und 53/tcp | dynamische Zonen |
|
||||||
|
| DHCP | Clients → Kea (Broadcast) bzw. Relay → Kea (Unicast) | 67/udp | DHCP-Agent |
|
||||||
|
| DHCP-Antworten | Kea → Clients bzw. Kea → Relay | 68/udp (Clients), 67/udp (Relay) | DHCP-Agent |
|
||||||
|
| DHCP-Relay | Router/Switch (`ip helper-address`) → Kea | 67/udp | Netze ohne eigenen Kea im Segment |
|
||||||
|
| Kea-HA | Kea ↔ Kea, beide Richtungen | 8001/tcp (`ha_port` je Cluster) | DHCP-Cluster mit zwei Servern |
|
||||||
|
| Lizenzprüfung | Server → `license.beugsiud.de` | 443/tcp | ja (bei Ausfall 14 Tage Karenzzeit) |
|
||||||
|
| Installation von Kea | Agent-Host → `dl.cloudsmith.io` (ISC-Repository) | 443/tcp | nur bei Installation/Upgrade mit `--kea-source isc` |
|
||||||
|
| Release-Download | Hosts → `git.beugsiud.de` | 443/tcp | nur bei Installation/Upgrade (alternativ `--from-dir`) |
|
||||||
|
| Paketquellen der Distribution | alle Hosts → Spiegel | 80/443/tcp | bei Installation/Upgrade |
|
||||||
|
| Zeitsynchronisation | alle Hosts → NTP-Server | 123/udp | **ja** |
|
||||||
|
| PostgreSQL | Server → lokale Datenbank | Unix-Socket | ja (kein Netzport nötig) |
|
||||||
|
| `rndc`, Kea-Control-Socket | Agent → Dienst, lokal | 127.0.0.1:953/tcp bzw. Unix-Socket | ja (nur lokal) |
|
||||||
|
| Monitoring | Prometheus → Server `/metrics`, `/readyz` | 8443/tcp | optional, Zugriff begrenzen |
|
||||||
|
|
||||||
|
Ports 8443 und 8444 sind in `server.yaml` (`http.listen`, `agent_api.listen`) bzw. in der Oberfläche (`ha_port` je DHCP-Cluster) änderbar. Wer Agents über NAT oder einen Proxy anbindet: Der Agent-Port braucht durchgehendes TLS (kein TLS-aufbrechender Proxy), die Adresse im Enrollment-Befehl kommt aus `agent_api.public_address`.
|
||||||
|
|
||||||
|
### Zeitsynchronisation ist Pflicht
|
||||||
|
|
||||||
|
Zertifikate (14 Tage Laufzeit), TSIG (±5 Minuten), Lizenzprüfung (signierte Antworten höchstens 5 Minuten alt), TOTP (±30 s) und Kea-HA hängen an korrekten Uhren. Auf allen Hosts muss ein Zeitdienst laufen (`systemd-timesyncd`, `chronyd` oder `ntpd`). Der Installer warnt, wenn die Uhr nicht synchronisiert ist.
|
||||||
|
|
||||||
|
## 6. Raspberry Pi und andere ARM-Systeme
|
||||||
|
|
||||||
|
- Unterstützt ist **64-Bit-ARM** (`arm64`/`aarch64`) mit einem 64-Bit-Betriebssystem (z. B. Raspberry Pi OS 64 Bit auf Debian-12-Basis, Ubuntu 24.04 für Raspberry Pi). 32-Bit-Systeme (`armhf`) nicht.
|
||||||
|
- Ein Raspberry Pi 4 oder 5 mit 2 GB (Agents) bzw. 4 GB (Server, klein) genügt nach den Messungen; für den Server mit 50.000 Adressen einen Pi 5 mit 8 GB oder eine VM wählen.
|
||||||
|
- **SSD statt SD-Karte:** PostgreSQL (Server), die Lease-Datei von Kea (jede Vergabe wird geschrieben), BIND-Journale dynamischer Zonen und die Journale von systemd schreiben laufend. SD-Karten verschleißen dadurch schnell und sind langsam. Für den Server ist eine SSD über USB 3 oder NVMe **Pflicht**, für Agents dringend empfohlen. Wo nur eine SD-Karte möglich ist: hochwertige Karte („High Endurance“), `Storage=volatile` oder eine Größenbegrenzung für journald, keine Swap-Datei auf der Karte.
|
||||||
|
- Ohne batteriegepufferte Uhr startet ein Pi mit falscher Zeit: Zeitsynchronisation vor dem Start der Dienste abwarten (`systemd-time-wait-sync.service` aktivieren), sonst schlagen TLS und TSIG bis zur Synchronisation fehl.
|
||||||
|
|
||||||
|
## 7. Plattenplatz-Planung
|
||||||
|
|
||||||
|
Was wächst, mit gemessenen Werten aus Abschnitt 4:
|
||||||
|
|
||||||
|
| Was | Wachstum (gemessen) | Beispiel |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| **Revisionen** (Server) | 0,7 MiB je Revision bei 5.000, **4,6 MiB** bei 50.000 Adressen (alle Dateien jeder Revision, komprimiert gespeichert; davon 4,2 MiB Daten, der Rest Tabellen- und Indexaufwand) | 50.000 Adressen, 10 Revisionen pro Arbeitstag: ≈ 46 MiB/Tag, ≈ 10 GiB/Jahr |
|
||||||
|
| **Audit-Log** (Server) | ≈ 1,5–1,6 KiB je Änderung (vorher/nachher als JSON); ein Import erzeugt einen Eintrag je Zeile | 1.000 Änderungen pro Tag: ≈ 0,5 GiB/Jahr |
|
||||||
|
| Adressen | ≈ 0,4 KiB je Eintrag inkl. Indizes | 50.000 Einträge: 20 MiB |
|
||||||
|
| Lease-Erfassung | erzeugt keine Audit-Einträge; Leases und `dynamic`-Einträge nur einmal je Adresse | vernachlässigbar |
|
||||||
|
| PostgreSQL-WAL, Sicherungen | WAL bis `max_wal_size` (Standard 1 GiB); Dumps etwa in Größe der Datenbank, komprimiert deutlich kleiner | Platz für mehrere Dumps einplanen |
|
||||||
|
| Agent: lokale Revisionen | die letzten 10 Revisionen der eigenen Rolle | 50.000 Adressen: DNS ≈ 55 MiB, DHCP ≈ 15 MiB |
|
||||||
|
| BIND: Journale dynamischer Zonen | je nach Update-Rate, BIND verdichtet sie selbst | meist < 100 MiB |
|
||||||
|
| Kea: Lease-Datei | ≈ 85 Byte je Vergabe/Verlängerung, stündlich verdichtet | 10.000 Clients: wenige MiB |
|
||||||
|
| Logs (journald) | nach Konfiguration von journald | Standard: max. 10 % des Dateisystems |
|
||||||
|
|
||||||
|
**Aufbewahrung:** Ohne Einstellung bleiben alle Revisionen und Audit-Einträge erhalten. Bei großen Datenbeständen und häufigem Ausrollen `retention.revisions_keep` (z. B. 200–500) und bei Bedarf `retention.audit_days` setzen ([OPERATIONS.md §7](OPERATIONS.md#7-aufbewahrung-retention)); die neueste, die von Agents angewendeten und die offen ausgerollten Revisionen werden nie gelöscht. Mit `revisions_keep: 500` bleiben bei 50.000 Adressen höchstens ≈ 2,3 GiB Revisionen.
|
||||||
|
|
||||||
|
Die Plattenempfehlungen in Abschnitt 3 (20 GB bzw. 50 GB für den Server) reichen damit für mehrere Jahre bei moderater Änderungsrate; bei täglich vielen Revisionen ohne Aufbewahrungsregel ist mit ≈ 10 GiB pro Jahr und 50.000 Adressen zu rechnen.
|
||||||
|
|
||||||
|
## 8. Sicherung, Wiederherstellung, Upgrade (Kurzfassung)
|
||||||
|
|
||||||
|
Einzelheiten in [OPERATIONS.md](OPERATIONS.md).
|
||||||
|
|
||||||
|
- **Sichern:** PostgreSQL-Datenbank (`pg_dump`), den **Master-Key** `/etc/ddi-suite/master.key` (getrennt aufbewahren), `/etc/ddi-suite/` und optional die Agent-Identitäten (`/var/lib/ddi-suite/agent-<rolle>/identity/`). CA- und Bundle-Schlüssel liegen verschlüsselt in der Datenbank und sind damit Teil des Dumps.
|
||||||
|
- **Wiederherstellen:** Server installieren, Master-Key und Konfiguration zurücklegen, Dump einspielen, Server starten; Agents verbinden sich wieder. **Ohne Master-Key sind alle Geheimnisse verloren** (CA, TSIG, HA-Passwörter): dann neu aufbauen und Agents neu registrieren.
|
||||||
|
- **Upgrade:** erst den Server (`install.sh --upgrade`, Migrationen laufen beim Start), dann die Agents. Vorher die Datenbank sichern. DNS und DHCP laufen während eines Upgrades weiter.
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
# 0022 – Ausrollen: Betriebsmodi, Push, Änderungsübersicht, Diff, Rollback, Live-Status (M4)
|
||||||
|
|
||||||
|
- **Status:** Akzeptiert
|
||||||
|
- **Datum:** 2026-10-13
|
||||||
|
|
||||||
|
## Kontext
|
||||||
|
|
||||||
|
M3 rollt jede neue Revision sofort auf alle Agents aus. M4 verlangt laut Brief Betriebsmodi pro Agent, „Jetzt ausrollen“ aus dem UI, Entwürfe, eine Diff-Ansicht, den Deployment-Status live und Rollback über das UI. Grundlage sind ADR 0007, 0009 und 0021.
|
||||||
|
|
||||||
|
## Entscheidung
|
||||||
|
|
||||||
|
### Betriebsmodi und Soll-Revision
|
||||||
|
|
||||||
|
- `auto_pull` (Standard): Soll-Revision ist immer die neueste Revision; neue Revisionen werden sofort gepusht (wie M3).
|
||||||
|
- `manual`: Soll-Revision ist die zuletzt ausdrücklich für diesen Agent ausgerollte Revision (`agents.target_revision`, anfangs 0). Ohne Push ändert sich nichts.
|
||||||
|
- Umschalten über `PATCH /agents/{id}` (`mode`, Recht `settings.admin`). Der Server teilt dem verbundenen Agent den neuen Modus über ein erneutes `Welcome` mit (Stream wird dazu neu aufgebaut: der Hub trennt die Verbindung, der Agent verbindet sich sofort neu).
|
||||||
|
|
||||||
|
### Push („Jetzt ausrollen“)
|
||||||
|
|
||||||
|
- `POST /revisions/{n}/deploy` (Recht `deploy`) mit optionaler Agent-Liste (leer = alle nicht gesperrten Agents). Für jeden Agent legt der Server ein Deployment im Zustand `pending` mit eigener ID an, setzt bei `manual`-Agents `target_revision = n` und sendet `ApplyRevisionCommand(n, deployment_id)` über den Stream, falls verbunden.
|
||||||
|
- Ältere Revisionen als die neueste dürfen nicht auf `auto_pull`-Agents gepusht werden (sie würden beim nächsten Abruf wieder auf die neueste wechseln), und keine Revision darf auf einen Agent gepusht werden, der bereits eine neuere aktiv hat (der Replay-Schutz des Agents nach ADR 0009 würde sie ablehnen): in beiden Fällen Fehler `rollback_required`; dafür gibt es den Rollback. Die gerade aktive Revision erneut zu pushen ist erlaubt (erneutes Anwenden).
|
||||||
|
- Der Agent merkt sich die IDs der zuletzt bearbeiteten Push-Deployments und wendet dieselbe ID nie zweimal an; ein erneut angekündigter, schon bearbeiteter Push führt nur zum erneuten Senden des Berichts. Der Server beantwortet doppelte Berichte erfolgreich, ohne etwas zu ändern, und kündigt nur Deployments im Zustand `pending` an.
|
||||||
|
- **Nicht verbundene Agents** erhalten offene Push-Aufträge beim nächsten Verbindungsaufbau (der Server sendet die offenen `pending`-Deployments erneut) bzw. beim Polling: `GetDesiredStateResponse.deployment_id` ist gesetzt, solange ein Push offen ist; der Agent behandelt die Soll-Revision dann als Push, auch im Modus `manual`.
|
||||||
|
- `ReportDeployment` mit dieser ID schließt das Deployment ab (Ergebnis wie bisher). Berichte ohne ID (Pulls) werden wie in M3 als neue Zeile gespeichert.
|
||||||
|
|
||||||
|
### Änderungsübersicht („Entwürfe“)
|
||||||
|
|
||||||
|
- IPAM-Änderungen wirken sofort in der Datenbank; ausgerollt wird erst mit einer Revision. Eine eigene `pending_change`-Tabelle ist deshalb unnötig: Die offenen Änderungen ergeben sich aus dem Audit-Log seit der neuesten Revision, der Unterschied in der Konfiguration aus dem Vergleich „jetzt erzeugt“ gegen „neueste Revision“ (erzeugt mit deren Nummer, damit die SOA-Seriennummer keinen Unterschied vortäuscht).
|
||||||
|
- `GET /config/pending` liefert beides; die Oberfläche zeigt „X Änderungen warten auf Ausrollen“ in der Kopfzeile.
|
||||||
|
|
||||||
|
### Diff
|
||||||
|
|
||||||
|
- `GET /revisions/{n}/diff?against=m` (Standard m = n−1) liefert pro Datei Status (`added`, `removed`, `modified`) und einen Unified-Diff (Paket `server/internal/textdiff`, Myers-Algorithmus, 3 Kontextzeilen). Unveränderte Dateien werden ausgelassen.
|
||||||
|
|
||||||
|
### Rollback
|
||||||
|
|
||||||
|
- `POST /revisions/{n}/rollback` erzeugt eine **neue** Revision mit dem Inhalt von n (ADR 0009). Damit die SOA-Seriennummer trotzdem steigt, wird nicht der alte Text kopiert, sondern die gespeicherte **Generator-Eingabe** von n (`config_revisions.source`, JSON, ab Migration 00004) mit der neuen Nummer erneut gerendert. Revisionen ohne gespeicherte Eingabe (vor M4) können nicht zurückgerollt werden (`rollback_unavailable`).
|
||||||
|
- Danach gilt die neue Revision wie jede andere: `auto_pull`-Agents erhalten sie sofort, `manual`-Agents nach einem Push.
|
||||||
|
|
||||||
|
### Live-Status
|
||||||
|
|
||||||
|
- `GET /events` liefert einen **Server-Sent-Events**-Strom für angemeldete Benutzer (Recht `ipam.read`). Ereignisse enthalten nur Kennungen, keine Daten: `agent` (`id`), `deployment` (`id`, `agent_id`, `revision`), `revision` (`number`), `pending`; seit M5 außerdem `addresses` (`network_ids`) für Adressen, die die Lease-Erfassung angelegt oder geändert hat (ADR 0023). Die Oberfläche lädt daraufhin die betroffenen Abfragen neu und fällt bei Verbindungsabbruch auf Polling zurück. Alle 25 s ein Kommentar als Keepalive.
|
||||||
|
- SSE statt WebSocket: nur Server→Browser nötig, funktioniert mit Sitzungscookie, Proxys und `EventSource` ohne Zusatzbibliothek; der Endpunkt nutzt die bestehende Sitzungsprüfung.
|
||||||
|
- Quelle ist ein prozessinterner Ereignisbus (`server/internal/events`), den Dienst und Agent-API bei Änderungen benachrichtigen. Mehrere Server-Instanzen sind nicht vorgesehen (ADR 0006).
|
||||||
|
|
||||||
|
## Präzisierungen bei der Umsetzung
|
||||||
|
|
||||||
|
- Beim Wechsel nach `manual` wird `target_revision` auf die neueste Revision gesetzt: Der Agent bleibt auf seinem Stand, statt eine Soll-Revision 0 anzuzeigen.
|
||||||
|
- Offene Pushes werden auch dann `superseded`, wenn eine neue Revision oder ein Rollback sie für `auto_pull`-Agents überholt, beim Wechsel nach `auto_pull` (für ältere Revisionen) und wenn beim Verbinden oder Abrufen eine andere Revision Soll ist. Ein später doch eintreffender Bericht überschreibt `superseded` mit dem echten Ergebnis.
|
||||||
|
- „Änderungen seit der neuesten Revision“ werden über die Audit-ID des `revision.create`/`revision.rollback`-Eintrags abgegrenzt, nicht über Zeitstempel (Server- und Datenbankuhr können abweichen). Die Einträge enthalten keine IP-Adressen, weil auch Leser sie abrufen.
|
||||||
|
- Die Revisionsnummer steht auch im Kopfkommentar der BIND-Dateien; ein Rollback-Diff zeigt daher neben der Seriennummer eine Kommentarzeile je Datei.
|
||||||
|
- Der Ereignisstrom beginnt mit `retry: 5000`, sendet alle 25 s `: keepalive` und endet mit der Sitzung (abgemeldet, abgelaufen, Benutzer gesperrt; geprüft je Keepalive-Intervall, ohne die Sitzung zu verlängern).
|
||||||
|
|
||||||
|
## Konsequenzen
|
||||||
|
|
||||||
|
- Revisionen bleiben unveränderlich, Rollbacks sind nachvollziehbar und die Seriennummer steigt immer.
|
||||||
|
- Die Oberfläche braucht kein Polling mehr für Agents und Deployments; Polling bleibt als Rückfall.
|
||||||
|
- Ein offener Push für einen dauerhaft abgeschalteten Agent bleibt `pending`, bis der Agent sich meldet, gelöscht wird oder ein neuer Push ihn ersetzt (ältere offene Deployments desselben Agents werden dabei als `superseded` abgeschlossen).
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# 0023 – Cluster, Zonen, Records, TSIG und Lease-Erfassung (M5)
|
||||||
|
|
||||||
|
- **Status:** Akzeptiert
|
||||||
|
- **Datum:** 2026-10-14
|
||||||
|
|
||||||
|
## Kontext
|
||||||
|
|
||||||
|
Bis M4 erhalten alle DNS-Agents dieselben Dateien (jede Zone als Primary) und alle DHCP-Agents dieselbe Kea-Konfiguration. Zonen werden aus den Domains und CIDRs der Netze abgeleitet. M5 verlangt laut Brief DNS-Primary/Secondary mit NOTIFY und TSIG-gesichertem AXFR/IXFR, Kea-HA, Zonen- und Record-Verwaltung, dynamische Zonen mit Active-Directory-Beispiel und die automatische Erfassung dynamischer Leases als Adressen. Grundlage sind ADR 0004, 0005, 0009, 0014, 0015, 0021 und 0022.
|
||||||
|
|
||||||
|
## Entscheidung
|
||||||
|
|
||||||
|
### Cluster
|
||||||
|
|
||||||
|
- Tabelle `clusters` (`id`, `name` eindeutig, `role` = `dns`|`dhcp` als bestehender Typ `agent_role`, `description`, Versionsfeld). Mitglieder in `cluster_members` (`cluster_id`, `agent_id` eindeutig – ein Agent gehört höchstens einem Cluster an –, `role` = `primary`|`secondary`, `address`). Die Rolle des Agents muss zur Rolle des Clusters passen; die Datenbank erzwingt das über zusammengesetzte Fremdschlüssel auf `(id, role)` von `clusters` und `agents`.
|
||||||
|
- **DNS-Cluster:** genau ein `primary` (partieller Unique-Index), beliebig viele `secondary`. `address` ist die IP, über die Primary und Secondaries einander erreichen (NOTIFY, AXFR/IXFR, Port 53). Optional überschreiben `primary_ns` (SOA-MNAME) und `name_servers` (NS-Records) die Generator-Einstellungen für die Zonen des Clusters. Zu jedem DNS-Cluster legt der Server automatisch einen **Transfer-Schlüssel** (TSIG, `hmac-sha256`) an.
|
||||||
|
- **DHCP-Cluster:** höchstens ein `primary` und ein `secondary`. Mit beiden Mitgliedern wird Kea-HA erzeugt, im Modus `hot-standby` (Standard; der `secondary` wird Keas `standby`) oder `load-balancing`. Mit einem Mitglied arbeitet es als Einzelserver. `address` ist die IP des HA-Listeners, `ha_port` (Standard 8001) dessen Port.
|
||||||
|
- Netze erhalten `dhcp_cluster_id`, Zonen `cluster_id` (beide optional). In den Generator-Einstellungen bestimmen `dns.default_cluster_id` und `dhcp.default_cluster_id`, wohin Zonen bzw. Netze ohne eigene Zuordnung gehören.
|
||||||
|
- **Standardgruppe:** Zonen und Netze, die danach keinem Cluster gehören, erhalten wie bisher alle Agents der Rolle, die **keinem** Cluster angehören (jede Zone als Primary, kein HA). Ohne Cluster verhält sich das System also genau wie in M4.
|
||||||
|
- Ein Agent wird erst nach der Registrierung im UI einem Cluster zugeordnet; die Bindung eines Enrollment-Tokens an einen Cluster (ADR 0008) entfällt vorerst.
|
||||||
|
|
||||||
|
### Revisionen pro Ziel
|
||||||
|
|
||||||
|
- Revisionen bleiben global und fortlaufend (Nummer = SOA-Seriennummer). Die Dateien einer Revision tragen zusätzlich ein **Ziel** (`config_revision_files.target`): `''` für die Standardgruppe, sonst die Agent-ID eines Cluster-Mitglieds. Jedes Cluster-Mitglied erhält ein eigenes Ziel, auch wenn es nichts bedient (dann ohne Zonen bzw. Subnetze) – der Generator erzeugt je Ziel immer mindestens die Hauptdateien.
|
||||||
|
- Ein Agent erhält beim Abruf die Dateien des Ziels mit seiner ID, wenn die Revision eines hat, sonst die der Standardgruppe. Maßgeblich ist allein der Inhalt der Revision: Änderungen an Clustern wirken wie alle anderen Änderungen erst mit der nächsten Revision und erscheinen vorher unter den offenen Änderungen.
|
||||||
|
- Revision, Vorschau, Diff und offene Änderungen nennen das Ziel jeder Datei; `targets` beschreibt die Ziele (Rolle, Cluster, Mitgliedsrolle) mit den Namen zum Zeitpunkt der Revision.
|
||||||
|
- `configgen.Source` erhält ein Feld `Version` (M5: 2). Gespeicherte Eingaben älterer Revisionen enthalten keine Zonen, Records und Cluster; sie werden damit genau wie in M4 erzeugt und bleiben für Rollbacks renderbar.
|
||||||
|
|
||||||
|
### Geheimnisse in Revisionen
|
||||||
|
|
||||||
|
- TSIG-Schlüssel (`tsig_keys`: `name` eindeutig, `algorithm` aus `hmac-sha256`, `hmac-sha384`, `hmac-sha512`, `secret` mit dem Master-Key versiegelt nach ADR 0015) und das HA-Passwort eines DHCP-Clusters (versiegelt in `clusters`) gelangen in Konfigurationsdateien. Solche Dateien markiert der Generator als **geheim** (`Artifact.Secret`); sie enthalten nur die Geheimnisse, nie andere Konfiguration.
|
||||||
|
- Inhalte geheimer Dateien liegen in `config_revision_files` versiegelt (zugehörige Daten: Revision, Rolle, Ziel, Pfad). Die REST-API liefert sie **nie** aus (`secret: true`, `content: ""`); Diffs nennen nur den Status. Nur das signierte Bundle an den Agent enthält sie im Klartext (mTLS).
|
||||||
|
- In der gespeicherten Generator-Eingabe (`config_revisions.source`) stehen keine Geheimnisse; sie liegen versiegelt in `config_revisions.secrets` (JSON-Objekt Name → Wert) und werden für Rollbacks wieder eingesetzt.
|
||||||
|
- Schlüssel werden vom Server erzeugt (Zufall, Länge = Hash-Länge). Administratoren können das Geheimnis anzeigen (`GET /tsig-keys/{id}/secret`, auditiert, z. B. für `nsupdate` oder DHCP-Server von Domain Controllern) und erneuern (`POST /tsig-keys/{id}/rotate`). Transfer-Schlüssel gehören ihrem Cluster und werden mit ihm gelöscht.
|
||||||
|
|
||||||
|
### DNS: Zonen, Records, Primary/Secondary
|
||||||
|
|
||||||
|
- **Explizite Zonen** (`zones`: `name` eindeutig, `kind` `forward`|`reverse`, `mode` `managed`|`dynamic`, `cluster_id`, `default_ttl` optional, `allow_update` als CIDR-Liste, Update-Schlüssel über `zone_update_keys`, `description`).
|
||||||
|
- **Abgeleitete Zonen** bleiben erhalten: Für jede Netz-Domain ohne explizite Zone gleichen Namens oder darüber entsteht eine managed Forward-Zone, für jedes Netz die Reverse-Zonen wie bisher, sofern keine explizite Zone gleichen Namens oder darüber existiert. `GET /zones/derived` listet sie; das UI bietet an, sie als explizite Zone zu übernehmen.
|
||||||
|
- A/AAAA-Records aus Adressen kommen in die Forward-Zone mit dem **längsten passenden Suffix** des FQDN, PTR-Records entsprechend in die Reverse-Zonen. Gibt es keine, entsteht eine Warnung.
|
||||||
|
- **Records** (`dns_records`) gehören zu expliziten Zonen: `A`, `AAAA`, `CNAME`, `MX`, `TXT`, `SRV`, `NS`, `PTR`; Name relativ zur Zone (`@` = Apex), TTL optional, typisierte Datenfelder. Der Server prüft beim Speichern mit denselben Regeln wie der Renderer. Konflikte, die erst aus dem Zusammenspiel entstehen (CNAME neben anderen Daten, auch neben A-Records aus Adressen), werden beim Erzeugen verworfen und als Warnung gemeldet.
|
||||||
|
- **Dynamische Zonen:** Records gehen nur in die Anfangsdatei (`CreateOnly`). `allow-update` erlaubt die Quellen aus `allow_update` und die zugeordneten TSIG-Schlüssel (`key "<name>"` in derselben ACL). Für Active Directory: Records unter `_msdcs` usw. in der dynamischen Zone, unsichere Updates nur von den IPs der Domain Controller oder per TSIG; GSS-TSIG ist nicht Teil von Version 1 (siehe `docs/ACTIVE-DIRECTORY.md`).
|
||||||
|
- **Primary/Secondary:** Auf dem Primary erhalten die Zonen eines Clusters `notify explicit`, `also-notify` mit den Adressen der Secondaries und dem Transfer-Schlüssel sowie `allow-transfer { key "<transfer-key>"; }`. Secondaries erhalten für jede Zone nur `type secondary`, `primaries { <primary-address> key "<transfer-key>"; }` und eine Zonendatei unter `<zone_dir>/secondary/db.<zone>`, die BIND schreibt (der DNS-Agent legt das Verzeichnis an und verändert dessen Inhalt nie). Dynamische Zonen sind auf Secondaries normale Secondary-Zonen. Ein Cluster ohne Primary bedient keine Zonen (Warnung).
|
||||||
|
- Schlüssel stehen in der geheimen Datei **`ddi-suite-keys.conf`**, die `named.conf` auf oberster Ebene **vor** `ddi-suite.conf` einbindet (Dateimodus 0640). Sie wird immer erzeugt, notfalls nur mit Kommentar.
|
||||||
|
|
||||||
|
### DHCP: Kea-HA
|
||||||
|
|
||||||
|
- HA nutzt `libdhcp_ha.so` (frei) zusammen mit `libdhcp_lease_cmds.so` und erfordert **Kea ≥ 3.0**: Der dedizierte HA-Listener prüft in Kea keine Anmeldedaten. Stattdessen öffnet `kea-dhcp4` einen eigenen HTTP-Control-Socket an `address:ha_port` mit Basic-Auth (`authentication.clients` mit `user-file` und `password-file`), `http-dedicated-listener` ist aus, und jeder Peer meldet sich mit `basic-auth-user-file` und `basic-auth-password-file` beim anderen an. **Benutzer und Passwort stehen nur in Dateien:** Kea 3.x lehnt Klartext-`user`/`password` in der HTTP-Authentifizierung ab („use of clear text 'user' is NOT SECURE“, Kea-Handbuch, Sicherheitsprüfungen ab 3.0). Benutzername und Passwort erzeugt der Server pro Cluster; Benutzer- und Passwortdatei (`ddi-suite-ha-user`, `ddi-suite-ha-password`) sind geheime Dateien des Bundles. TLS für HA folgt später.
|
||||||
|
- Peer-Namen sind fest (`primary`, `secondary`); `this-server-name` unterscheidet die Ziele. `auto-failover` ist an.
|
||||||
|
- Leases melden beide Peers; die Tabelle `dhcp_leases` hält sie je Agent.
|
||||||
|
|
||||||
|
### Lease-Erfassung als Adressen
|
||||||
|
|
||||||
|
> **Ersetzt durch [ADR 0025](0025-dhcp-pro-adresse-pruefungen-ui.md)** („Lease-Übernahme“): Leases aktualisieren nur vorhandene Einträge, legen keine an und ändern keinen Hostnamen; der vom Client gemeldete Name steht in `lease_hostname`. Der folgende Abschnitt beschreibt den Stand von M5.
|
||||||
|
|
||||||
|
- Beim Speichern gemeldeter Leases gleicht der Server die Adresstabelle ab: Eine **aktive** Lease auf eine IP ohne Eintrag, die in einem Pool eines Netzes liegt, legt einen Eintrag vom Typ `dynamic` an (MAC, Hostname aus der Lease, wenn er ein gültiges Label ist, `first_seen`, `last_seen`, `lease_state`, `lease_expires_at`). Bestehende Einträge erhalten `last_seen`, `lease_state` und `lease_expires_at`; bei `dynamic`-Einträgen werden auch MAC und Hostname aus der Lease übernommen. Abgelaufene und freigegebene Leases ändern nur den Lease-Zustand. Einträge werden nie automatisch gelöscht.
|
||||||
|
- Diese Änderungen erzeugen keine Audit-Einträge pro Lease (sie ändern keine Konfiguration: `dynamic` erzeugt weder DNS noch DHCP-Reservierungen), sondern ein Ereignis für die Oberfläche. Aus einem erfassten Eintrag wird per Typwechsel nach `manual_dhcp` eine Reservierung.
|
||||||
|
|
||||||
|
### Rechte
|
||||||
|
|
||||||
|
- Cluster und TSIG-Schlüssel: Lesen mit `ipam.read` (ohne Geheimnisse), Ändern mit `settings.admin`. Zonen und Records: Lesen mit `ipam.read`, Ändern mit `ipam.write`. Alle Änderungen schreiben Audit-Einträge und zählen zu den offenen Änderungen.
|
||||||
|
|
||||||
|
## Präzisierungen bei der Umsetzung (Server)
|
||||||
|
|
||||||
|
- **Schema (Migration 00005):** `cluster_members` trägt neben der Mitgliedsrolle (`member_role`) die Rolle von Agent und Cluster (`role`); die Fremdschlüssel `(cluster_id, role)` und `(agent_id, role)` erzwingen gleiche Rollen. Zonen (`cluster_role`, fest `dns`) und Netze (`dhcp_cluster_role`, fest `dhcp`) verweisen ebenso über `(id, role)` auf Cluster. Der Transfer-Schlüssel gehört über `tsig_keys.cluster_id` (Löschen kaskadiert) seinem Cluster; `clusters.transfer_key_id` verweist auf `(id, cluster_id)` des Schlüssels, sodass er sich nicht allein löschen lässt. Adressen eines Clusters sind je Cluster eindeutig. Records sind (TTL ausgenommen) je Zone eindeutig, TXT-Daten über einen Hash im Index.
|
||||||
|
- **Geheimnisse:** TSIG-Geheimnisse liegen als Rohbytes versiegelt in `tsig_keys.secret` (zugehörige Daten: Tabelle, Spalte, ID), das HA-Passwort in `clusters.ha_password`. Der HA-Benutzer heißt `ddi-ha-<12 Hex-Zeichen der Cluster-ID>`, der Transfer-Schlüssel `transfer-<Cluster-ID>`. `config_revisions.secrets` enthält `{"key:<id>": "<base64>", "ha:<cluster-id>": "<passwort>"}`; fehlt ein benötigter Wert, ist ein Rollback `rollback_unavailable`. In die Generator-Eingabe gelangen nur Schlüssel, auf die Zonen oder Cluster verweisen; ein unbenutzter Schlüssel ändert die Konfiguration nicht.
|
||||||
|
- **Offene Änderungen:** Änderungen an Clustern, Zonen, Records und TSIG-Schlüsseln (`tsig_key.create`/`update`/`delete`/`rotate`) zählen dazu, das Anzeigen eines Geheimnisses (`tsig_key.read_secret`) nicht.
|
||||||
|
- **Dynamische Zonen** brauchen mindestens eine Quelle in `allow_update` oder einen Schlüssel in `update_key_ids` (`update_source_required`); bei managed Zonen werden beide Listen geleert. Reverse-Zonen werden auf gültige Oktette bzw. Nibbles geprüft.
|
||||||
|
- **Lease-Erfassung (ersetzt durch ADR 0025):** Ein Hostname wird nur übernommen, wenn er ein gültiges Label ist (sonst bleibt er leer bzw. unverändert); der FQDN folgt aus der Domain des Netzes. Lease-Felder (`last_seen`, `lease_state`, `lease_expires_at`) ändern die `version` nicht, eine geänderte MAC oder ein geänderter Hostname eines `dynamic`-Eintrags schon. Ist das Adresslimit der Lizenz erreicht, werden keine weiteren Einträge angelegt. Die Oberfläche erhält das Ereignis `addresses` mit `network_ids` (ADR 0022).
|
||||||
|
- **Fehlercodes:** `key_exists`, `invalid_key_name`, `key_in_use`, `key_owned_by_cluster`, `cluster_exists`, `cluster_role_mismatch`, `agent_in_other_cluster`, `cluster_primary_exists`, `cluster_member_limit`, `duplicate_member` (Agent oder Adresse doppelt), `unknown_agent`, `cluster_in_use` (Parameter `zones`, `networks`, `default`, `key_zones`), `zone_exists`, `zone_kind_mismatch`, `zone_not_empty` (`count`), `update_source_required`, `record_exists`, `cname_at_apex`, `field_not_allowed`, `invalid_label`, `invalid_txt`, `ip_family`, `not_found` (als Feldfehler für verwiesene Cluster und Schlüssel), `secrets_unavailable` (kein Master-Key).
|
||||||
|
|
||||||
|
## Präzisierungen bei der Umsetzung (Generator und Agent)
|
||||||
|
|
||||||
|
- **Warnungen:** `dns.no_zone` (`ip`, `fqdn`), `dns.cname_conflict` (`zone`, `name`, `target`; CNAME neben anderen Daten, am Apex, auf einem Glue-Namen oder doppelt), `dns.unknown_cluster` (`zone`, `cluster_id`; die Zone wird von niemandem bedient), `dns.cluster_without_primary` (`cluster`, `cluster_id`; nur wenn der Cluster Zonen hat), `dns.unknown_key` (`zone`, `key` = Schlüssel-ID), `dns.record_unknown_zone` (`zone_id`, `name`), `dhcp.unknown_cluster` (`network_id`, `cidr`, `cluster_id`).
|
||||||
|
- Secondaries erhalten `notify no;`, damit sie einander nicht benachrichtigen. `allow-transfer { key …; }` steht beim Primary, sobald ein Transfer-Schlüssel gesetzt ist.
|
||||||
|
- Der Kopf von `ddi-suite-keys.conf` enthält keine Revisionsnummer: Die Datei ist geheim, ein Diff zeigt also nur „geändert“, und das soll eine Schlüsseländerung bedeuten.
|
||||||
|
- Die HA-Zugangsdaten stehen in zwei geheimen Dateien, `ddi-suite-ha-password` und `ddi-suite-ha-user` (Modus 0640), jeweils mit Zeilenumbruch am Ende (Kea liest nur die erste Zeile). Klartext-Benutzer oder -Passwörter stehen nirgends in der Konfiguration, weil Kea 3.x sie ablehnt (Quelltext `basic_auth_config.cc`: „use of clear text 'user' is NOT SECURE“). Die Benutzerdatei liegt im Verzeichnis der Passwortdatei (Einstellung `ha_password_file`); deren Dateiname muss `ddi-suite-ha-password` sein, sonst meldet der Generator einen Fehler. Der DHCP-Agent schreibt nur Dateien dieser beiden Namen in ein vorhandenes, gemeinsames Verzeichnis, auf das Control-Socket-Clients und HA-Peers übereinstimmend verweisen, und zwar vor der Konfiguration; scheitert das Neuladen, stellt er beide wieder her, entfällt HA, löscht er sie. `kea-dhcp4 -t` läuft auf einer Kopie der Konfiguration, die auf die Dateien der Revision zeigt. Der Health-Check vergleicht beide Dateien, ohne Inhalte zu nennen.
|
||||||
|
- Der DNS-Agent legt `<zone_dir>/secondary` mit Besitzer und Modus von `zone_dir` an. Noch nicht übertragene Secondary-Zonen sind im Health-Check ein eingeschränkter Einzelcheck, aber kein Fehler (kein Rollback). Revisionen von vor M5 erhalten beim Anwenden eine leere Schlüsseldatei, damit `named.conf` sie weiter einbinden kann.
|
||||||
|
- Load-Balancing verlangt getrennte Pools je Server (Kea-Handbuch, HA): Der Generator teilt jeden Pool in zwei Hälften, die untere für den Primary (`client-classes: ["HA_primary"]`), die obere für den Secondary (`HA_secondary`); ein Pool aus einer Adresse geht an den Primary. Standard bleibt Hot-Standby.
|
||||||
|
|
||||||
|
## Konsequenzen
|
||||||
|
|
||||||
|
- Server ohne Cluster verhalten sich unverändert; Golden-Files von M2–M4 bleiben gültig.
|
||||||
|
- Mitglieder verschiedener Rollen eines Clusters erhalten unterschiedliche Dateien; ein Rollback stellt auch die damalige Cluster-Zuordnung wieder her.
|
||||||
|
- Ein Rollback im Agent kann die Seriennummer auf dem Primary senken; Secondaries behalten dann die höhere Seriennummer, bis eine neue Revision kommt. Rollbacks über das UI erzeugen immer eine neue, höhere Nummer.
|
||||||
|
- Kea-HA setzt Kea 3.x voraus; mit Kea 2.6 bleibt nur der Einzelserver.
|
||||||
|
- `named.conf` muss eine weitere Include-Datei einbinden; Entwicklungsumgebung, End-to-End-Test und Installer (M6) werden angepasst.
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# 0024 – Auslieferung: Installer, systemd, Pakete, Release-Signatur (M6)
|
||||||
|
|
||||||
|
- **Status:** Akzeptiert
|
||||||
|
- **Datum:** 2026-10-14
|
||||||
|
|
||||||
|
## Kontext
|
||||||
|
|
||||||
|
Brief §10 verlangt `scripts/install.sh` für die Rollen `server`, `agent-dns` und `agent-dhcp` auf Debian 12/13, Ubuntu 22.04/24.04 und RHEL-Familie 9, mit Vorabprüfung, Paketinstallation, systemd-Units, Datenbank, Master-Key, Enrollment, Prüfsummen und Signatur, idempotent mit `--upgrade`, `--uninstall`, `--dry-run`, `--non-interactive`, `--yes`. §8 verlangt minimale Rechte und systemd-Hardening. Bisher legen nur die Entwicklungsumgebung und der End-to-End-Test fest, wie BIND, Kea und die Agents zusammenspielen (ADR 0004, 0005, 0021, 0023). Die CI-Runner können privilegierte Container mit systemd starten (geprüft mit Debian 12, Ubuntu 24.04 und Rocky 9).
|
||||||
|
|
||||||
|
## Entscheidung
|
||||||
|
|
||||||
|
### Installer
|
||||||
|
|
||||||
|
- `scripts/install.sh` (Bash, `set -euo pipefail`, shellcheck-sauber). Namen stehen einmal im Variablenblock oben (ADR 0018). Logdatei `/var/log/<produkt>/install.log` (ohne Geheimnisse: Tokens, Lizenzschlüssel und Passwörter werden nie geschrieben).
|
||||||
|
- **Optionen:** `--role server|agent-dns|agent-dhcp` (mehrfach oder mit Komma), `--version <tag>` (Standard: neuestes Release), `--server <host:port> --token <token> --ca-hash sha256:<hex>` (Agents; die Werte stehen im Enrollment-Befehl der Oberfläche), `--public-url`, `--tls-cert`/`--tls-key` (sonst selbstsigniertes Zertifikat), `--license-key-file` bzw. Abfrage (optional), `--kea-source isc|distro` (Standard `isc`), `--from-dir <dir>` (Release-Artefakte aus einem Verzeichnis statt Download; Tests, Offline), `--upgrade`, `--uninstall` (mit `--purge` auch Daten, Datenbank und Schlüssel), `--dry-run`, `--non-interactive`, `--yes`, `--force` (Vorabprüfung nur warnen). Umgebung: `DDI_RELEASE_BASE_URL` (Standard `https://git.beugsiud.de/beug.k/DDI/releases/download/<tag>/`), `DDI_GIT_TOKEN`/`--git-token`.
|
||||||
|
- **Ablauf:** OS und Architektur aus `/etc/os-release`/`uname -m` → Vorabprüfung nach `docs/SYSTEM-REQUIREMENTS.md` (CPU, RAM, Platte, belegte Ports, Zeitsynchronisation) → Artefakte laden, `SHA256SUMS` prüfen, Signatur prüfen (s. u.) → Pakete → Benutzer, Verzeichnisse, Konfiguration → Units → Dienste starten → Ergebnis ausgeben (URL, einmaliges Admin-Passwort bzw. „Agent registriert“). Bei Abbruch werden in diesem Lauf angelegte Dateien wieder entfernt; Pakete bleiben installiert.
|
||||||
|
- **Idempotent:** Vorhandene Konfiguration, Master-Key, Datenbank und Agent-Identität werden nie überschrieben. Ein zweiter Lauf ohne `--upgrade` ändert nichts, was schon stimmt. `--upgrade` ersetzt nur Binaries und Units und startet die Dienste neu (Migrationen laufen beim Serverstart).
|
||||||
|
|
||||||
|
### Server-Rolle
|
||||||
|
|
||||||
|
- Pakete: PostgreSQL der Distribution (≥ 13; EL9: Modul-Stream ≥ 15), `openssl`, `curl`.
|
||||||
|
- Systembenutzer `<produkt>` (z. B. `ddi-suite`), Konfiguration `/etc/<produkt>/server.yaml` (0640 root:`<produkt>`), Master-Key `/etc/<produkt>/master.key` (0400, Besitzer der Dienstbenutzer – der Server verweigert den Start, wenn Gruppe oder andere lesen dürfen; erzeugt mit `ddi-server gen-master-key`), Zustand `/var/lib/<produkt>/server` (systemd `StateDirectory`).
|
||||||
|
- Datenbank: Rolle und Datenbank `<produkt>` mit **Peer-Authentifizierung über den Unix-Socket** (`postgres:///<produkt>?host=/var/run/postgresql`): kein Datenbankpasswort.
|
||||||
|
- HTTPS auf Port 8443 (Standard), Agent-API auf 8444. Ohne `--tls-cert`/`--tls-key` erzeugt der Installer ein selbstsigniertes Zertifikat für den Hostnamen aus `--public-url` und weist darauf hin.
|
||||||
|
- Erster Administrator: `ddi-server bootstrap-admin` (Einmal-Passwort wird nur am Ende ausgegeben). Lizenzschlüssel optional über `ddi-server license set-key` (liest den Schlüssel von stdin); vorher wird `https://license.beugsiud.de` angefragt (nur Warnung).
|
||||||
|
|
||||||
|
### Agent-Rollen
|
||||||
|
|
||||||
|
- **Ein Agent läuft als Benutzer des Dienstes, den er verwaltet:** DNS-Agent als BIND-Benutzer (`bind` bzw. `named`), DHCP-Agent als Kea-Benutzer (`_kea` bzw. `kea`). Ein Agent schreibt ohnehin die Konfiguration dieses Dienstes; mehr Rechte als der Dienst selbst erhält er so nicht, und root ist nicht nötig. Der Benutzer wird per Drop-in (`<unit>.d/10-user.conf`) gesetzt.
|
||||||
|
- **BIND:** Paket der Distribution (Debian/Ubuntu `bind9`, EL9 `bind9.18`, sonst `bind` mit Warnung bei < 9.18). `conf_dir` `/etc/bind/<produkt>` bzw. `/etc/named/<produkt>`, `zone_dir` überall `/var/lib/bind/<produkt>` (Gruppe des BIND-Benutzers, setgid, schreibbar für named; EL: SELinux-Kontext `named_cache_t` per `semanage fcontext`). Der Installer bindet `ddi-suite-keys.conf`, `ddi-suite.conf` und `ddi-suite-options.conf` in `named.conf` ein (markierter Block, beim Deinstallieren entfernt) und entfernt bzw. kommentiert Optionen der Distribution, die der Generator setzt (`recursion`, `allow-recursion`, `forwarders`, `allow-transfer`, `listen-on` nur falls auf localhost beschränkt).
|
||||||
|
- **Kea:** Standard aus dem ISC-Repository `isc/kea-3-2` (Cloudsmith, Paketsignatur geprüft), weil die Distributionen Kea 2.0–2.6 liefern und HA Kea ≥ 3.0 braucht (ADR 0023). Mit `--kea-source distro` das Paket der Distribution (ohne HA). Initiale `kea-dhcp4.conf` mit Control-Socket und `lease_cmds`; Pfade wie die Standard-Generator-Einstellungen (`/run/kea/kea4-ctrl-socket`, `/var/lib/kea/kea-leases4.csv`, `/etc/kea/ddi-suite-ha-*`).
|
||||||
|
- Agent-Konfiguration `/etc/<produkt>/agent-dns.yaml` bzw. `agent-dhcp.yaml`, Zustand `/var/lib/<produkt>/agent-<rolle>`. Enrollment mit `--server --token --ca-hash` (wie der Befehl aus der Oberfläche) als Dienstbenutzer. Ohne Token wird der Agent installiert, aber nicht gestartet.
|
||||||
|
|
||||||
|
### systemd
|
||||||
|
|
||||||
|
- Vorlagen `deploy/systemd/*.service.in` mit Platzhaltern (`@PRODUCT@`, `@DISPLAY_NAME@`, `@BIN_SERVER@`, `@BIN_AGENT_DNS@`, `@BIN_AGENT_DHCP@`, `@BINDIR@`, `@CONFIG_DIR@`, `@ENV_PREFIX@`). `build-release.sh` legt die gerenderten Units in die Tarballs (`@BINDIR@` = `/usr/local/bin`), Pakete rendern sie mit `/usr/bin`.
|
||||||
|
- Hardening in allen Units: `NoNewPrivileges`, `ProtectSystem=strict` mit gezielten `ReadWritePaths`, `ProtectHome`, `PrivateTmp`, `PrivateDevices`, `ProtectKernel*`, `ProtectControlGroups`, `ProtectClock`, `RestrictAddressFamilies`, `RestrictNamespaces`, `RestrictSUIDSGID`, `LockPersonality`, `MemoryDenyWriteExecute`, `SystemCallFilter=@system-service`, leere `CapabilityBoundingSet` (Ausnahme seit ADR 0025: der Server hat `CAP_NET_RAW` für die Ping-Prüfung), `UMask=0027`. Server: eigener Benutzer.
|
||||||
|
|
||||||
|
### Release
|
||||||
|
|
||||||
|
- Tarballs enthalten Binary, Unit und Lizenztexte. Zusätzlich optional `.deb`/`.rpm` mit `nfpm` (`make packages`); die Pakete enthalten nur Binary und Unit, eingerichtet wird mit dem Installer.
|
||||||
|
- **Signatur:** `SHA256SUMS.sig` ist eine Ed25519-Signatur über `SHA256SUMS` (`openssl pkeyutl -sign -rawin`). Der Release-Workflow signiert, wenn das Secret `RELEASE_SIGNING_KEY` (PEM) gesetzt ist. Der Installer enthält den öffentlichen Schlüssel im Variablenblock; ist er gesetzt, muss die Signatur gültig sein, sonst nur Prüfsummen mit Hinweis.
|
||||||
|
- Die CI prüft, dass Units und Installer keine Produktnamen außerhalb der Variablenblöcke enthalten (ADR 0018).
|
||||||
|
|
||||||
|
### Server-Ergänzungen
|
||||||
|
|
||||||
|
- `ddi-server license set-key` (Schlüssel von stdin, aktiviert wie `PUT /license`).
|
||||||
|
- Aufbewahrung (`retention.audit_days`, Standard 0 = unbegrenzt; `retention.revisions_keep`, Standard 0 = alle): täglicher Aufräumlauf. Revisionen, die ein Agent anwendet, die neueste Revision und Revisionen mit offenen Deployments werden nie gelöscht.
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
|
||||||
|
- CI-Job „Installation“: Release-Artefakte bauen, für jedes System (Debian 12/13, Ubuntu 22.04/24.04, Rocky 9) einen privilegierten systemd-Container starten, Installer und Artefakte per `docker cp` hineinlegen (`--from-dir`), alle drei Rollen installieren, Agents mit einem Token aus der API registrieren, eine Änderung ausrollen und mit `dig` und der Kea-Konfiguration prüfen, Installer erneut laufen lassen (idempotent), `--upgrade`, `--uninstall`.
|
||||||
|
|
||||||
|
## Konsequenzen
|
||||||
|
|
||||||
|
- Gemischte Distributionen in einem Cluster funktionieren, weil `zone_dir` und die Kea-Pfade überall gleich sind.
|
||||||
|
- Die Kea-Installation hängt standardmäßig vom ISC-Repository ab; ohne Internetzugang bleibt `--kea-source distro` oder ein eigener Spiegel.
|
||||||
|
- Agents haben die Rechte ihres Dienstes; ein kompromittierter Agent kann diesen Dienst umkonfigurieren, aber nicht mehr.
|
||||||
|
|
||||||
|
## Präzisierungen (Umsetzung)
|
||||||
|
|
||||||
|
### `license set-key`
|
||||||
|
|
||||||
|
- Liest den Schlüssel von stdin (höchstens 4096 Byte Eingabe, nach dem Trimmen nicht leer, eine Zeile, höchstens 512 Zeichen) und ruft denselben Service wie `PUT /api/v1/license` auf; der Audit-Eintrag `license.set_key` trägt den Akteur `system` (wie `bootstrap-admin`). Ausgegeben werden Status, Grund, Lizenzname, Ablauf, Grenzen und Features, nie der Schlüssel.
|
||||||
|
- Exit-Codes: `0` aktiviert, `1` sonstiger Fehler (Konfiguration, Datenbank), `2` Eingabe leer/zu groß/mehrzeilig, `3` Schlüssel abgelehnt (`license_invalid`, `license_in_use`), `4` Lizenzserver nicht erreichbar oder Antwort nicht vertrauenswürdig. Wie bei `PUT /license` wird bei `3` und `4` nichts gespeichert; der Installer behandelt `4` als Warnung.
|
||||||
|
|
||||||
|
### Aufbewahrung
|
||||||
|
|
||||||
|
- Die Löschung braucht keine Migration: Der Unveränderlichkeits-Trigger der Revisionen greift nur bei `UPDATE`; Dateien werden per `ON DELETE CASCADE` mitgelöscht.
|
||||||
|
- Der Aufräumlauf läuft fünf Minuten nach dem Start und dann alle 24 Stunden, in einer Transaktion mit der Revisionssperre (wie Erzeugen und Ausrollen). Er läuft auch im Lizenz-Lesemodus.
|
||||||
|
- Geschützt sind die neuesten `revisions_keep` Revisionen (mindestens die neueste) sowie jede Revision, die in `agents.applied_revision`, `last_good_revision` oder `target_revision` steht oder ein Deployment mit Ergebnis `pending` hat.
|
||||||
|
- **Deployments bleiben erhalten**, auch wenn ihre Revision gelöscht ist: Sie speichern nur die Nummer und sind Teil der Historie. Der Diff einer Revision gegen eine gelöschte Vorgängerin liefert `not_found`; ein Rollback auf eine gelöschte Revision ebenso.
|
||||||
|
- Audit-Einträge werden nach `at` gelöscht. Hat der Lauf etwas gelöscht, schreibt er `retention.cleanup` (Objekttyp `system`) mit den Anzahlen und dem Bereich der gelöschten Revisionsnummern. Die Anzeige „offene Änderungen“ bleibt korrekt, weil sie ohne den Audit-Eintrag der Revision auf deren Zeitpunkt zurückfällt.
|
||||||
|
|
||||||
|
### Pakete, Signatur, Namensprüfung
|
||||||
|
|
||||||
|
- **Pakete:** `scripts/build-packages.sh` (`make packages`, `make release PACKAGES=1`) verpackt die Binaries aus den Tarballs (keine zweite Übersetzung) mit nfpm 2.48.0, installiert mit Prüfsumme über `scripts/ci/install-tools.sh` (kein `go run`: nfpm gehört nicht in den Modulgraphen). Paketname = Binary-Name; Inhalt `/usr/bin/<binary>`, `/usr/lib/systemd/system/<binary>.service` (gerendert mit `/usr/bin`), `/usr/share/doc/<binary>/LICENSE`; Paket-Skripte nur `systemctl daemon-reload`. Keine Abhängigkeiten (PostgreSQL, BIND und Kea richtet der Installer ein, Kea je nach `--kea-source` mit anderen Paketnamen). Danach umfasst `SHA256SUMS` Tarballs und Pakete. Details: [RELEASE.md](../RELEASE.md).
|
||||||
|
- **Signatur:** `scripts/sign-release.sh` (`sign`, `verify`, `public-key`, `selftest`); die Signatur ist binär (64 Byte). Der Release-Workflow prüft die neue Signatur mit dem öffentlichen Schlüssel aus `scripts/install.sh`, falls dort einer steht. Die CI prüft Signieren und Verifizieren bei jedem Lauf mit einem Wegwerf-Schlüssel.
|
||||||
|
- **Namensprüfung:** `scripts/check-brand.sh` (`make lint-brand`, Job „Shell“) sucht `ddi-suite`, `ddi-server`, `ddi-agent-dns`, `ddi-agent-dhcp` (ohne Groß-/Kleinschreibung) in `deploy/systemd/*.in`, `deploy/nfpm/*` und `scripts/install.sh`. Erlaubt sind die Namen nur im Block zwischen den Zeilen `# --- names (ADR 0018) ---` und `# --- end names ---`, die im Installer genau einmal vorkommen müssen. Die nfpm-Konfiguration ist deshalb eine Vorlage (`deploy/nfpm/package.yaml.in`) mit Platzhaltern wie die Units.
|
||||||
|
|
||||||
|
### Installer
|
||||||
|
|
||||||
|
- `/etc/<produkt>` ist 0755 root:root: Die Agents (BIND- bzw. Kea-Benutzer) müssen ihre YAML-Datei dort lesen; jede Datei ist einzeln geschützt. Der Master-Key ist 0400 und gehört dem Dienstbenutzer des Servers (der Server startet sonst nicht).
|
||||||
|
- `conf_dir` des DNS-Agents gehört dem BIND-Benutzer (der Agent schreibt dort ohne root), `zone_dir` und `secondary/` sind 2770.
|
||||||
|
- Die Kea-Pakete von ISC sind mit `/var/run/kea` gebaut und vergleichen den Socket-Pfad wörtlich. Der Installer setzt `KEA_CONTROL_SOCKET_DIR=/run/kea` per Drop-in für Kea und den DHCP-Agent; so bleibt der Standardpfad der Generator-Einstellungen gültig.
|
||||||
|
- EL9: Die ISC-RPMs brauchen `log4cplus` aus EPEL; der Installer richtet EPEL ein und weist darauf hin. Der ISC-Schlüssel wird nur mit dem erwarteten Fingerprint angenommen.
|
||||||
|
- Zusätzlich zu den Generator-Optionen wird `allow-query { localhost; }` auskommentiert (Rocky-Standard). Abgeschaltete Zeilen tragen das Präfix `//<produkt>-disabled: ` und werden beim Deinstallieren wiederhergestellt.
|
||||||
|
- Basiswerkzeuge (curl, openssl, …) werden vor der Vorabprüfung installiert, weil die Erreichbarkeitsprüfungen sie brauchen. `--upgrade` überspringt die Ressourcenprüfung.
|
||||||
|
- Je Lauf wird höchstens ein Agent registriert (ein Token). Ein bereits registrierter Agent wird nicht erneut registriert (Neuregistrierung: `enroll --force`, siehe `OPERATIONS.md`).
|
||||||
|
- `DDI_RELEASE_BASE_URL` darf `<tag>` enthalten; ohne Platzhalter gilt sie als Verzeichnis der Artefakte. `--uninstall --purge` ohne installierte Rollen räumt alle Rollen ab.
|
||||||
|
- Die systemd-Unit des DHCP-Agents erlaubt `AF_NETLINK`: `kea-dhcp4 -t` erkennt die Schnittstellen per Netlink.
|
||||||
|
- Nicht in der CI geprüft: `--kea-source distro` (die Hooks werden ohne Pfad referenziert, was Kea 2.x nicht immer auflöst) sowie AppArmor und SELinux im erzwingenden Modus (Container setzen sie nicht durch).
|
||||||
|
- **Registrierung von Hand (Rückmeldung 2026-10-17):** Ein Agent, der ohne Token installiert und dann mit dem `enroll`-Befehl der Oberfläche registriert wurde, lief nicht als Dienst (Unit nie eingeschaltet, Identität gehörte root). Seitdem schaltet der Installer die Agent-Unit immer ein; `ConditionPathExists` auf `identity/agent.json` lässt systemd sie bis zur Registrierung überspringen. `enroll` als root übergibt das Zustandsverzeichnis an dessen Besitzer (den Dienstbenutzer) und ruft `systemctl enable --now` auf (`--no-start` verhindert das; der Installer nutzt es, weil er selbst startet). Erneuter Lauf und `--upgrade` reparieren die Besitzer und schalten einen registrierten Agent ein. Die Oberfläche zeigt neben dem `enroll`-Befehl den passenden Installer-Aufruf (`install_command`); der Installer kennt dafür `--server-name`.
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
# 0025 – DHCP pro Adresse, DNS für dynamische Einträge, Bereichs- und Massenänderungen, Erreichbarkeitsprüfung, Oberfläche
|
||||||
|
|
||||||
|
- **Status:** Akzeptiert
|
||||||
|
- **Datum:** 2026-10-16
|
||||||
|
|
||||||
|
## Kontext
|
||||||
|
|
||||||
|
Rückmeldung nach M6 (2026-10-16):
|
||||||
|
|
||||||
|
1. Netze sollen aufklappbar sein und **alle** IPs zeigen, belegt oder frei. DHCP soll nicht über Pools, sondern **pro IP** (ohne MAC) festgelegt werden.
|
||||||
|
2. Die Oberfläche wirkt generiert; sie soll wie ein von Hand gebautes Verwaltungswerkzeug aussehen.
|
||||||
|
3. Massenänderungen sollen möglich sein; einzelne Einträge sollen sich per Ping und DNS-Abfrage prüfen lassen.
|
||||||
|
4. Ein neuer dynamischer Eintrag erhält einen zufälligen Hostnamen, damit sich der DNS-Eintrag zur IP prüfen lässt.
|
||||||
|
5. Auch dynamische Einträge sollen DNS-Einträge erhalten (alle Typen außer `reserved`).
|
||||||
|
|
||||||
|
Bisher (ARCHITECTURE §3.2, ADR 0014) bestimmen Pools (`dhcp_pools`) den DHCP-Bereich; `dynamic` muss im Pool liegen und erzeugt kein DNS.
|
||||||
|
|
||||||
|
## Entscheidung
|
||||||
|
|
||||||
|
### Typen
|
||||||
|
|
||||||
|
| Typ | DHCP | DNS (A/PTR) |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `static` | nein | ja |
|
||||||
|
| `reserved` | nein (gesperrt) | nein |
|
||||||
|
| `manual_dhcp` | Reservierung MAC → IP | ja |
|
||||||
|
| `dynamic` | **IP gehört zum DHCP-Bereich** (ohne MAC) | **ja** (neu) |
|
||||||
|
|
||||||
|
### DHCP-Bereich aus Einzeladressen
|
||||||
|
|
||||||
|
- Pools werden nicht mehr gepflegt. Der DHCP-Bereich eines Netzes (mit `dhcp_enabled`) ist die Menge seiner `dynamic`-Einträge; für Kea werden sie zu **zusammenhängenden Bereichen** zusammengefasst (jede ununterbrochene Folge von `dynamic`-IPs ist ein Kea-Pool).
|
||||||
|
- `NetworkRequest.pools` entfällt; `Network.pools` bleibt in der Antwort als **abgeleitete**, schreibgeschützte Liste dieser Bereiche.
|
||||||
|
- Migration 00006: Für jeden vorhandenen Pool werden alle freien IPs des Pools als `dynamic`-Einträge angelegt (ohne Netz-, Broadcast- und Gateway-Adresse), dann entfällt `dhcp_pools`. Bestehende `dynamic`-Einträge ohne Hostname erhalten einen Zufallsnamen.
|
||||||
|
- `configgen.SourceVersion` wird **3**: Ab Version 3 erzeugt `dynamic` A/PTR-Records. Ältere gespeicherte Eingaben (Rollback) werden wie bisher erzeugt; ihre Pools stehen in den gespeicherten Netzen.
|
||||||
|
|
||||||
|
### Zufällige Hostnamen
|
||||||
|
|
||||||
|
- Wird ein `dynamic`-Eintrag ohne Hostnamen angelegt (Formular, CSV-Import, Bereichsoperation, Typwechsel nach `dynamic`, Migration), erzeugt der Server `dyn-` + 8 Zeichen aus `[a-z0-9]` (kryptographischer Zufall). Der Name ist je Zone eindeutig (bei Kollision neu würfeln).
|
||||||
|
- Der eindeutige Index auf `fqdn` gilt nun für `static`, `manual_dhcp` **und** `dynamic`.
|
||||||
|
- Der Hostname gehört dem Eintrag: Eine Lease ändert ihn **nicht** (sonst entstünde nach jeder Vergabe eine Konfigurationsänderung). Den vom Client gemeldeten Namen speichert der Server in der neuen Spalte `lease_hostname`; die Oberfläche zeigt ihn und bietet „Hostname aus Lease übernehmen“ an (normale Änderung, wirkt mit der nächsten Revision).
|
||||||
|
|
||||||
|
### Lease-Übernahme (ersetzt ADR 0023, Abschnitt „Lease-Erfassung“)
|
||||||
|
|
||||||
|
- Leases aktualisieren nur vorhandene Einträge: `last_seen`, `lease_state`, `lease_expires_at`, `lease_hostname`, bei `dynamic` zusätzlich `mac`. Für IPs ohne Eintrag wird nichts angelegt (Kea vergibt nur IPs aus `dynamic`-Einträgen).
|
||||||
|
|
||||||
|
### Alle IPs eines Netzes, Bereichsoperationen
|
||||||
|
|
||||||
|
- `GET /networks/{id}/ips?offset&limit&filter=all|free|used`: jede Host-Adresse eines IPv4-Netzes (bis /16) mit Zustand `free`, `network`, `broadcast`, `gateway` oder `used` samt Eintrag. IPv6-Netze nur mit `filter=used`.
|
||||||
|
- `POST /networks/{id}/range` (Recht `ipam.write`): `assign` legt für alle **freien** IPs eines Bereichs Einträge eines Typs an (`dynamic`, `static`, `reserved`; nicht `manual_dhcp`, das braucht MACs), `clear` löscht Einträge der angegebenen Typen (Standard `dynamic`, `reserved`) im Bereich. Mit `dry_run` nur zählen. Höchstens 65.536 Adressen, ein Audit-Eintrag je Operation (Bereich, Typ, Anzahlen).
|
||||||
|
|
||||||
|
### Massenänderungen
|
||||||
|
|
||||||
|
- `POST /addresses/bulk` erhält zusätzlich `set_description`, `regenerate_hostnames` (neue Zufallsnamen für `dynamic`-Einträge) und `dry_run` (nichts ändern, Probleme und Auswirkungen melden). Wie bisher alles oder nichts, ein Audit-Eintrag je Adresse.
|
||||||
|
|
||||||
|
### Erreichbarkeits- und DNS-Prüfung
|
||||||
|
|
||||||
|
- `POST /addresses/check` (Recht `ipam.read`, 1–100 Einträge, parallel, je Prüfung höchstens wenige Sekunden): **Ping** vom Server aus, zuerst über unprivilegierte ICMP-Echo-Sockets (`net.ipv4.ping_group_range`), sind die nicht erlaubt (z. B. in LXC-Containern), über einen Raw-Socket; dafür hat die Server-Unit als einzige Capability `CAP_NET_RAW` (wie `/bin/ping`). Geht beides nicht → Status `unavailable`. **DNS** vorwärts (FQDN → IP) und rückwärts (IP → FQDN).
|
||||||
|
- Gefragt werden die autoritativen Server der Zone: Mitgliedsadressen des DNS-Clusters bzw. die Adressen der Nameserver aus den Generator-Einstellungen; bei Zonen der Standardgruppe zusätzlich die DNS-Agents ohne Cluster (Adresse ihrer letzten Verbindung, Port 53); erst ohne all das der System-Resolver. Jeder Server hat eine eigene Frist von 2 s, damit ein falsch eingetragener Nameserver die anderen nicht verdrängt. Ergebnis je Richtung `ok`, `missing`, `mismatch` oder `error`, mit befragtem Server und Antworten, dazu Hinweise (`notes`): `dynamic_zone` (Name liegt in einer dynamischen Zone, die Einträge aus der Adresstabelle nur über die Anfangsdatei erhält), `system_resolver` (kein zuständiger Server bekannt), `not_deployed` (Eintrag oder sein Netz seit der letzten Revision geändert; abgegrenzt über Audit-IDs wie die Änderungsübersicht). Die Abfragen gehen direkt an den Server, ohne `/etc/hosts`.
|
||||||
|
- Der Server prüft nur Adressen aus der Adresstabelle (kein freies Ziel); es gibt keinen periodischen Scan.
|
||||||
|
|
||||||
|
### Oberfläche
|
||||||
|
|
||||||
|
- Aufbau eines Verwaltungswerkzeugs statt einer Präsentationsseite: linke Navigation in Gruppen, volle Breite, dichte Tabellen, Typ als kleines farbiges Kürzel statt Auswahlliste je Zeile, Erklärungen als Tooltip statt Absatz, eine Hauptschaltfläche je Seite, keine Taglines.
|
||||||
|
- Netze lassen sich in der Netzliste aufklappen (IP-Liste mit Bereichsauswahl per Umschalt-Klick, Aktionen für die Auswahl: DHCP, statisch, reserviert, freigeben, prüfen).
|
||||||
|
|
||||||
|
## Konsequenzen
|
||||||
|
|
||||||
|
- DHCP-Bereiche sind so fein wie Einzeladressen; große Bereiche bedeuten viele Zeilen (eine /16 voll dynamisch: 65.534 Einträge – im Rahmen der Messungen aus M6).
|
||||||
|
- Jede DHCP-Adresse hat einen DNS-Namen; Clients sind über den Namen ihrer IP auflösbar, nicht über ihren eigenen Hostnamen (dafür später Kea-DDNS, siehe LOGBUCH).
|
||||||
|
- Die Prüfung verlangt, dass ICMP vom Server zu den Netzen erlaubt ist; sonst meldet sie „nicht erreichbar“, was nicht „aus“ bedeutet.
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# 0026 – Einträge der Adresstabelle in dynamischen Zonen (RFC-2136-Updates durch den Agent)
|
||||||
|
|
||||||
|
- **Status:** Akzeptiert
|
||||||
|
- **Datum:** 2026-10-17
|
||||||
|
|
||||||
|
## Kontext
|
||||||
|
|
||||||
|
Der Nutzer will die DNS-Zone seiner Windows-Domäne (z. B. `ad.beugsiud.de`) in DDI betreiben. Domain Controller tragen ihre SRV- und A-Records per RFC 2136 selbst ein; die Zone muss deshalb dynamisch sein (ADR 0004, 0023). Bisher schreibt DDI Einträge der Adresstabelle in eine dynamische Zone nur einmalig in die Anfangsdatei – danach fehlen neue oder geänderte Adressen dort dauerhaft (gesehen bei `ddi-test.ad.beugsiud.de`). Der Brief (§6.2) sieht vor: „Records in dynamischen Zonen verwaltet der Agent höchstens per `nsupdate`.“
|
||||||
|
|
||||||
|
## Entscheidung
|
||||||
|
|
||||||
|
- Für jedes Ziel, das mindestens eine dynamische Zone **als Primary** bedient, erzeugt der Generator zwei weitere Artefakte:
|
||||||
|
- `ddi-suite-update.key` (geheim, 0640): die Schlüsseldefinition im `named.conf`-/`nsupdate`-Format (`key "<name>" { algorithm …; secret "…"; };`). Derselbe Schlüssel steht auch in `ddi-suite-keys.conf`, damit `named` ihn kennt.
|
||||||
|
- `dynamic-records.json` (nicht geheim, 0640): die von DDI verwalteten Records je dynamischer Zone:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"version": 1, "key": "ddi-agent-update",
|
||||||
|
"zones": [{"zone": "ad.example.org",
|
||||||
|
"records": [{"name": "srv1.ad.example.org.", "ttl": 3600, "type": "A", "data": "192.0.2.5"}]}]}
|
||||||
|
```
|
||||||
|
|
||||||
|
Namen absolut mit Punkt, `data` in Präsentationsform (wie in einer Zonendatei bzw. für `nsupdate`), Zonen und Records sortiert. Enthalten sind A/AAAA/PTR aus der Adresstabelle und die in DDI angelegten Records der Zone (ohne SOA/NS des Apex).
|
||||||
|
- Der Schlüssel (`ddi-agent-update`, `hmac-sha256`) ist ein **Systemschlüssel**: Der Server legt ihn an, sobald es eine dynamische Zone gibt (beim Anlegen/Ändern einer dynamischen Zone und beim Start), er steht in der Liste der TSIG-Schlüssel (nicht löschbar, rotierbar) und wird automatisch in die Update-ACL jeder dynamischen Zone aufgenommen – zusätzlich zu `allow_update` und den Update-Schlüsseln der Zone.
|
||||||
|
- Die Anfangsdatei einer dynamischen Zone enthält weiterhin dieselben Records (einmalig, `CreateOnly`).
|
||||||
|
- **Agent (DNS-Rolle):** Nach dem Aktivieren und Neuladen von BIND gleicht er für jede Zone ab: Records der vorherigen aktiven Revision, die in der neuen fehlen, werden gelöscht (`update delete <name> <type> <data>`, also genau dieser Record), alle Records der neuen Revision werden hinzugefügt (`update add`; vorhandene identische Records ändern nichts). Ausführung mit `nsupdate -k <Schlüsseldatei der Revision>` gegen `dns_address` (Standard 127.0.0.1:53), je Zone eine Transaktion. Ist die Zone direkt nach `rndc reconfig` noch nicht geladen, wird einige Sekunden wiederholt. Ein Fehler lässt das Aktivieren scheitern (Rollback auf die vorige Revision, die ihren eigenen Stand wieder einträgt).
|
||||||
|
- Fremde Records (der Domain Controller, anderer Clients, per Hand) fasst der Agent nie an: Er löscht ausschließlich Records, die in der vorigen Revision als von DDI verwaltet standen.
|
||||||
|
- Secondaries erhalten die Änderungen wie bisher per NOTIFY/IXFR.
|
||||||
|
- Der Hinweis `dynamic_zone` der Adressprüfung (ADR 0025) entfällt für Einträge, die DDI so verwaltet.
|
||||||
|
|
||||||
|
## Präzisierungen bei der Umsetzung (Generator und Server)
|
||||||
|
|
||||||
|
- **Generator-Eingabe Version 4:** `Source.UpdateKeyID` nennt die ID des Systemschlüssels in `Source.Keys`; sein Geheimnis liegt wie bei jedem Schlüssel versiegelt in `config_revisions.secrets` (`key:<id>`), Rollbacks auf Revisionen ab Version 4 bringen also auch den damaligen Schlüssel mit. Gespeicherte Eingaben bis Version 3 erzeugen byte-gleich wie bisher (kein Schlüssel in der ACL, keine neuen Dateien).
|
||||||
|
- **Modell:** `DNSConfig.UpdateKey` nennt einen Schlüssel aus `DNSConfig.Keys` (wie `TransferKey`), Dateinamen als Konstanten `configgen.UpdateKeyFile` und `configgen.DynamicRecordsFile`. `derive` setzt ihn nur für Ziele, die mindestens eine dynamische Zone als Primary bedienen; Secondaries und Ziele mit nur managed Zonen erhalten weder Schlüssel noch Dateien. `bindgen` lehnt `UpdateKey` ohne dynamische Primary-Zone oder mit unbekanntem Schlüssel ab (Pfad `update_key`). Fehlt der Systemschlüssel in der Eingabe, meldet der Generator `dns.unknown_key` (`zone`, `key` = `UpdateKeyID`, ggf. leer) für jede dynamische Primary-Zone des Ziels und erzeugt sie wie vor Version 4.
|
||||||
|
- **Update-ACL:** Der Schlüssel steht in der ACL jeder dynamischen Primary-Zone, alphabetisch zwischen den Update-Schlüsseln der Zone und nur einmal, auch wenn die Zone ihn selbst nennt.
|
||||||
|
- **`ddi-suite-update.key`** (geheim, 0640): genau eine `key`-Anweisung ohne Kommentare, im Format von `named`s `session.key`. `nsupdate -k` liest sie über seinen Rückfall für Session-Keys (der Versuch als `K*.key`/`.private`-Paar scheitert vorher still); `named-checkconf` akzeptiert die Datei für sich allein.
|
||||||
|
- **`dynamic-records.json`** (0640, nicht geheim): Schlüssel `version` (1), `key`, `zones`. Jede dynamische Primary-Zone steht darin (nach Namen sortiert, ohne Punkt am Ende), auch ohne Records (`"records": []`), damit der Agent beim letzten Record einer Zone löschen kann. Records stehen in der Reihenfolge der Zonendatei (Owner kanonisch nach RFC 4034, dann Typ, dann Daten), eine Zeile je Record, mit `name` (absolut, mit Punkt), `ttl` (Record-TTL oder Zonen-Standard), `type`, `data` (Präsentationsform wie in der Zonendatei; TXT als gequotete, escapte Character-Strings je höchstens 255 Bytes, Steuerzeichen und Nicht-ASCII als `\DDD`). Inhalt sind alle Records, die der Generator für die Zone erzeugt (A/AAAA/PTR der Adresstabelle, Records der Zone nach Auflösung von CNAME-Konflikten; Records, die sich nur in der TTL unterscheiden, einmal mit der kleineren), außer NS-Records am Apex. Glue-Records der Namensserver stehen nicht darin; ein Record der Adresstabelle, der einem Glue-Record gleicht, aber schon – sonst sähe er gelöscht aus, sobald er Glue wird.
|
||||||
|
- **Systemschlüssel:** neue Spalte `tsig_keys.system` (Migration 00007; ein Systemschlüssel gehört keinem Cluster). Der Name `ddi-agent-update` ist reserviert: Anlegen per API ergibt `key_exists`, die Migration erklärt einen schon vorhandenen Schlüssel dieses Namens zum Systemschlüssel (sein Geheimnis bleibt gültig). Der Server legt ihn (`hmac-sha256`) in derselben Transaktion an, in der eine Zone als dynamisch angelegt oder geändert wird, sowie beim Start, wenn es dynamische Zonen gibt (ein Fehler dabei wird protokolliert und ist nicht fatal). Das Anlegen steht als `tsig_key.create` mit dem Akteur `system` im Audit-Log und zählt zu den offenen Änderungen. Löschen ergibt `key_system` (409); Rotieren und Beschreibung ändern gehen. Die API zeigt ihn mit `system: true`. Er bleibt bestehen, wenn die letzte dynamische Zone gelöscht wird, gelangt dann aber nicht mehr in die Generator-Eingabe.
|
||||||
|
- **Adressprüfung:** `dynamic_zone` wird nicht mehr gemeldet; der Wert bleibt in der Spezifikation (als veraltet beschrieben).
|
||||||
|
- **Gefunden beim Integrationstest:** `named` lehnt mit `check-integrity` (Standard bei Primary-Zonen) ein Update ab, das einen MX-Record auf einen Namen in der Zone ohne A/AAAA-Record hinzufügt – die ganze Transaktion der Zone scheitert dann, und mit ihr das Aktivieren. MX-Ziele in dynamischen Zonen brauchen daher eine Adresse (oder liegen außerhalb der Zone).
|
||||||
|
|
||||||
|
## Konsequenzen
|
||||||
|
|
||||||
|
- Eine Active-Directory-Zone kann vollständig in DDI liegen: Die DCs registrieren sich selbst (Freigabe per IP oder TSIG), Server, Reservierungen und DHCP-Adressen kommen aus der Adresstabelle.
|
||||||
|
- Windows-Clients können sich nicht selbst „sicher“ registrieren (GSS-TSIG fehlt weiterhin). Ihre Namen kommen aus der Adresstabelle; Namen dynamischer DHCP-Clients wären Aufgabe von Kea-DDNS (offen).
|
||||||
|
- Ändert jemand einen von DDI verwalteten Record von Hand, setzt die nächste Revision ihn auf den DDI-Stand zurück; einen von Hand gelöschten trägt sie wieder ein.
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# 0027 – Funktionen per Entitlement, Agent-Limit
|
||||||
|
|
||||||
|
- **Status:** Akzeptiert
|
||||||
|
- **Datum:** 2026-10-18
|
||||||
|
|
||||||
|
## Kontext
|
||||||
|
|
||||||
|
ADR 0016 sieht Feature-Flags aus Keygen-Entitlements und die Limits `maxAgents`/`maxAddresses` aus den Lizenz-Metadaten vor. Umgesetzt war nur `maxAddresses`; die Entitlements wurden geladen und angezeigt, schalteten aber nichts, und `maxAgents` wurde nicht geprüft. Der Nutzer will Cluster, Kea-HA, SSO und dynamische Zonen getrennt lizenzieren und Agents zählen.
|
||||||
|
|
||||||
|
## Entscheidung
|
||||||
|
|
||||||
|
- **Entitlement-Codes** (Keygen, Groß-/Kleinschreibung wie angegeben):
|
||||||
|
|
||||||
|
| Code | Schaltet frei | Ohne den Code gesperrt |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `DDI_CLUSTER` | DNS- und DHCP-Cluster | Cluster anlegen; Agents zu einem Cluster hinzufügen |
|
||||||
|
| `DDI_KEA_HA` | Kea-HA | einen DHCP-Cluster zum HA-Paar machen (Primary **und** Secondary) |
|
||||||
|
| `DDI_DYNAMIC_ZONES` | dynamische Zonen (RFC 2136, AD) | Zone dynamisch anlegen; Zone auf dynamisch umstellen |
|
||||||
|
| `DDI_SSO` | Anmeldung per OIDC | SSO einschalten |
|
||||||
|
|
||||||
|
Ein HA-Paar braucht `DDI_CLUSTER` und `DDI_KEA_HA`.
|
||||||
|
- **Bestand bleibt:** Gesperrt wird nur, was eine Funktion neu in Gebrauch nimmt. Was besteht (aus der Testphase oder einer früheren Lizenz), läuft weiter, bleibt bearbeitbar und löschbar: Cluster lassen sich umbenennen und verkleinern, ein HA-Paar bleibt eins (auch mit getauschtem Partner, wenn `DDI_CLUSTER` da ist), eine dynamische Zone bleibt dynamisch und editierbar, eingeschaltetes SSO bleibt eingeschaltet und änderbar. Der Generator berücksichtigt Lizenzen nicht. Grund: wie in ADR 0016 darf eine Lizenzänderung DNS, DHCP und den Zugang nicht abschalten.
|
||||||
|
- **Testphase:** schaltet alle Funktionen frei (wie bisher ohne Limits). **Karenzzeit:** es gelten die Entitlements der zuletzt gültigen Lizenz. Ohne Lizenz-Manager (Tests, Werkzeuge) ist alles erlaubt.
|
||||||
|
- **Agents:** `maxAgents` zählt alle nicht gesperrten Agents (`revoked_at IS NULL`). Geprüft beim Erzeugen eines Registrierungs-Tokens und – maßgeblich – bei der Registrierung selbst, dort unter einer Advisory-Sperre, damit parallele Registrierungen das Limit nicht gemeinsam überschreiten. Bestehende Agents über dem Limit (Lizenz verkleinert) laufen weiter. Eine Neuregistrierung (`enroll --force`) legt einen neuen Agent an; am Limit muss der alte vorher gesperrt oder gelöscht werden.
|
||||||
|
- **API:** Fehler `403 license_feature` mit Parameter `feature` (Code), `403 license_limit` mit `kind=agents`. `GET /license` liefert zusätzlich `available_features` (die freigeschalteten bekannten Codes, in der Testphase alle) und zählt `usage.agents`.
|
||||||
|
- **Oberfläche:** Die Lizenzseite zeigt die vier Funktionen mit Status. Gesperrte Bedienelemente sind deaktiviert und erklärt (Cluster anlegen und Mitglied hinzufügen, zweites DHCP-Mitglied, Modus „dynamisch“, SSO einschalten); der Server prüft unabhängig davon.
|
||||||
|
- **Keygen:** `tools/keygen-setup/keygen-setup.sh setup` legt die vier Entitlements an; `create-license --features …` und `features --license … --add/--remove …` ordnen sie Lizenzen zu.
|
||||||
|
|
||||||
|
## Konsequenzen
|
||||||
|
|
||||||
|
- Wer nach der Testphase eine Lizenz ohne eine Funktion einspielt, behält das in der Testphase Eingerichtete. Das ist bewusst großzügig (Soft-Control, siehe ADR 0016).
|
||||||
|
- Bestehende Lizenzen ohne Entitlements verlieren das Anlegen von Clustern, HA-Paaren, dynamischen Zonen und das Einschalten von SSO; die Entitlements müssen ihnen zugeordnet werden.
|
||||||
|
- Netze sind weiterhin nicht begrenzt; das Adresslimit bleibt `maxAddresses`.
|
||||||
@@ -25,3 +25,9 @@ Jede Grundsatzentscheidung wird hier als kurze ADR festgehalten. Format siehe [0
|
|||||||
| [0019](0019-openapi-vertragstests.md) | OpenAPI: Vertragstests statt generierter Server-Stubs | Akzeptiert |
|
| [0019](0019-openapi-vertragstests.md) | OpenAPI: Vertragstests statt generierter Server-Stubs | Akzeptiert |
|
||||||
| [0020](0020-authentifizierung-sitzungen.md) | Authentifizierung, Sitzungen und Rollen | Akzeptiert |
|
| [0020](0020-authentifizierung-sitzungen.md) | Authentifizierung, Sitzungen und Rollen | Akzeptiert |
|
||||||
| [0021](0021-agent-strecke-m3.md) | Agent-Strecke: Revisionen, PKI, Ablauf im Agent (M3) | Akzeptiert |
|
| [0021](0021-agent-strecke-m3.md) | Agent-Strecke: Revisionen, PKI, Ablauf im Agent (M3) | Akzeptiert |
|
||||||
|
| [0022](0022-ausrollen-pull-push-m4.md) | Ausrollen: Betriebsmodi, Push, Änderungsübersicht, Diff, Rollback, Live-Status (M4) | Akzeptiert |
|
||||||
|
| [0023](0023-cluster-und-zonen-m5.md) | Cluster, Zonen, Records, TSIG und Lease-Erfassung (M5) | Akzeptiert |
|
||||||
|
| [0024](0024-auslieferung-installer-m6.md) | Auslieferung: Installer, systemd, Pakete, Release-Signatur (M6) | Akzeptiert |
|
||||||
|
| [0025](0025-dhcp-pro-adresse-pruefungen-ui.md) | DHCP pro Adresse, DNS für dynamische Einträge, Bereichs- und Massenänderungen, Prüfungen, Oberfläche | Akzeptiert |
|
||||||
|
| [0026](0026-eintraege-in-dynamischen-zonen.md) | Einträge der Adresstabelle in dynamischen Zonen (RFC-2136-Updates durch den Agent) | Akzeptiert |
|
||||||
|
| [0027](0027-funktionen-per-entitlement-agent-limit.md) | Funktionen per Entitlement (Cluster, Kea-HA, dynamische Zonen, SSO), Agent-Limit | Akzeptiert |
|
||||||
|
|||||||
@@ -192,6 +192,10 @@ message GetDesiredStateResponse {
|
|||||||
uint64 desired_revision = 1;
|
uint64 desired_revision = 1;
|
||||||
OperatingMode mode = 2;
|
OperatingMode mode = 2;
|
||||||
google.protobuf.Duration pull_interval = 3;
|
google.protobuf.Duration pull_interval = 3;
|
||||||
|
// Set while an explicit push of desired_revision is open (not yet
|
||||||
|
// reported). The agent then applies desired_revision as a push with this
|
||||||
|
// deployment ID, also in manual mode (docs/adr/0022-ausrollen-pull-push-m4.md).
|
||||||
|
string deployment_id = 4;
|
||||||
}
|
}
|
||||||
|
|
||||||
message FetchBundleRequest {
|
message FetchBundleRequest {
|
||||||
|
|||||||
Generated
+16
-4
@@ -1416,8 +1416,12 @@ type GetDesiredStateResponse struct {
|
|||||||
DesiredRevision uint64 `protobuf:"varint,1,opt,name=desired_revision,json=desiredRevision,proto3" json:"desired_revision,omitempty"`
|
DesiredRevision uint64 `protobuf:"varint,1,opt,name=desired_revision,json=desiredRevision,proto3" json:"desired_revision,omitempty"`
|
||||||
Mode OperatingMode `protobuf:"varint,2,opt,name=mode,proto3,enum=ddi.agent.v1.OperatingMode" json:"mode,omitempty"`
|
Mode OperatingMode `protobuf:"varint,2,opt,name=mode,proto3,enum=ddi.agent.v1.OperatingMode" json:"mode,omitempty"`
|
||||||
PullInterval *durationpb.Duration `protobuf:"bytes,3,opt,name=pull_interval,json=pullInterval,proto3" json:"pull_interval,omitempty"`
|
PullInterval *durationpb.Duration `protobuf:"bytes,3,opt,name=pull_interval,json=pullInterval,proto3" json:"pull_interval,omitempty"`
|
||||||
unknownFields protoimpl.UnknownFields
|
// Set while an explicit push of desired_revision is open (not yet
|
||||||
sizeCache protoimpl.SizeCache
|
// reported). The agent then applies desired_revision as a push with this
|
||||||
|
// deployment ID, also in manual mode (docs/adr/0022-ausrollen-pull-push-m4.md).
|
||||||
|
DeploymentId string `protobuf:"bytes,4,opt,name=deployment_id,json=deploymentId,proto3" json:"deployment_id,omitempty"`
|
||||||
|
unknownFields protoimpl.UnknownFields
|
||||||
|
sizeCache protoimpl.SizeCache
|
||||||
}
|
}
|
||||||
|
|
||||||
func (x *GetDesiredStateResponse) Reset() {
|
func (x *GetDesiredStateResponse) Reset() {
|
||||||
@@ -1471,6 +1475,13 @@ func (x *GetDesiredStateResponse) GetPullInterval() *durationpb.Duration {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (x *GetDesiredStateResponse) GetDeploymentId() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.DeploymentId
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
type FetchBundleRequest struct {
|
type FetchBundleRequest struct {
|
||||||
state protoimpl.MessageState `protogen:"open.v1"`
|
state protoimpl.MessageState `protogen:"open.v1"`
|
||||||
Revision uint64 `protobuf:"varint,1,opt,name=revision,proto3" json:"revision,omitempty"`
|
Revision uint64 `protobuf:"varint,1,opt,name=revision,proto3" json:"revision,omitempty"`
|
||||||
@@ -2053,11 +2064,12 @@ const file_ddi_agent_v1_agent_proto_rawDesc = "" +
|
|||||||
"\baccepted\x18\x02 \x01(\bR\baccepted\x12\x18\n" +
|
"\baccepted\x18\x02 \x01(\bR\baccepted\x12\x18\n" +
|
||||||
"\amessage\x18\x03 \x01(\tR\amessage\"C\n" +
|
"\amessage\x18\x03 \x01(\tR\amessage\"C\n" +
|
||||||
"\x16GetDesiredStateRequest\x12)\n" +
|
"\x16GetDesiredStateRequest\x12)\n" +
|
||||||
"\x10applied_revision\x18\x01 \x01(\x04R\x0fappliedRevision\"\xb5\x01\n" +
|
"\x10applied_revision\x18\x01 \x01(\x04R\x0fappliedRevision\"\xda\x01\n" +
|
||||||
"\x17GetDesiredStateResponse\x12)\n" +
|
"\x17GetDesiredStateResponse\x12)\n" +
|
||||||
"\x10desired_revision\x18\x01 \x01(\x04R\x0fdesiredRevision\x12/\n" +
|
"\x10desired_revision\x18\x01 \x01(\x04R\x0fdesiredRevision\x12/\n" +
|
||||||
"\x04mode\x18\x02 \x01(\x0e2\x1b.ddi.agent.v1.OperatingModeR\x04mode\x12>\n" +
|
"\x04mode\x18\x02 \x01(\x0e2\x1b.ddi.agent.v1.OperatingModeR\x04mode\x12>\n" +
|
||||||
"\rpull_interval\x18\x03 \x01(\v2\x19.google.protobuf.DurationR\fpullInterval\"0\n" +
|
"\rpull_interval\x18\x03 \x01(\v2\x19.google.protobuf.DurationR\fpullInterval\x12#\n" +
|
||||||
|
"\rdeployment_id\x18\x04 \x01(\tR\fdeploymentId\"0\n" +
|
||||||
"\x12FetchBundleRequest\x12\x1a\n" +
|
"\x12FetchBundleRequest\x12\x1a\n" +
|
||||||
"\brevision\x18\x01 \x01(\x04R\brevision\"\x85\x01\n" +
|
"\brevision\x18\x01 \x01(\x04R\brevision\"\x85\x01\n" +
|
||||||
"\x13FetchBundleResponse\x12\x1a\n" +
|
"\x13FetchBundleResponse\x12\x1a\n" +
|
||||||
|
|||||||
Executable
+158
@@ -0,0 +1,158 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
# Builds .deb and .rpm packages with nfpm from the release tarballs in DIST
|
||||||
|
# (made by scripts/build-release.sh) and rewrites DIST/SHA256SUMS to cover
|
||||||
|
# tarballs and packages (ADR 0024).
|
||||||
|
#
|
||||||
|
# Usage: scripts/build-packages.sh [-d DIST] [-p "linux/amd64 linux/arm64"]
|
||||||
|
#
|
||||||
|
# Each package holds the binary from its tarball as /usr/bin/<binary>, the
|
||||||
|
# systemd unit rendered for /usr/bin and the license text. Names and version
|
||||||
|
# come from the environment (Makefile, ADR 0018): VERSION, PRODUCT,
|
||||||
|
# DISPLAY_NAME, BIN_SERVER, BIN_AGENT_DNS, BIN_AGENT_DHCP. NFPM names the
|
||||||
|
# nfpm binary (default: nfpm from PATH, installed by scripts/ci/install-tools.sh).
|
||||||
|
# Optional: PKG_MAINTAINER, PKG_VENDOR, PKG_HOMEPAGE.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PRODUCT="${PRODUCT:-ddi-suite}"
|
||||||
|
DISPLAY_NAME="${DISPLAY_NAME:-DDI-Suite}"
|
||||||
|
BIN_SERVER="${BIN_SERVER:-ddi-server}"
|
||||||
|
BIN_AGENT_DNS="${BIN_AGENT_DNS:-ddi-agent-dns}"
|
||||||
|
BIN_AGENT_DHCP="${BIN_AGENT_DHCP:-ddi-agent-dhcp}"
|
||||||
|
NFPM="${NFPM:-nfpm}"
|
||||||
|
|
||||||
|
dist="dist"
|
||||||
|
platforms="linux/amd64 linux/arm64"
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
sed -n '4,16p' "$0" | sed 's/^# \{0,1\}//'
|
||||||
|
}
|
||||||
|
|
||||||
|
while getopts ":d:p:h" opt; do
|
||||||
|
case "$opt" in
|
||||||
|
d) dist="$OPTARG" ;;
|
||||||
|
p) platforms="$OPTARG" ;;
|
||||||
|
h)
|
||||||
|
usage
|
||||||
|
exit 0
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
usage >&2
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
root="$(git rev-parse --show-toplevel)"
|
||||||
|
cd "$root"
|
||||||
|
|
||||||
|
if ! command -v "$NFPM" >/dev/null; then
|
||||||
|
echo "nfpm not found (set NFPM or run scripts/ci/install-tools.sh)" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
VERSION="${VERSION:-$(git describe --tags --always --dirty 2>/dev/null || echo dev)}"
|
||||||
|
BUILD_DATE="${BUILD_DATE:-$(git log -1 --format=%cI 2>/dev/null || date -u +%Y-%m-%dT%H:%M:%SZ)}"
|
||||||
|
|
||||||
|
# Package versions must be semantic versions: v1.2.3 -> 1.2.3; anything else
|
||||||
|
# (a commit hash, "dev") becomes a 0.0.0 pre-release that sorts below every
|
||||||
|
# real release.
|
||||||
|
if [[ "$VERSION" =~ ^v?([0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.+-]*)?)$ ]]; then
|
||||||
|
pkg_version="${BASH_REMATCH[1]}"
|
||||||
|
else
|
||||||
|
pkg_version="0.0.0-dev.$(tr -c '0-9A-Za-z.\n' '.' <<<"$VERSION")"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Reproducible timestamps inside the packages.
|
||||||
|
SOURCE_DATE_EPOCH="$(date -u -d "$BUILD_DATE" +%s 2>/dev/null || echo 0)"
|
||||||
|
export SOURCE_DATE_EPOCH
|
||||||
|
|
||||||
|
declare -A descriptions=(
|
||||||
|
["$BIN_SERVER"]="${DISPLAY_NAME} management server (IPAM, DNS and DHCP)"
|
||||||
|
["$BIN_AGENT_DNS"]="${DISPLAY_NAME} agent for BIND 9"
|
||||||
|
["$BIN_AGENT_DHCP"]="${DISPLAY_NAME} agent for Kea DHCPv4"
|
||||||
|
)
|
||||||
|
declare -A licenses=(
|
||||||
|
["$BIN_SERVER"]="LICENSES/LicenseRef-DDI-Proprietary.txt"
|
||||||
|
["$BIN_AGENT_DNS"]="LICENSES/Apache-2.0.txt"
|
||||||
|
["$BIN_AGENT_DHCP"]="LICENSES/Apache-2.0.txt"
|
||||||
|
)
|
||||||
|
declare -A license_names=(
|
||||||
|
["$BIN_SERVER"]="Proprietary"
|
||||||
|
["$BIN_AGENT_DNS"]="Apache-2.0"
|
||||||
|
["$BIN_AGENT_DHCP"]="Apache-2.0"
|
||||||
|
)
|
||||||
|
|
||||||
|
workdir="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$workdir"' EXIT
|
||||||
|
# Git Bash on Windows (development): nfpm.exe needs Windows paths.
|
||||||
|
if command -v cygpath >/dev/null; then
|
||||||
|
workdir="$(cygpath -m "$workdir")"
|
||||||
|
fi
|
||||||
|
|
||||||
|
export PRODUCT DISPLAY_NAME BIN_SERVER BIN_AGENT_DNS BIN_AGENT_DHCP
|
||||||
|
scripts/render-units.sh /usr/bin "$workdir/units"
|
||||||
|
|
||||||
|
PKG_MAINTAINER="${PKG_MAINTAINER:-${DISPLAY_NAME} <maintainer@example.invalid>}"
|
||||||
|
PKG_VENDOR="${PKG_VENDOR:-$DISPLAY_NAME}"
|
||||||
|
PKG_HOMEPAGE="${PKG_HOMEPAGE:-https://git.beugsiud.de/beug.k/DDI}"
|
||||||
|
|
||||||
|
# render_config NAME ARCH SRC_DIR LICENSE DESCRIPTION > nfpm.yaml
|
||||||
|
render_config() {
|
||||||
|
local -a subst=(
|
||||||
|
PKG_NAME "$1" PKG_ARCH "$2" PKG_SRC_DIR "$3" PKG_LICENSE "$4" PKG_DESCRIPTION "$5"
|
||||||
|
PKG_VERSION "$pkg_version" PKG_MAINTAINER "$PKG_MAINTAINER" PKG_VENDOR "$PKG_VENDOR"
|
||||||
|
PKG_HOMEPAGE "$PKG_HOMEPAGE" PKG_SCRIPTS_DIR "$root/deploy/nfpm"
|
||||||
|
)
|
||||||
|
local -a expr=()
|
||||||
|
local i value
|
||||||
|
for ((i = 0; i < ${#subst[@]}; i += 2)); do
|
||||||
|
value="${subst[i + 1]}"
|
||||||
|
# The values end up in sed replacements and double-quoted YAML.
|
||||||
|
if [[ "$value" == *[\|\&\\\"]* ]]; then
|
||||||
|
echo "unsafe value for ${subst[i]}: ${value}" >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
expr+=(-e "s|@${subst[i]}@|${value}|g")
|
||||||
|
done
|
||||||
|
sed "${expr[@]}" deploy/nfpm/package.yaml.in
|
||||||
|
}
|
||||||
|
|
||||||
|
for platform in $platforms; do
|
||||||
|
goos="${platform%/*}"
|
||||||
|
goarch="${platform#*/}"
|
||||||
|
for bin in "$BIN_SERVER" "$BIN_AGENT_DNS" "$BIN_AGENT_DHCP"; do
|
||||||
|
name="${bin}_${VERSION}_${goos}_${goarch}"
|
||||||
|
tarball="${dist}/${name}.tar.gz"
|
||||||
|
if [[ ! -f "$tarball" ]]; then
|
||||||
|
echo "missing ${tarball}: run make release first" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
src="${workdir}/${name}"
|
||||||
|
mkdir -p "$src"
|
||||||
|
tar -xzf "$tarball" -C "$workdir" "${name}/${bin}"
|
||||||
|
mv "${workdir}/${name}/${bin}" "${src}/binary"
|
||||||
|
cp "$workdir/units/${bin}.service" "${src}/unit.service"
|
||||||
|
cp "${licenses[$bin]}" "${src}/LICENSE"
|
||||||
|
|
||||||
|
render_config "$bin" "$goarch" "$src" "${license_names[$bin]}" "${descriptions[$bin]}" >"${src}/nfpm.yaml"
|
||||||
|
if grep -q '@[A-Z_]*@' "${src}/nfpm.yaml"; then
|
||||||
|
echo "unreplaced placeholder in the nfpm configuration of ${name}" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
for packager in deb rpm; do
|
||||||
|
echo "packaging ${bin} ${pkg_version} ${goarch} (${packager})"
|
||||||
|
"$NFPM" package --config "${src}/nfpm.yaml" --packager "$packager" --target "$dist/" >/dev/null
|
||||||
|
done
|
||||||
|
done
|
||||||
|
done
|
||||||
|
|
||||||
|
(
|
||||||
|
cd "$dist"
|
||||||
|
shopt -s nullglob
|
||||||
|
sha256sum -- *.tar.gz *.deb *.rpm >SHA256SUMS
|
||||||
|
)
|
||||||
|
echo "artefacts in ${dist}:"
|
||||||
|
cat "${dist}/SHA256SUMS"
|
||||||
+17
-11
@@ -2,7 +2,8 @@
|
|||||||
# SPDX-License-Identifier: Apache-2.0
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
#
|
#
|
||||||
# Builds release artefacts: static binaries for each target platform, one
|
# Builds release artefacts: static binaries for each target platform, one
|
||||||
# tarball per binary and platform, and SHA256SUMS.
|
# tarball per binary and platform (binary, its systemd unit for
|
||||||
|
# /usr/local/bin, LICENSE and LICENSES/), and SHA256SUMS.
|
||||||
#
|
#
|
||||||
# Usage: scripts/build-release.sh [-o OUTDIR] [-p "linux/amd64 linux/arm64"]
|
# Usage: scripts/build-release.sh [-o OUTDIR] [-p "linux/amd64 linux/arm64"]
|
||||||
#
|
#
|
||||||
@@ -28,7 +29,7 @@ outdir="dist"
|
|||||||
platforms="linux/amd64 linux/arm64"
|
platforms="linux/amd64 linux/arm64"
|
||||||
|
|
||||||
usage() {
|
usage() {
|
||||||
sed -n '4,12p' "$0" | sed 's/^# \{0,1\}//'
|
sed -n '4,14p' "$0" | sed 's/^# \{0,1\}//'
|
||||||
}
|
}
|
||||||
|
|
||||||
while getopts ":o:p:h" opt; do
|
while getopts ":o:p:h" opt; do
|
||||||
@@ -85,17 +86,12 @@ add_x internal/brand.LogDir "/var/log/${PRODUCT}"
|
|||||||
add_x server/internal/license.EmbeddedAccountID "$KEYGEN_ACCOUNT_ID"
|
add_x server/internal/license.EmbeddedAccountID "$KEYGEN_ACCOUNT_ID"
|
||||||
add_x server/internal/license.EmbeddedPublicKey "$KEYGEN_PUBLIC_KEY"
|
add_x server/internal/license.EmbeddedPublicKey "$KEYGEN_PUBLIC_KEY"
|
||||||
|
|
||||||
# binary name -> package, license file shipped with it
|
# binary name -> package
|
||||||
declare -A packages=(
|
declare -A packages=(
|
||||||
["$BIN_SERVER"]="./server/cmd/ddi-server"
|
["$BIN_SERVER"]="./server/cmd/ddi-server"
|
||||||
["$BIN_AGENT_DNS"]="./agent/cmd/ddi-agent-dns"
|
["$BIN_AGENT_DNS"]="./agent/cmd/ddi-agent-dns"
|
||||||
["$BIN_AGENT_DHCP"]="./agent/cmd/ddi-agent-dhcp"
|
["$BIN_AGENT_DHCP"]="./agent/cmd/ddi-agent-dhcp"
|
||||||
)
|
)
|
||||||
declare -A licenses=(
|
|
||||||
["$BIN_SERVER"]="LICENSES/LicenseRef-DDI-Proprietary.txt"
|
|
||||||
["$BIN_AGENT_DNS"]="LICENSES/Apache-2.0.txt"
|
|
||||||
["$BIN_AGENT_DHCP"]="LICENSES/Apache-2.0.txt"
|
|
||||||
)
|
|
||||||
|
|
||||||
workdir="$(mktemp -d)"
|
workdir="$(mktemp -d)"
|
||||||
trap 'rm -rf "$workdir"' EXIT
|
trap 'rm -rf "$workdir"' EXIT
|
||||||
@@ -103,6 +99,11 @@ trap 'rm -rf "$workdir"' EXIT
|
|||||||
rm -rf "$outdir"
|
rm -rf "$outdir"
|
||||||
mkdir -p "$outdir"
|
mkdir -p "$outdir"
|
||||||
|
|
||||||
|
# systemd units for binaries in /usr/local/bin (ADR 0024); each tarball
|
||||||
|
# carries the unit of its binary.
|
||||||
|
units="${workdir}/units"
|
||||||
|
scripts/render-units.sh /usr/local/bin "$units"
|
||||||
|
|
||||||
for platform in $platforms; do
|
for platform in $platforms; do
|
||||||
goos="${platform%/*}"
|
goos="${platform%/*}"
|
||||||
goarch="${platform#*/}"
|
goarch="${platform#*/}"
|
||||||
@@ -116,9 +117,14 @@ for platform in $platforms; do
|
|||||||
go build -trimpath -buildvcs=false -ldflags "$ldflags" \
|
go build -trimpath -buildvcs=false -ldflags "$ldflags" \
|
||||||
-o "${stage}/${bin}" "${packages[$bin]}"
|
-o "${stage}/${bin}" "${packages[$bin]}"
|
||||||
|
|
||||||
cp "${licenses[$bin]}" "${stage}/LICENSE"
|
# Unit and license texts: LICENSE says which license covers what
|
||||||
chmod 0755 "${stage}" "${stage}/${bin}"
|
# (the server is proprietary, the unit files are Apache-2.0).
|
||||||
chmod 0644 "${stage}/LICENSE"
|
cp "${units}/${bin}.service" "${stage}/${bin}.service"
|
||||||
|
cp LICENSE "${stage}/LICENSE"
|
||||||
|
mkdir -p "${stage}/LICENSES"
|
||||||
|
cp LICENSES/*.txt "${stage}/LICENSES/"
|
||||||
|
chmod 0755 "${stage}" "${stage}/LICENSES" "${stage}/${bin}"
|
||||||
|
chmod 0644 "${stage}/${bin}.service" "${stage}/LICENSE" "${stage}/LICENSES/"*.txt
|
||||||
|
|
||||||
# Reproducible tarball: fixed order, owner and timestamps.
|
# Reproducible tarball: fixed order, owner and timestamps.
|
||||||
tar --sort=name --owner=0 --group=0 --numeric-owner \
|
tar --sort=name --owner=0 --group=0 --numeric-owner \
|
||||||
|
|||||||
Executable
+66
@@ -0,0 +1,66 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
# Fails if systemd unit templates, nfpm package files or the installer
|
||||||
|
# contain hard-coded product or binary names (ADR 0018). Names belong in the
|
||||||
|
# variables of the Makefile and the scripts; templates use placeholders.
|
||||||
|
#
|
||||||
|
# Usage: scripts/check-brand.sh [FILE...]
|
||||||
|
# Without FILE the default set is checked: deploy/systemd/*.in,
|
||||||
|
# deploy/nfpm/*, scripts/install.sh. Missing files are skipped.
|
||||||
|
#
|
||||||
|
# The installer may define the names once, in a block between the lines
|
||||||
|
# # --- names (ADR 0018) ---
|
||||||
|
# # --- end names ---
|
||||||
|
# Each marker must appear exactly once, in this order; everything outside the
|
||||||
|
# block is checked. The same applies to any checked file containing a marker.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
readonly BEGIN_MARKER="# --- names (ADR 0018) ---"
|
||||||
|
readonly END_MARKER="# --- end names ---"
|
||||||
|
# Literal names that must not appear (case-insensitive).
|
||||||
|
readonly PATTERN='ddi-suite|ddi-server|ddi-agent-dns|ddi-agent-dhcp'
|
||||||
|
|
||||||
|
cd "$(git rev-parse --show-toplevel)"
|
||||||
|
|
||||||
|
files=("$@")
|
||||||
|
if ((${#files[@]} == 0)); then
|
||||||
|
shopt -s nullglob
|
||||||
|
files=(deploy/systemd/*.in deploy/nfpm/* scripts/install.sh)
|
||||||
|
shopt -u nullglob
|
||||||
|
fi
|
||||||
|
|
||||||
|
failed=0
|
||||||
|
checked=0
|
||||||
|
for f in "${files[@]}"; do
|
||||||
|
[[ -f "$f" ]] || continue
|
||||||
|
checked=$((checked + 1))
|
||||||
|
begins="$(grep -cxF -- "$BEGIN_MARKER" "$f" || true)"
|
||||||
|
ends="$(grep -cxF -- "$END_MARKER" "$f" || true)"
|
||||||
|
if [[ "$f" == scripts/install.sh ]] || ((begins + ends > 0)); then
|
||||||
|
if ((begins != 1 || ends != 1)); then
|
||||||
|
echo "$f: expected exactly one '${BEGIN_MARKER}' and one '${END_MARKER}' line" >&2
|
||||||
|
failed=1
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
# "line:text" for every offending line outside the names block.
|
||||||
|
hits="$(awk -v b="$BEGIN_MARKER" -v e="$END_MARKER" -v pat="$PATTERN" '
|
||||||
|
$0 == b { inside = 1; next }
|
||||||
|
$0 == e { if (!inside) print NR ":end marker before begin marker"; inside = 0; next }
|
||||||
|
!inside && tolower($0) ~ pat { print NR ":" $0 }
|
||||||
|
' "$f")"
|
||||||
|
if [[ -n "$hits" ]]; then
|
||||||
|
while IFS= read -r line; do
|
||||||
|
echo "${f}:${line}" >&2
|
||||||
|
done <<<"$hits"
|
||||||
|
failed=1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if ((failed)); then
|
||||||
|
echo "hard-coded product or binary names found (ADR 0018): use the variables or placeholders" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "brand check passed (${checked} files)"
|
||||||
+51
-21
@@ -2,9 +2,10 @@
|
|||||||
# SPDX-License-Identifier: Apache-2.0
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
#
|
#
|
||||||
# Installs pinned, checksum-verified development tools on Linux (amd64/arm64)
|
# Installs pinned, checksum-verified development tools on Linux (amd64/arm64)
|
||||||
# for CI: golangci-lint, buf, shellcheck.
|
# for CI: golangci-lint, buf, shellcheck, nfpm.
|
||||||
#
|
#
|
||||||
# Usage: scripts/ci/install-tools.sh [BINDIR] (default: $HOME/.local/bin)
|
# Usage: scripts/ci/install-tools.sh [BINDIR] [TOOL...]
|
||||||
|
# BINDIR defaults to $HOME/.local/bin; without TOOL all tools are installed.
|
||||||
# In GitHub/Gitea Actions the directory is appended to $GITHUB_PATH.
|
# In GitHub/Gitea Actions the directory is appended to $GITHUB_PATH.
|
||||||
|
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
@@ -12,25 +13,35 @@ set -euo pipefail
|
|||||||
readonly GOLANGCI_LINT_VERSION="2.14.0"
|
readonly GOLANGCI_LINT_VERSION="2.14.0"
|
||||||
readonly BUF_VERSION="1.73.0"
|
readonly BUF_VERSION="1.73.0"
|
||||||
readonly SHELLCHECK_VERSION="0.11.0"
|
readonly SHELLCHECK_VERSION="0.11.0"
|
||||||
|
readonly NFPM_VERSION="2.48.0"
|
||||||
|
|
||||||
bindir="${1:-$HOME/.local/bin}"
|
bindir="${1:-$HOME/.local/bin}"
|
||||||
|
shift || true
|
||||||
|
tools=("$@")
|
||||||
|
if ((${#tools[@]} == 0)); then
|
||||||
|
tools=(golangci-lint buf shellcheck nfpm)
|
||||||
|
fi
|
||||||
|
|
||||||
case "$(uname -m)" in
|
case "$(uname -m)" in
|
||||||
x86_64 | amd64)
|
x86_64 | amd64)
|
||||||
golangci_arch="amd64"
|
golangci_arch="amd64"
|
||||||
buf_arch="x86_64"
|
buf_arch="x86_64"
|
||||||
shellcheck_arch="x86_64"
|
shellcheck_arch="x86_64"
|
||||||
|
nfpm_arch="x86_64"
|
||||||
golangci_sha="ab90aeb7b066f92a33415b638a50fe5344bbb75a0d32ad30cc248d88f81032ab"
|
golangci_sha="ab90aeb7b066f92a33415b638a50fe5344bbb75a0d32ad30cc248d88f81032ab"
|
||||||
buf_sha="8f2986298ad08f0cc1bf999b9797b7c383adf32d7edf0f73d6f1e1a701baeac1"
|
buf_sha="8f2986298ad08f0cc1bf999b9797b7c383adf32d7edf0f73d6f1e1a701baeac1"
|
||||||
shellcheck_sha="b7af85e41cc99489dcc21d66c6d5f3685138f06d34651e6d34b42ec6d54fe6f6"
|
shellcheck_sha="b7af85e41cc99489dcc21d66c6d5f3685138f06d34651e6d34b42ec6d54fe6f6"
|
||||||
|
nfpm_sha="6d7f9a28b2f397934403950fcbba83f598b08d02edbe79a0815b3b4897341750"
|
||||||
;;
|
;;
|
||||||
aarch64 | arm64)
|
aarch64 | arm64)
|
||||||
golangci_arch="arm64"
|
golangci_arch="arm64"
|
||||||
buf_arch="aarch64"
|
buf_arch="aarch64"
|
||||||
shellcheck_arch="aarch64"
|
shellcheck_arch="aarch64"
|
||||||
|
nfpm_arch="arm64"
|
||||||
golangci_sha="ee7ec5f3453d15ddf106fae5a4d6c71737712348a979d1fe9cd52ec7ea299bae"
|
golangci_sha="ee7ec5f3453d15ddf106fae5a4d6c71737712348a979d1fe9cd52ec7ea299bae"
|
||||||
buf_sha="902b75267db7f4391e99b7fa0756050e5354234cc0437ef50eee9c788950c7a3"
|
buf_sha="902b75267db7f4391e99b7fa0756050e5354234cc0437ef50eee9c788950c7a3"
|
||||||
shellcheck_sha="68a8133197a50beb8803f8d42f9908d1af1c5540d4bb05fdfca8c1fa47decefc"
|
shellcheck_sha="68a8133197a50beb8803f8d42f9908d1af1c5540d4bb05fdfca8c1fa47decefc"
|
||||||
|
nfpm_sha="a9a75213763783b7669719e505474c748c5ad7dc66591a195619deb50f85c2f4"
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
echo "unsupported architecture: $(uname -m)" >&2
|
echo "unsupported architecture: $(uname -m)" >&2
|
||||||
@@ -48,26 +59,45 @@ fetch() {
|
|||||||
echo "$3 $2" | sha256sum -c --quiet -
|
echo "$3 $2" | sha256sum -c --quiet -
|
||||||
}
|
}
|
||||||
|
|
||||||
name="golangci-lint-${GOLANGCI_LINT_VERSION}-linux-${golangci_arch}"
|
for tool in "${tools[@]}"; do
|
||||||
fetch "https://github.com/golangci/golangci-lint/releases/download/v${GOLANGCI_LINT_VERSION}/${name}.tar.gz" \
|
case "$tool" in
|
||||||
"$workdir/golangci.tar.gz" "$golangci_sha"
|
golangci-lint)
|
||||||
tar -xzf "$workdir/golangci.tar.gz" -C "$workdir"
|
name="golangci-lint-${GOLANGCI_LINT_VERSION}-linux-${golangci_arch}"
|
||||||
install -m 0755 "$workdir/${name}/golangci-lint" "$bindir/golangci-lint"
|
fetch "https://github.com/golangci/golangci-lint/releases/download/v${GOLANGCI_LINT_VERSION}/${name}.tar.gz" \
|
||||||
|
"$workdir/golangci.tar.gz" "$golangci_sha"
|
||||||
fetch "https://github.com/bufbuild/buf/releases/download/v${BUF_VERSION}/buf-Linux-${buf_arch}" \
|
tar -xzf "$workdir/golangci.tar.gz" -C "$workdir"
|
||||||
"$workdir/buf" "$buf_sha"
|
install -m 0755 "$workdir/${name}/golangci-lint" "$bindir/golangci-lint"
|
||||||
install -m 0755 "$workdir/buf" "$bindir/buf"
|
"$bindir/golangci-lint" version
|
||||||
|
;;
|
||||||
name="shellcheck-v${SHELLCHECK_VERSION}"
|
buf)
|
||||||
fetch "https://github.com/koalaman/shellcheck/releases/download/v${SHELLCHECK_VERSION}/${name}.linux.${shellcheck_arch}.tar.gz" \
|
fetch "https://github.com/bufbuild/buf/releases/download/v${BUF_VERSION}/buf-Linux-${buf_arch}" \
|
||||||
"$workdir/shellcheck.tar.gz" "$shellcheck_sha"
|
"$workdir/buf" "$buf_sha"
|
||||||
tar -xzf "$workdir/shellcheck.tar.gz" -C "$workdir"
|
install -m 0755 "$workdir/buf" "$bindir/buf"
|
||||||
install -m 0755 "$workdir/${name}/shellcheck" "$bindir/shellcheck"
|
"$bindir/buf" --version
|
||||||
|
;;
|
||||||
|
shellcheck)
|
||||||
|
name="shellcheck-v${SHELLCHECK_VERSION}"
|
||||||
|
fetch "https://github.com/koalaman/shellcheck/releases/download/v${SHELLCHECK_VERSION}/${name}.linux.${shellcheck_arch}.tar.gz" \
|
||||||
|
"$workdir/shellcheck.tar.gz" "$shellcheck_sha"
|
||||||
|
tar -xzf "$workdir/shellcheck.tar.gz" -C "$workdir"
|
||||||
|
install -m 0755 "$workdir/${name}/shellcheck" "$bindir/shellcheck"
|
||||||
|
"$bindir/shellcheck" --version | head -n 2
|
||||||
|
;;
|
||||||
|
nfpm)
|
||||||
|
fetch "https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${NFPM_VERSION}_Linux_${nfpm_arch}.tar.gz" \
|
||||||
|
"$workdir/nfpm.tar.gz" "$nfpm_sha"
|
||||||
|
tar -xzf "$workdir/nfpm.tar.gz" -C "$workdir" nfpm
|
||||||
|
install -m 0755 "$workdir/nfpm" "$bindir/nfpm"
|
||||||
|
"$bindir/nfpm" --version >"$workdir/nfpm.version"
|
||||||
|
grep GitVersion "$workdir/nfpm.version"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "unknown tool: $tool" >&2
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
if [[ -n "${GITHUB_PATH:-}" ]]; then
|
if [[ -n "${GITHUB_PATH:-}" ]]; then
|
||||||
echo "$bindir" >>"$GITHUB_PATH"
|
echo "$bindir" >>"$GITHUB_PATH"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
"$bindir/golangci-lint" version
|
|
||||||
"$bindir/buf" --version
|
|
||||||
"$bindir/shellcheck" --version | head -n 2
|
|
||||||
|
|||||||
Executable
+1848
File diff suppressed because it is too large
Load Diff
Executable
+50
@@ -0,0 +1,50 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
# Renders the systemd unit templates deploy/systemd/*.service.in (ADR 0024).
|
||||||
|
#
|
||||||
|
# Usage: scripts/render-units.sh <bindir> <outdir>
|
||||||
|
# writes <outdir>/<BIN_SERVER>.service, <BIN_AGENT_DNS>.service and
|
||||||
|
# <BIN_AGENT_DHCP>.service with @BINDIR@ = <bindir>.
|
||||||
|
#
|
||||||
|
# Names come from the environment (set by the Makefile, ADR 0018): PRODUCT,
|
||||||
|
# DISPLAY_NAME, BIN_SERVER, BIN_AGENT_DNS, BIN_AGENT_DHCP, ENV_PREFIX.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
if [[ $# -ne 2 ]]; then
|
||||||
|
sed -n '4,11p' "$0" | sed 's/^# \{0,1\}//' >&2
|
||||||
|
exit 2
|
||||||
|
fi
|
||||||
|
bindir="$1"
|
||||||
|
outdir="$2"
|
||||||
|
|
||||||
|
PRODUCT="${PRODUCT:-ddi-suite}"
|
||||||
|
DISPLAY_NAME="${DISPLAY_NAME:-DDI-Suite}"
|
||||||
|
BIN_SERVER="${BIN_SERVER:-ddi-server}"
|
||||||
|
BIN_AGENT_DNS="${BIN_AGENT_DNS:-ddi-agent-dns}"
|
||||||
|
BIN_AGENT_DHCP="${BIN_AGENT_DHCP:-ddi-agent-dhcp}"
|
||||||
|
ENV_PREFIX="${ENV_PREFIX:-DDI_}"
|
||||||
|
|
||||||
|
# Values end up in sed replacements: allow only safe characters.
|
||||||
|
for v in "$bindir" "$PRODUCT" "$BIN_SERVER" "$BIN_AGENT_DNS" "$BIN_AGENT_DHCP" "$ENV_PREFIX"; do
|
||||||
|
[[ "$v" =~ ^[A-Za-z0-9._/+-]+$ ]] || { echo "unsafe value: $v" >&2; exit 2; }
|
||||||
|
done
|
||||||
|
[[ "$DISPLAY_NAME" =~ ^[A-Za-z0-9\ ._+-]+$ ]] || { echo "unsafe display name: $DISPLAY_NAME" >&2; exit 2; }
|
||||||
|
|
||||||
|
src="$(cd "$(dirname "$0")/../deploy/systemd" && pwd)"
|
||||||
|
mkdir -p "$outdir"
|
||||||
|
render() {
|
||||||
|
sed -e "s|@PRODUCT@|$PRODUCT|g" -e "s|@DISPLAY_NAME@|$DISPLAY_NAME|g" \
|
||||||
|
-e "s|@BIN_SERVER@|$BIN_SERVER|g" -e "s|@BIN_AGENT_DNS@|$BIN_AGENT_DNS|g" \
|
||||||
|
-e "s|@BIN_AGENT_DHCP@|$BIN_AGENT_DHCP|g" -e "s|@BINDIR@|$bindir|g" \
|
||||||
|
-e "s|@CONFIG_DIR@|/etc/$PRODUCT|g" -e "s|@ENV_PREFIX@|$ENV_PREFIX|g" \
|
||||||
|
"$src/$1" >"$outdir/$2"
|
||||||
|
if grep -q '@[A-Z_]*@' "$outdir/$2"; then
|
||||||
|
echo "unreplaced placeholder in $2" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
render server.service.in "$BIN_SERVER.service"
|
||||||
|
render agent-dns.service.in "$BIN_AGENT_DNS.service"
|
||||||
|
render agent-dhcp.service.in "$BIN_AGENT_DHCP.service"
|
||||||
Executable
+131
@@ -0,0 +1,131 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
# Signs and verifies release checksums with Ed25519 (ADR 0024, docs/RELEASE.md).
|
||||||
|
# The signature is the raw 64-byte output of
|
||||||
|
# `openssl pkeyutl -sign -rawin` over SHA256SUMS, stored as SHA256SUMS.sig.
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# scripts/sign-release.sh sign SUMS [KEY_FILE]
|
||||||
|
# writes SUMS.sig; without KEY_FILE the PEM private key is taken from
|
||||||
|
# the environment variable RELEASE_SIGNING_KEY (it is written to a
|
||||||
|
# private temporary file and removed again, never printed)
|
||||||
|
# scripts/sign-release.sh verify SUMS SIG PUBLIC_KEY_FILE
|
||||||
|
# exits 0 only if SIG is a valid signature of SUMS
|
||||||
|
# scripts/sign-release.sh public-key KEY_FILE
|
||||||
|
# prints the PEM public key that belongs to a private key
|
||||||
|
# scripts/sign-release.sh selftest
|
||||||
|
# signs and verifies with a throwaway key (CI); a tampered file and a
|
||||||
|
# foreign key must fail
|
||||||
|
#
|
||||||
|
# Requires OpenSSL 3.
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
sed -n '4,21p' "$0" | sed 's/^# \{0,1\}//'
|
||||||
|
}
|
||||||
|
|
||||||
|
die() {
|
||||||
|
echo "$*" >&2
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
command -v openssl >/dev/null || die "openssl is required"
|
||||||
|
|
||||||
|
# sign SUMS KEY_FILE
|
||||||
|
sign_with_file() {
|
||||||
|
local sums="$1" key="$2"
|
||||||
|
[[ -f "$sums" ]] || die "no such file: $sums"
|
||||||
|
[[ -f "$key" ]] || die "no such key file: $key"
|
||||||
|
openssl pkeyutl -sign -rawin -inkey "$key" -in "$sums" -out "${sums}.sig"
|
||||||
|
[[ "$(wc -c <"${sums}.sig")" -eq 64 ]] || die "unexpected signature size (is the key an Ed25519 key?)"
|
||||||
|
echo "signed ${sums} -> ${sums}.sig"
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd_sign() {
|
||||||
|
(($# >= 1 && $# <= 2)) || {
|
||||||
|
usage >&2
|
||||||
|
exit 2
|
||||||
|
}
|
||||||
|
if (($# == 2)); then
|
||||||
|
sign_with_file "$1" "$2"
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
[[ -n "${RELEASE_SIGNING_KEY:-}" ]] || die "RELEASE_SIGNING_KEY is not set and no key file was given"
|
||||||
|
local dir
|
||||||
|
dir="$(umask 077 && mktemp -d)"
|
||||||
|
# shellcheck disable=SC2064 # expand now: $dir is local
|
||||||
|
trap "rm -rf '$dir'" EXIT
|
||||||
|
(umask 077 && printf '%s\n' "$RELEASE_SIGNING_KEY" >"$dir/key.pem")
|
||||||
|
sign_with_file "$1" "$dir/key.pem"
|
||||||
|
rm -rf "$dir"
|
||||||
|
trap - EXIT
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd_verify() {
|
||||||
|
(($# == 3)) || {
|
||||||
|
usage >&2
|
||||||
|
exit 2
|
||||||
|
}
|
||||||
|
local sums="$1" sig="$2" pub="$3"
|
||||||
|
for f in "$sums" "$sig" "$pub"; do
|
||||||
|
[[ -f "$f" ]] || die "no such file: $f"
|
||||||
|
done
|
||||||
|
if openssl pkeyutl -verify -pubin -inkey "$pub" -rawin -in "$sums" -sigfile "$sig" >/dev/null 2>&1; then
|
||||||
|
echo "signature of ${sums} is valid"
|
||||||
|
else
|
||||||
|
die "signature of ${sums} is NOT valid"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd_public_key() {
|
||||||
|
(($# == 1)) || {
|
||||||
|
usage >&2
|
||||||
|
exit 2
|
||||||
|
}
|
||||||
|
openssl pkey -in "$1" -pubout
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd_selftest() {
|
||||||
|
local dir
|
||||||
|
dir="$(umask 077 && mktemp -d)"
|
||||||
|
# shellcheck disable=SC2064 # expand now: $dir is local
|
||||||
|
trap "rm -rf '$dir'" EXIT
|
||||||
|
openssl genpkey -algorithm ed25519 -out "$dir/key.pem" 2>/dev/null
|
||||||
|
openssl pkey -in "$dir/key.pem" -pubout -out "$dir/pub.pem"
|
||||||
|
openssl genpkey -algorithm ed25519 -out "$dir/other.pem" 2>/dev/null
|
||||||
|
openssl pkey -in "$dir/other.pem" -pubout -out "$dir/other-pub.pem"
|
||||||
|
printf '%s example_v0.0.0_linux_amd64.tar.gz\n' "$(printf 'x' | sha256sum | cut -d' ' -f1)" >"$dir/SHA256SUMS"
|
||||||
|
|
||||||
|
# Signing from the environment, as the release workflow does.
|
||||||
|
RELEASE_SIGNING_KEY="$(cat "$dir/key.pem")" bash "$0" sign "$dir/SHA256SUMS" >/dev/null
|
||||||
|
cmd_verify "$dir/SHA256SUMS" "$dir/SHA256SUMS.sig" "$dir/pub.pem" >/dev/null ||
|
||||||
|
die "selftest: valid signature rejected"
|
||||||
|
if bash "$0" verify "$dir/SHA256SUMS" "$dir/SHA256SUMS.sig" "$dir/other-pub.pem" >/dev/null 2>&1; then
|
||||||
|
die "selftest: signature accepted with a foreign key"
|
||||||
|
fi
|
||||||
|
printf 'tampered\n' >>"$dir/SHA256SUMS"
|
||||||
|
if bash "$0" verify "$dir/SHA256SUMS" "$dir/SHA256SUMS.sig" "$dir/pub.pem" >/dev/null 2>&1; then
|
||||||
|
die "selftest: tampered file accepted"
|
||||||
|
fi
|
||||||
|
echo "selftest passed: sign, verify, foreign key and tampered file rejected"
|
||||||
|
}
|
||||||
|
|
||||||
|
(($# >= 1)) || {
|
||||||
|
usage >&2
|
||||||
|
exit 2
|
||||||
|
}
|
||||||
|
cmd="$1"
|
||||||
|
shift
|
||||||
|
case "$cmd" in
|
||||||
|
sign) cmd_sign "$@" ;;
|
||||||
|
verify) cmd_verify "$@" ;;
|
||||||
|
public-key) cmd_public_key "$@" ;;
|
||||||
|
selftest) cmd_selftest "$@" ;;
|
||||||
|
-h | --help | help) usage ;;
|
||||||
|
*)
|
||||||
|
usage >&2
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
+972
-15
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,171 @@
|
|||||||
|
// SPDX-License-Identifier: LicenseRef-DDI-Proprietary
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.beugsiud.de/beug.k/DDI/internal/brand"
|
||||||
|
"git.beugsiud.de/beug.k/DDI/server/internal/app"
|
||||||
|
"git.beugsiud.de/beug.k/DDI/server/internal/config"
|
||||||
|
"git.beugsiud.de/beug.k/DDI/server/internal/service"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Exit codes of `license set-key` besides 0 (stored) and 1 (other errors,
|
||||||
|
// e.g. configuration or database). The installer uses them to decide
|
||||||
|
// whether to warn or to fail.
|
||||||
|
const (
|
||||||
|
exitUsage = 2 // bad arguments, empty or oversized input
|
||||||
|
exitKeyRejected = 3 // the license service rejected the key
|
||||||
|
exitLicenseSvc = 4 // the license service is unreachable or untrusted
|
||||||
|
)
|
||||||
|
|
||||||
|
// maxKeyInput bounds what is read from stdin; maxKeyLength matches the
|
||||||
|
// limit of the license manager.
|
||||||
|
const (
|
||||||
|
maxKeyInput = 4096
|
||||||
|
maxKeyLength = 512
|
||||||
|
)
|
||||||
|
|
||||||
|
// exitError carries a specific exit code.
|
||||||
|
type exitError struct {
|
||||||
|
code int
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *exitError) Error() string { return e.err.Error() }
|
||||||
|
func (e *exitError) Unwrap() error { return e.err }
|
||||||
|
|
||||||
|
func licenseUsage(w io.Writer) {
|
||||||
|
_, _ = fmt.Fprintf(w, `Usage: %[1]s license set-key < keyfile
|
||||||
|
|
||||||
|
set-key read a license key from stdin, validate and activate it online
|
||||||
|
(like PUT /api/v1/license) and print the resulting license state
|
||||||
|
|
||||||
|
Exit codes: 0 activated, 1 other error, 2 empty or oversized input,
|
||||||
|
3 key rejected, 4 license server unreachable (nothing was changed).
|
||||||
|
`, brand.ServerBinary)
|
||||||
|
}
|
||||||
|
|
||||||
|
func cmdLicense(ctx context.Context, args []string, lookup config.LookupFunc, stdin io.Reader, stdout, logOut io.Writer) error {
|
||||||
|
if len(args) == 0 || args[0] == "help" || args[0] == "-h" || args[0] == "--help" {
|
||||||
|
if len(args) == 0 {
|
||||||
|
licenseUsage(logOut)
|
||||||
|
return &exitError{code: exitUsage, err: errors.New("license: missing subcommand")}
|
||||||
|
}
|
||||||
|
licenseUsage(stdout)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
switch args[0] {
|
||||||
|
case "set-key":
|
||||||
|
if len(args) > 1 {
|
||||||
|
return &exitError{code: exitUsage, err: errors.New("license set-key takes no arguments; pass the key on stdin")}
|
||||||
|
}
|
||||||
|
return cmdLicenseSetKey(ctx, lookup, stdin, stdout, logOut)
|
||||||
|
default:
|
||||||
|
licenseUsage(logOut)
|
||||||
|
return &exitError{code: exitUsage, err: fmt.Errorf("license: unknown subcommand %q", args[0])}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// readKey reads the license key from r: trimmed, not empty, bounded.
|
||||||
|
func readKey(r io.Reader) (string, error) {
|
||||||
|
data, err := io.ReadAll(io.LimitReader(r, maxKeyInput+1))
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("read license key from stdin: %w", err)
|
||||||
|
}
|
||||||
|
if len(data) > maxKeyInput {
|
||||||
|
return "", &exitError{code: exitUsage, err: fmt.Errorf("input on stdin is larger than %d bytes; expected a single license key", maxKeyInput)}
|
||||||
|
}
|
||||||
|
key := string(bytes.TrimSpace(data))
|
||||||
|
switch {
|
||||||
|
case key == "":
|
||||||
|
return "", &exitError{code: exitUsage, err: errors.New("no license key on stdin")}
|
||||||
|
case len(key) > maxKeyLength:
|
||||||
|
return "", &exitError{code: exitUsage, err: fmt.Errorf("license key is longer than %d characters", maxKeyLength)}
|
||||||
|
case strings.ContainsAny(key, "\r\n"):
|
||||||
|
return "", &exitError{code: exitUsage, err: errors.New("expected a single license key, got several lines")}
|
||||||
|
}
|
||||||
|
return key, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func cmdLicenseSetKey(ctx context.Context, lookup config.LookupFunc, stdin io.Reader, stdout, logOut io.Writer) error {
|
||||||
|
if f, ok := stdin.(*os.File); ok {
|
||||||
|
if fi, err := f.Stat(); err == nil && fi.Mode()&os.ModeCharDevice != 0 {
|
||||||
|
_, _ = fmt.Fprintln(logOut, "reading the license key from stdin (finish with Ctrl-D)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
key, err := readKey(stdin)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
cfg, log, err := setup(lookup, logOut)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
core, err := app.Open(ctx, cfg, log, true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer core.Close()
|
||||||
|
st, err := core.Service.SetLicenseKey(ctx, service.SystemActor, key)
|
||||||
|
if err != nil {
|
||||||
|
return licenseCLIError(err)
|
||||||
|
}
|
||||||
|
return printLicense(stdout, st)
|
||||||
|
}
|
||||||
|
|
||||||
|
// licenseCLIError maps service errors to messages and exit codes.
|
||||||
|
func licenseCLIError(err error) error {
|
||||||
|
var se *service.Error
|
||||||
|
if !errors.As(err, &se) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
msg := se.Message
|
||||||
|
if pc := se.Params["provider_code"]; pc != "" {
|
||||||
|
msg += " (" + pc + ")"
|
||||||
|
}
|
||||||
|
switch se.Kind {
|
||||||
|
case service.KindUnavailable:
|
||||||
|
return &exitError{code: exitLicenseSvc, err: fmt.Errorf("license key not stored: %s [%s]", msg, se.Code)}
|
||||||
|
case service.KindInvalid, service.KindConflict:
|
||||||
|
return &exitError{code: exitKeyRejected, err: fmt.Errorf("license key rejected: %s [%s]", msg, se.Code)}
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func printLicense(w io.Writer, st service.LicenseStatus) error {
|
||||||
|
limit := func(v *int) string {
|
||||||
|
if v == nil {
|
||||||
|
return "unlimited"
|
||||||
|
}
|
||||||
|
return strconv.Itoa(*v)
|
||||||
|
}
|
||||||
|
day := func(t *time.Time) string {
|
||||||
|
if t == nil {
|
||||||
|
return "never"
|
||||||
|
}
|
||||||
|
return t.UTC().Format(time.RFC3339)
|
||||||
|
}
|
||||||
|
features := strings.Join(st.Features, ", ")
|
||||||
|
if features == "" {
|
||||||
|
features = "-"
|
||||||
|
}
|
||||||
|
name := st.Name
|
||||||
|
if st.LicenseID != "" {
|
||||||
|
name = strings.TrimSpace(name + " (" + st.LicenseID + ")")
|
||||||
|
}
|
||||||
|
_, err := fmt.Fprintf(w, "status: %s\nreason: %s\nlicense: %s\nexpires: %s\n"+
|
||||||
|
"max agents: %s\nmax addresses: %s (in use: %d)\nfeatures: %s\n",
|
||||||
|
st.State, st.Reason, name, day(st.ExpiresAt), limit(st.Limits.MaxAgents), limit(st.Limits.MaxAddresses),
|
||||||
|
st.Usage.Addresses, features)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
// SPDX-License-Identifier: LicenseRef-DDI-Proprietary
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/ed25519"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
const testKeygenAccount = "9de54794-8e94-4250-83f6-87e3d5686a0b"
|
||||||
|
|
||||||
|
// fakeKeygen answers the requests of license activation with signed
|
||||||
|
// responses: "GOOD-KEY" is valid (no machine activation needed), every
|
||||||
|
// other key does not exist.
|
||||||
|
func fakeKeygen(t *testing.T) (url string, pub ed25519.PublicKey) {
|
||||||
|
t.Helper()
|
||||||
|
pub, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
path := strings.TrimPrefix(r.URL.Path, "/v1/accounts/"+testKeygenAccount)
|
||||||
|
body, _ := io.ReadAll(r.Body)
|
||||||
|
var resp any
|
||||||
|
switch {
|
||||||
|
case r.Method == http.MethodPost && path == "/licenses/actions/validate-key":
|
||||||
|
var req struct {
|
||||||
|
Meta struct {
|
||||||
|
Key string `json:"key"`
|
||||||
|
Nonce int64 `json:"nonce"`
|
||||||
|
} `json:"meta"`
|
||||||
|
}
|
||||||
|
_ = json.Unmarshal(body, &req)
|
||||||
|
meta := map[string]any{"valid": false, "code": "NOT_FOUND", "detail": "does not exist", "nonce": req.Meta.Nonce}
|
||||||
|
var data any
|
||||||
|
if req.Meta.Key == "GOOD-KEY" {
|
||||||
|
meta["valid"], meta["code"], meta["detail"] = true, "VALID", "valid"
|
||||||
|
data = map[string]any{"id": "lic-1", "type": "licenses", "attributes": map[string]any{
|
||||||
|
"name": "CLI Test", "expiry": "2030-01-01T00:00:00Z", "status": "ACTIVE",
|
||||||
|
"metadata": map[string]any{"maxAgents": 5},
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
resp = map[string]any{"meta": meta, "data": data}
|
||||||
|
case r.Method == http.MethodGet && path == "/licenses/lic-1/entitlements":
|
||||||
|
resp = map[string]any{"data": []any{map[string]any{"attributes": map[string]any{"code": "HA"}}}}
|
||||||
|
default:
|
||||||
|
w.WriteHeader(http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out, _ := json.Marshal(resp)
|
||||||
|
sum := sha256.Sum256(out)
|
||||||
|
digest := "sha-256=" + base64.StdEncoding.EncodeToString(sum[:])
|
||||||
|
date := time.Now().UTC().Format(http.TimeFormat)
|
||||||
|
signing := "(request-target): " + strings.ToLower(r.Method) + " " + r.URL.RequestURI() + "\nhost: " + r.Host +
|
||||||
|
"\ndate: " + date + "\ndigest: " + digest
|
||||||
|
sig := ed25519.Sign(priv, []byte(signing))
|
||||||
|
w.Header().Set("Date", date)
|
||||||
|
w.Header().Set("Digest", digest)
|
||||||
|
w.Header().Set("Keygen-Signature", `keyid="`+testKeygenAccount+`", algorithm="ed25519", signature="`+
|
||||||
|
base64.StdEncoding.EncodeToString(sig)+`", headers="(request-target) host date digest"`)
|
||||||
|
w.Header().Set("Content-Type", "application/vnd.api+json")
|
||||||
|
_, _ = w.Write(out)
|
||||||
|
}))
|
||||||
|
t.Cleanup(srv.Close)
|
||||||
|
return srv.URL, pub
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReadKey(t *testing.T) {
|
||||||
|
if k, err := readKey(strings.NewReader(" ABCD-1234 \n")); err != nil || k != "ABCD-1234" {
|
||||||
|
t.Errorf("trimmed key: %q %v", k, err)
|
||||||
|
}
|
||||||
|
for name, in := range map[string]string{
|
||||||
|
"empty": "",
|
||||||
|
"blank": " \n\t\n",
|
||||||
|
"too long": strings.Repeat("A", maxKeyLength+1),
|
||||||
|
"oversized": strings.Repeat("A", maxKeyInput+1),
|
||||||
|
"two lines": "KEY-1\nKEY-2\n",
|
||||||
|
"blank line": "KEY-1\r\nKEY-2",
|
||||||
|
} {
|
||||||
|
_, err := readKey(strings.NewReader(in))
|
||||||
|
ee, ok := err.(*exitError) //nolint:errorlint // readKey returns it unwrapped
|
||||||
|
if !ok || ee.code != exitUsage {
|
||||||
|
t.Errorf("%s: %v", name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLicenseCommandUsage(t *testing.T) {
|
||||||
|
var out, errOut bytes.Buffer
|
||||||
|
if code := run(context.Background(), []string{"license"}, lookupFrom(nil), nil, &out, &errOut); code != exitUsage {
|
||||||
|
t.Errorf("without subcommand: %d", code)
|
||||||
|
}
|
||||||
|
if code := run(context.Background(), []string{"license", "frob"}, lookupFrom(nil), nil, &out, &errOut); code != exitUsage {
|
||||||
|
t.Errorf("unknown subcommand: %d", code)
|
||||||
|
}
|
||||||
|
if code := run(context.Background(), []string{"license", "set-key", "KEY"}, lookupFrom(nil), nil, &out, &errOut); code != exitUsage ||
|
||||||
|
!strings.Contains(errOut.String(), "stdin") {
|
||||||
|
t.Errorf("key as argument: %d %q", code, errOut.String())
|
||||||
|
}
|
||||||
|
out.Reset()
|
||||||
|
if code := run(context.Background(), []string{"license", "help"}, lookupFrom(nil), nil, &out, &errOut); code != 0 ||
|
||||||
|
!strings.Contains(out.String(), "set-key") {
|
||||||
|
t.Errorf("help: %d %q", code, out.String())
|
||||||
|
}
|
||||||
|
errOut.Reset()
|
||||||
|
if code := run(context.Background(), []string{"license", "set-key"}, lookupFrom(nil), strings.NewReader("\n"), &out, &errOut); code != exitUsage ||
|
||||||
|
!strings.Contains(errOut.String(), "no license key") {
|
||||||
|
t.Errorf("empty stdin: %d %q", code, errOut.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLicenseSetKey(t *testing.T) {
|
||||||
|
dbURL := testDatabase(t)
|
||||||
|
dir := t.TempDir()
|
||||||
|
keyFile := filepath.Join(dir, "master.key")
|
||||||
|
if code := run(context.Background(), []string{"gen-master-key", "-out", keyFile}, lookupFrom(nil), nil, io.Discard, io.Discard); code != 0 {
|
||||||
|
t.Fatal("gen-master-key failed")
|
||||||
|
}
|
||||||
|
keygenURL, pub := fakeKeygen(t)
|
||||||
|
env := map[string]string{
|
||||||
|
"DDI_DATABASE_URL": dbURL, "DDI_MASTER_KEY_FILE": keyFile, "DDI_STATE_DIR": dir, "DDI_LOG_LEVEL": "error",
|
||||||
|
"KEYGEN_URL": keygenURL, "KEYGEN_ACCOUNT_ID": testKeygenAccount, "KEYGEN_PUBLIC_KEY": hex.EncodeToString(pub),
|
||||||
|
}
|
||||||
|
setKey := func(key string, env map[string]string) (int, string, string) {
|
||||||
|
var out, errOut bytes.Buffer
|
||||||
|
code := run(context.Background(), []string{"license", "set-key"}, lookupFrom(env), strings.NewReader(key), &out, &errOut)
|
||||||
|
return code, out.String(), errOut.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
code, out, errOut := setKey("UNKNOWN-KEY\n", env)
|
||||||
|
if code != exitKeyRejected || !strings.Contains(errOut, "license_invalid") || !strings.Contains(errOut, "NOT_FOUND") {
|
||||||
|
t.Errorf("unknown key: %d %q", code, errOut)
|
||||||
|
}
|
||||||
|
if strings.Contains(out+errOut, "UNKNOWN-KEY") {
|
||||||
|
t.Error("the key must not be printed")
|
||||||
|
}
|
||||||
|
|
||||||
|
unreachable := map[string]string{}
|
||||||
|
for k, v := range env {
|
||||||
|
unreachable[k] = v
|
||||||
|
}
|
||||||
|
unreachable["KEYGEN_URL"] = "http://127.0.0.1:1"
|
||||||
|
if code, _, errOut := setKey("GOOD-KEY", unreachable); code != exitLicenseSvc || !strings.Contains(errOut, "license_server_unreachable") {
|
||||||
|
t.Errorf("unreachable license server: %d %q", code, errOut)
|
||||||
|
}
|
||||||
|
|
||||||
|
code, out, errOut = setKey(" GOOD-KEY\n", env)
|
||||||
|
if code != 0 {
|
||||||
|
t.Fatalf("set-key: %d %s", code, errOut)
|
||||||
|
}
|
||||||
|
for _, want := range []string{"status: valid", "CLI Test (lic-1)", "expires: 2030-01-01T00:00:00Z",
|
||||||
|
"max agents: 5", "max addresses: unlimited", "features: HA"} {
|
||||||
|
if !strings.Contains(out, want) {
|
||||||
|
t.Errorf("output lacks %q:\n%s", want, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(out+errOut, "GOOD-KEY") {
|
||||||
|
t.Error("the key must not be printed")
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := pgx.Connect(context.Background(), dbURL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer conn.Close(context.Background()) //nolint:errcheck // test
|
||||||
|
var actor string
|
||||||
|
var n int
|
||||||
|
if err := conn.QueryRow(context.Background(),
|
||||||
|
`SELECT min(actor_name), count(*) FROM audit_log WHERE action = 'license.set_key'`).Scan(&actor, &n); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if n != 1 || actor != "system" {
|
||||||
|
t.Errorf("audit: %d entries by %q", n, actor)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -26,7 +26,7 @@ import (
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
code := run(ctx, os.Args[1:], os.LookupEnv, os.Stdout, os.Stderr)
|
code := run(ctx, os.Args[1:], os.LookupEnv, os.Stdin, os.Stdout, os.Stderr)
|
||||||
stop()
|
stop()
|
||||||
os.Exit(code)
|
os.Exit(code)
|
||||||
}
|
}
|
||||||
@@ -39,15 +39,16 @@ Commands:
|
|||||||
migrate apply database migrations and exit
|
migrate apply database migrations and exit
|
||||||
bootstrap-admin create the first administrator and print its one-time password
|
bootstrap-admin create the first administrator and print its one-time password
|
||||||
gen-master-key write a new master key file (refuses to overwrite)
|
gen-master-key write a new master key file (refuses to overwrite)
|
||||||
|
license set-key read a license key from stdin and activate it (%[1]s license help)
|
||||||
version print version information
|
version print version information
|
||||||
help show this help
|
help show this help
|
||||||
|
|
||||||
Configuration: YAML file from $DDI_CONFIG_FILE (if set), overridden by
|
Configuration: YAML file from $%[2]s (if set), overridden by
|
||||||
environment variables; see docs/ARCHITECTURE.md.
|
environment variables; see docs/ARCHITECTURE.md.
|
||||||
`, brand.ServerBinary)
|
`, brand.ServerBinary, config.EnvName("CONFIG_FILE"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func run(ctx context.Context, args []string, lookup config.LookupFunc, stdout, stderr io.Writer) int {
|
func run(ctx context.Context, args []string, lookup config.LookupFunc, stdin io.Reader, stdout, stderr io.Writer) int {
|
||||||
cmd := "serve"
|
cmd := "serve"
|
||||||
if len(args) > 0 {
|
if len(args) > 0 {
|
||||||
cmd, args = args[0], args[1:]
|
cmd, args = args[0], args[1:]
|
||||||
@@ -62,6 +63,8 @@ func run(ctx context.Context, args []string, lookup config.LookupFunc, stdout, s
|
|||||||
err = cmdBootstrapAdmin(ctx, args, lookup, stdout, stderr)
|
err = cmdBootstrapAdmin(ctx, args, lookup, stdout, stderr)
|
||||||
case "gen-master-key":
|
case "gen-master-key":
|
||||||
err = cmdGenMasterKey(args, lookup, stdout)
|
err = cmdGenMasterKey(args, lookup, stdout)
|
||||||
|
case "license":
|
||||||
|
err = cmdLicense(ctx, args, lookup, stdin, stdout, stderr)
|
||||||
case "version", "--version":
|
case "version", "--version":
|
||||||
err = buildinfo.Print(stdout, brand.ServerBinary)
|
err = buildinfo.Print(stdout, brand.ServerBinary)
|
||||||
case "help", "-h", "--help":
|
case "help", "-h", "--help":
|
||||||
@@ -73,6 +76,9 @@ func run(ctx context.Context, args []string, lookup config.LookupFunc, stdout, s
|
|||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
_, _ = fmt.Fprintf(stderr, "%s: %v\n", brand.ServerBinary, err)
|
_, _ = fmt.Fprintf(stderr, "%s: %v\n", brand.ServerBinary, err)
|
||||||
|
if ee, ok := errors.AsType[*exitError](err); ok {
|
||||||
|
return ee.code
|
||||||
|
}
|
||||||
return 1
|
return 1
|
||||||
}
|
}
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
@@ -28,28 +28,28 @@ func lookupFrom(m map[string]string) func(string) (string, bool) {
|
|||||||
|
|
||||||
func TestRunVersionAndHelp(t *testing.T) {
|
func TestRunVersionAndHelp(t *testing.T) {
|
||||||
var out, errOut bytes.Buffer
|
var out, errOut bytes.Buffer
|
||||||
if code := run(context.Background(), []string{"version"}, lookupFrom(nil), &out, &errOut); code != 0 {
|
if code := run(context.Background(), []string{"version"}, lookupFrom(nil), nil, &out, &errOut); code != 0 {
|
||||||
t.Fatalf("version exit code %d", code)
|
t.Fatalf("version exit code %d", code)
|
||||||
}
|
}
|
||||||
if !strings.HasPrefix(out.String(), "ddi-server ") {
|
if !strings.HasPrefix(out.String(), "ddi-server ") {
|
||||||
t.Errorf("version output %q", out.String())
|
t.Errorf("version output %q", out.String())
|
||||||
}
|
}
|
||||||
out.Reset()
|
out.Reset()
|
||||||
if code := run(context.Background(), []string{"help"}, lookupFrom(nil), &out, &errOut); code != 0 || !strings.Contains(out.String(), "bootstrap-admin") {
|
if code := run(context.Background(), []string{"help"}, lookupFrom(nil), nil, &out, &errOut); code != 0 || !strings.Contains(out.String(), "bootstrap-admin") {
|
||||||
t.Errorf("help: code %d, output %q", code, out.String())
|
t.Errorf("help: code %d, output %q", code, out.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRunUnknownCommand(t *testing.T) {
|
func TestRunUnknownCommand(t *testing.T) {
|
||||||
var out, errOut bytes.Buffer
|
var out, errOut bytes.Buffer
|
||||||
if code := run(context.Background(), []string{"frobnicate"}, lookupFrom(nil), &out, &errOut); code != 2 {
|
if code := run(context.Background(), []string{"frobnicate"}, lookupFrom(nil), nil, &out, &errOut); code != 2 {
|
||||||
t.Errorf("exit code %d, want 2", code)
|
t.Errorf("exit code %d, want 2", code)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRunInvalidConfig(t *testing.T) {
|
func TestRunInvalidConfig(t *testing.T) {
|
||||||
var errOut bytes.Buffer
|
var errOut bytes.Buffer
|
||||||
code := run(context.Background(), []string{"serve"}, lookupFrom(map[string]string{"DDI_HTTP_LISTEN": "bad"}), io.Discard, &errOut)
|
code := run(context.Background(), []string{"serve"}, lookupFrom(map[string]string{"DDI_HTTP_LISTEN": "bad"}), nil, io.Discard, &errOut)
|
||||||
if code != 1 || !strings.Contains(errOut.String(), "invalid configuration") {
|
if code != 1 || !strings.Contains(errOut.String(), "invalid configuration") {
|
||||||
t.Errorf("code %d, stderr %q", code, errOut.String())
|
t.Errorf("code %d, stderr %q", code, errOut.String())
|
||||||
}
|
}
|
||||||
@@ -58,7 +58,7 @@ func TestRunInvalidConfig(t *testing.T) {
|
|||||||
func TestServeFailsWithoutMasterKey(t *testing.T) {
|
func TestServeFailsWithoutMasterKey(t *testing.T) {
|
||||||
var errOut bytes.Buffer
|
var errOut bytes.Buffer
|
||||||
env := map[string]string{"DDI_MASTER_KEY_FILE": filepath.Join(t.TempDir(), "missing.key"), "DDI_DATABASE_URL": "postgres://x"}
|
env := map[string]string{"DDI_MASTER_KEY_FILE": filepath.Join(t.TempDir(), "missing.key"), "DDI_DATABASE_URL": "postgres://x"}
|
||||||
if code := run(context.Background(), []string{"serve"}, lookupFrom(env), io.Discard, &errOut); code != 1 || !strings.Contains(errOut.String(), "master key") {
|
if code := run(context.Background(), []string{"serve"}, lookupFrom(env), nil, io.Discard, &errOut); code != 1 || !strings.Contains(errOut.String(), "master key") {
|
||||||
t.Errorf("code %d, stderr %q", code, errOut.String())
|
t.Errorf("code %d, stderr %q", code, errOut.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -66,14 +66,14 @@ func TestServeFailsWithoutMasterKey(t *testing.T) {
|
|||||||
func TestGenMasterKey(t *testing.T) {
|
func TestGenMasterKey(t *testing.T) {
|
||||||
path := filepath.Join(t.TempDir(), "sub", "master.key")
|
path := filepath.Join(t.TempDir(), "sub", "master.key")
|
||||||
var out, errOut bytes.Buffer
|
var out, errOut bytes.Buffer
|
||||||
if code := run(context.Background(), []string{"gen-master-key", "-out", path}, lookupFrom(nil), &out, &errOut); code != 0 {
|
if code := run(context.Background(), []string{"gen-master-key", "-out", path}, lookupFrom(nil), nil, &out, &errOut); code != 0 {
|
||||||
t.Fatalf("code %d: %s", code, errOut.String())
|
t.Fatalf("code %d: %s", code, errOut.String())
|
||||||
}
|
}
|
||||||
data, err := os.ReadFile(path)
|
data, err := os.ReadFile(path)
|
||||||
if err != nil || !strings.Contains(string(data), "k1 ") {
|
if err != nil || !strings.Contains(string(data), "k1 ") {
|
||||||
t.Fatalf("key file: %q %v", data, err)
|
t.Fatalf("key file: %q %v", data, err)
|
||||||
}
|
}
|
||||||
if code := run(context.Background(), []string{"gen-master-key", "-out", path}, lookupFrom(nil), &out, &errOut); code != 1 {
|
if code := run(context.Background(), []string{"gen-master-key", "-out", path}, lookupFrom(nil), nil, &out, &errOut); code != 1 {
|
||||||
t.Error("existing key file must not be overwritten")
|
t.Error("existing key file must not be overwritten")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -141,7 +141,7 @@ func TestServeEndToEnd(t *testing.T) {
|
|||||||
dbURL := testDatabase(t)
|
dbURL := testDatabase(t)
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
keyFile := filepath.Join(dir, "master.key")
|
keyFile := filepath.Join(dir, "master.key")
|
||||||
if code := run(context.Background(), []string{"gen-master-key", "-out", keyFile}, lookupFrom(nil), io.Discard, io.Discard); code != 0 {
|
if code := run(context.Background(), []string{"gen-master-key", "-out", keyFile}, lookupFrom(nil), nil, io.Discard, io.Discard); code != 0 {
|
||||||
t.Fatal("gen-master-key failed")
|
t.Fatal("gen-master-key failed")
|
||||||
}
|
}
|
||||||
addr := freeAddr(t)
|
addr := freeAddr(t)
|
||||||
@@ -152,20 +152,20 @@ func TestServeEndToEnd(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var out bytes.Buffer
|
var out bytes.Buffer
|
||||||
if code := run(context.Background(), []string{"bootstrap-admin", "-username", "root"}, lookupFrom(env), &out, io.Discard); code != 0 {
|
if code := run(context.Background(), []string{"bootstrap-admin", "-username", "root"}, lookupFrom(env), nil, &out, io.Discard); code != 0 {
|
||||||
t.Fatalf("bootstrap-admin failed: %s", out.String())
|
t.Fatalf("bootstrap-admin failed: %s", out.String())
|
||||||
}
|
}
|
||||||
if !strings.Contains(out.String(), "username: root") || !strings.Contains(out.String(), "password: ") {
|
if !strings.Contains(out.String(), "username: root") || !strings.Contains(out.String(), "password: ") {
|
||||||
t.Errorf("bootstrap output %q", out.String())
|
t.Errorf("bootstrap output %q", out.String())
|
||||||
}
|
}
|
||||||
if code := run(context.Background(), []string{"bootstrap-admin"}, lookupFrom(env), io.Discard, io.Discard); code != 1 {
|
if code := run(context.Background(), []string{"bootstrap-admin"}, lookupFrom(env), nil, io.Discard, io.Discard); code != 1 {
|
||||||
t.Error("second bootstrap must fail")
|
t.Error("second bootstrap must fail")
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
done := make(chan int, 1)
|
done := make(chan int, 1)
|
||||||
var logs bytes.Buffer
|
var logs bytes.Buffer
|
||||||
go func() { done <- run(ctx, []string{"serve"}, lookupFrom(env), io.Discard, &syncWriter{w: &logs}) }()
|
go func() { done <- run(ctx, []string{"serve"}, lookupFrom(env), nil, io.Discard, &syncWriter{w: &logs}) }()
|
||||||
|
|
||||||
base := fmt.Sprintf("http://%s", addr)
|
base := fmt.Sprintf("http://%s", addr)
|
||||||
get := func(path string) (int, string) {
|
get := func(path string) (int, string) {
|
||||||
|
|||||||
@@ -0,0 +1,129 @@
|
|||||||
|
// SPDX-License-Identifier: LicenseRef-DDI-Proprietary
|
||||||
|
|
||||||
|
package agentapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/netip"
|
||||||
|
"strconv"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"google.golang.org/grpc/codes"
|
||||||
|
"google.golang.org/protobuf/types/known/timestamppb"
|
||||||
|
|
||||||
|
agentv1 "git.beugsiud.de/beug.k/DDI/proto/gen/ddi/agent/v1"
|
||||||
|
"git.beugsiud.de/beug.k/DDI/server/internal/ipam"
|
||||||
|
"git.beugsiud.de/beug.k/DDI/server/internal/service"
|
||||||
|
)
|
||||||
|
|
||||||
|
// connect opens a stream, sends Hello and returns the Welcome.
|
||||||
|
func connect(t *testing.T, a *testAgent, applied uint64) (agentv1.AgentService_ConnectClient, *agentv1.Welcome) {
|
||||||
|
t.Helper()
|
||||||
|
stream, err := a.client.Connect(ctxT(t))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := stream.Send(&agentv1.ConnectRequest{Message: &agentv1.ConnectRequest_Hello{Hello: &agentv1.Hello{
|
||||||
|
AppliedRevision: applied, LastGoodRevision: applied}}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
msg, err := stream.Recv()
|
||||||
|
if err != nil || msg.GetWelcome() == nil {
|
||||||
|
t.Fatalf("welcome %v %v", msg, err)
|
||||||
|
}
|
||||||
|
return stream, msg.GetWelcome()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPushModesAndReports(t *testing.T) {
|
||||||
|
e := newTestEnv(t)
|
||||||
|
ctx := ctxT(t)
|
||||||
|
a := e.enroll("dns")
|
||||||
|
e.configureGenerator(3600)
|
||||||
|
if _, _, err := e.svc.CreateRevision(ctx, service.SystemActor, ""); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ag, err := e.svc.SetAgentMode(ctx, service.SystemActor, a.id, "manual"); err != nil || ag.TargetRevision != 1 {
|
||||||
|
t.Fatalf("mode %+v %v", ag, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A push while the agent is offline is announced by polling ...
|
||||||
|
targets, err := e.svc.DeployRevision(ctx, service.SystemActor, 1, []string{a.id})
|
||||||
|
if err != nil || len(targets) != 1 || targets[0].Sent {
|
||||||
|
t.Fatalf("deploy %+v %v", targets, err)
|
||||||
|
}
|
||||||
|
id := strconv.FormatInt(targets[0].DeploymentID, 10)
|
||||||
|
st, err := a.client.GetDesiredState(ctx, &agentv1.GetDesiredStateRequest{})
|
||||||
|
if err != nil || st.GetDeploymentId() != id || st.GetDesiredRevision() != 1 || st.GetMode() != agentv1.OperatingMode_OPERATING_MODE_MANUAL {
|
||||||
|
t.Fatalf("desired state %v %v", st, err)
|
||||||
|
}
|
||||||
|
// ... and sent again when it connects.
|
||||||
|
stream, w := connect(t, a, 0)
|
||||||
|
if w.GetMode() != agentv1.OperatingMode_OPERATING_MODE_MANUAL || w.GetDesiredRevision() != 1 {
|
||||||
|
t.Errorf("welcome %v", w)
|
||||||
|
}
|
||||||
|
msg, err := stream.Recv()
|
||||||
|
if err != nil || msg.GetCommand().GetApplyRevision().GetRevision() != 1 || msg.GetCommand().GetApplyRevision().GetDeploymentId() != id {
|
||||||
|
t.Fatalf("pending push %v %v", msg, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The report completes the deployment; it is not announced any more and
|
||||||
|
// a resent report is accepted without changes.
|
||||||
|
report := &agentv1.ReportDeploymentRequest{DeploymentId: id, Revision: 1,
|
||||||
|
Trigger: agentv1.DeploymentTrigger_DEPLOYMENT_TRIGGER_PUSH, Outcome: agentv1.DeploymentOutcome_DEPLOYMENT_OUTCOME_SUCCEEDED,
|
||||||
|
ActiveRevision: 1, StartedAt: timestamppb.New(time.Now().Add(-time.Second)), FinishedAt: timestamppb.Now()}
|
||||||
|
for range 2 {
|
||||||
|
if _, err := a.client.ReportDeployment(ctx, report); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
deps, err := e.svc.ListDeployments(ctx, service.DeploymentFilter{AgentID: a.id})
|
||||||
|
if err != nil || len(deps.Items) != 1 || deps.Items[0].Outcome != "succeeded" || deps.Items[0].FinishedAt == nil ||
|
||||||
|
deps.Items[0].RequestedByName != "system" {
|
||||||
|
t.Fatalf("deployments %+v %v", deps, err)
|
||||||
|
}
|
||||||
|
if st, err := a.client.GetDesiredState(ctx, &agentv1.GetDesiredStateRequest{}); err != nil || st.GetDeploymentId() != "" {
|
||||||
|
t.Errorf("desired state after report %v %v", st, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A manual agent gets no new revisions, but a push while connected.
|
||||||
|
var netID string
|
||||||
|
if err := e.st.Pool().QueryRow(ctx, `SELECT id FROM networks`).Scan(&netID); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := e.svc.CreateAddress(ctx, service.SystemActor, service.AddressInput{NetworkID: netID,
|
||||||
|
IP: netip.MustParseAddr("192.0.2.10"), Type: ipam.TypeStatic, Hostname: "www"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if rev, created, err := e.svc.CreateRevision(ctx, service.SystemActor, ""); err != nil || !created || rev.Number != 2 {
|
||||||
|
t.Fatalf("revision 2 %+v %v %v", rev, created, err)
|
||||||
|
}
|
||||||
|
targets, err = e.svc.DeployRevision(ctx, service.SystemActor, 2, nil)
|
||||||
|
if err != nil || len(targets) != 1 || !targets[0].Sent {
|
||||||
|
t.Fatalf("push %+v %v", targets, err)
|
||||||
|
}
|
||||||
|
msg, err = stream.Recv()
|
||||||
|
if err != nil || msg.GetCommand().GetApplyRevision().GetRevision() != 2 ||
|
||||||
|
msg.GetCommand().GetApplyRevision().GetDeploymentId() != strconv.FormatInt(targets[0].DeploymentID, 10) {
|
||||||
|
t.Fatalf("push command %v %v", msg, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A mode change reconnects the agent with the new mode.
|
||||||
|
if _, err := e.svc.SetAgentMode(ctx, service.SystemActor, a.id, "auto_pull"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, err = stream.Recv()
|
||||||
|
wantCode(t, err, codes.Unavailable)
|
||||||
|
stream, w = connect(t, a, 1)
|
||||||
|
if w.GetMode() != agentv1.OperatingMode_OPERATING_MODE_AUTO_PULL || w.GetDesiredRevision() != 2 {
|
||||||
|
t.Errorf("welcome after mode change %v", w)
|
||||||
|
}
|
||||||
|
// The open push of revision 2 is still pending (the desired revision).
|
||||||
|
msg, err = stream.Recv()
|
||||||
|
if err != nil || msg.GetCommand().GetApplyRevision().GetRevision() != 2 {
|
||||||
|
t.Errorf("open push after reconnect %v %v", msg, err)
|
||||||
|
}
|
||||||
|
eventually(t, "connected", func() bool { return e.hub.Connected(a.id) })
|
||||||
|
if err := stream.CloseSend(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -116,6 +116,7 @@ func (s *Server) GetDesiredState(ctx context.Context, _ *agentv1.GetDesiredState
|
|||||||
}
|
}
|
||||||
return &agentv1.GetDesiredStateResponse{
|
return &agentv1.GetDesiredStateResponse{
|
||||||
DesiredRevision: st.DesiredRevision, Mode: modeProto(st.Mode), PullInterval: durationpb.New(service.PullInterval),
|
DesiredRevision: st.DesiredRevision, Mode: modeProto(st.Mode), PullInterval: durationpb.New(service.PullInterval),
|
||||||
|
DeploymentId: st.PushDeploymentID,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -123,7 +124,7 @@ func (s *Server) GetDesiredState(ctx context.Context, _ *agentv1.GetDesiredState
|
|||||||
// for the calling agent and its role; equal input gives equal bytes.
|
// for the calling agent and its role; equal input gives equal bytes.
|
||||||
func (s *Server) FetchBundle(ctx context.Context, req *agentv1.FetchBundleRequest) (*agentv1.FetchBundleResponse, error) {
|
func (s *Server) FetchBundle(ctx context.Context, req *agentv1.FetchBundleRequest) (*agentv1.FetchBundleResponse, error) {
|
||||||
c := callerFrom(ctx)
|
c := callerFrom(ctx)
|
||||||
createdAt, arts, err := s.svc.RevisionArtifacts(ctx, req.GetRevision(), c.Role)
|
createdAt, arts, err := s.svc.RevisionArtifacts(ctx, req.GetRevision(), c.Role, c.AgentID)
|
||||||
if errors.Is(err, service.ErrNotFound) {
|
if errors.Is(err, service.ErrNotFound) {
|
||||||
return nil, status.Errorf(codes.NotFound, "revision %d does not exist", req.GetRevision())
|
return nil, status.Errorf(codes.NotFound, "revision %d does not exist", req.GetRevision())
|
||||||
}
|
}
|
||||||
@@ -240,7 +241,10 @@ func (s *Server) Connect(stream agentv1.AgentService_ConnectServer) error {
|
|||||||
// Register before reading the desired revision, so that a revision
|
// Register before reading the desired revision, so that a revision
|
||||||
// created in between is pushed rather than missed.
|
// created in between is pushed rather than missed.
|
||||||
conn := s.hub.Attach(c.AgentID, c.Role, c.Mode)
|
conn := s.hub.Attach(c.AgentID, c.Role, c.Mode)
|
||||||
defer s.hub.Detach(conn)
|
defer func() {
|
||||||
|
s.hub.Detach(conn)
|
||||||
|
s.svc.AgentDisconnected(c.AgentID)
|
||||||
|
}()
|
||||||
settings, err := s.svc.AgentHello(ctx, c.AgentID, service.HelloInput{
|
settings, err := s.svc.AgentHello(ctx, c.AgentID, service.HelloInput{
|
||||||
Hostname: hello.GetHostname(), AgentVersion: hello.GetAgentVersion(), ServiceVersion: hello.GetServiceVersion(),
|
Hostname: hello.GetHostname(), AgentVersion: hello.GetAgentVersion(), ServiceVersion: hello.GetServiceVersion(),
|
||||||
AppliedRevision: hello.GetAppliedRevision(), LastGoodRevision: hello.GetLastGoodRevision(),
|
AppliedRevision: hello.GetAppliedRevision(), LastGoodRevision: hello.GetLastGoodRevision(),
|
||||||
@@ -249,6 +253,9 @@ func (s *Server) Connect(stream agentv1.AgentService_ConnectServer) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
// The mode read with Hello is the one Welcome announces; it may be
|
||||||
|
// newer than the one from the authentication (a concurrent mode change).
|
||||||
|
s.hub.SetMode(c.AgentID, settings.Mode)
|
||||||
if err := stream.Send(&agentv1.ConnectResponse{Message: &agentv1.ConnectResponse_Welcome{Welcome: &agentv1.Welcome{
|
if err := stream.Send(&agentv1.ConnectResponse{Message: &agentv1.ConnectResponse_Welcome{Welcome: &agentv1.Welcome{
|
||||||
Mode: modeProto(settings.Mode), PullInterval: durationpb.New(service.PullInterval),
|
Mode: modeProto(settings.Mode), PullInterval: durationpb.New(service.PullInterval),
|
||||||
HeartbeatInterval: durationpb.New(service.HeartbeatInterval), DesiredRevision: settings.DesiredRevision,
|
HeartbeatInterval: durationpb.New(service.HeartbeatInterval), DesiredRevision: settings.DesiredRevision,
|
||||||
@@ -259,6 +266,18 @@ func (s *Server) Connect(stream agentv1.AgentService_ConnectServer) error {
|
|||||||
slog.String("role", c.Role), slog.Uint64("applied_revision", hello.GetAppliedRevision()),
|
slog.String("role", c.Role), slog.Uint64("applied_revision", hello.GetAppliedRevision()),
|
||||||
slog.Uint64("desired_revision", settings.DesiredRevision))
|
slog.Uint64("desired_revision", settings.DesiredRevision))
|
||||||
|
|
||||||
|
// An open push is sent again: the agent may have missed it while it was
|
||||||
|
// offline (ADR 0022). Only the latest one is still pending.
|
||||||
|
if settings.PushDeploymentID != "" {
|
||||||
|
cmd := agenthub.ApplyCommand(settings.DesiredRevision, settings.PushDeploymentID)
|
||||||
|
if err := stream.Send(&agentv1.ConnectResponse{Message: &agentv1.ConnectResponse_Command{Command: cmd}}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s.log.Info("pending push sent", slog.String("request_id", c.RequestID), slog.String("agent_id", c.AgentID),
|
||||||
|
slog.String("command_id", cmd.GetCommandId()), slog.Uint64("revision", settings.DesiredRevision),
|
||||||
|
slog.String("deployment_id", settings.PushDeploymentID))
|
||||||
|
}
|
||||||
|
|
||||||
recvErr := make(chan error, 1)
|
recvErr := make(chan error, 1)
|
||||||
go func() {
|
go func() {
|
||||||
for {
|
for {
|
||||||
|
|||||||
@@ -29,7 +29,10 @@ const (
|
|||||||
ReasonDeleted = "agent deleted"
|
ReasonDeleted = "agent deleted"
|
||||||
ReasonReplaced = "replaced by a newer connection"
|
ReasonReplaced = "replaced by a newer connection"
|
||||||
ReasonShutdown = "server shutting down"
|
ReasonShutdown = "server shutting down"
|
||||||
reasonEnded = "stream ended"
|
// ReasonModeChanged closes the stream after a mode change; the agent
|
||||||
|
// reconnects and receives the new mode in Welcome (ADR 0022).
|
||||||
|
ReasonModeChanged = "operating mode changed"
|
||||||
|
reasonEnded = "stream ended"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Hub is the registry of open streams. It is safe for concurrent use.
|
// Hub is the registry of open streams. It is safe for concurrent use.
|
||||||
@@ -126,6 +129,16 @@ func (h *Hub) Disconnect(agentID, reason string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetMode updates the mode of the agent's open stream (the mode the agent
|
||||||
|
// was told in Welcome), which decides whether new revisions are pushed.
|
||||||
|
func (h *Hub) SetMode(agentID, mode string) {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
if c := h.conns[agentID]; c != nil {
|
||||||
|
c.Mode = mode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Count returns the number of open streams per role.
|
// Count returns the number of open streams per role.
|
||||||
func (h *Hub) Count() map[string]int {
|
func (h *Hub) Count() map[string]int {
|
||||||
h.mu.Lock()
|
h.mu.Lock()
|
||||||
@@ -150,21 +163,42 @@ func (h *Hub) NotifyRevision(revision uint64) int {
|
|||||||
h.mu.Unlock()
|
h.mu.Unlock()
|
||||||
n := 0
|
n := 0
|
||||||
for _, c := range targets {
|
for _, c := range targets {
|
||||||
cmd := &agentv1.Command{
|
if c.enqueue(ApplyCommand(revision, NewID())) {
|
||||||
CommandId: NewID(),
|
|
||||||
Action: &agentv1.Command_ApplyRevision{ApplyRevision: &agentv1.ApplyRevisionCommand{
|
|
||||||
Revision: revision, DeploymentId: NewID(),
|
|
||||||
}},
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case c.cmds <- cmd:
|
|
||||||
n++
|
n++
|
||||||
default: // queue full: the agent will pull
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return n
|
return n
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ApplyCommand builds an ApplyRevisionCommand with a new command ID.
|
||||||
|
func ApplyCommand(revision uint64, deploymentID string) *agentv1.Command {
|
||||||
|
return &agentv1.Command{
|
||||||
|
CommandId: NewID(),
|
||||||
|
Action: &agentv1.Command_ApplyRevision{ApplyRevision: &agentv1.ApplyRevisionCommand{
|
||||||
|
Revision: revision, DeploymentId: deploymentID,
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send queues cmd for the agent's stream and reports whether it has one
|
||||||
|
// (and its queue had room). Without, the agent picks the work up when it
|
||||||
|
// reconnects or polls.
|
||||||
|
func (h *Hub) Send(agentID string, cmd *agentv1.Command) bool {
|
||||||
|
h.mu.Lock()
|
||||||
|
c := h.conns[agentID]
|
||||||
|
h.mu.Unlock()
|
||||||
|
return c != nil && c.enqueue(cmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Conn) enqueue(cmd *agentv1.Command) bool {
|
||||||
|
select {
|
||||||
|
case c.cmds <- cmd:
|
||||||
|
return true
|
||||||
|
default: // queue full: the agent will pull
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// NewID returns a random UUID (version 4) in canonical lowercase form.
|
// NewID returns a random UUID (version 4) in canonical lowercase form.
|
||||||
func NewID() string {
|
func NewID() string {
|
||||||
var b [16]byte
|
var b [16]byte
|
||||||
|
|||||||
@@ -61,3 +61,33 @@ func TestHub(t *testing.T) {
|
|||||||
}
|
}
|
||||||
h.Disconnect("unknown", "x") // no-op
|
h.Disconnect("unknown", "x") // no-op
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSend(t *testing.T) {
|
||||||
|
h := New()
|
||||||
|
if h.Send("m", ApplyCommand(3, "12")) {
|
||||||
|
t.Error("sent to an agent without stream")
|
||||||
|
}
|
||||||
|
m := h.Attach("m", "dns", ModeManual)
|
||||||
|
if !h.Send("m", ApplyCommand(3, "12")) {
|
||||||
|
t.Fatal("not sent")
|
||||||
|
}
|
||||||
|
cmd := <-m.Commands()
|
||||||
|
if cmd.GetApplyRevision().GetRevision() != 3 || cmd.GetApplyRevision().GetDeploymentId() != "12" ||
|
||||||
|
!agentpki.ValidAgentID(cmd.GetCommandId()) {
|
||||||
|
t.Errorf("command %v", cmd)
|
||||||
|
}
|
||||||
|
for range queueSize {
|
||||||
|
h.Send("m", ApplyCommand(4, "13"))
|
||||||
|
}
|
||||||
|
if h.Send("m", ApplyCommand(5, "14")) {
|
||||||
|
t.Error("sent to a full queue")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only streams in auto_pull mode get new revisions.
|
||||||
|
x := h.Attach("x", "dhcp", ModeAutoPull)
|
||||||
|
h.SetMode("x", ModeManual)
|
||||||
|
h.SetMode("unknown", ModeManual) // no-op
|
||||||
|
if n := h.NotifyRevision(9); n != 0 || len(x.Commands()) != 0 {
|
||||||
|
t.Errorf("manual stream notified: %d", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import (
|
|||||||
"git.beugsiud.de/beug.k/DDI/server/internal/agentapi"
|
"git.beugsiud.de/beug.k/DDI/server/internal/agentapi"
|
||||||
"git.beugsiud.de/beug.k/DDI/server/internal/agenthub"
|
"git.beugsiud.de/beug.k/DDI/server/internal/agenthub"
|
||||||
"git.beugsiud.de/beug.k/DDI/server/internal/config"
|
"git.beugsiud.de/beug.k/DDI/server/internal/config"
|
||||||
|
"git.beugsiud.de/beug.k/DDI/server/internal/events"
|
||||||
"git.beugsiud.de/beug.k/DDI/server/internal/httpapi"
|
"git.beugsiud.de/beug.k/DDI/server/internal/httpapi"
|
||||||
"git.beugsiud.de/beug.k/DDI/server/internal/httpserver"
|
"git.beugsiud.de/beug.k/DDI/server/internal/httpserver"
|
||||||
"git.beugsiud.de/beug.k/DDI/server/internal/license"
|
"git.beugsiud.de/beug.k/DDI/server/internal/license"
|
||||||
@@ -66,6 +67,7 @@ type Core struct {
|
|||||||
Service *service.Service
|
Service *service.Service
|
||||||
PKI *pki.Authority
|
PKI *pki.Authority
|
||||||
Hub *agenthub.Hub
|
Hub *agenthub.Hub
|
||||||
|
Events *events.Bus
|
||||||
Log *slog.Logger
|
Log *slog.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,10 +106,12 @@ func Open(ctx context.Context, cfg config.Config, log *slog.Logger, migrate bool
|
|||||||
return nil, fmt.Errorf("agent PKI: %w", err)
|
return nil, fmt.Errorf("agent PKI: %w", err)
|
||||||
}
|
}
|
||||||
core.Hub = agenthub.New()
|
core.Hub = agenthub.New()
|
||||||
|
core.Events = events.New()
|
||||||
core.Service = service.New(service.Options{
|
core.Service = service.New(service.Options{
|
||||||
Store: st, Keyring: kr, License: core.License, ProductName: brand.DisplayName,
|
Store: st, Keyring: kr, License: core.License, ProductName: brand.DisplayName,
|
||||||
SessionLifetime: cfg.Session.Lifetime.Std(), SessionIdle: cfg.Session.IdleTimeout.Std(), Logger: log,
|
SessionLifetime: cfg.Session.Lifetime.Std(), SessionIdle: cfg.Session.IdleTimeout.Std(), Logger: log,
|
||||||
PKI: core.PKI, Hub: core.Hub, AgentAPIAddress: cfg.AgentAPI.PublicAddress, AgentServerNames: cfg.AgentAPI.ServerNames,
|
PKI: core.PKI, Hub: core.Hub, AgentAPIAddress: cfg.AgentAPI.PublicAddress, AgentServerNames: cfg.AgentAPI.ServerNames,
|
||||||
|
Events: core.Events,
|
||||||
})
|
})
|
||||||
return core, nil
|
return core, nil
|
||||||
}
|
}
|
||||||
@@ -174,10 +178,18 @@ func Serve(ctx context.Context, core *Core) error {
|
|||||||
return fmt.Errorf("agent API listener: %w", err)
|
return fmt.Errorf("agent API listener: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Dynamic zones of older versions get the update key of the DNS agents
|
||||||
|
// (ADR 0026). A failure is not fatal: revisions then report the missing
|
||||||
|
// key, and creating or changing a dynamic zone tries again.
|
||||||
|
if err := core.Service.EnsureSystemKeys(ctx); err != nil {
|
||||||
|
log.Error("cannot create the system TSIG keys", slog.Any("error", err))
|
||||||
|
}
|
||||||
|
|
||||||
jobs, stopJobs := context.WithCancel(ctx)
|
jobs, stopJobs := context.WithCancel(ctx)
|
||||||
defer stopJobs()
|
defer stopJobs()
|
||||||
go core.License.Run(jobs)
|
go core.License.Run(jobs)
|
||||||
go cleanup(jobs, core)
|
go cleanup(jobs, core)
|
||||||
|
go retention(jobs, core, retentionStartDelay, retentionInterval)
|
||||||
|
|
||||||
log.Info("starting server", slog.String("version", info.Version), slog.String("commit", info.Commit),
|
log.Info("starting server", slog.String("version", info.Version), slog.String("commit", info.Commit),
|
||||||
slog.String("listen", cfg.HTTP.Listen), slog.Bool("tls", cfg.TLSEnabled()),
|
slog.String("listen", cfg.HTTP.Listen), slog.Bool("tls", cfg.TLSEnabled()),
|
||||||
@@ -212,6 +224,9 @@ func Serve(ctx context.Context, core *Core) error {
|
|||||||
log.Info("shutting down", slog.Duration("timeout", cfg.ShutdownTimeout.Std()))
|
log.Info("shutting down", slog.Duration("timeout", cfg.ShutdownTimeout.Std()))
|
||||||
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cfg.ShutdownTimeout.Std())
|
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), cfg.ShutdownTimeout.Std())
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
// Event streams never become idle: end them so that the HTTP server
|
||||||
|
// can shut down gracefully.
|
||||||
|
core.Events.Close()
|
||||||
agentSrv.Shutdown(shutdownCtx)
|
agentSrv.Shutdown(shutdownCtx)
|
||||||
if err := srv.Shutdown(shutdownCtx); err != nil && runErr == nil {
|
if err := srv.Shutdown(shutdownCtx); err != nil && runErr == nil {
|
||||||
runErr = fmt.Errorf("graceful shutdown: %w", err)
|
runErr = fmt.Errorf("graceful shutdown: %w", err)
|
||||||
@@ -229,6 +244,43 @@ func Serve(ctx context.Context, core *Core) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The retention cleanup runs shortly after the start (not during it, so
|
||||||
|
// that a restart loop does not hammer the database) and then daily.
|
||||||
|
const (
|
||||||
|
retentionStartDelay = 5 * time.Minute
|
||||||
|
retentionInterval = 24 * time.Hour
|
||||||
|
)
|
||||||
|
|
||||||
|
// retention applies the configured retention policy (ADR 0024).
|
||||||
|
func retention(ctx context.Context, core *Core, delay, interval time.Duration) {
|
||||||
|
policy := service.RetentionPolicy{AuditDays: core.Config.Retention.AuditDays,
|
||||||
|
RevisionsKeep: core.Config.Retention.RevisionsKeep}
|
||||||
|
if !policy.Enabled() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log := core.Log.With(slog.String("component", "retention"))
|
||||||
|
t := time.NewTimer(delay)
|
||||||
|
defer t.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-t.C:
|
||||||
|
}
|
||||||
|
res, err := core.Service.ApplyRetention(ctx, policy)
|
||||||
|
switch {
|
||||||
|
case err != nil:
|
||||||
|
log.Warn("retention cleanup failed", slog.Any("error", err))
|
||||||
|
case res.AuditDeleted > 0 || len(res.RevisionsDeleted) > 0:
|
||||||
|
log.Info("retention cleanup", slog.Int64("audit_entries_deleted", res.AuditDeleted),
|
||||||
|
slog.Int("revisions_deleted", len(res.RevisionsDeleted)))
|
||||||
|
default:
|
||||||
|
log.Debug("retention cleanup: nothing to delete")
|
||||||
|
}
|
||||||
|
t.Reset(interval)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// cleanup removes expired sessions and old enrollment tokens periodically.
|
// cleanup removes expired sessions and old enrollment tokens periodically.
|
||||||
func cleanup(ctx context.Context, core *Core) {
|
func cleanup(ctx context.Context, core *Core) {
|
||||||
t := time.NewTicker(15 * time.Minute)
|
t := time.NewTicker(15 * time.Minute)
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
// SPDX-License-Identifier: LicenseRef-DDI-Proprietary
|
||||||
|
|
||||||
|
package app
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.beugsiud.de/beug.k/DDI/server/internal/config"
|
||||||
|
"git.beugsiud.de/beug.k/DDI/server/internal/service"
|
||||||
|
"git.beugsiud.de/beug.k/DDI/server/internal/store"
|
||||||
|
"git.beugsiud.de/beug.k/DDI/server/internal/store/storetest"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRetentionJob(t *testing.T) {
|
||||||
|
st := storetest.New(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
if err := st.Q().InsertAudit(ctx, &store.AuditEntry{ActorName: "admin", Action: "old.one", ObjectType: "test"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := st.Pool().Exec(ctx, `UPDATE audit_log SET at = now() - interval '10 days'`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
log := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||||
|
cfg := config.Defaults()
|
||||||
|
core := &Core{Config: cfg, Store: st, Log: log, Service: service.New(service.Options{Store: st, Logger: log})}
|
||||||
|
|
||||||
|
// Disabled policy: returns at once.
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() { retention(ctx, core, 0, time.Hour); close(done) }()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("disabled retention job did not return")
|
||||||
|
}
|
||||||
|
|
||||||
|
core.Config.Retention.AuditDays = 7
|
||||||
|
jobCtx, cancel := context.WithCancel(ctx)
|
||||||
|
done = make(chan struct{})
|
||||||
|
go func() { retention(jobCtx, core, 10*time.Millisecond, time.Hour); close(done) }()
|
||||||
|
deadline := time.Now().Add(10 * time.Second)
|
||||||
|
for {
|
||||||
|
entries, err := st.Q().ListAudit(ctx, store.AuditFilter{Action: "old.one"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(entries) == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatal("old audit entry was not deleted")
|
||||||
|
}
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
}
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("retention job did not stop")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -71,15 +71,28 @@ func (d Duration) Std() time.Duration { return time.Duration(d) }
|
|||||||
|
|
||||||
// Config is the server configuration.
|
// Config is the server configuration.
|
||||||
type Config struct {
|
type Config struct {
|
||||||
HTTP HTTP `yaml:"http"`
|
HTTP HTTP `yaml:"http"`
|
||||||
AgentAPI AgentAPI `yaml:"agent_api"`
|
AgentAPI AgentAPI `yaml:"agent_api"`
|
||||||
Database Database `yaml:"database"`
|
Database Database `yaml:"database"`
|
||||||
MasterKeyFile string `yaml:"master_key_file"`
|
MasterKeyFile string `yaml:"master_key_file"`
|
||||||
StateDir string `yaml:"state_dir"`
|
StateDir string `yaml:"state_dir"`
|
||||||
Log Log `yaml:"log"`
|
Log Log `yaml:"log"`
|
||||||
Session Session `yaml:"session"`
|
Session Session `yaml:"session"`
|
||||||
License License `yaml:"license"`
|
License License `yaml:"license"`
|
||||||
ShutdownTimeout Duration `yaml:"shutdown_timeout"`
|
Retention Retention `yaml:"retention"`
|
||||||
|
ShutdownTimeout Duration `yaml:"shutdown_timeout"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retention limits how long history is kept (ADR 0024). A daily cleanup
|
||||||
|
// applies it; 0 keeps everything.
|
||||||
|
type Retention struct {
|
||||||
|
// AuditDays deletes audit entries older than this many days.
|
||||||
|
AuditDays int `yaml:"audit_days"`
|
||||||
|
// RevisionsKeep keeps the newest this many configuration revisions.
|
||||||
|
// The latest revision, revisions an agent runs, falls back to or is
|
||||||
|
// told to apply, and revisions with pending deployments are always
|
||||||
|
// kept in addition.
|
||||||
|
RevisionsKeep int `yaml:"revisions_keep"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// HTTP configures the web UI/API listener.
|
// HTTP configures the web UI/API listener.
|
||||||
@@ -289,6 +302,17 @@ func str(dst func(*Config) *string) func(*Config, string) error {
|
|||||||
return func(c *Config, v string) error { *dst(c) = v; return nil }
|
return func(c *Config, v string) error { *dst(c) = v; return nil }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func integer(dst func(*Config) *int) func(*Config, string) error {
|
||||||
|
return func(c *Config, v string) error {
|
||||||
|
n, err := strconv.Atoi(strings.TrimSpace(v))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("invalid number %q", v)
|
||||||
|
}
|
||||||
|
*dst(c) = n
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func dur(dst func(*Config) *Duration) func(*Config, string) error {
|
func dur(dst func(*Config) *Duration) func(*Config, string) error {
|
||||||
return func(c *Config, v string) error {
|
return func(c *Config, v string) error {
|
||||||
d, err := ParseDuration(v)
|
d, err := ParseDuration(v)
|
||||||
@@ -326,6 +350,8 @@ var envBindings = []envBinding{
|
|||||||
{name: "SESSION_LIFETIME", set: dur(func(c *Config) *Duration { return &c.Session.Lifetime })},
|
{name: "SESSION_LIFETIME", set: dur(func(c *Config) *Duration { return &c.Session.Lifetime })},
|
||||||
{name: "SESSION_IDLE_TIMEOUT", set: dur(func(c *Config) *Duration { return &c.Session.IdleTimeout })},
|
{name: "SESSION_IDLE_TIMEOUT", set: dur(func(c *Config) *Duration { return &c.Session.IdleTimeout })},
|
||||||
{name: "LICENSE_GRACE_PERIOD", set: dur(func(c *Config) *Duration { return &c.License.GracePeriod })},
|
{name: "LICENSE_GRACE_PERIOD", set: dur(func(c *Config) *Duration { return &c.License.GracePeriod })},
|
||||||
|
{name: "RETENTION_AUDIT_DAYS", set: integer(func(c *Config) *int { return &c.Retention.AuditDays })},
|
||||||
|
{name: "RETENTION_REVISIONS_KEEP", set: integer(func(c *Config) *int { return &c.Retention.RevisionsKeep })},
|
||||||
// Names given by the project brief, accepted without prefix.
|
// Names given by the project brief, accepted without prefix.
|
||||||
{name: "KEYGEN_URL", raw: true, set: str(func(c *Config) *string { return &c.License.KeygenURL })},
|
{name: "KEYGEN_URL", raw: true, set: str(func(c *Config) *string { return &c.License.KeygenURL })},
|
||||||
{name: "KEYGEN_ACCOUNT_ID", raw: true, set: str(func(c *Config) *string { return &c.License.AccountID })},
|
{name: "KEYGEN_ACCOUNT_ID", raw: true, set: str(func(c *Config) *string { return &c.License.AccountID })},
|
||||||
@@ -389,6 +415,12 @@ func (c Config) Validate() error {
|
|||||||
if c.Database.MaxConns < 1 {
|
if c.Database.MaxConns < 1 {
|
||||||
errs = append(errs, errors.New("database.max_conns must be at least 1"))
|
errs = append(errs, errors.New("database.max_conns must be at least 1"))
|
||||||
}
|
}
|
||||||
|
if c.Retention.AuditDays < 0 || c.Retention.AuditDays > 36500 {
|
||||||
|
errs = append(errs, errors.New("retention.audit_days must be between 0 (keep all) and 36500"))
|
||||||
|
}
|
||||||
|
if c.Retention.RevisionsKeep < 0 {
|
||||||
|
errs = append(errs, errors.New("retention.revisions_keep must not be negative (0 keeps all)"))
|
||||||
|
}
|
||||||
errs = append(errs, c.AgentAPI.validate()...)
|
errs = append(errs, c.AgentAPI.validate()...)
|
||||||
return errors.Join(errs...)
|
return errors.Join(errs...)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,6 +43,9 @@ func TestDefaults(t *testing.T) {
|
|||||||
if !strings.HasSuffix(filepath.ToSlash(cfg.MasterKeyFile), "/master.key") {
|
if !strings.HasSuffix(filepath.ToSlash(cfg.MasterKeyFile), "/master.key") {
|
||||||
t.Errorf("master key default %q", cfg.MasterKeyFile)
|
t.Errorf("master key default %q", cfg.MasterKeyFile)
|
||||||
}
|
}
|
||||||
|
if cfg.Retention != (Retention{}) {
|
||||||
|
t.Errorf("retention must default to keeping everything: %+v", cfg.Retention)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFileAndEnvPrecedence(t *testing.T) {
|
func TestFileAndEnvPrecedence(t *testing.T) {
|
||||||
@@ -57,11 +60,15 @@ license:
|
|||||||
grace_period: 7d
|
grace_period: 7d
|
||||||
session:
|
session:
|
||||||
idle_timeout: 30m
|
idle_timeout: 30m
|
||||||
|
retention:
|
||||||
|
audit_days: 365
|
||||||
|
revisions_keep: 50
|
||||||
`)
|
`)
|
||||||
cfg, err := Load(path, env(map[string]string{
|
cfg, err := Load(path, env(map[string]string{
|
||||||
"DDI_DATABASE_URL": "postgres://env",
|
"DDI_DATABASE_URL": "postgres://env",
|
||||||
"KEYGEN_PRODUCT_ID": "prod-1",
|
"KEYGEN_PRODUCT_ID": "prod-1",
|
||||||
"DDI_LOG_LEVEL": "debug",
|
"DDI_LOG_LEVEL": "debug",
|
||||||
|
"DDI_RETENTION_REVISIONS_KEEP": "20",
|
||||||
}))
|
}))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -81,6 +88,9 @@ session:
|
|||||||
if cfg.Session.IdleTimeout.Std() != 30*time.Minute || cfg.Log.Level != "debug" {
|
if cfg.Session.IdleTimeout.Std() != 30*time.Minute || cfg.Log.Level != "debug" {
|
||||||
t.Errorf("session/log: %+v %+v", cfg.Session, cfg.Log)
|
t.Errorf("session/log: %+v %+v", cfg.Session, cfg.Log)
|
||||||
}
|
}
|
||||||
|
if cfg.Retention.AuditDays != 365 || cfg.Retention.RevisionsKeep != 20 {
|
||||||
|
t.Errorf("retention: %+v", cfg.Retention)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestDatabaseURLFile(t *testing.T) {
|
func TestDatabaseURLFile(t *testing.T) {
|
||||||
@@ -116,6 +126,9 @@ func TestValidation(t *testing.T) {
|
|||||||
"http keygen": {map[string]string{"KEYGEN_URL": "http://license.example.test"}, "keygen_url"},
|
"http keygen": {map[string]string{"KEYGEN_URL": "http://license.example.test"}, "keygen_url"},
|
||||||
"relative public": {map[string]string{"DDI_PUBLIC_URL": "/ddi"}, "public_url"},
|
"relative public": {map[string]string{"DDI_PUBLIC_URL": "/ddi"}, "public_url"},
|
||||||
"bad grace in days": {map[string]string{"DDI_LICENSE_GRACE_PERIOD": "xd"}, "LICENSE_GRACE_PERIOD"},
|
"bad grace in days": {map[string]string{"DDI_LICENSE_GRACE_PERIOD": "xd"}, "LICENSE_GRACE_PERIOD"},
|
||||||
|
"audit days text": {map[string]string{"DDI_RETENTION_AUDIT_DAYS": "1y"}, "RETENTION_AUDIT_DAYS"},
|
||||||
|
"negative audit": {map[string]string{"DDI_RETENTION_AUDIT_DAYS": "-1"}, "retention.audit_days"},
|
||||||
|
"negative keep": {map[string]string{"DDI_RETENTION_REVISIONS_KEEP": "-3"}, "retention.revisions_keep"},
|
||||||
}
|
}
|
||||||
for name, tt := range tests {
|
for name, tt := range tests {
|
||||||
t.Run(name, func(t *testing.T) {
|
t.Run(name, func(t *testing.T) {
|
||||||
|
|||||||
@@ -2,8 +2,9 @@
|
|||||||
|
|
||||||
// Package bindgen renders a configgen.DNSConfig into BIND 9 (≥ 9.18)
|
// Package bindgen renders a configgen.DNSConfig into BIND 9 (≥ 9.18)
|
||||||
// configuration: a named.conf include with the zone statements, a second
|
// configuration: a named.conf include with the zone statements, a second
|
||||||
// include with statements for the options block, and one zone file per zone
|
// include with statements for the options block, a third (secret) include
|
||||||
// (ADR 0004, ADR 0014).
|
// with the TSIG keys, and one zone file per primary zone (ADR 0004,
|
||||||
|
// ADR 0014, ADR 0023).
|
||||||
//
|
//
|
||||||
// The distribution's named.conf includes the generated files like this:
|
// The distribution's named.conf includes the generated files like this:
|
||||||
//
|
//
|
||||||
@@ -11,15 +12,30 @@
|
|||||||
// directory "/var/cache/bind";
|
// directory "/var/cache/bind";
|
||||||
// include "/etc/bind/ddi-suite/ddi-suite-options.conf";
|
// include "/etc/bind/ddi-suite/ddi-suite-options.conf";
|
||||||
// };
|
// };
|
||||||
|
// include "/etc/bind/ddi-suite/ddi-suite-keys.conf";
|
||||||
// include "/etc/bind/ddi-suite/ddi-suite.conf";
|
// include "/etc/bind/ddi-suite/ddi-suite.conf";
|
||||||
//
|
//
|
||||||
// BIND accepts only one options block, so the generator cannot emit its own;
|
// BIND accepts only one options block, so the generator cannot emit its own;
|
||||||
// BIND accepts "include" wherever a clause of a block may appear, so the
|
// BIND accepts "include" wherever a clause of a block may appear, so the
|
||||||
// options are included into the distribution's block instead.
|
// options are included into the distribution's block instead. The keys come
|
||||||
|
// before the zones that refer to them.
|
||||||
|
//
|
||||||
|
// Primary zones in a cluster notify the secondaries explicitly
|
||||||
|
// ("notify explicit", "also-notify" with the transfer key per server) and
|
||||||
|
// allow transfers only with the transfer key; secondary zones transfer from
|
||||||
|
// their primaries with the key and are written by BIND to
|
||||||
|
// <ZoneDir>/secondary/db.<zone>, so no artifact is generated for them.
|
||||||
|
//
|
||||||
|
// With DNSConfig.UpdateKey every dynamic primary zone also accepts updates
|
||||||
|
// signed with that key, and two more files are written at the configuration
|
||||||
|
// root (ADR 0026): configgen.UpdateKeyFile with the key alone (for
|
||||||
|
// "nsupdate -k") and configgen.DynamicRecordsFile with the records DDI owns
|
||||||
|
// in the dynamic zones, which the DNS agent adds and removes with nsupdate.
|
||||||
//
|
//
|
||||||
// Every value is validated before anything is written. Names are restricted
|
// Every value is validated before anything is written. Names are restricted
|
||||||
// to letters, digits, '-' and (where DNS needs it) a leading '_', so no input
|
// to letters, digits, '-' and (where DNS needs it) a leading '_', so no input
|
||||||
// can leave a quoted string or a statement.
|
// can leave a quoted string or a statement; TSIG secrets must be canonical
|
||||||
|
// base64.
|
||||||
package bindgen
|
package bindgen
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -32,28 +48,45 @@ const (
|
|||||||
ConfFile = "ddi-suite.conf"
|
ConfFile = "ddi-suite.conf"
|
||||||
// OptionsFile holds statements for the options block.
|
// OptionsFile holds statements for the options block.
|
||||||
OptionsFile = "ddi-suite-options.conf"
|
OptionsFile = "ddi-suite-options.conf"
|
||||||
|
// KeysFile holds the TSIG keys (a secret artifact, always generated).
|
||||||
|
KeysFile = "ddi-suite-keys.conf"
|
||||||
// ZonesDir holds the zone files; the agent maps it to DNSConfig.ZoneDir.
|
// ZonesDir holds the zone files; the agent maps it to DNSConfig.ZoneDir.
|
||||||
ZonesDir = "zones"
|
ZonesDir = "zones"
|
||||||
|
// SecondaryDir is the directory below DNSConfig.ZoneDir where BIND
|
||||||
|
// writes the files of secondary zones. The DNS agent creates it.
|
||||||
|
SecondaryDir = "secondary"
|
||||||
)
|
)
|
||||||
|
|
||||||
// fileMode is the mode of every generated file (readable by the named group).
|
// fileMode is the mode of every generated file (readable by the named group).
|
||||||
const fileMode = 0o640
|
const fileMode = 0o640
|
||||||
|
|
||||||
// Render validates cfg and returns the include files followed by one zone
|
// Render validates cfg and returns the include files (ddi-suite.conf,
|
||||||
// file per zone, sorted by zone name. Invalid input yields a
|
// ddi-suite-options.conf, ddi-suite-keys.conf), with cfg.UpdateKey the
|
||||||
// *configgen.ValidationError and no artifacts.
|
// update key file and the records of the dynamic zones (ADR 0026), followed
|
||||||
|
// by one zone file per primary zone, sorted by zone name. Invalid input
|
||||||
|
// yields a *configgen.ValidationError and no artifacts.
|
||||||
func Render(cfg configgen.DNSConfig) ([]configgen.Artifact, error) {
|
func Render(cfg configgen.DNSConfig) ([]configgen.Artifact, error) {
|
||||||
m, err := validate(cfg)
|
m, err := validate(cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
out := make([]configgen.Artifact, 0, 2+len(m.zones))
|
out := make([]configgen.Artifact, 0, 5+len(m.zones))
|
||||||
out = append(out,
|
out = append(out,
|
||||||
configgen.Artifact{Path: ConfFile, Mode: fileMode, Content: renderConf(m)},
|
configgen.Artifact{Path: ConfFile, Mode: fileMode, Content: renderConf(m)},
|
||||||
configgen.Artifact{Path: OptionsFile, Mode: fileMode, Content: renderOptions(m)},
|
configgen.Artifact{Path: OptionsFile, Mode: fileMode, Content: renderOptions(m)},
|
||||||
|
configgen.Artifact{Path: KeysFile, Mode: fileMode, Content: renderKeys(m), Secret: true},
|
||||||
)
|
)
|
||||||
|
if m.updateKey != nil {
|
||||||
|
out = append(out,
|
||||||
|
configgen.Artifact{Path: configgen.UpdateKeyFile, Mode: fileMode, Content: renderUpdateKey(m), Secret: true},
|
||||||
|
configgen.Artifact{Path: configgen.DynamicRecordsFile, Mode: fileMode, Content: renderDynamicRecords(m)},
|
||||||
|
)
|
||||||
|
}
|
||||||
for i := range m.zones {
|
for i := range m.zones {
|
||||||
z := &m.zones[i]
|
z := &m.zones[i]
|
||||||
|
if z.secondary {
|
||||||
|
continue
|
||||||
|
}
|
||||||
out = append(out, configgen.Artifact{
|
out = append(out, configgen.Artifact{
|
||||||
Path: ZonesDir + "/" + zoneFileName(z.name),
|
Path: ZonesDir + "/" + zoneFileName(z.name),
|
||||||
Mode: fileMode,
|
Mode: fileMode,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ package bindgen
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -13,6 +14,7 @@ import (
|
|||||||
"path"
|
"path"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"slices"
|
"slices"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
@@ -137,12 +139,119 @@ func recursionOptions() configgen.DNSOptions {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
xferKey = "xfer.dns-a"
|
||||||
|
xferSecret = "eGZlci1zZWNyZXQtb2YtZG5zLWEtMzItYnl0ZXMhIQ=="
|
||||||
|
)
|
||||||
|
|
||||||
|
func testKeys() []configgen.TSIGKey {
|
||||||
|
return []configgen.TSIGKey{
|
||||||
|
{Name: xferKey, Algorithm: "hmac-sha256", Secret: xferSecret},
|
||||||
|
{Name: "dhcp-update", Algorithm: "hmac-sha512", Secret: "ZGhjcC11cGRhdGUtc2VjcmV0"},
|
||||||
|
{Name: "admin.update", Algorithm: "hmac-sha384", Secret: "YWRtaW4tdXBkYXRl"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The update key of the DNS agents (ADR 0026).
|
||||||
|
const (
|
||||||
|
agentKey = "ddi-agent-update"
|
||||||
|
agentKeySecret = "ZGRpLWFnZW50LXVwZGF0ZS1zZWNyZXQtMzItYnl0ZXM="
|
||||||
|
)
|
||||||
|
|
||||||
|
func agentUpdateKey() configgen.TSIGKey {
|
||||||
|
return configgen.TSIGKey{Name: agentKey, Algorithm: "hmac-sha256", Secret: agentKeySecret}
|
||||||
|
}
|
||||||
|
|
||||||
|
// dynamicUpdateZones are dynamic zones with every record type that the DNS
|
||||||
|
// agent keeps up to date (ADR 0026), next to a managed and a secondary zone
|
||||||
|
// whose records it never touches.
|
||||||
|
func dynamicUpdateZones() []configgen.Zone {
|
||||||
|
fwd := forwardZone()
|
||||||
|
fwd.Mode = configgen.ZoneDynamic
|
||||||
|
fwd.AllowUpdate = []netip.Prefix{pfx("192.0.2.20/32")}
|
||||||
|
fwd.UpdateKeys = []string{"dhcp-update", agentKey} // listed once in the ACL
|
||||||
|
fwd.Records = append(fwd.Records,
|
||||||
|
// Apex NS records are never managed by the agent.
|
||||||
|
configgen.Record{Name: "@", Type: configgen.TypeNS, Target: "ns3.example.net"},
|
||||||
|
configgen.Record{Name: "@", Type: configgen.TypeNS, Target: "ns1.office.test"},
|
||||||
|
// Differs only in TTL from "www A 192.0.2.9": written once.
|
||||||
|
configgen.Record{Name: "www", TTL: 60, Type: configgen.TypeA, Addr: ip("192.0.2.9")},
|
||||||
|
)
|
||||||
|
rev := reverseZones()[0]
|
||||||
|
rev.Mode = configgen.ZoneDynamic
|
||||||
|
rev.AllowUpdate = []netip.Prefix{pfx("192.0.2.20/32")}
|
||||||
|
managed := dynamicZones()[1]
|
||||||
|
sec := secondaryZones()[0]
|
||||||
|
sec.Name = "remote.test"
|
||||||
|
return []configgen.Zone{fwd, rev, managed, sec}
|
||||||
|
}
|
||||||
|
|
||||||
|
// primaryZones are the zones of a cluster primary with two secondaries.
|
||||||
|
func primaryZones() []configgen.Zone {
|
||||||
|
notify := func() []configgen.Remote {
|
||||||
|
return []configgen.Remote{{Addr: ip("2001:db8::2"), Key: xferKey}, {Addr: ip("192.0.2.3"), Key: xferKey}}
|
||||||
|
}
|
||||||
|
fwd := forwardZone()
|
||||||
|
fwd.Type = configgen.ZonePrimary
|
||||||
|
fwd.AlsoNotify = notify()
|
||||||
|
fwd.TransferKey = xferKey
|
||||||
|
rev := reverseZones()[0]
|
||||||
|
rev.AlsoNotify = notify()
|
||||||
|
rev.TransferKey = xferKey
|
||||||
|
return []configgen.Zone{fwd, rev}
|
||||||
|
}
|
||||||
|
|
||||||
|
// secondaryZones are the same zones on a secondary.
|
||||||
|
func secondaryZones() []configgen.Zone {
|
||||||
|
primaries := func() []configgen.Remote { return []configgen.Remote{{Addr: ip("192.0.2.1"), Key: xferKey}} }
|
||||||
|
return []configgen.Zone{
|
||||||
|
{Name: "office.test", Kind: configgen.ZoneForward, Type: configgen.ZoneSecondary, Primaries: primaries()},
|
||||||
|
{Name: "2.0.192.in-addr.arpa", Kind: configgen.ZoneReverse, Type: configgen.ZoneSecondary, Primaries: primaries()},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// dynamicKeyZones are dynamic zones that accept updates signed with keys.
|
||||||
|
func dynamicKeyZones() []configgen.Zone {
|
||||||
|
zs := dynamicZones()
|
||||||
|
zs[0].UpdateKeys = []string{"dhcp-update", "admin.update"}
|
||||||
|
only := zs[0]
|
||||||
|
only.Name = "keys-only.test"
|
||||||
|
only.AllowUpdate = nil
|
||||||
|
only.UpdateKeys = []string{"dhcp-update"}
|
||||||
|
only.Records = nil
|
||||||
|
return append(zs, only)
|
||||||
|
}
|
||||||
|
|
||||||
func goldenCases() map[string]configgen.DNSConfig {
|
func goldenCases() map[string]configgen.DNSConfig {
|
||||||
return map[string]configgen.DNSConfig{
|
return map[string]configgen.DNSConfig{
|
||||||
"forward": {Serial: 42, ZoneDir: testZoneDir, Zones: []configgen.Zone{forwardZone()}},
|
"forward": {Serial: 42, ZoneDir: testZoneDir, Zones: []configgen.Zone{forwardZone()}},
|
||||||
"reverse": {Serial: 42, ZoneDir: testZoneDir, Zones: reverseZones()},
|
"reverse": {Serial: 42, ZoneDir: testZoneDir, Zones: reverseZones()},
|
||||||
"dynamic": {Serial: 7, ZoneDir: testZoneDir, Zones: dynamicZones()},
|
"dynamic": {Serial: 7, ZoneDir: testZoneDir, Zones: dynamicZones()},
|
||||||
"recursion": {Serial: 1, ZoneDir: testZoneDir, Options: recursionOptions()},
|
"recursion": {Serial: 1, ZoneDir: testZoneDir, Options: recursionOptions()},
|
||||||
|
"cluster-primary": {Serial: 11, ZoneDir: testZoneDir, Zones: primaryZones(), Keys: testKeys()[:1]},
|
||||||
|
"secondary": {Serial: 11, ZoneDir: testZoneDir, Zones: secondaryZones(), Keys: testKeys()[:1]},
|
||||||
|
"dynamic-keys": {Serial: 8, ZoneDir: testZoneDir, Zones: dynamicKeyZones(),
|
||||||
|
Keys: append(testKeys(), agentUpdateKey()), UpdateKey: agentKey},
|
||||||
|
"dynamic-update": {Serial: 12, ZoneDir: testZoneDir, Zones: dynamicUpdateZones(),
|
||||||
|
Keys: append(testKeys(), agentUpdateKey()), UpdateKey: agentKey},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestGoldenFilesComplete fails for golden files no artifact produces any
|
||||||
|
// more (e.g. after a zone was removed from a case).
|
||||||
|
func TestGoldenFilesComplete(t *testing.T) {
|
||||||
|
for name, cfg := range goldenCases() {
|
||||||
|
arts, err := Render(cfg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("%s: %v", name, err)
|
||||||
|
}
|
||||||
|
files, err := filepath.Glob(filepath.Join("testdata", name, "*.golden"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(files) != len(arts) {
|
||||||
|
t.Errorf("%s: %d golden files for %d artifacts", name, len(files), len(arts))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -182,34 +291,77 @@ func TestRenderArtifacts(t *testing.T) {
|
|||||||
Path string
|
Path string
|
||||||
Mode uint32
|
Mode uint32
|
||||||
CreateOnly bool
|
CreateOnly bool
|
||||||
|
Secret bool
|
||||||
}
|
}
|
||||||
cfg := configgen.DNSConfig{Serial: 3, ZoneDir: testZoneDir}
|
cfg := configgen.DNSConfig{Serial: 3, ZoneDir: testZoneDir, Keys: testKeys()}
|
||||||
cfg.Zones = append(cfg.Zones, dynamicZones()...)
|
cfg.Zones = append(cfg.Zones, dynamicZones()...)
|
||||||
cfg.Zones = append(cfg.Zones, forwardZone())
|
cfg.Zones = append(cfg.Zones, forwardZone())
|
||||||
cfg.Zones = append(cfg.Zones, reverseZones()...)
|
cfg.Zones = append(cfg.Zones, reverseZones()...)
|
||||||
|
sec := secondaryZones()[0]
|
||||||
|
sec.Name = "remote.test"
|
||||||
|
cfg.Zones = append(cfg.Zones, sec)
|
||||||
arts, err := Render(cfg)
|
arts, err := Render(cfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Render: %v", err)
|
t.Fatalf("Render: %v", err)
|
||||||
}
|
}
|
||||||
var got []meta
|
var got []meta
|
||||||
for _, a := range arts {
|
for _, a := range arts {
|
||||||
got = append(got, meta{a.Path, a.Mode, a.CreateOnly})
|
got = append(got, meta{a.Path, a.Mode, a.CreateOnly, a.Secret})
|
||||||
if len(a.Content) == 0 || a.Content[len(a.Content)-1] != '\n' {
|
if len(a.Content) == 0 || a.Content[len(a.Content)-1] != '\n' {
|
||||||
t.Errorf("%s does not end with a newline", a.Path)
|
t.Errorf("%s does not end with a newline", a.Path)
|
||||||
}
|
}
|
||||||
|
if a.Secret != bytes.Contains(a.Content, []byte("secret ")) {
|
||||||
|
t.Errorf("%s: secret flag %v does not match its content", a.Path, a.Secret)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
want := []meta{
|
want := []meta{
|
||||||
{"ddi-suite.conf", 0o640, false},
|
{"ddi-suite.conf", 0o640, false, false},
|
||||||
{"ddi-suite-options.conf", 0o640, false},
|
{"ddi-suite-options.conf", 0o640, false, false},
|
||||||
{"zones/db.2.0.192.in-addr.arpa", 0o640, false},
|
{"ddi-suite-keys.conf", 0o640, false, true},
|
||||||
{"zones/db.8.b.d.0.1.0.0.2.ip6.arpa", 0o640, false},
|
{"zones/db.2.0.192.in-addr.arpa", 0o640, false, false},
|
||||||
{"zones/db.dyn.test", 0o640, true},
|
{"zones/db.8.b.d.0.1.0.0.2.ip6.arpa", 0o640, false, false},
|
||||||
{"zones/db.office.test", 0o640, false},
|
{"zones/db.dyn.test", 0o640, true, false},
|
||||||
{"zones/db.static.test", 0o640, false},
|
{"zones/db.office.test", 0o640, false, false},
|
||||||
|
{"zones/db.static.test", 0o640, false, false},
|
||||||
}
|
}
|
||||||
if !slices.Equal(got, want) {
|
if !slices.Equal(got, want) {
|
||||||
t.Errorf("artifacts\n got %v\nwant %v", got, want)
|
t.Errorf("artifacts\n got %v\nwant %v", got, want)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// With the update key of the DNS agents (ADR 0026).
|
||||||
|
cfg.Keys = append(cfg.Keys, agentUpdateKey())
|
||||||
|
cfg.UpdateKey = agentKey
|
||||||
|
if arts, err = Render(cfg); err != nil {
|
||||||
|
t.Fatalf("Render: %v", err)
|
||||||
|
}
|
||||||
|
got = got[:0]
|
||||||
|
for _, a := range arts[:5] {
|
||||||
|
got = append(got, meta{a.Path, a.Mode, a.CreateOnly, a.Secret})
|
||||||
|
if a.Secret != bytes.Contains(a.Content, []byte("secret ")) {
|
||||||
|
t.Errorf("%s: secret flag %v does not match its content", a.Path, a.Secret)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
want = []meta{
|
||||||
|
{"ddi-suite.conf", 0o640, false, false},
|
||||||
|
{"ddi-suite-options.conf", 0o640, false, false},
|
||||||
|
{"ddi-suite-keys.conf", 0o640, false, true},
|
||||||
|
{"ddi-suite-update.key", 0o640, false, true},
|
||||||
|
{"dynamic-records.json", 0o640, false, false},
|
||||||
|
}
|
||||||
|
if !slices.Equal(got, want) || len(arts) != 10 {
|
||||||
|
t.Errorf("artifacts with update key\n got %v (%d)\nwant %v", got, len(arts), want)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Without keys the keys file holds only comments.
|
||||||
|
arts, err = Render(validConfig())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, l := range strings.Split(strings.TrimSpace(artifact(t, arts, KeysFile)), "\n") {
|
||||||
|
if !strings.HasPrefix(l, "//") {
|
||||||
|
t.Errorf("keys file without keys has line %q", l)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// validConfig is the base of the validation table: one zone "office.test".
|
// validConfig is the base of the validation table: one zone "office.test".
|
||||||
@@ -239,6 +391,16 @@ func TestRenderValidation(t *testing.T) {
|
|||||||
c.Options = configgen.DNSOptions{Recursion: true, AllowRecursion: allow, Forwarders: fwd}
|
c.Options = configgen.DNSOptions{Recursion: true, AllowRecursion: allow, Forwarders: fwd}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
keys := func(f func(k []configgen.TSIGKey)) func(c *configgen.DNSConfig) {
|
||||||
|
return func(c *configgen.DNSConfig) { c.Keys = testKeys(); f(c.Keys) }
|
||||||
|
}
|
||||||
|
secondary := func(primaries ...configgen.Remote) func(c *configgen.DNSConfig) {
|
||||||
|
return func(c *configgen.DNSConfig) {
|
||||||
|
c.Keys = testKeys()
|
||||||
|
c.Zones[0].Type = configgen.ZoneSecondary
|
||||||
|
c.Zones[0].Primaries = primaries
|
||||||
|
}
|
||||||
|
}
|
||||||
longText := make([]string, 300)
|
longText := make([]string, 300)
|
||||||
for i := range longText {
|
for i := range longText {
|
||||||
longText[i] = strings.Repeat("x", 255)
|
longText[i] = strings.Repeat("x", 255)
|
||||||
@@ -328,6 +490,58 @@ func TestRenderValidation(t *testing.T) {
|
|||||||
{"txt without strings", records(configgen.Record{Name: "x", Type: configgen.TypeTXT}), zp + ".records[0].text"},
|
{"txt without strings", records(configgen.Record{Name: "x", Type: configgen.TypeTXT}), zp + ".records[0].text"},
|
||||||
{"txt too long", records(configgen.Record{Name: "x", Type: configgen.TypeTXT, Text: longText}), zp + ".records[0].text"},
|
{"txt too long", records(configgen.Record{Name: "x", Type: configgen.TypeTXT, Text: longText}), zp + ".records[0].text"},
|
||||||
|
|
||||||
|
{"key name invalid", keys(func(k []configgen.TSIGKey) { k[1].Name = `x"; }; key "y` }), "keys[1].name"},
|
||||||
|
{"key name trailing dot", keys(func(k []configgen.TSIGKey) { k[0].Name = "xfer." }), "keys[0].name"},
|
||||||
|
{"key duplicate", keys(func(k []configgen.TSIGKey) { k[2].Name = k[0].Name }), "keys[2].name"},
|
||||||
|
{"key algorithm unknown", keys(func(k []configgen.TSIGKey) { k[0].Algorithm = "hmac-md5" }), "keys[0].algorithm"},
|
||||||
|
{"key algorithm empty", keys(func(k []configgen.TSIGKey) { k[1].Algorithm = "" }), "keys[1].algorithm"},
|
||||||
|
{"key secret empty", keys(func(k []configgen.TSIGKey) { k[0].Secret = "" }), "keys[0].secret"},
|
||||||
|
{"key secret not base64", keys(func(k []configgen.TSIGKey) { k[0].Secret = "not base64!" }), "keys[0].secret"},
|
||||||
|
{"key secret quote", keys(func(k []configgen.TSIGKey) { k[0].Secret = `YQ=="; };` }), "keys[0].secret"},
|
||||||
|
{"key secret unpadded", keys(func(k []configgen.TSIGKey) { k[0].Secret = "YQ" }), "keys[0].secret"},
|
||||||
|
{"key secret newline", keys(func(k []configgen.TSIGKey) { k[0].Secret = "YWFh\nYWFh" }), "keys[0].secret"},
|
||||||
|
{"key secret URL alphabet", keys(func(k []configgen.TSIGKey) { k[0].Secret = "-_-_" }), "keys[0].secret"},
|
||||||
|
|
||||||
|
{"zone type unknown", zone(func(z *configgen.Zone) { z.Type = "slave" }), zp + ".type"},
|
||||||
|
{"secondary without primaries", zone(func(z *configgen.Zone) { z.Type = configgen.ZoneSecondary }), zp + ".primaries"},
|
||||||
|
{"secondary primary invalid", secondary(configgen.Remote{}), zp + ".primaries[0].addr"},
|
||||||
|
{"secondary primary multicast", secondary(configgen.Remote{Addr: ip("ff02::1")}), zp + ".primaries[0].addr"},
|
||||||
|
{"secondary primary duplicate", secondary(configgen.Remote{Addr: ip("192.0.2.1")}, configgen.Remote{Addr: ip("192.0.2.1"), Key: xferKey}), zp + ".primaries[1].addr"},
|
||||||
|
{"secondary primary unknown key", secondary(configgen.Remote{Addr: ip("192.0.2.1"), Key: "nope"}), zp + ".primaries[0].key"},
|
||||||
|
{"primary zone with primaries", zone(func(z *configgen.Zone) {
|
||||||
|
z.Primaries = []configgen.Remote{{Addr: ip("192.0.2.1")}}
|
||||||
|
}), zp + ".primaries"},
|
||||||
|
{"also-notify invalid", zone(func(z *configgen.Zone) { z.AlsoNotify = []configgen.Remote{{}} }), zp + ".also_notify[0].addr"},
|
||||||
|
{"also-notify mapped", zone(func(z *configgen.Zone) {
|
||||||
|
z.AlsoNotify = []configgen.Remote{{Addr: ip("::ffff:192.0.2.1")}}
|
||||||
|
}), zp + ".also_notify[0].addr"},
|
||||||
|
{"also-notify duplicate", zone(func(z *configgen.Zone) {
|
||||||
|
z.AlsoNotify = []configgen.Remote{{Addr: ip("192.0.2.2")}, {Addr: ip("192.0.2.2")}}
|
||||||
|
}), zp + ".also_notify[1].addr"},
|
||||||
|
{"also-notify unknown key", zone(func(z *configgen.Zone) {
|
||||||
|
z.AlsoNotify = []configgen.Remote{{Addr: ip("192.0.2.2"), Key: xferKey}}
|
||||||
|
}), zp + ".also_notify[0].key"},
|
||||||
|
{"transfer key unknown", zone(func(z *configgen.Zone) { z.TransferKey = xferKey }), zp + ".transfer_key"},
|
||||||
|
{"update key unknown", func(c *configgen.DNSConfig) {
|
||||||
|
c.Keys = testKeys()
|
||||||
|
c.Zones[0].Mode = configgen.ZoneDynamic
|
||||||
|
c.Zones[0].UpdateKeys = []string{"dhcp-update", "gone"}
|
||||||
|
}, zp + ".update_keys[1]"},
|
||||||
|
|
||||||
|
{"update key unknown", func(c *configgen.DNSConfig) {
|
||||||
|
dynamic(pfx("192.0.2.0/24"))(c)
|
||||||
|
c.UpdateKey = agentKey
|
||||||
|
}, "update_key"},
|
||||||
|
{"update key without dynamic zone", func(c *configgen.DNSConfig) {
|
||||||
|
c.Keys = []configgen.TSIGKey{agentUpdateKey()}
|
||||||
|
c.UpdateKey = agentKey
|
||||||
|
}, "update_key"},
|
||||||
|
{"update key without zones", func(c *configgen.DNSConfig) {
|
||||||
|
c.Zones = nil
|
||||||
|
c.Keys = []configgen.TSIGKey{agentUpdateKey()}
|
||||||
|
c.UpdateKey = agentKey
|
||||||
|
}, "update_key"},
|
||||||
|
|
||||||
{"dynamic without allow-update", dynamic(), zp + ".allow_update"},
|
{"dynamic without allow-update", dynamic(), zp + ".allow_update"},
|
||||||
{"allow-update not masked", dynamic(pfx("192.0.2.0/24"), pfx("192.0.2.1/24")), zp + ".allow_update[1]"},
|
{"allow-update not masked", dynamic(pfx("192.0.2.0/24"), pfx("192.0.2.1/24")), zp + ".allow_update[1]"},
|
||||||
{"allow-update any", dynamic(pfx("0.0.0.0/0")), zp + ".allow_update[0]"},
|
{"allow-update any", dynamic(pfx("0.0.0.0/0")), zp + ".allow_update[0]"},
|
||||||
@@ -387,6 +601,28 @@ func TestRenderAccepts(t *testing.T) {
|
|||||||
{"forwarders ignored without recursion", func(c *configgen.DNSConfig) {
|
{"forwarders ignored without recursion", func(c *configgen.DNSConfig) {
|
||||||
c.Options.Forwarders = []netip.Addr{ip("192.0.2.1")}
|
c.Options.Forwarders = []netip.Addr{ip("192.0.2.1")}
|
||||||
}},
|
}},
|
||||||
|
{"unreferenced keys", func(c *configgen.DNSConfig) { c.Keys = testKeys() }},
|
||||||
|
{"secondary zone uses only name, kind and primaries", func(c *configgen.DNSConfig) {
|
||||||
|
z := &c.Zones[0]
|
||||||
|
z.Type = configgen.ZoneSecondary
|
||||||
|
z.Primaries = []configgen.Remote{{Addr: ip("2001:db8::1")}, {Addr: ip("192.0.2.1")}}
|
||||||
|
z.Mode, z.DefaultTTL, z.SOA, z.NameServers = "", 0, configgen.SOA{}, nil
|
||||||
|
}},
|
||||||
|
{"explicit primary type", func(c *configgen.DNSConfig) { c.Zones[0].Type = configgen.ZonePrimary }},
|
||||||
|
{"notify without key, transfer key without notify", func(c *configgen.DNSConfig) {
|
||||||
|
c.Keys = testKeys()
|
||||||
|
c.Zones[0].AlsoNotify = []configgen.Remote{{Addr: ip("192.0.2.2")}}
|
||||||
|
c.Zones = append(c.Zones, fuzzConfig().Zones[0])
|
||||||
|
c.Zones[1].TransferKey = xferKey
|
||||||
|
}},
|
||||||
|
{"dynamic zone with keys only", func(c *configgen.DNSConfig) {
|
||||||
|
c.Keys = testKeys()
|
||||||
|
c.Zones[0].Mode = configgen.ZoneDynamic
|
||||||
|
c.Zones[0].UpdateKeys = []string{xferKey, xferKey}
|
||||||
|
}},
|
||||||
|
{"update keys ignored for managed zones", func(c *configgen.DNSConfig) {
|
||||||
|
c.Zones[0].UpdateKeys = []string{"gone"}
|
||||||
|
}},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
@@ -399,6 +635,111 @@ func TestRenderAccepts(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestDynamicRecords checks dynamic-records.json against the zone files
|
||||||
|
// (ADR 0026) and that the update key changes nothing but the update ACLs.
|
||||||
|
func TestDynamicRecords(t *testing.T) {
|
||||||
|
cfg := goldenCases()["dynamic-update"]
|
||||||
|
arts, err := Render(cfg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var doc struct {
|
||||||
|
Version int `json:"version"`
|
||||||
|
Key string `json:"key"`
|
||||||
|
Zones []struct {
|
||||||
|
Zone string `json:"zone"`
|
||||||
|
Records []struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
TTL uint32 `json:"ttl"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Data string `json:"data"`
|
||||||
|
} `json:"records"`
|
||||||
|
} `json:"zones"`
|
||||||
|
}
|
||||||
|
dec := json.NewDecoder(strings.NewReader(artifact(t, arts, configgen.DynamicRecordsFile)))
|
||||||
|
dec.DisallowUnknownFields()
|
||||||
|
if err := dec.Decode(&doc); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if doc.Version != 1 || doc.Key != agentKey || len(doc.Zones) != 2 ||
|
||||||
|
doc.Zones[0].Zone != "2.0.192.in-addr.arpa" || doc.Zones[1].Zone != "office.test" {
|
||||||
|
t.Fatalf("unexpected document %+v", doc)
|
||||||
|
}
|
||||||
|
for _, z := range doc.Zones {
|
||||||
|
// Every record is a line of the zone file, written with the
|
||||||
|
// absolute owner and the effective TTL.
|
||||||
|
zf := artifact(t, arts, "zones/db."+z.Zone)
|
||||||
|
ttl := uint32(86400)
|
||||||
|
if z.Zone == "office.test" {
|
||||||
|
ttl = 3600
|
||||||
|
}
|
||||||
|
lines := map[string]bool{}
|
||||||
|
for _, l := range strings.Split(zf, "\n") {
|
||||||
|
f := strings.Fields(l)
|
||||||
|
if len(f) < 4 || strings.HasPrefix(l, ";") || strings.HasPrefix(l, "$") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
owner := f[0] + "." + z.Zone + "."
|
||||||
|
if f[0] == "@" {
|
||||||
|
owner = z.Zone + "."
|
||||||
|
}
|
||||||
|
rest, t0 := f[1:], ttl
|
||||||
|
if rest[0] != "IN" {
|
||||||
|
v, _ := strconv.ParseUint(rest[0], 10, 32)
|
||||||
|
t0, rest = uint32(v), rest[1:] //nolint:gosec // parsed with 32 bits
|
||||||
|
}
|
||||||
|
lines[fmt.Sprintf("%s %d %s %s", owner, t0, rest[1], strings.Join(rest[2:], " "))] = true
|
||||||
|
}
|
||||||
|
n := 0
|
||||||
|
for _, r := range z.Records {
|
||||||
|
line := fmt.Sprintf("%s %d %s %s", r.Name, r.TTL, r.Type, r.Data)
|
||||||
|
if !lines[line] {
|
||||||
|
t.Errorf("%s: %q is not in the zone file:\n%s", z.Zone, line, zf)
|
||||||
|
}
|
||||||
|
if r.Name == z.Zone+"." && r.Type == "NS" {
|
||||||
|
t.Errorf("%s: apex NS record %q listed", z.Zone, line)
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
want := map[string]int{"2.0.192.in-addr.arpa": 3, "office.test": 14}[z.Zone]
|
||||||
|
if n != want {
|
||||||
|
t.Errorf("%s: %d records, want %d", z.Zone, n, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Without the update key only the ACLs of the dynamic zones differ.
|
||||||
|
plain := cfg
|
||||||
|
plain.UpdateKey = ""
|
||||||
|
without, err := Render(plain)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(without) != len(arts)-2 {
|
||||||
|
t.Fatalf("%d artifacts without update key, %d with", len(without), len(arts))
|
||||||
|
}
|
||||||
|
for _, a := range without {
|
||||||
|
with := artifact(t, arts, a.Path)
|
||||||
|
if a.Path != ConfFile {
|
||||||
|
if with != string(a.Content) {
|
||||||
|
t.Errorf("%s depends on the update key", a.Path)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
wl, pl := strings.Split(with, "\n"), strings.Split(string(a.Content), "\n")
|
||||||
|
for i := range pl {
|
||||||
|
if wl[i] != pl[i] && (!strings.HasPrefix(pl[i], "acl ") || strings.Replace(wl[i], `key "ddi-agent-update"; `, "", 1) != pl[i]) {
|
||||||
|
t.Errorf("conf line %d: %q, without update key %q", i, wl[i], pl[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if conf := artifact(t, arts, ConfFile); strings.Count(conf, `key "ddi-agent-update";`) != 2 {
|
||||||
|
t.Errorf("update key not in both ACLs exactly once:\n%s", conf)
|
||||||
|
}
|
||||||
|
if got := artifact(t, arts, configgen.UpdateKeyFile); got != "key \"ddi-agent-update\" {\n algorithm hmac-sha256;\n secret \""+agentKeySecret+"\";\n};\n" {
|
||||||
|
t.Errorf("update key file:\n%s", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestTXTRData(t *testing.T) {
|
func TestTXTRData(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
in []string
|
in []string
|
||||||
@@ -434,10 +775,15 @@ func TestCompareOwners(t *testing.T) {
|
|||||||
|
|
||||||
// fullConfig combines every golden case into one configuration.
|
// fullConfig combines every golden case into one configuration.
|
||||||
func fullConfig() configgen.DNSConfig {
|
func fullConfig() configgen.DNSConfig {
|
||||||
cfg := configgen.DNSConfig{Serial: 9, ZoneDir: testZoneDir, Options: recursionOptions()}
|
cfg := configgen.DNSConfig{Serial: 9, ZoneDir: testZoneDir, Options: recursionOptions(),
|
||||||
|
Keys: []configgen.TSIGKey{agentUpdateKey()}, UpdateKey: agentKey}
|
||||||
cfg.Zones = append(cfg.Zones, forwardZone())
|
cfg.Zones = append(cfg.Zones, forwardZone())
|
||||||
cfg.Zones = append(cfg.Zones, reverseZones()...)
|
cfg.Zones = append(cfg.Zones, reverseZones()...)
|
||||||
cfg.Zones = append(cfg.Zones, dynamicZones()...)
|
cfg.Zones = append(cfg.Zones, dynamicZones()...)
|
||||||
|
dyn := forwardZone()
|
||||||
|
dyn.Name, dyn.Mode, dyn.AllowUpdate = "dyn2.test", configgen.ZoneDynamic, []netip.Prefix{pfx("192.0.2.20/32")}
|
||||||
|
dyn.NameServers = []configgen.NameServer{{Name: "ns2.example.net"}}
|
||||||
|
cfg.Zones = append(cfg.Zones, dyn)
|
||||||
return cfg
|
return cfg
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
// SPDX-License-Identifier: LicenseRef-DDI-Proprietary
|
||||||
|
|
||||||
|
package bindgen
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"strconv"
|
||||||
|
)
|
||||||
|
|
||||||
|
// dynamicRecordsVersion is the format version of configgen.DynamicRecordsFile.
|
||||||
|
const dynamicRecordsVersion = 1
|
||||||
|
|
||||||
|
// dynamicRecord is one record of configgen.DynamicRecordsFile; the field
|
||||||
|
// order is the order in the file.
|
||||||
|
type dynamicRecord struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
TTL uint32 `json:"ttl"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Data string `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderDynamicRecords writes configgen.DynamicRecordsFile (ADR 0026): one
|
||||||
|
// entry per dynamic primary zone, sorted by name, each with the records DDI
|
||||||
|
// owns in it, one record per line so that revision diffs show single
|
||||||
|
// records. Strings are written by encoding/json; validated names and RDATA
|
||||||
|
// are plain ASCII, so the file is too.
|
||||||
|
func renderDynamicRecords(m *model) []byte {
|
||||||
|
var b bytes.Buffer
|
||||||
|
b.WriteString("{\n \"version\": ")
|
||||||
|
b.WriteString(strconv.Itoa(dynamicRecordsVersion))
|
||||||
|
b.WriteString(",\n \"key\": ")
|
||||||
|
writeJSON(&b, m.updateKey.Name)
|
||||||
|
b.WriteString(",\n \"zones\": [")
|
||||||
|
first := true
|
||||||
|
for i := range m.zones {
|
||||||
|
z := &m.zones[i]
|
||||||
|
if !z.dynamic {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !first {
|
||||||
|
b.WriteByte(',')
|
||||||
|
}
|
||||||
|
first = false
|
||||||
|
b.WriteString("\n {\n \"zone\": ")
|
||||||
|
writeJSON(&b, z.name)
|
||||||
|
b.WriteString(",\n \"records\": [")
|
||||||
|
for j, r := range z.owned {
|
||||||
|
if j > 0 {
|
||||||
|
b.WriteByte(',')
|
||||||
|
}
|
||||||
|
b.WriteString("\n ")
|
||||||
|
ttl := r.ttl
|
||||||
|
if ttl == 0 {
|
||||||
|
ttl = z.defaultTTL
|
||||||
|
}
|
||||||
|
writeJSON(&b, dynamicRecord{Name: absoluteName(r.owner, z.name), TTL: ttl, Type: string(r.typ), Data: r.rdata})
|
||||||
|
}
|
||||||
|
if len(z.owned) > 0 {
|
||||||
|
b.WriteString("\n ")
|
||||||
|
}
|
||||||
|
b.WriteString("]\n }")
|
||||||
|
}
|
||||||
|
if !first {
|
||||||
|
b.WriteString("\n ")
|
||||||
|
}
|
||||||
|
b.WriteString("]\n}\n")
|
||||||
|
return b.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeJSON appends the compact JSON encoding of v without HTML escaping.
|
||||||
|
// v is a string or a dynamicRecord, which always encode.
|
||||||
|
func writeJSON(b *bytes.Buffer, v any) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
enc := json.NewEncoder(&buf)
|
||||||
|
enc.SetEscapeHTML(false)
|
||||||
|
if err := enc.Encode(v); err != nil {
|
||||||
|
panic("bindgen: " + err.Error()) // unreachable for strings and dynamicRecord
|
||||||
|
}
|
||||||
|
b.Write(bytes.TrimSuffix(buf.Bytes(), []byte("\n")))
|
||||||
|
}
|
||||||
|
|
||||||
|
// absoluteName returns the owner (relative to zone, "@" for the apex) as an
|
||||||
|
// absolute name with trailing dot.
|
||||||
|
func absoluteName(owner, zone string) string {
|
||||||
|
if owner == "@" {
|
||||||
|
return zone + "."
|
||||||
|
}
|
||||||
|
return owner + "." + zone + "."
|
||||||
|
}
|
||||||
@@ -6,7 +6,10 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"git.beugsiud.de/beug.k/DDI/server/internal/configgen"
|
||||||
)
|
)
|
||||||
|
|
||||||
// confWriter writes named.conf statements. Every value it receives has been
|
// confWriter writes named.conf statements. Every value it receives has been
|
||||||
@@ -67,6 +70,22 @@ func prefixStrings(ps []netip.Prefix) []string {
|
|||||||
// updateACL is the name of the ACL of a dynamic zone's update sources.
|
// updateACL is the name of the ACL of a dynamic zone's update sources.
|
||||||
func updateACL(zone string) string { return "ddi-update-" + zone }
|
func updateACL(zone string) string { return "ddi-update-" + zone }
|
||||||
|
|
||||||
|
// keyElem is a key reference in a match list or server list.
|
||||||
|
func keyElem(name string) string { return "key " + quoted(name) }
|
||||||
|
|
||||||
|
// remoteList renders a primaries or also-notify list, e.g.
|
||||||
|
// `{ 192.0.2.1 key "xfer"; }`.
|
||||||
|
func remoteList(rs []remote) string {
|
||||||
|
elems := make([]string, len(rs))
|
||||||
|
for i, r := range rs {
|
||||||
|
elems[i] = r.addr.String()
|
||||||
|
if r.key != "" {
|
||||||
|
elems[i] += " " + keyElem(r.key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return braceList(elems)
|
||||||
|
}
|
||||||
|
|
||||||
// renderConf writes ddi-suite.conf: ACLs, then one zone statement per zone.
|
// renderConf writes ddi-suite.conf: ACLs, then one zone statement per zone.
|
||||||
func renderConf(m *model) []byte {
|
func renderConf(m *model) []byte {
|
||||||
var w confWriter
|
var w confWriter
|
||||||
@@ -84,25 +103,91 @@ func renderConf(m *model) []byte {
|
|||||||
w.blank()
|
w.blank()
|
||||||
first = false
|
first = false
|
||||||
}
|
}
|
||||||
w.stmt(0, fmt.Sprintf("acl %s %s;", quoted(updateACL(z.name)), braceList(prefixStrings(z.allowUpdate))))
|
elems := prefixStrings(z.allowUpdate)
|
||||||
|
keys := z.updateKeys
|
||||||
|
if m.updateKey != nil && !slices.Contains(keys, m.updateKey.Name) {
|
||||||
|
keys = slices.Sorted(slices.Values(append(slices.Clone(keys), m.updateKey.Name)))
|
||||||
|
}
|
||||||
|
for _, k := range keys {
|
||||||
|
elems = append(elems, keyElem(k))
|
||||||
|
}
|
||||||
|
w.stmt(0, fmt.Sprintf("acl %s %s;", quoted(updateACL(z.name)), braceList(elems)))
|
||||||
}
|
}
|
||||||
for i := range m.zones {
|
for i := range m.zones {
|
||||||
z := &m.zones[i]
|
z := &m.zones[i]
|
||||||
|
w.blank()
|
||||||
|
w.stmt(0, fmt.Sprintf("zone %s {", quoted(z.name)))
|
||||||
|
if z.secondary {
|
||||||
|
// BIND writes the transferred zone; the DNS agent creates the
|
||||||
|
// directory and never touches its content.
|
||||||
|
w.stmt(1, "type secondary;")
|
||||||
|
w.stmt(1, fmt.Sprintf("file %s;", quoted(m.zoneDir+"/"+SecondaryDir+"/"+zoneFileName(z.name))))
|
||||||
|
w.stmt(1, fmt.Sprintf("primaries %s;", remoteList(z.primaries)))
|
||||||
|
w.stmt(1, "notify no;")
|
||||||
|
w.stmt(0, "};")
|
||||||
|
continue
|
||||||
|
}
|
||||||
update := "none"
|
update := "none"
|
||||||
if z.dynamic {
|
if z.dynamic {
|
||||||
update = quoted(updateACL(z.name))
|
update = quoted(updateACL(z.name))
|
||||||
}
|
}
|
||||||
w.blank()
|
|
||||||
w.stmt(0, fmt.Sprintf("zone %s {", quoted(z.name)))
|
|
||||||
w.stmt(1, "type primary;")
|
w.stmt(1, "type primary;")
|
||||||
w.stmt(1, fmt.Sprintf("file %s;", quoted(m.zoneDir+"/"+zoneFileName(z.name))))
|
w.stmt(1, fmt.Sprintf("file %s;", quoted(m.zoneDir+"/"+zoneFileName(z.name))))
|
||||||
w.stmt(1, "notify no;")
|
if len(z.alsoNotify) > 0 {
|
||||||
|
w.stmt(1, "notify explicit;")
|
||||||
|
w.stmt(1, fmt.Sprintf("also-notify %s;", remoteList(z.alsoNotify)))
|
||||||
|
} else {
|
||||||
|
w.stmt(1, "notify no;")
|
||||||
|
}
|
||||||
|
if z.transferKey != "" {
|
||||||
|
w.stmt(1, fmt.Sprintf("allow-transfer %s;", braceList([]string{keyElem(z.transferKey)})))
|
||||||
|
}
|
||||||
w.stmt(1, fmt.Sprintf("allow-update %s;", braceList([]string{update})))
|
w.stmt(1, fmt.Sprintf("allow-update %s;", braceList([]string{update})))
|
||||||
|
if z.dynamic {
|
||||||
|
// Active Directory registers A records below _msdcs (e.g.
|
||||||
|
// gc._msdcs.<domain>), which the default host name check of
|
||||||
|
// primary zones refuses.
|
||||||
|
w.stmt(1, "check-names ignore;")
|
||||||
|
}
|
||||||
w.stmt(0, "};")
|
w.stmt(0, "};")
|
||||||
}
|
}
|
||||||
return w.b.Bytes()
|
return w.b.Bytes()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// renderKeys writes ddi-suite-keys.conf: one key statement per TSIG key. The
|
||||||
|
// header carries no revision number: the file is secret, so a diff can only
|
||||||
|
// say that it changed, which should mean that a key changed.
|
||||||
|
func renderKeys(m *model) []byte {
|
||||||
|
var w confWriter
|
||||||
|
w.comment(
|
||||||
|
"Generated by DDI Suite. Do not edit: the DNS agent",
|
||||||
|
"overwrites this file. It holds the TSIG keys: include it at the top level",
|
||||||
|
"of named.conf before ddi-suite.conf and keep it readable for named only.",
|
||||||
|
)
|
||||||
|
for _, k := range m.keys {
|
||||||
|
w.blank()
|
||||||
|
w.key(k)
|
||||||
|
}
|
||||||
|
return w.b.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
// key writes one key statement.
|
||||||
|
func (w *confWriter) key(k configgen.TSIGKey) {
|
||||||
|
w.stmt(0, fmt.Sprintf("key %s {", quoted(k.Name)))
|
||||||
|
w.stmt(1, fmt.Sprintf("algorithm %s;", k.Algorithm))
|
||||||
|
w.stmt(1, fmt.Sprintf("secret %s;", quoted(k.Secret)))
|
||||||
|
w.stmt(0, "};")
|
||||||
|
}
|
||||||
|
|
||||||
|
// renderUpdateKey writes the update key file (ADR 0026): the key statement
|
||||||
|
// alone, without comments, in the format named writes its session key in,
|
||||||
|
// which "nsupdate -k" reads.
|
||||||
|
func renderUpdateKey(m *model) []byte {
|
||||||
|
var w confWriter
|
||||||
|
w.key(*m.updateKey)
|
||||||
|
return w.b.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
// renderOptions writes ddi-suite-options.conf, the statements included into
|
// renderOptions writes ddi-suite-options.conf, the statements included into
|
||||||
// the options block of named.conf.
|
// the options block of named.conf.
|
||||||
func renderOptions(m *model) []byte {
|
func renderOptions(m *model) []byte {
|
||||||
|
|||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
; Zone 2.0.192.in-addr.arpa, generated by DDI Suite (revision 11).
|
||||||
|
; Do not edit: the DNS agent overwrites this file.
|
||||||
|
$ORIGIN 2.0.192.in-addr.arpa.
|
||||||
|
$TTL 86400
|
||||||
|
@ IN SOA ns1.office.test. hostmaster.office.test. 11 3600 600 604800 300
|
||||||
|
@ IN NS ns1.office.test.
|
||||||
|
10 IN PTR www.office.test.
|
||||||
|
53 IN PTR ns1.office.test.
|
||||||
|
9 IN PTR www.office.test.
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
; Zone office.test, generated by DDI Suite (revision 11).
|
||||||
|
; Do not edit: the DNS agent overwrites this file.
|
||||||
|
$ORIGIN office.test.
|
||||||
|
$TTL 3600
|
||||||
|
@ IN SOA ns1.office.test. hostmaster.office.test. 11 3600 600 604800 300
|
||||||
|
@ IN NS ns1.office.test.
|
||||||
|
@ IN NS ns2.example.net.
|
||||||
|
ns1 IN A 192.0.2.53
|
||||||
|
ns1 IN AAAA 2001:db8::53
|
||||||
|
@ IN MX 10 mail.office.test.
|
||||||
|
@ IN MX 20 mx.example.net.
|
||||||
|
@ IN TXT "v=spf1 mx -all"
|
||||||
|
_ldap._tcp IN SRV 0 100 389 dc1.office.test.
|
||||||
|
dc1 IN A 192.0.2.20
|
||||||
|
info 600 IN TXT "012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234" "567890123456789012345678901234567890123456789" "say \"hi\" C:\\temp" "caf\195\169" "tab\009here"
|
||||||
|
intranet IN CNAME www.office.test.
|
||||||
|
mail 300 IN A 192.0.2.25
|
||||||
|
sub IN NS ns1.sub.office.test.
|
||||||
|
ns1.sub IN A 192.0.2.60
|
||||||
|
www IN A 192.0.2.9
|
||||||
|
www IN A 192.0.2.10
|
||||||
|
www IN AAAA 2001:db8::10
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
// Generated by DDI Suite. Do not edit: the DNS agent
|
||||||
|
// overwrites this file. It holds the TSIG keys: include it at the top level
|
||||||
|
// of named.conf before ddi-suite.conf and keep it readable for named only.
|
||||||
|
|
||||||
|
key "xfer.dns-a" {
|
||||||
|
algorithm hmac-sha256;
|
||||||
|
secret "eGZlci1zZWNyZXQtb2YtZG5zLWEtMzItYnl0ZXMhIQ==";
|
||||||
|
};
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
// Generated by DDI Suite (revision 11). Do not edit: the DNS agent
|
||||||
|
// overwrites this file. Include it inside the options block of named.conf
|
||||||
|
// and do not set the statements below there as well.
|
||||||
|
|
||||||
|
recursion no;
|
||||||
|
allow-transfer { none; };
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
// Generated by DDI Suite (revision 11). Do not edit: the DNS agent
|
||||||
|
// overwrites this file. Include it at the top level of named.conf.
|
||||||
|
|
||||||
|
zone "2.0.192.in-addr.arpa" {
|
||||||
|
type primary;
|
||||||
|
file "/etc/bind/ddi-suite/zones/db.2.0.192.in-addr.arpa";
|
||||||
|
notify explicit;
|
||||||
|
also-notify { 192.0.2.3 key "xfer.dns-a"; 2001:db8::2 key "xfer.dns-a"; };
|
||||||
|
allow-transfer { key "xfer.dns-a"; };
|
||||||
|
allow-update { none; };
|
||||||
|
};
|
||||||
|
|
||||||
|
zone "office.test" {
|
||||||
|
type primary;
|
||||||
|
file "/etc/bind/ddi-suite/zones/db.office.test";
|
||||||
|
notify explicit;
|
||||||
|
also-notify { 192.0.2.3 key "xfer.dns-a"; 2001:db8::2 key "xfer.dns-a"; };
|
||||||
|
allow-transfer { key "xfer.dns-a"; };
|
||||||
|
allow-update { none; };
|
||||||
|
};
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
; Initial file of the dynamic zone dyn.test, generated by DDI Suite (revision 8).
|
||||||
|
; BIND owns this file once it exists; the DNS agent never overwrites it.
|
||||||
|
$ORIGIN dyn.test.
|
||||||
|
$TTL 1200
|
||||||
|
@ IN SOA ns1.dyn.test. hostmaster.dyn.test. 8 3600 600 604800 300
|
||||||
|
@ IN NS ns1.dyn.test.
|
||||||
|
ns1 IN A 192.0.2.53
|
||||||
|
dc1 IN A 192.0.2.20
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
; Initial file of the dynamic zone keys-only.test, generated by DDI Suite (revision 8).
|
||||||
|
; BIND owns this file once it exists; the DNS agent never overwrites it.
|
||||||
|
$ORIGIN keys-only.test.
|
||||||
|
$TTL 1200
|
||||||
|
@ IN SOA ns1.dyn.test. hostmaster.dyn.test. 8 3600 600 604800 300
|
||||||
|
@ IN NS ns1.dyn.test.
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
; Zone static.test, generated by DDI Suite (revision 8).
|
||||||
|
; Do not edit: the DNS agent overwrites this file.
|
||||||
|
$ORIGIN static.test.
|
||||||
|
$TTL 3600
|
||||||
|
@ IN SOA ns1.dyn.test. hostmaster.dyn.test. 8 3600 600 604800 300
|
||||||
|
@ IN NS ns1.dyn.test.
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
// Generated by DDI Suite. Do not edit: the DNS agent
|
||||||
|
// overwrites this file. It holds the TSIG keys: include it at the top level
|
||||||
|
// of named.conf before ddi-suite.conf and keep it readable for named only.
|
||||||
|
|
||||||
|
key "admin.update" {
|
||||||
|
algorithm hmac-sha384;
|
||||||
|
secret "YWRtaW4tdXBkYXRl";
|
||||||
|
};
|
||||||
|
|
||||||
|
key "ddi-agent-update" {
|
||||||
|
algorithm hmac-sha256;
|
||||||
|
secret "ZGRpLWFnZW50LXVwZGF0ZS1zZWNyZXQtMzItYnl0ZXM=";
|
||||||
|
};
|
||||||
|
|
||||||
|
key "dhcp-update" {
|
||||||
|
algorithm hmac-sha512;
|
||||||
|
secret "ZGhjcC11cGRhdGUtc2VjcmV0";
|
||||||
|
};
|
||||||
|
|
||||||
|
key "xfer.dns-a" {
|
||||||
|
algorithm hmac-sha256;
|
||||||
|
secret "eGZlci1zZWNyZXQtb2YtZG5zLWEtMzItYnl0ZXMhIQ==";
|
||||||
|
};
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
// Generated by DDI Suite (revision 8). Do not edit: the DNS agent
|
||||||
|
// overwrites this file. Include it inside the options block of named.conf
|
||||||
|
// and do not set the statements below there as well.
|
||||||
|
|
||||||
|
recursion no;
|
||||||
|
allow-transfer { none; };
|
||||||
+4
@@ -0,0 +1,4 @@
|
|||||||
|
key "ddi-agent-update" {
|
||||||
|
algorithm hmac-sha256;
|
||||||
|
secret "ZGRpLWFnZW50LXVwZGF0ZS1zZWNyZXQtMzItYnl0ZXM=";
|
||||||
|
};
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
// Generated by DDI Suite (revision 8). Do not edit: the DNS agent
|
||||||
|
// overwrites this file. Include it at the top level of named.conf.
|
||||||
|
|
||||||
|
acl "ddi-update-dyn.test" { 192.0.2.10/32; 192.0.2.11/32; 2001:db8:1::/64; key "admin.update"; key "ddi-agent-update"; key "dhcp-update"; };
|
||||||
|
acl "ddi-update-keys-only.test" { key "ddi-agent-update"; key "dhcp-update"; };
|
||||||
|
|
||||||
|
zone "dyn.test" {
|
||||||
|
type primary;
|
||||||
|
file "/etc/bind/ddi-suite/zones/db.dyn.test";
|
||||||
|
notify no;
|
||||||
|
allow-update { "ddi-update-dyn.test"; };
|
||||||
|
check-names ignore;
|
||||||
|
};
|
||||||
|
|
||||||
|
zone "keys-only.test" {
|
||||||
|
type primary;
|
||||||
|
file "/etc/bind/ddi-suite/zones/db.keys-only.test";
|
||||||
|
notify no;
|
||||||
|
allow-update { "ddi-update-keys-only.test"; };
|
||||||
|
check-names ignore;
|
||||||
|
};
|
||||||
|
|
||||||
|
zone "static.test" {
|
||||||
|
type primary;
|
||||||
|
file "/etc/bind/ddi-suite/zones/db.static.test";
|
||||||
|
notify no;
|
||||||
|
allow-update { none; };
|
||||||
|
};
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user