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
4 changed files with 1981 additions and 0 deletions

View file

@ -0,0 +1,67 @@
# asxpio-ops: Traefik, Forgejo, storage, the app stacks.
# Services are added here as they move over from ../../ansible (see
# MIGRATION.md at the repo root); until then this is the base system only.
{ lib, ... }:
{
imports = [
./forgejo.nix
./garage.nix
./postgres.nix
];
networking.hostName = lib.mkDefault "asxpio-ops";
networking.domain = "asxp.io";
system.stateVersion = "26.05";
systemd.network.networks."10-public".address = [ "2a01:4f9:c013:3258::1/64" ];
sops.defaultSopsFile = lib.mkDefault ../../secrets/asxpio-ops.yaml;
# --- WireGuard hub -------------------------------------------------------
asxpio.wireguard = {
interface = "wg0";
address = [
"10.20.0.10/24"
"fd69:69:69::1/64"
];
listenPort = 60101;
hub = true;
peers = lib.mkDefault (
map
(p: {
inherit (p) name publicKey;
allowedIPs = [
"10.20.0.${toString p.id}/32"
"fd69:69:69::${toString p.id}/128"
];
})
[
{ id = 20; name = "asxpio-services"; publicKey = "I2D4RvGHm0bW2mMlq9lPvbINHvnP9MsZg4XGMKTLiSU="; }
{ id = 2; name = "laptop"; publicKey = "6xYBPCiAa1MBusj7ilHGvwIoj26cXymvVksrOQLY52g="; }
{ id = 3; name = "aleks"; publicKey = "Csqd94oo6eRLUrlzeEkFxlW2IZtQG61ASXdK+ZjKzGI="; }
{ id = 4; name = "zerrtika"; publicKey = "uBRSmDuM25ciVaS9GxlCbjNPMUlmtphPDvtcEFzs8kI="; }
{ id = 5; name = "sanya"; publicKey = "tegWIorm7PjagnixbzQjCGLqDKVImynLNgk/bfx2PEk="; }
]
);
};
swapDevices = [
{
device = "/swapfile";
size = 2048;
}
];
# --- Backup ---------------------------------------------------------------
# Each service adds its own paths and hooks next to its definition:
# Postgres as a dump, Garage with a metadata snapshot, Forgejo's SQLite
# through the online backup API.
asxpio.backup = {
hostName = "asxpio-ops";
schedule = "*-*-* 03:30:00";
paths = [
"/etc/ssh" # the host key decrypts this host's secrets
"/opt"
];
};
}

View file

