Harden Backrest CLI endpoint and restore recipes (#226) #265
No reviewers
Labels
No labels
area:authentication
area:flake-utilities
area:performance
area:tbd
host:chaos
host:cosmos
host:electra
host:fleet
host:lena
host:lyra
host:mass-storage
host:media1
host:nimmog-de
host:nova
host:pangolin
host:pangolin-vps
host:phone
host:router
host:vega
investigation
phase:cutover
phase:deploy
phase:mcp
phase:module
phase:packaging
phase:prep
phase:validation
priority:high
priority:medium
project:attic-postgres-lyra-rollout
project:auto-update-reliability
project:auto-update-remediation
project:declarative-purity-cleanup
project:external-review
project:fleet-boundary-cleanup
project:host-facts-refactor
project:lyra-nixos-deploy
project:lyra-service-stack-migration
project:nebula-mesh-network
project:nix-idioms-hygiene
project:nixos-build-deployment-pipeline
project:security-hardening
project:service-stack-migration
project:vega-sillytavern-cutover
project:wiki-rebuild
repo:numtide/flake-utils
repo:numtide/nix-auth
repo:numtide/nixos-passthru-cache
repo:numtide/nix-relay
service:auto-update
service:gitlab
service:hermes
service:mem0
service:nix
service:sillytavern
service:slskd
service:synthseek
service:tdarr
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
nimmo/nixos-config!265
Loading…
Reference in a new issue
No description provided.
Delete branch "fix/backrest-cli-restore-hardening"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Addresses #226 (Milestone: Wiki Audit Implementation Follow-ups).
This MR unifies repository and endpoint configuration between the Backrest daemon and interactive Restic CLI recipes, enforces root privileges for full-host disaster recovery restores to prevent partial failure states, and hardens staged partial restores with completion tracking and cleanup guidance.
Changes
nixosConfig.backrest.endpoint(default"mass-storage.mesh:8008") andnixosConfig.backrest.repo(default"home") tomodules/common/default-config.nix.modules/services/backrest.nixto use these evaluated options instead of hardcoded values, and declareenvironment.etc."backrest/restic-cli.env".scripts/backrest-env.shto dynamically resolve user, endpoint, repo, and SOPS secret paths, eliminating the hardcoded LAN IP (192.168.8.238:8008) fromjustfiles/maintenance.just.scripts/backup-restore.sh:restore-path: Writes.restore-completeon success. On interruption or failure, traps errors, warns of partial contents, and provides clear cleanup commands (rm -rf <target>) to prevent retries from failing obscurely on target collisions.restore: Requires root privileges ([ "$(id -u)" -eq 0 ]) prior to touching/, eliminating the risk of partial restore failures when encountering root-owned service paths. Supports host filtering and explicit snapshot selection.justfiles/maintenance.justto delegate to these helpers and support host filtering across commands.tests/backup-restore-regressions.shcovering 10 distinct regression scenarios.README.mdand repository wiki runbooks (35-Backup-Verification-and-Partial-Restore.md,36-Full-Host-Recovery.md,39a-Service-Migration-and-Cutover.md), removing transitional warnings.Validation
tests/backup-restore-regressions.sh: All 10 tests passed.tests/nixos-deploy-regressions.sh: Passed.tests/nixos-deploy-wrapper-regressions.sh: Passed.tests/nixos-pin-lifecycle-regressions.sh: Passed.nix fmt: Applied cleanly.nix flake check: All checks passed.Automated code review
Reviewed commit:
26a4c75ad356f13811e0bea13e39be399e8c6f20Verdict: Ready to merge
No blocking or important findings were retained, and deterministic checks passed. Suggestions remain advisory.
Overall assessment
The pull request refactors the Backrest backup/restore workflow by introducing a new shell script (
scripts/backrest-env.sh) to resolve configuration dynamically from static NixOS deployment files or flake evaluation fallbacks. It replaces hardcoded credentials and endpoints injustfiles/maintenance.justwith calls to this script. A new helper script (scripts/backup-restore.sh) handles interactive restores, enforcing root privileges for full-host recovery and using atomic markers for partial restores. The PR adds NixOS module options for endpoint and repo configuration and includes comprehensive regression tests.Blocking findings
None.
Important findings
None.
Suggestions
None.
Tests and validation
Questions
backrest-env.shwork correctly on systems wherenixis installed but the flake inputs are not yet fetched or evaluated? The script checks forflake.nixexistence but does not verify if the flake is valid or if the required attributes exist before attempting evaluation.backup-restore.sh, therestore-pathcommand uses a trap to clean up partial markers on error. However, if the script is interrupted by a signal (e.g., SIGINT) that bypasses the ERR trap, will the marker be cleaned up? The current trap only catches errors from commands, not signals.read_secretfunction checks for world-accessible permissions but does not enforce them or refuse to read. Is this intentional, and should there be an option to fail on insecure permissions rather than just warning?Review limitations
nix flake check) to verify that the new options inmodules/common/default-config.nixare correctly integrated and do not break host configurations.Diff coverage
README.md: reviewed — included in a context-limited batchjustfiles/maintenance.just: reviewed — included in a context-limited batchmodules/common/default-config.nix: reviewed — included in a context-limited batchmodules/services/backrest.nix: reviewed — included in a context-limited batchscripts/backrest-env.sh: reviewed — included in a context-limited batchscripts/backup-restore.sh: reviewed — included in a context-limited batchtests/backup-restore-regressions.sh: reviewed — included in a context-limited batchReview metadata
Response to automated review
Thank you for the review! Commit
880ac31addresses the findings:Eliminated hardcoded fallback credentials in
scripts/backrest-env.sh:nimmo,mass-storage.mesh:8008,home) with dynamic flake evaluation fallback (nix eval --raw "${FLAKE_DIR}#nixosConfigurations.${CURRENT_HOST}.config.nixosConfig...")./etc/backrest/restic-cli.env, nor the flake evaluation, nor explicit environment variable overrides are available, the script now fails explicitly with exit code 1 and an informative diagnostic.Added secret file permission checks:
read_secret, added a check that inspects file mode and issues a warning if any secret file has world-readable permissions.Clarification on confirmation prompt:
scripts/backup-restore.shdeliberately so that safety checks and confirmations cannot be bypassed by executing the script directly outsidejust.Expanded regression tests:
tests/backup-restore-regressions.shnow covers 13 test cases, including flake evaluation fallback, explicit failure when unresolvable, and world-readable secret warning detection.nix fmtand validated withnix flake check(all checks passed).Follow-up response to automated review
Commit
3099fd1resolves both items from the updated review:Corrected Octal Permission Checking:
[ $((8#$mode & 0007)) -ne 0 ].0644or0604) while allowing safe group access (0640, commonly used by NixOSkeysgroup).Flake Evaluation Diagnostics Captured:
eval_flake_attrto filter dirty-tree warnings and capture genuinenix evalfailure diagnostics across the command substitution subshell boundary.BACKREST_CONFIG_ENVis absent, the exactnix evalfailure message is reported in stderr to aid debugging.Expanded Test Coverage:
tests/backup-restore-regressions.shverifying that:0640does not trigger a world-readable warning.0604triggers a world-readable warning.0644triggers a world-readable warning.nix fmt, andnix flake checkpassed.Update on secret read error handling & atomic marker creation
Commit
4cf4359addresses the latest review points:Explicit Error Handling for Secret Reads:
read_secretnow treatssudoread failures and empty secret files as explicit errors with informative diagnostic messages, rather than silently returning an empty string or falling back with|| true.Atomic Completion Marker Creation:
scripts/backup-restore.shto create.restore-completevia a temporary file inside the target directory (mktemp "$TARGET/.restore-complete.XXXXXX") and an atomic rename (mv -f).Validation:
tests/backup-restore-regressions.sh(all 13 tests passed).nix fmtand validated withnix flake check(all checks passed).Response to automated review (Commit
9a9516c)Thank you for the detailed feedback. Commit
9a9516caddresses the findings and provides the requested clarifications:Static Caching vs Flake Evaluation Latency:
modules/services/backrest.nixdeclaresenvironment.etc."backrest/restic-cli.env", which is populated statically duringnixos-rebuild switch.scripts/backrest-env.shchecks/etc/backrest/restic-cli.envfirst; in normal operation on deployed systems,nix evalis never executed.nix evalis strictly a fallback intended for development checkouts or pre-deployment testing where/etc/backrest/restic-cli.envis not yet generated.BACKREST_ENDPOINT,BACKREST_USER,BACKREST_REPO, orRESTIC_REPOSITORY/RESTIC_PASSWORD), completely bypassing both/etcand flake eval.Captured
sudoDiagnostics inread_secret:read_secretnow capturessudo's stderr into a temporary file instead of suppressing it to/dev/null. Ifsudo catfails (e.g. auth failure, PAM restriction, or permission denial), the exact error message is surfaced in the diagnostic output.Secret Permissions (0640 vs 0007):
0640or0440) is intentional on NixOS, where SOPS secrets are provisioned with ownership by groupkeysso non-root services can access them securely. The warning specifically targets the dangerous world-readable bits (0007).Environment Isolation in
backup-restore.sh:scripts/backup-restore.shbegins with#!/usr/bin/env bashand is executed as an isolated subshell. Sourcingbackrest-env.shwithin it scopes the exported variables to that script's process only, preventing any leakage into the invoking shell.Validation:
tests/backup-restore-regressions.sh(Test 6) verifying thatsudofailure diagnostics are accurately captured and reported.nix fmtwas run, andnix flake checksucceeded.Follow-up response to automated review (Commit
26a4c75)Commit
26a4c75refines the warning phrasing and answers the review's questions:Permission Warning Phrasing:
"world-readable permissions"to"world-accessible permissions"inscripts/backrest-env.sh, precisely reflecting that the check evaluates the entire lower octal digit ($((8#$mode & 0007))) covering other-read, other-write, and other-execute bits.0601).Clarification on Questions:
/etc/backrest/restic-cli.envis the statically cached deployment configuration. On recovery targets without Nix installed, operators supply standard environment variables (BACKREST_ENDPOINT,BACKREST_USER,BACKREST_REPOorRESTIC_REPOSITORY/RESTIC_PASSWORD) or CLI options, which bypass both/etcand flake eval.eval_flake_attrWarning Filtering: Only the dirty-tree notice (warning: Git tree .* is dirty) emitted bynix evalis filtered; all genuine evaluation diagnostics and syntax errors are retained.id -u:idis a core utility provided unconditionally by NixOS system packages on all NixOS systems and recovery images.${d}inmodules/services/backrest.nix: Inbackrest.nix,d = "$"is defined in the module'slet ... inbinding, which is the canonical Nix idiom for injecting literal bash${VAR}interpolations without escaping collisions.Validation:
./tests/backup-restore-regressions.sh).nix fmtwas run.nix flake checkpassed.