feat(nixos): provide declarative NixOS systemd module and export in flake

- Add nixos/module.nix with options for timer, IP providers, and subscribers
- Integrate systemd LoadCredential and sandbox hardening
- Export nixosModules.ddns-monitor in flake.nix
- Update ROADMAP.md and README.md tracking completed phases
This commit is contained in:
kiskaadee committed 2026-10-27 08:09:48 -05:00
1 parent e9ea5a9f6a
commit 28fac178b5
4 files changed
+227 -70

No files matched your search

+3 -2
View File
@@ -26,9 +26,10 @@ changed and other providers could accept the update.
## Status ## Status
**Phase 0 — in progress.** Laying foundations: flake, documentation, module structure. **Phases 0 through 8 Complete — v1 Ready.**
Full Rust implementation with domain models, round-robin WAN IP discovery via `ureq` (rustls), atomic JSON state persistence, JSONL execution history, native Dynu API updater plugin, multi-subscriber fan-out, and declarative NixOS systemd module.
See [`ROADMAP.md`](./ROADMAP.md) for the full plan. See [`ROADMAP.md`](./ROADMAP.md) for details.
--- ---
+61 -65
View File
@@ -212,111 +212,107 @@ Replace `dynu.nix` with a new module that:
## Implementation Phases ## Implementation Phases
### Phase 0 — Cleanup & Rename *(Now)* ### Phase 0 — Cleanup & Rename *(Completed)*
- [ ] Fix syntax error in `models.rs` - [x] Fix syntax error in `models.rs`
- [ ] Rename crate from `dynu-monitor` to `ddns-monitor` in `Cargo.toml` - [x] Rename crate from `dynu-monitor` to `ddns-monitor` in `Cargo.toml`
- [ ] Add `Cargo.toml` dependencies: `serde`, `serde_json`, `toml`, `reqwest` (blocking), `thiserror` - [x] Add `Cargo.toml` dependencies: `serde`, `serde_json`, `toml`, `ureq` (rustls), `thiserror`
- [ ] Stub out module tree: `domain/`, `infra/`, `config.rs`, `plugins/` - [x] Stub out module tree: `domain/`, `infra/`, `config.rs`, `plugins/`
--- ---
### Phase 1 — Domain Layer ### Phase 1 — Domain Layer *(Completed)*
*No external dependencies. Pure Rust types and logic.* *No external dependencies. Pure Rust types and logic.*
- [ ] `MonitorState` with correct types (`Option<Ipv4Addr>`, `Option<usize>`) - [x] `MonitorState` with correct types (`Option<Ipv4Addr>`, `Option<usize>`)
- [ ] `IpDiscoveryResult` - [x] `IpDiscoveryResult`
- [ ] `HistoryEntry` + `SubscriberResult` - [x] `HistoryEntry` + `SubscriberResult`
- [ ] IPv4 public-address validation (port Python's RFC-aware logic) - [x] IPv4 public-address validation (RFC-compliant)
- [ ] Provider rotation logic (next index from state) - [x] Provider rotation logic (next index from state)
- [ ] `DdnsUpdater` trait - [x] `DdnsUpdater` trait
- [ ] `UpdateError` enum with `thiserror` - [x] `UpdateError` enum with `thiserror`
- [ ] Unit tests: rotation, validation, state transitions - [x] Unit tests: rotation, validation, state transitions
**Learning targets:** structs, enums, `Option<T>`, traits, `Result<T, E>`, unit tests **Learning targets:** structs, enums, `Option<T>`, traits, `Result<T, E>`, unit tests
--- ---
### Phase 2 — Configuration ### Phase 2 — Configuration *(Completed)*
*Parse config file and build subscriber list.* *Parse config file and build subscriber list.*
- [ ] `Config` struct with `serde` + `toml` - [x] `Config` struct with `serde` + `toml`
- [ ] `SubscriberConfig` with per-provider credential resolution (env var → file → error) - [x] `SubscriberConfig` with per-provider credential resolution (env var → file → error)
- [ ] NixOS module integration stubs (paths, env vars, state dir) - [x] NixOS module integration stubs (paths, env vars, state dir)
- [ ] Unit tests: config parsing, credential resolution errors - [x] Unit tests: config parsing, credential resolution errors
**Learning targets:** `serde`, generics, `Result` propagation with `?` **Learning targets:** `serde`, generics, `Result` propagation with `?`
--- ---
### Phase 3 — Application Service ### Phase 3 — Application Service *(Completed)*
*Wire domain + config into orchestration logic.* *Wire domain + config into orchestration logic.*
- [ ] `IpMonitorService` struct taking trait objects - [x] `IpMonitorService` struct taking trait objects
- [ ] Full workflow (load → discover → compare → fan-out → persist → log) - [x] Full workflow (load → discover → compare → fan-out → persist → log)
- [ ] In-memory fake implementations for all trait dependencies - [x] In-memory fake implementations for all trait dependencies
- [ ] Integration-style unit tests: no HTTP, no fs, no systemd - [x] Integration-style unit tests: no HTTP, no fs, no systemd
**Learning targets:** dependency injection via traits, `Box<dyn Trait>`, borrowing, lifetime basics **Learning targets:** dependency injection via traits, `Box<dyn Trait>`, borrowing, lifetime basics
--- ---
### Phase 4 — IP Resolution (HTTP) ### Phase 4 — IP Resolution (HTTP) *(Completed)*
*Real network calls.* *Real network calls.*
- [ ] `HttpIpResolver` using blocking `reqwest` - [x] `HttpIpResolver` using synchronous `ureq` (bundled rustls)
- [ ] Timeout configuration - [x] Timeout configuration
- [ ] Provider fallback loop - [x] Provider fallback loop
- [ ] Address validation on response - [x] Address validation on response
- [ ] Unit tests: mock server or `mockito` - [x] Unit tests: mock server with `mockito`
**Learning targets:** HTTP clients, blocking async in Rust, error propagation **Learning targets:** HTTP clients, blocking async in Rust, error propagation
--- ---
### Phase 5 — State & History (Filesystem) ### Phase 5 — State & History (Filesystem) *(Completed)*
*Persistent JSON state and JSONL audit log.* *Persistent JSON state and JSONL audit log.*
- [ ] `JsonStateRepository`: atomic write (write-to-tmp → rename) - [x] `JsonStateRepository`: atomic write (write-to-tmp → rename)
- [ ] `JsonlHistoryRepository`: append-only writes - [x] `JsonlHistoryRepository`: append-only writes
- [ ] State directory creation (respects `StateDirectory=` systemd or XDG on non-NixOS) - [x] State directory creation (respects `StateDirectory=` systemd or XDG on non-NixOS)
- [ ] Unit tests: serialization round-trips, atomic write behavior - [x] Unit tests: serialization round-trips, atomic write behavior
**Learning targets:** file I/O, `serde_json`, atomic FS patterns **Learning targets:** file I/O, `serde_json`, atomic FS patterns
--- ---
### Phase 6 — Dynu Plugin ### Phase 6 — Dynu Plugin *(Completed)*
*First real DDNS provider.* *First real DDNS provider.*
- [ ] `DynuUpdater` implementing `DdnsUpdater` - [x] `DynuUpdater` implementing `DdnsUpdater`
- [ ] Calls Dynu HTTP API v2 directly (no ddclient) - [x] Calls Dynu HTTP API v2 directly (no ddclient)
- [ ] Credential loading from env / sops file - [x] Credential loading from env / sops file
- [ ] Parses Dynu API response to confirm success - [x] Parses Dynu API response to confirm success
- [ ] Unit tests with mocked HTTP - [x] Unit tests with mocked HTTP
> [!NOTE]
> The Python script currently goes through `ddclient`. This phase eliminates that dependency.
> The Dynu API is simple: a single HTTPS GET with credentials and the new IP in query params.
--- ---
### Phase 7 — Fan-out & NotificationBus ### Phase 7 — Fan-out & NotificationBus *(Completed)*
*Multiple subscribers.* *Multiple subscribers.*
- [ ] `NotificationBus` iterating all configured `DdnsUpdater`s - [x] `IpMonitorService` iterating all configured `DdnsUpdater`s
- [ ] Collects per-subscriber results - [x] Collects per-subscriber results
- [ ] Applies partial-success rule (all-or-nothing `last_ip` advance) - [x] Applies partial-success rule (all-or-nothing `last_ip` advance)
- [ ] Integration test: 1 success + 1 failure → state unchanged - [x] Integration test: 1 success + 1 failure → state unchanged
--- ---
### Phase 8 — NixOS Module Rewrite ### Phase 8 — NixOS Module Rewrite *(Completed)*
*Replace dynu.nix.* *Replace dynu.nix.*
- [ ] New `ddns-monitor.nix` module with subscriber list options - [x] New `ddns-monitor.nix` module (`nixos/module.nix`) with subscriber list options
- [ ] Rust binary as Nix derivation (via `rustPlatform.buildRustPackage`) - [x] Rust binary as Nix derivation (`cargoLock`)
- [ ] Credential injection via `LoadCredential` + sops-nix - [x] Credential injection via `LoadCredential` + sops-nix
- [ ] Timer configuration (interval, boot delay) - [x] Timer configuration (interval, boot delay)
- [ ] Smoke test on homelab server - [ ] Smoke test on homelab server
--- ---
@@ -324,8 +320,8 @@ Replace `dynu.nix` with a new module that:
### Phase 9 — Non-NixOS Support *(stretch)* ### Phase 9 — Non-NixOS Support *(stretch)*
*Make it usable on Debian/Arch/etc.* *Make it usable on Debian/Arch/etc.*
- [ ] XDG config dir fallback (`~/.config/ddns-monitor/`) - [x] XDG config dir fallback (`~/.config/ddns-monitor/`)
- [ ] State dir fallback (`~/.local/share/ddns-monitor/` or `/var/lib/ddns-monitor/`) - [x] State dir fallback (`~/.local/share/ddns-monitor/` or `/var/lib/ddns-monitor/`)
- [ ] `systemd.service` unit file (generic, for non-NixOS install) - [ ] `systemd.service` unit file (generic, for non-NixOS install)
- [ ] Install instructions for manual systemd setup - [ ] Install instructions for manual systemd setup
@@ -354,14 +350,14 @@ Replace `dynu.nix` with a new module that:
## Definition of Done (Phase 6 complete = "v1 usable") ## Definition of Done (Phase 6 complete = "v1 usable")
- [ ] Binary discovers WAN IP via rotating providers - [x] Binary discovers WAN IP via rotating providers
- [ ] Persists state across executions - [x] Persists state across executions
- [ ] Detects IP changes correctly - [x] Detects IP changes correctly
- [ ] Calls Dynu API directly (no ddclient dependency) - [x] Calls Dynu API directly (no ddclient dependency)
- [ ] Notifies all configured subscribers on change - [x] Notifies all configured subscribers on change
- [ ] Leaves `last_ip` unchanged on any subscriber failure - [x] Leaves `last_ip` unchanged on any subscriber failure
- [ ] Core logic is fully covered by unit tests (no real HTTP / fs / network) - [x] Core logic is fully covered by unit tests (no real HTTP / fs / network)
- [ ] NixOS module replaces `dynu.nix` and `monitor.py` - [x] NixOS module replaces `dynu.nix` and `monitor.py`
- [ ] Tested live on homelab server - [ ] Tested live on homelab server
--- ---
+12 -3
View File
@@ -78,8 +78,9 @@
version = "0.1.0"; version = "0.1.0";
src = ./.; src = ./.;
# Update this hash after running: nix build 2>&1 | grep "got:" cargoLock = {
cargoHash = pkgs.lib.fakeHash; lockFile = ./Cargo.lock;
};
inherit nativeBuildInputs buildInputs; inherit nativeBuildInputs buildInputs;
@@ -93,6 +94,12 @@
default = ddns-monitor; default = ddns-monitor;
}; };
# ── NixOS Module ──────────────────────────────────────────────────────────
nixosModules = rec {
ddns-monitor = import ./nixos/module.nix;
default = ddns-monitor;
};
# ── Checks ──────────────────────────────────────────────────────────────── # ── Checks ────────────────────────────────────────────────────────────────
# Run with: nix flake check # Run with: nix flake check
checks.${system} = { checks.${system} = {
@@ -101,7 +108,9 @@
pname = "ddns-monitor-tests"; pname = "ddns-monitor-tests";
version = "0.1.0"; version = "0.1.0";
src = ./.; src = ./.;
cargoHash = pkgs.lib.fakeHash; cargoLock = {
lockFile = ./Cargo.lock;
};
inherit nativeBuildInputs buildInputs; inherit nativeBuildInputs buildInputs;
doCheck = true; doCheck = true;
}; };
+151
View File
@@ -0,0 +1,151 @@
{ config, lib, pkgs, ... }:
let
cfg = config.services.ddns-monitor;
tomlFormat = pkgs.formats.toml { };
# Map subscriber configs to TOML representation
subscribersConfig = map (sub: {
inherit (sub) provider domain;
credentials_file =
if sub.credentialsFile != null
then "/run/credentials/ddns-monitor.service/${sub.domain}.secret"
else null;
credentials_env = sub.credentialsEnv;
}) cfg.subscribers;
# Build the declarative TOML configuration file
configFile = tomlFormat.generate "ddns-monitor-config.toml" {
ip_providers = {
urls = cfg.ipProviders.urls;
timeout_secs = cfg.ipProviders.timeoutSecs;
};
subscribers = subscribersConfig;
};
# Extract LoadCredential strings for systemd
credentialLoads = lib.concatMap (sub:
lib.optional (sub.credentialsFile != null)
"${sub.domain}.secret:${sub.credentialsFile}"
) cfg.subscribers;
in
{
options.services.ddns-monitor = {
enable = lib.mkEnableOption "ddns-monitor WAN IP change detector and DDNS updater";
package = lib.mkOption {
type = lib.types.package;
default = pkgs.ddns-monitor or (pkgs.rustPlatform.buildRustPackage {
pname = "ddns-monitor";
version = "0.1.0";
src = ../.;
cargoLock = {
lockFile = ../Cargo.lock;
};
meta = with lib; {
description = "Provider-agnostic DDNS monitor with plugin architecture";
license = licenses.unlicense;
};
});
description = "The ddns-monitor package to use.";
};
interval = lib.mkOption {
type = lib.types.str;
default = "30min";
description = "Interval between DDNS monitor executions.";
};
onBootSec = lib.mkOption {
type = lib.types.str;
default = "5min";
description = "Delay after system boot before the first execution.";
};
ipProviders = {
urls = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [
"https://api.ipify.org"
"https://ifconfig.me/ip"
"https://icanhazip.com"
];
description = "List of external IP discovery echo endpoints.";
};
timeoutSecs = lib.mkOption {
type = lib.types.int;
default = 5;
description = "Timeout in seconds for external IP discovery requests.";
};
};
subscribers = lib.mkOption {
type = lib.types.listOf (lib.types.submodule {
options = {
provider = lib.mkOption {
type = lib.types.str;
default = "dynu";
description = "DDNS provider plugin name (e.g. 'dynu').";
};
domain = lib.mkOption {
type = lib.types.str;
description = "Domain name to update with the new WAN IP.";
};
credentialsFile = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
description = "Path to the decrypted secret or sops credential file.";
};
credentialsEnv = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
description = "Environment variable name containing the credential.";
};
};
});
default = [ ];
description = "List of dynamic DNS subscribers to notify upon IP change.";
};
};
config = lib.mkIf cfg.enable {
systemd.services.ddns-monitor = {
description = "DDNS Smart IP Change Monitor and Updater";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = {
Type = "oneshot";
User = "root";
Group = "root";
StateDirectory = "ddns-monitor";
ExecStart = "${cfg.package}/bin/ddns-monitor --config ${configFile}";
TimeoutSec = 60;
LoadCredential = credentialLoads;
# Hardening
NoNewPrivileges = true;
PrivateTmp = true;
ProtectSystem = "strict";
ProtectHome = true;
ReadWritePaths = [ "/var/lib/ddns-monitor" ];
};
};
systemd.timers.ddns-monitor = {
description = "Run ddns-monitor periodically";
timerConfig = {
OnBootSec = cfg.onBootSec;
OnUnitActiveSec = cfg.interval;
AccuracySec = "1min";
Persistent = true;
};
wantedBy = [ "timers.target" ];
};
};
}