@ -0,0 +1,131 @@
# Forgejo at git.asxp.io (git.czsk.it is an alias), with its package
# registry and Actions. It runs as user git, so git@git.asxp.io reaches
# it through the host's sshd with no passthrough.
#
# State: /var/lib/forgejo (repositories/, data/forgejo.db, data/lfs, ...).
{
config,
lib,
pkgs,
...
}:
let
cfg = config.services.forgejo;
secret = name: config.sops.secrets."forgejo/${name}".path;
in
{
sops.secrets = lib.genAttrs (map (n: "forgejo/${n}") [
"secret_key"
"internal_token"
"jwt_secret"
"lfs_jwt_secret"
"smtp_user"
"smtp_password"
"metrics_token"
]) (_: { owner = cfg.user; });
users.users.git = {
isSystemUser = true;
group = "git";
home = cfg.stateDir;
useDefaultShell = true;
};
users.groups.git = { };
# Anyone may try a key against git; Forgejo decides what it may do
services.openssh.settings.AllowUsers = [ "git" ];
services.forgejo = {
enable = true;
package = pkgs.forgejo; # the current release, not the LTS: the data is from 17
user = "git";
group = "git";
database.type = "sqlite3";
lfs.enable = true;
secrets = {
security.SECRET_KEY = lib.mkForce (secret "secret_key");
security.INTERNAL_TOKEN = lib.mkForce (secret "internal_token");
oauth2.JWT_SECRET = lib.mkForce (secret "jwt_secret");
server.LFS_JWT_SECRET = lib.mkForce (secret "lfs_jwt_secret");
mailer.USER = secret "smtp_user";
mailer.PASSWD = secret "smtp_password";
metrics.TOKEN = secret "metrics_token";
};
settings = {
DEFAULT.APP_NAME = "Git with a cup of tea";
server = {
DOMAIN = "git.asxp.io";
ROOT_URL = "https://git.asxp.io/";
HTTP_PORT = 3000;
SSH_DOMAIN = "git.asxp.io";
SSH_PORT = 22;
LANDING_PAGE = "explore";
};
repository = {
DEFAULT_BRANCH = "main";
DEFAULT_PRIVATE = "private";
ENABLE_PUSH_CREATE_USER = true;
ENABLE_PUSH_CREATE_ORG = false;
DEFAULT_REPO_UNITS = "repo.code,repo.releases,repo.issues,repo.pulls,repo.wiki,repo.projects,repo.packages,repo.actions";
};
"repository.pull-request".DEFAULT_MERGE_STYLE = "merge";
"repository.signing".DEFAULT_TRUST_MODEL = "collaborator";
ui = {
THEMES = "forgejo-auto,forgejo-light,forgejo-dark,gitea-auto,gitea-light,gitea-dark";
DEFAULT_THEME = "forgejo-auto";
};
security.PASSWORD_HASH_ALGO = "pbkdf2";
service = {
DISABLE_REGISTRATION = true;
REQUIRE_SIGNIN_VIEW = false;
REGISTER_EMAIL_CONFIRM = false;
ENABLE_NOTIFY_MAIL = true;
DEFAULT_KEEP_EMAIL_PRIVATE = true;
DEFAULT_ALLOW_CREATE_ORGANIZATION = true;
DEFAULT_ENABLE_TIMETRACKING = true;
NO_REPLY_ADDRESS = "noreply.git.asxp.io";
};
oauth2.ENABLED = true;
mailer = {
ENABLED = lib.mkDefault true;
FROM = "Czechoslovakia Git <noreply@asxp.io>";
PROTOCOL = "smtp+starttls";
SMTP_ADDR = "smtp.fastmail.com";
SMTP_PORT = 587;
};
session.PROVIDER = "file";
log.LEVEL = "Info";
actions = {
ENABLED = true;
DEFAULT_ACTIONS_URL = "https://github.com";
ARTIFACT_RETENTION_DAYS = 365;
};
packages.ENABLED = true;
other = {
SHOW_FOOTER_VERSION = false;
SHOW_FOOTER_TEMPLATE_LOAD_TIME = false;
SHOW_FOOTER_POWERED_BY = false;
};
metrics.ENABLED = true;
};
};
asxpio.waitForData = [
"forgejo"
"forgejo-secrets"
];
# `forgejo-admin regenerate keys`, `forgejo-admin user list`, ...
environment.systemPackages = [
(pkgs.writeShellScriptBin "forgejo-admin" ''
exec ${pkgs.util-linux}/bin/runuser -u ${cfg.user} -- env \
HOME=${cfg.stateDir} FORGEJO_WORK_DIR=${cfg.stateDir} FORGEJO_CUSTOM=${cfg.customDir} \
${lib.getExe cfg.package} --config ${cfg.customDir}/conf/app.ini admin "$@"
'')
];
asxpio.backup.paths = [ "/var/lib/forgejo" ];
asxpio.backup.hooks = [
''sqlite3 /var/lib/forgejo/data/forgejo.db ".backup '$STAGE/forgejo.db'"''
];
}

View file

