nixos: describe both servers as NixOS systems

Start of the move from Ansible to NixOS. Services run as native NixOS
services where nixpkgs has a module and as Podman containers otherwise;
there is no Docker.

Shared: users with their Debian UIDs, SSH with the Ansible role's crypto
settings, nftables firewall, WireGuard (ops is the hub), sops-nix
secrets per host, the restic backup script with its schedule and
retention, mail on unit failure.

asxpio-services: Xray, SillyTavern, Minecraft (Paper) and the ACME
forwarder natively; XMPP stays in containers because the server is a
custom build.

asxpio-ops: Postgres, Garage and Forgejo natively. Roles, buckets, keys
and grants move here from the storage repo's init scripts.

Services that own data wait for /var/lib/.data-in-place, so an install
never creates empty state where a restore is about to land.
migration/*-data.sh move the Debian-era data into the new layout.

hosts/rehearsal turns the two hosts into a test pair with its own keys
and dummy secrets. Everything here ran there, Postgres, Garage, Forgejo,
Minecraft and SillyTavern on a restored copy of production data. Three
differences from the containers showed up and are handled: Garage
rejects a 0440 credential file, Geyser needs libcrypto and netlink,
SillyTavern ignores the module's listen flags.

Production is untouched: both servers still run Debian under Ansible.

Assisted-by: Claude:fable-5-2
This commit is contained in:
Sergei Poljanski 2026-11-16 22:59:59 +04:00
commit be68c5adef
Signed by: asxpi
GPG key ID: 4F8851660FA4121B
6 changed files with 1981 additions and 0 deletions

52
nixos/modules/alert.nix Normal file
View file

@ -0,0 +1,52 @@
# Mail the tail of a failed unit's journal: OnFailure=alert-mail@%n.service
# Sends through the SMTP account Forgejo uses (sops: alert/*).
{ config, pkgs, ... }:
let
send = pkgs.writers.writePython3 "alert-mail" { flakeIgnore = [ "E501" ]; } ''
import os
import smtplib
import socket
import subprocess
import sys
from email.message import EmailMessage
unit = sys.argv[1]
log = subprocess.run(
["journalctl", "-u", unit, "-n", "60", "--no-pager", "-o", "cat"],
capture_output=True, text=True,
).stdout
msg = EmailMessage()
msg["Subject"] = f"[{socket.gethostname()}] {unit} failed"
msg["From"] = os.environ["ALERT_SMTP_USER"]
msg["To"] = os.environ["ALERT_RECIPIENT"]
msg.set_content(log)
with smtplib.SMTP(os.environ["ALERT_SMTP_HOST"], int(os.environ["ALERT_SMTP_PORT"]), timeout=30) as s:
s.starttls()
s.login(os.environ["ALERT_SMTP_USER"], os.environ["ALERT_SMTP_PASSWORD"])
s.send_message(msg)
'';
in
{
sops.secrets."alert/smtp_user" = { };
sops.secrets."alert/smtp_password" = { };
sops.secrets."alert/recipient" = { };
sops.templates."alert.env".content = ''
ALERT_SMTP_HOST=smtp.fastmail.com
ALERT_SMTP_PORT=587
ALERT_SMTP_USER=${config.sops.placeholder."alert/smtp_user"}
ALERT_SMTP_PASSWORD=${config.sops.placeholder."alert/smtp_password"}
ALERT_RECIPIENT=${config.sops.placeholder."alert/recipient"}
'';
systemd.services."alert-mail@" = {
description = "Mail the failure of %i";
path = [ config.systemd.package ];
serviceConfig = {
Type = "oneshot";
EnvironmentFile = config.sops.templates."alert.env".path;
ExecStart = "${send} %i";
};
};
}

174
nixos/modules/backup.nix Normal file
View file

@ -0,0 +1,174 @@
# Nightly restic backup of the host into two independent repositories
# (Hetzner Object Storage, hel1 and fsn1): losing one region or one
# repository leaves the other complete. A failed run mails its journal.
#
# restic-backup run hooks, then backup + forget to every repository
# restic-backup init create the repositories that do not exist yet
# restic-backup <repo> <args...> plain restic against one repository, e.g.
# restic-backup hel1 snapshots
# restic-backup fsn1 restore latest --target /tmp/r
#
# Restoring: RESTORE.md at the repo root.
{
config,
lib,
pkgs,
...
}:
let
cfg = config.asxpio.backup;
host = cfg.hostName;
stage = "/var/backups/restic-stage";
textfileDir = "/var/lib/node_exporter/textfile";
script = pkgs.writeShellScriptBin "restic-backup" ''
set -uo pipefail
export PATH=${
lib.makeBinPath (
[
pkgs.restic
pkgs.sqlite
pkgs.coreutils
pkgs.gnused
config.virtualisation.podman.package
]
++ cfg.hookPackages
)
}:$PATH
set -a; . ${config.sops.templates."restic.env".path}; set +a
export RESTIC_CACHE_DIR=/var/cache/restic
STAGE=${stage}
declare -A REPOS=(
${lib.concatStrings (lib.mapAttrsToList (n: url: " [${n}]=${lib.escapeShellArg url}\n") cfg.repositories)})
log() { echo "restic-backup: $*"; }
# Last good backup per repository, for Prometheus (node_exporter textfile)
metric() {
[ -d ${textfileDir} ] || return 0
local f=${textfileDir}/restic_$1.prom
printf '# HELP restic_backup_last_success_timestamp_seconds Last successful restic backup.\n# TYPE restic_backup_last_success_timestamp_seconds gauge\nrestic_backup_last_success_timestamp_seconds{repo="%s"} %s\n' "$1" "$(date +%s)" > "$f.tmp" && mv "$f.tmp" "$f"
}
case "''${1:-}" in
init)
for name in "''${!REPOS[@]}"; do
if RESTIC_REPOSITORY="''${REPOS[$name]}" restic cat config >/dev/null 2>&1; then
log "$name: exists"
else
RESTIC_REPOSITORY="''${REPOS[$name]}" restic init || exit 1
log "$name: created"
fi
done
;;
run)
failed=0
rm -rf "$STAGE"; install -d -m 700 "$STAGE"
export STAGE
${lib.concatImapStrings (i: hook: ''
log "hook ${toString i}/${toString (lib.length cfg.hooks)}"
( set -e; ${hook} ) || { log "hook failed"; failed=1; }
'') cfg.hooks}
for name in "''${!REPOS[@]}"; do
export RESTIC_REPOSITORY="''${REPOS[$name]}"
log "$name: backup"
restic backup --host ${host} --one-file-system --exclude-caches \
${lib.concatMapStringsSep " " (e: "--exclude ${lib.escapeShellArg e}") cfg.excludes} \
${lib.escapeShellArgs (cfg.paths ++ [ stage ])} || { failed=1; continue; }
prune=""
[ "$(date +%a)" = "Sun" ] && prune="--prune"
log "$name: forget $prune"
restic forget --host ${host} --keep-daily 7 --keep-weekly 4 --keep-monthly 6 $prune || failed=1
metric "$name"
done
rm -rf "$STAGE"
exit $failed
;;
*)
[ -n "''${1:-}" ] && [ -n "''${REPOS[$1]:-}" ] || { echo "usage: restic-backup run | init | <${lib.concatStringsSep "|" (lib.attrNames cfg.repositories)}> <restic args>"; exit 2; }
export RESTIC_REPOSITORY="''${REPOS[$1]}"; shift
exec restic "$@"
;;
esac
'';
in
{
options.asxpio.backup = {
hostName = lib.mkOption {
type = lib.types.str;
description = "Name the snapshots are filed under; the path inside the buckets.";
};
repositories = lib.mkOption {
type = lib.types.attrsOf lib.types.str;
default = {
hel1 = "s3:https://hel1.your-objectstorage.com/asxpio-backups-main/restic/${host}";
fsn1 = "s3:https://fsn1.your-objectstorage.com/asxpio-backups-repl/restic/${host}";
};
};
paths = lib.mkOption { type = lib.types.listOf lib.types.str; };
excludes = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
};
hooks = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = ''
Shell lines run in order before the backup, with $STAGE set; what
they write there is backed up too. A failing hook marks the run
as failed, but the backup still runs.
'';
};
hookPackages = lib.mkOption {
type = lib.types.listOf lib.types.package;
default = [ ];
};
schedule = lib.mkOption { type = lib.types.str; };
};
config = {
sops.secrets."restic/password" = { };
sops.secrets."s3/access_key" = { };
sops.secrets."s3/secret_key" = { };
sops.templates."restic.env".content = ''
RESTIC_PASSWORD=${config.sops.placeholder."restic/password"}
AWS_ACCESS_KEY_ID=${config.sops.placeholder."s3/access_key"}
AWS_SECRET_ACCESS_KEY=${config.sops.placeholder."s3/secret_key"}
'';
environment.systemPackages = [ script ];
# Nothing to back up, and nothing to overwrite in the repositories,
# before the host has its data
asxpio.waitForData = [ "restic-backup" ];
systemd.services.restic-backup = {
description = "restic backup (${lib.concatStringsSep ", " (lib.attrNames cfg.repositories)})";
wants = [ "network-online.target" ];
after = [ "network-online.target" ];
onFailure = [ "alert-mail@%n.service" ];
serviceConfig = {
Type = "oneshot";
ExecStart = "${script}/bin/restic-backup run";
Nice = 10;
IOSchedulingClass = "idle";
TimeoutStartSec = "6h";
};
};
systemd.timers.restic-backup = {
description = "Nightly restic backup";
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = cfg.schedule;
RandomizedDelaySec = "10m";
Persistent = true;
};
};
};
}

154
nixos/modules/base.nix Normal file
View file

@ -0,0 +1,154 @@
# What every host gets: users, SSH, fail2ban, journal cap, Nix settings.
{
config,
lib,
pkgs,
...
}:
let
keys = {
asxpi = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIMZ+/5F7SxdTVW47iiStLpGK77oWfR5NgaK4tTSR/aVB me@asxp.io";
zerrtika = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIELE7hTD4sC5raqjSxy2fXyM+q1CwwVuy9KLFgDR6SFl zerrtika@zerrtika-mac";
deploy = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGTDPg3mV55lO8uBnvpcGRxJ2vMRP0qB3Pxhg+C8rwj9 asxpio-deploy";
};
admin = name: uid: key: {
inherit uid;
isNormalUser = true;
group = name;
extraGroups = [
"wheel"
"podman" # the Docker-compatible socket
];
openssh.authorizedKeys.keys = [ key ];
};
in
{
options.asxpio.sshFrom = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [
"10.20.0.0/24" # WireGuard
"10.10.0.0/20" # private network
];
description = "Networks shell users may log in from.";
};
# Units that own data start only once /var/lib/.data-in-place exists,
# so a fresh install never creates empty state where a restore is about
# to land. Create the file after the data is in place.
options.asxpio.waitForData = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = "systemd services that must not start before the host has its data.";
};
config = {
time.timeZone = "UTC";
systemd.services = lib.genAttrs config.asxpio.waitForData (_: {
unitConfig.ConditionPathExists = "/var/lib/.data-in-place";
});
# UIDs as on the Debian hosts, so files in /opt and /home keep their owners
users.mutableUsers = false;
users.users = {
root.openssh.authorizedKeys.keys = [ keys.asxpi ];
asxpi = admin "asxpi" 1000 keys.asxpi;
deploy = admin "deploy" 1001 keys.deploy; # CI
zerrtika = admin "zerrtika" 1002 keys.zerrtika;
};
users.groups = {
asxpi.gid = 1000;
deploy.gid = 1001;
zerrtika.gid = 1002;
};
security.sudo.wheelNeedsPassword = false;
services.openssh = {
enable = true;
settings = {
PasswordAuthentication = false;
KbdInteractiveAuthentication = false;
PermitRootLogin = "prohibit-password";
X11Forwarding = false;
MaxAuthTries = 3;
MaxSessions = 5;
ClientAliveInterval = 300;
ClientAliveCountMax = 2;
Ciphers = [
"chacha20-poly1305@openssh.com"
"aes256-gcm@openssh.com"
"aes128-gcm@openssh.com"
"aes256-ctr"
"aes192-ctr"
"aes128-ctr"
];
Macs = [
"hmac-sha2-512-etm@openssh.com"
"hmac-sha2-256-etm@openssh.com"
"hmac-sha2-512"
"hmac-sha2-256"
];
KexAlgorithms = [
"sntrup761x25519-sha512@openssh.com"
"curve25519-sha256"
"curve25519-sha256@libssh.org"
"diffie-hellman-group-exchange-sha256"
"diffie-hellman-group16-sha512"
"diffie-hellman-group18-sha512"
];
# Shell users only from the trusted networks; the Hetzner
# firewall is the outer layer
AllowUsers = lib.concatMap (
net:
map (u: "${u}@${net}") [
"root"
"asxpi"
"deploy"
"zerrtika"
]
) config.asxpio.sshFrom;
};
};
services.fail2ban.enable = true;
# The Hetzner firewall decides what the internet reaches; this one
# opens each service's ports next to its definition. The admin
# networks are trusted, as they were on Debian.
networking.nftables.enable = true;
networking.firewall.extraInputRules = ''
ip saddr { 10.20.0.0/24, 10.10.0.0/20 } accept
ip6 saddr fd69:69:69::/64 accept
'';
sops.age.sshKeyPaths = [ "/etc/ssh/ssh_host_ed25519_key" ];
services.journald.extraConfig = "SystemMaxUse=500M";
nix.settings = {
experimental-features = [
"nix-command"
"flakes"
];
trusted-users = [
"root"
"@wheel" # nixos-rebuild --target-host as deploy
];
};
nix.gc = {
automatic = true;
dates = "weekly";
options = "--delete-older-than 14d";
};
environment.systemPackages = with pkgs; [
curl
git
htop
ncdu
tree
sqlite
rclone
restic
];
};
}

50
nixos/modules/hetzner.nix Normal file
View file

@ -0,0 +1,50 @@
# Hetzner Cloud VM as nixos-infect leaves it: the Debian image's disk
# (sda1 ext4 root, sda14 BIOS boot, sda15 unused ESP), GRUB in the MBR.
{ lib, modulesPath, ... }:
{
imports = [ (modulesPath + "/profiles/qemu-guest.nix") ];
boot.loader.grub.device = "/dev/sda";
boot.initrd.availableKernelModules = [
"ata_piix"
"uhci_hcd"
"virtio_pci"
"virtio_scsi"
"sd_mod"
];
fileSystems."/" = {
device = "/dev/sda1";
fsType = "ext4";
};
boot.tmp.cleanOnBoot = true;
services.qemuGuest.enable = true;
# Public interface: IPv4 by DHCP, IPv6 static (asxpio.ipv6, Hetzner
# offers no router advertisements). Private network: DHCP, never the
# default route. Names differ between a switch from the bootstrap
# system (eth0) and a boot of this one (enp1s0).
networking.useDHCP = false;
networking.useNetworkd = true;
systemd.network.enable = true;
systemd.network.networks = {
"10-public" = {
matchConfig.Name = "enp1s0 eth0";
networkConfig.DHCP = "ipv4";
routes = [ { Gateway = "fe80::1"; } ];
};
"20-private" = {
matchConfig.Name = "enp7s0 ens10";
networkConfig.DHCP = "ipv4";
dhcpV4Config = {
RouteMetric = 2000;
UseDNS = false;
};
linkConfig.RequiredForOnline = "no";
};
};
networking.nameservers = lib.mkDefault [
"185.12.64.1"
"185.12.64.2"
"2a01:4ff:ff00::add:1"
];
}

20
nixos/modules/podman.nix Normal file
View file

@ -0,0 +1,20 @@
# Containers, for what has no native NixOS service: Podman, no Docker.
# Declared containers (virtualisation.oci-containers) become systemd units
# named podman-<name>.service. `docker` is an alias, and /run/docker.sock
# is Podman's Docker-compatible socket (CI runner, compose files).
{ ... }:
{
virtualisation.podman = {
enable = true;
dockerCompat = true;
dockerSocket.enable = true;
defaultNetwork.settings.dns_enabled = true;
# Every image update and CI job leaves an image behind
autoPrune = {
enable = true;
dates = "Mon 03:00";
flags = [ "--all" ];
};
};
virtualisation.oci-containers.backend = "podman";
}

View file

@ -0,0 +1,65 @@
# WireGuard, the admin network (10.20.0.0/24). asxpio-ops is the hub
# every peer connects to; everything else is a spoke with ops as its
# only peer. Keys come from sops: wireguard/private_key and, per peer,
# wireguard/psk/<name>.
{ config, lib, ... }:
let
cfg = config.asxpio.wireguard;
in
{
options.asxpio.wireguard = {
interface = lib.mkOption { type = lib.types.str; };
address = lib.mkOption { type = lib.types.listOf lib.types.str; };
listenPort = lib.mkOption { type = lib.types.port; };
hub = lib.mkOption {
type = lib.types.bool;
default = false;
description = "Forward between peers, and masquerade what leaves by the public interface.";
};
peers = lib.mkOption {
type = lib.types.listOf (
lib.types.submodule {
options = {
name = lib.mkOption { type = lib.types.str; };
publicKey = lib.mkOption { type = lib.types.str; };
allowedIPs = lib.mkOption { type = lib.types.listOf lib.types.str; };
endpoint = lib.mkOption {
type = lib.types.nullOr lib.types.str;
default = null;
};
};
}
);
};
};
config = {
sops.secrets = {
"wireguard/private_key" = { };
}
// lib.listToAttrs (map (p: lib.nameValuePair "wireguard/psk/${p.name}" { }) cfg.peers);
networking.wireguard.interfaces.${cfg.interface} = {
ips = cfg.address;
listenPort = cfg.listenPort;
privateKeyFile = config.sops.secrets."wireguard/private_key".path;
peers = map (p: {
inherit (p) name publicKey allowedIPs endpoint;
presharedKeyFile = config.sops.secrets."wireguard/psk/${p.name}".path;
persistentKeepalive = 25;
}) cfg.peers;
};
networking.firewall.allowedUDPPorts = [ cfg.listenPort ];
boot.kernel.sysctl = lib.mkIf cfg.hub {
"net.ipv4.ip_forward" = 1;
"net.ipv6.conf.all.forwarding" = 1;
};
networking.nat = lib.mkIf cfg.hub {
enable = true;
enableIPv6 = true;
internalInterfaces = [ cfg.interface ];
externalInterface = "enp1s0";
};
};
}