@ -0,0 +1,173 @@
# Garage (S3) for the apps, single node. Buckets, keys and grants are set
# on every start from sops.
#
# asxpio-invoices asxpio rw
# datacenterbingo-photos asxpio rw, bingo ro
# public a website (anonymous reads through Traefik);
# asxpio and public-upload write only
#
# Garage only takes keys in its own format (GK + 24 hex, 64 hex). The
# apps' keys predate it and are hashed into that format, here and in each
# app's deploy workflow: keep the two in step.
{
config,
lib,
pkgs,
...
}:
let
garage = pkgs.garage_2;
rpcSecret = config.sops.secrets."garage/rpc_secret".path;
keys = [
"asxpio"
"bingo"
"public"
];
in
{
sops.secrets = {
"garage/rpc_secret" = { };
}
// lib.listToAttrs (
lib.concatMap (k: [
(lib.nameValuePair "garage/${k}_access_key" { })
(lib.nameValuePair "garage/${k}_secret_key" { })
]) keys
);
services.garage = {
enable = true;
package = garage;
# The RPC secret is a systemd credential: mode 0440, but in a
# directory only this service can enter
extraEnvironment.GARAGE_ALLOW_WORLD_READABLE_SECRETS = "true";
settings = {
# One node and no replica to repair from, so prefer the engine that
# survives an unclean stop, sync writes, and keep metadata snapshots
db_engine = "sqlite";
metadata_fsync = true;
data_fsync = true;
metadata_auto_snapshot_interval = "6h";
replication_factor = 1;
rpc_bind_addr = "[::]:3901";
rpc_public_addr = "127.0.0.1:3901";
rpc_secret_file = "/run/credentials/garage.service/rpc_secret";
# The apps sign for us-east-1, as they did against MinIO
s3_api = {
s3_region = "us-east-1";
api_bind_addr = "[::]:3900";
};
# Anonymous reads: a bucket marked as a website is served here,
# picked by Host: <bucket>.web.garage
s3_web = {
bind_addr = "[::]:3902";
root_domain = ".web.garage";
index = "index.html";
};
};
};
asxpio.waitForData = [
"garage"
"garage-bootstrap"
];
systemd.services.garage = {
serviceConfig = {
LoadCredential = [ "rpc_secret:${rpcSecret}" ];
ExecStart = lib.mkForce "${garage}/bin/garage server --single-node";
};
};
networking.firewall.interfaces."podman*".allowedTCPPorts = [ 3900 ];
# `garage` for root, e.g. garage status, garage bucket list
environment.systemPackages = [
(pkgs.writeShellScriptBin "garage" ''
export GARAGE_RPC_SECRET_FILE=${rpcSecret}
exec ${garage}/bin/garage -c /etc/garage.toml "$@"
'')
];
systemd.services.garage-bootstrap = {
description = "Garage buckets, keys and grants";
after = [ "garage.service" ];
requires = [ "garage.service" ];
wantedBy = [ "multi-user.target" ];
path = [
garage
pkgs.gnugrep
pkgs.coreutils
];
environment.GARAGE_RPC_SECRET_FILE = rpcSecret;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
};
script = ''
set -eu
g() { garage -c /etc/garage.toml "$@"; }
secret() { cat "/run/secrets/garage/$1"; }
key_id() {
if printf '%s' "$1" | grep -Eq '^GK[0-9a-f]{24}$'; then printf '%s' "$1"
else printf 'GK%s' "$(printf '%s' "$1" | sha256sum | cut -c1-24)"; fi
}
key_secret() {
if printf '%s' "$1" | grep -Eq '^[0-9a-f]{64}$'; then printf '%s' "$1"
else printf '%s' "$1" | sha256sum | cut -c1-64; fi
}
i=0
until g status >/dev/null 2>&1; do
i=$((i + 1))
[ "$i" -le 60 ] || { echo "garage did not come up" >&2; exit 1; }
sleep 1
done
ensure_bucket() { g bucket info "$1" >/dev/null 2>&1 || g bucket create "$1" >/dev/null; }
# ensure_key <name> <sops prefix>: prints the key id
ensure_key() {
id="$(key_id "$(secret "$2_access_key")")"
sec="$(key_secret "$(secret "$2_secret_key")")"
if g key info --show-secret "$id" >/dev/null 2>&1; then
if ! g key info --show-secret "$id" | grep -q "$sec"; then
g key delete --yes "$id" >/dev/null
g key import --yes -n "$1" "$id" "$sec" >/dev/null
fi
else
g key import --yes -n "$1" "$id" "$sec" >/dev/null
fi
printf '%s' "$id"
}
grant() {
case "$3" in
rw) g bucket allow --read --write "$1" --key "$2" >/dev/null
g bucket deny --owner "$1" --key "$2" >/dev/null ;;
ro) g bucket allow --read "$1" --key "$2" >/dev/null
g bucket deny --write --owner "$1" --key "$2" >/dev/null ;;
wo) g bucket allow --write "$1" --key "$2" >/dev/null
g bucket deny --read --owner "$1" --key "$2" >/dev/null ;;
esac
}
ensure_bucket asxpio-invoices
ensure_bucket datacenterbingo-photos
ensure_bucket public
g bucket website --allow public >/dev/null
asxpio="$(ensure_key asxpio asxpio)"
grant asxpio-invoices "$asxpio" rw
grant datacenterbingo-photos "$asxpio" rw
grant public "$asxpio" wo
bingo="$(ensure_key bingo bingo)"
grant datacenterbingo-photos "$bingo" ro
uploader="$(ensure_key public-upload public)"
grant public "$uploader" wo
'';
};
asxpio.backup.paths = [ "/var/lib/garage" ];
asxpio.backup.hooks = [ "/run/current-system/sw/bin/garage meta snapshot --all" ];
}

View file

@ -0,0 +1,99 @@
# Postgres for the apps. Roles and grants are set on every start from
# sops, so a password is changed by changing the secret.
#
# asxpio owns database asxpio (site, invoices, datacenter bingo admin)
# bingo read-only on the bingo tables, for datacenterbingo.xyz
{
config,
lib,
pkgs,
...
}:
let
pg = config.services.postgresql.package;
in
{
sops.secrets."postgres/asxpio_password" = { };
sops.secrets."postgres/bingo_password" = { };
services.postgresql = {
enable = true;
package = pkgs.postgresql_18;
# App containers connect from Podman's networks; the firewall decides
# who reaches the port
enableTCPIP = true;
authentication = ''
host all all 10.88.0.0/16 scram-sha-256
host all all 10.89.0.0/16 scram-sha-256
'';
};
networking.firewall.interfaces."podman*".allowedTCPPorts = [ 5432 ];
asxpio.waitForData = [
"postgresql"
"postgresql-setup"
"postgres-roles"
];
systemd.services.postgres-roles = {
description = "Postgres roles, databases and grants";
after = [ "postgresql.target" ];
requires = [ "postgresql.target" ];
wantedBy = [ "multi-user.target" ];
path = [ pg ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
User = "postgres";
LoadCredential = [
"asxpio:${config.sops.secrets."postgres/asxpio_password".path}"
"bingo:${config.sops.secrets."postgres/bingo_password".path}"
];
};
script = ''
set -eu
role() {
psql -v ON_ERROR_STOP=1 -v role="$1" -v pw="$(cat "$CREDENTIALS_DIRECTORY/$1")" <<'SQL'
SELECT format('CREATE ROLE %I LOGIN', :'role')
WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = :'role') \gexec
SELECT format('ALTER ROLE %I WITH LOGIN PASSWORD %L', :'role', :'pw') \gexec
SQL
}
role asxpio
role bingo
psql -tAc "SELECT 1 FROM pg_database WHERE datname = 'asxpio'" | grep -q 1 \
|| psql -c 'CREATE DATABASE asxpio OWNER asxpio'
psql -d asxpio -c 'CREATE EXTENSION IF NOT EXISTS citext'
# Tables that do not exist yet (fresh install, asxpio not migrated)
# are granted on the next start
psql -c 'ALTER ROLE bingo SET default_transaction_read_only = on'
psql -d asxpio -v ON_ERROR_STOP=1 <<'SQL'
GRANT CONNECT ON DATABASE asxpio TO bingo;
GRANT USAGE ON SCHEMA public TO bingo;
DO $$
DECLARE t text;
BEGIN
FOREACH t IN ARRAY ARRAY['bingo_datacenters', 'bingo_incidents', 'bingo_monitor_targets',
'bingo_monitor_samples', 'bingo_monitor_buckets'] LOOP
IF to_regclass('public.' || t) IS NOT NULL THEN
EXECUTE format('GRANT SELECT ON public.%I TO bingo', t);
ELSE
RAISE NOTICE 'bingo: % missing, not granted yet', t;
END IF;
END LOOP;
END $$;
SQL
'';
};
asxpio.backup.hookPackages = [
pg
pkgs.util-linux
];
asxpio.backup.hooks = [
''runuser -u postgres -- pg_dumpall > "$STAGE/pg_dumpall.sql"''
''runuser -u postgres -- pg_dump -Fc asxpio > "$STAGE/asxpio.dump"''
];
}