Jump to content

MindAttic.Agency/ops/hetzner-deploy-pipeline

From MindAttic Docs

Hetzner deploy pipeline — full runbook (MAT-T237)

Everything done, in order, to take a brand-new Hetzner account to a live, database-backed .NET app on mindattic-01. Written after standing up Gadfly (GAD-T786) as the first real pipeline run — every step below is copy-pasted from what actually worked, including the dead ends, so the next app (or Gadfly's next big migration) doesn't re-discover the same gotchas.

Companion doc: hetzner-bootstrap-chrome-prompt.md in this folder covers steps 1-4 below as a reusable Claude-for-Chrome prompt for the Hetzner console side. This doc picks up from an existing, reachable server and covers everything after that (OS, runtime, database, web server, the app itself).

1. Prerequisites (owner-only, can't be delegated)

  • A Hetzner Cloud account and a project (console.hetzner.cloud). 2FA recommended, not required to proceed.
  • A Tailscale account already in use for other MindAttic devices (reuses the existing tailnet).

2. Server bootstrap (Claude-for-Chrome console steps)

See hetzner-bootstrap-chrome-prompt.md. Produces: an SSH key registered in the project, a server with a Hetzner Cloud Firewall (80/443/22 open at creation), and the server's public IPv4.

Cost note from the real run: the console defaults to whatever region/type it lands on first. Check the total price shown before confirming — EU regions (Falkenstein fsn1, Helsinki hel1, Nuremberg nbg1) run dramatically cheaper than Ashburn US for the same specs on Hetzner's newer lines, and the "Cost-Optimized" (CX) line can be half the price of "Regular Performance" (CPX) for the same vCPU/RAM — worth comparing both before buying. Gadfly's run landed on CX33 (4 vCPU / 8 GB RAM / 80 GB SSD, Falkenstein) at ~$10.59/mo.

3. SSH key (local machine, before step 2)

ssh-keygen -t ed25519 -f C:\Users\ryand\.ssh\mindattic-hetzner -N "" -C "mindattic-hetzner-<date>"

Use the same keypair for every server unless there's a reason to separate them.

4. First connect and base packages

ssh -i C:\Users\ryand\.ssh\mindattic-hetzner -o StrictHostKeyChecking=accept-new root@<server-ip>

Then, over that SSH session:

export DEBIAN_FRONTEND=noninteractive
apt-get update -qq
apt-get -y -qq upgrade
apt-get -y -qq install curl gnupg2 ca-certificates apt-transport-https software-properties-common ufw unattended-upgrades

5. Tailscale (owner generates the auth key; the rest is scriptable)

Owner step (2 minutes, browser): https://login.tailscale.com/admin/settings/keys → Generate auth key → Reusable, not Ephemeral → copy the tskey-auth-... value.

Then:

curl -fsSL https://tailscale.com/install.sh | sh
tailscale up --authkey=<tskey-auth-...> --hostname=<server-name> --ssh
tailscale ip -4   # note this; it's the private address everything below should prefer

Tighten the Hetzner firewall once Tailscale is confirmed working (test SSH over the new Tailscale IP before doing this, so you don't lock yourself out):

ssh -i <key> -o StrictHostKeyChecking=accept-new root@<tailscale-ip> "echo ok"

Then, via the Hetzner API (needs the project's API token — Security > API Tokens in the console; reuse an existing Read & Write token rather than minting a new one per server):

TOKEN=<hetzner api token>
FIREWALL_ID=<id, from GET /v1/firewalls>
curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  https://api.hetzner.cloud/v1/firewalls/$FIREWALL_ID/actions/set_rules \
  -d '{"rules":[
    {"direction":"in","protocol":"tcp","port":"80","source_ips":["0.0.0.0/0","::/0"]},
    {"direction":"in","protocol":"tcp","port":"443","source_ips":["0.0.0.0/0","::/0"]}
  ]}'

This drops port 22 from the public firewall entirely. It does not affect Tailscale SSH at all — that traffic never touches the public interface's firewall, so this is safe the moment Tailscale is confirmed working. From here on, SSH only over the Tailscale IP.

6. .NET runtime (match the app's TargetFramework)

curl -sSL -O https://packages.microsoft.com/config/ubuntu/24.04/packages-microsoft-prod.deb
dpkg -i packages-microsoft-prod.deb && rm packages-microsoft-prod.deb
apt-get update -qq
apt-get -y -qq install dotnet-runtime-10.0 aspnetcore-runtime-10.0   # match the app's <TargetFramework>

7. SQL Server 2025 Express on Ubuntu 24.04

Gotcha #1: as of this run, Microsoft's SQL Server 2025 apt repo is only published for Ubuntu 22.04 (jammy), not 24.04 (noble) — use the 22.04 config path even on a 24.04 host:

curl -fsSL https://packages.microsoft.com/config/ubuntu/22.04/mssql-server-2025.list | tee /etc/apt/sources.list.d/mssql-server-2025.list
curl -sSL https://packages.microsoft.com/keys/microsoft.asc | gpg --yes --dearmor -o /usr/share/keyrings/microsoft-prod.gpg
sed -i 's#deb \[arch=amd64,arm64,armhf\]#deb [arch=amd64,arm64,armhf signed-by=/usr/share/keyrings/microsoft-prod.gpg]#' /etc/apt/sources.list.d/mssql-server-2025.list
apt-get update -qq
apt-get -y -qq install mssql-server

Gotcha #2: the jammy build of sqlservr dynamically links liblber-2.5.so.0 (OpenLDAP 2.5), which Ubuntu 24.04 no longer ships (it moved to 2.6). Without this, the service fails instantly with error while loading shared libraries: liblber-2.5.so.0 and systemd gives up after 3 rapid restarts. Fix: install the jammy-era compat package directly from the Ubuntu archive (safe — different SONAME from the 2.6 the OS already has, so it installs alongside, not instead of):

cd /tmp
curl -sSL -O http://archive.ubuntu.com/ubuntu/pool/main/o/openldap/libldap-2.5-0_2.5.20+dfsg-0ubuntu0.22.04.1_amd64.deb
dpkg -i libldap-2.5-0_2.5.20+dfsg-0ubuntu0.22.04.1_amd64.deb

(If that exact filename 404s, list the directory first: curl -s http://archive.ubuntu.com/ubuntu/pool/main/o/openldap/ | grep -oE 'libldap-2\.5-0_[^"]*amd64\.deb' and take the newest.)

Non-interactive setup with a password you control (don't let mssql-conf -n setup pick or prompt — set MSSQL_SA_PASSWORD yourself so you know what it is):

# Password must satisfy complexity: 3 of {upper, lower, digit, symbol}, 8+ chars.
# Avoid characters that break an ADO.NET connection string if possible (;, ", ') though none of
# upper/lower/digit/! typically do.
ACCEPT_EULA=Y MSSQL_PID=Express MSSQL_SA_PASSWORD='<strong password>' /opt/mssql/bin/mssql-conf -n setup

Install sqlcmd and verify the password actually works before wiring it into any app — this catches typos/mismatches immediately instead of after a confusing app-level login failure:

curl -sSL https://packages.microsoft.com/config/ubuntu/22.04/prod.list | tee /etc/apt/sources.list.d/mssql-tools.list
sed -i 's#deb \[arch=amd64,arm64,armhf\]#deb [arch=amd64,arm64,armhf signed-by=/usr/share/keyrings/microsoft-prod.gpg]#' /etc/apt/sources.list.d/mssql-tools.list
apt-get update -qq
ACCEPT_EULA=Y apt-get -y -qq install mssql-tools18 unixodbc-dev
/opt/mssql-tools18/bin/sqlcmd -C -S localhost -U sa -P '<strong password>' -Q 'SELECT @@VERSION'

If that fails with error 18456, re-run mssql-conf -n setup (stop the service first) with a new password rather than debugging — it's a one-command fix and faster than chasing the cause.

8. Caddy (reverse proxy)

curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --yes --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list
apt-get update -qq
apt-get -y -qq install caddy

Don't deploy on bare :80 if the app uses MindAttic.Authentication (or any app whose auth cookie sets SecurePolicy=Always/a __Host- prefix) — see Gadfly's real failure below. Get real HTTPS working from the start, with no domain purchase needed, via a free wildcard-DNS host that resolves straight to the server's own public IP:

# /etc/caddy/Caddyfile
<a-b-c-d>.sslip.io {
	reverse_proxy 127.0.0.1:<app port>
}

(sslip.io resolves any a-b-c-d.sslip.io to IP a.b.c.d — e.g. 2-31-204-8.sslip.io → 2.31.204.8. nip.io works the same way if sslip.io is ever unavailable.)

caddy validate --config /etc/caddy/Caddyfile && systemctl reload caddy

Caddy obtains a real Let's Encrypt cert automatically (ACME HTTP-01 over port 80, which the firewall already has open) — watch journalctl -u caddy -n 40 for "certificate obtained successfully". Once a real domain exists later, swap the sslip.io host for yourdomain.com the same way — no other config changes needed.

The gotcha this avoided (Gadfly, 2026-11-28, GAD-T860): the first pass at this pipeline ran Caddy on plain :80 with no domain, since nothing in this doc's earlier steps needs HTTPS to work — SQL Server, the .NET runtime, systemd, migration all succeed fine over bare HTTP. The app itself came up clean, and the login page rendered fine (static HTML needs no cookie). But sign-in silently did nothing: no error, just bounced back to an unauthenticated state. Root cause — MindAttic.Authentication's cookie is named __Host-MindAttic.Auth with CookieSecurePolicy.Always (MindAttic.Authentication/src/MindAttic.Authentication/Web/MindAtticAuthExtensions.cs:130-136). Both the __Host- prefix and SecurePolicy=Always are browser-enforced: the server sends a perfectly valid Set-Cookie, but the browser refuses to store it at all unless the page was served over a real HTTPS connection. Nothing in the app's own logs flags this — it looks, from the server side, exactly like a successful sign-in every time. Any future app sharing MindAttic.Authentication will hit this identically if it's ever deployed on bare HTTP. Do the sslip.io (or real domain) step before the first login attempt, not after.

9. App layout convention (repeat per app)

id -u <app> &>/dev/null || useradd --system --home-dir /opt/<app> --shell /usr/sbin/nologin <app>
mkdir -p /opt/<app>/server /opt/<app>/worker /var/lib/<app>/keys /etc/<app>
chown -R <app>:<app> /opt/<app> /var/lib/<app>
chmod 700 /etc/<app>

Publish locally and copy over (framework-dependent build, since the runtime's installed on the box):

dotnet publish <App>.Server/<App>.Server.csproj -c Release -r linux-x64 --self-contained false -o <tmp>/server
dotnet publish <App>.Worker/<App>.Worker.csproj -c Release -r linux-x64 --self-contained false -o <tmp>/worker
scp -i <key> -r <tmp>/server/* root@<tailscale-ip>:/opt/<app>/server/
scp -i <key> -r <tmp>/worker/* root@<tailscale-ip>:/opt/<app>/worker/
chown -R <app>:<app> /opt/<app>; chmod +x /opt/<app>/server/<App>.Server /opt/<app>/worker/<App>.Worker

10. The env file — and the one gotcha that costs the most time

Every MindAttic app's secrets come from Vault-shaped config keys (MindAttic:Vault:<bucket>:...), never checked-in config. On Linux, that means a root-only EnvironmentFile consumed by systemd:

cat > /etc/<app>/env <<'EOF'
ASPNETCORE_ENVIRONMENT=Production
ASPNETCORE_URLS=http://127.0.0.1:<port>
ConnectionStrings__<App>=Server=localhost;Database=<App>;User Id=sa;Password=<sa password>;TrustServerCertificate=True;
DataProtection__KeysPath=/var/lib/<app>/keys
<App>__AiMode=live
MindAttic__Vault__LLM__claude__type=anthropic
MindAttic__Vault__LLM__claude__apiKey=<anthropic key>
MindAttic__Vault__LLM__claude__model=claude-sonnet-5-5
MindAttic__Vault__Security__pepper_v1=<openssl rand -base64 32>
MindAttic__Vault__Security__reset_token_key=<openssl rand -base64 32>
MindAttic__Vault__Security__bootstrap_token=<a real password, 12+ chars -- this becomes the admin login>
EOF
chown root:<app> /etc/<app>/env; chmod 640 /etc/<app>/env

Where the values actually come from: never invent or ask the owner to retype a provider key -- every key the owner has already supplied to any app lives in this machine's local Vault store, %APPDATA%\MindAttic\LLM\providers.json (LLM/speech providers: claude, openai, elevenlabs, ...) and %APPDATA%\MindAttic\Notifications\providers.json (SMTP/SMS: email -- smtpHost/smtpPort/username/password/from -- and twilio). Read the one key a new app's AiMode/voice/notification config actually needs from there and copy it into the env file verbatim -- don't re-derive, don't ask "do you have an ElevenLabs key" when the answer is already on disk (confirmed live during the Gadfly run, GAD-T868/MAT-T349: the owner had already supplied ElevenLabs and OpenAI keys in a prior session; they were sitting unused in providers.json the whole time).

Optional add-ons, same env file, same MindAttic:Vault:<bucket>:... shape -- add only the ones the app actually uses:

# Email (password-reset / security-alert mail -- MindAttic.Authentication's AuthEmailStartup).
# Without this, the app still runs fine; these emails are just written to the log instead of sent.
MindAttic__Vault__Notifications__email__smtpHost=smtp.gmail.com
MindAttic__Vault__Notifications__email__smtpPort=587
MindAttic__Vault__Notifications__email__username=<gmail address>
MindAttic__Vault__Notifications__email__password=<gmail app password, not the account password>
MindAttic__Vault__Notifications__email__from=<gmail address>
# Required alongside the above, separately -- a reset link needs an absolute URL to put in the email.
# Easy to miss: the app starts fine and logs "auth email is delivered over SMTP" with this unset, then
# silently refuses to send the one email type that actually needs a link (GAD-T868).
MindAttic__Auth__Reset__PublicBaseUrl=https://<app's real public URL>

The SMTP credentials above are a real, working Gmail app-password already in %APPDATA%\MindAttic\Notifications\providers.json (email bucket) -- reuse it rather than setting up new SMTP per app, unless an app specifically needs its own sending identity.

A per-account SQL gotcha hit setting this up by hand (not an app bug): an ad-hoc sqlcmd ... -Q "UPDATE ..." against one of these apps' databases can fail with Msg 1934 ... QUOTED_IDENTIFIER (the app's own EF-generated schema uses filtered indexes/computed columns, which require it). Prefix any manual UPDATE/INSERT run this way with SET QUOTED_IDENTIFIER ON; in the same -Q string -- SELECTs are unaffected.

THE GOTCHA: systemd's EnvironmentFile parser silently drops any line whose variable name contains a character invalid in a POSIX identifier -- a hyphen, most commonly. MindAttic's own Vault key names use hyphens (reset-token-key, bootstrap-token), and the double-underscore env convention (Section__Key) doesn't fix that, since the hyphen is still inside a segment, not at a separator. Writing MindAttic__Vault__Security__bootstrap-token=... gets silently ignored -- no error in the app, just journalctl quietly logging "Ignoring invalid environment assignment" at the systemd level, which is easy to miss. Always spell these with underscores (bootstrap_token, reset_token_key, pepper_v1) -- MindAttic.Authentication's config reader already does punctuation-insensitive matching specifically for this (see ConfigAuthSecrets.FindByRelaxedName, built for exactly this Linux/Azure App Service mangling), so the underscored spelling resolves correctly with no extra config needed. Verify with:

systemd-run --uid=<app> --gid=<app> --property=EnvironmentFile=/etc/<app>/env --wait --pipe --collect --unit=envcheck /usr/bin/env | grep -i '<expected keys>'

If a key you wrote doesn't show up here, that's the hyphen bug -- fix the name, not the app.

What's required just to start (found by watching it crash-loop and reading the exception each time -- faster than guessing the full secret list up front):

  • ConnectionStrings__<App> -- obviously.
  • MindAttic__Vault__Security__pepper_v1 -- Argon2id password hashing pepper, base64, required even for --migrate (constructed eagerly by the password hasher).
  • MindAttic__Vault__Security__bootstrap_token -- becomes the literal initial admin password (MustChangePassword + MustEnrollMfa forced on first login). Required for the one-time admin seed that --migrate triggers. Save this value -- it's shown once and needed to actually log in.
  • MindAttic__Vault__Security__reset_token_key -- not required at migrate time but needed before any password-reset/invite flow is exercised; set it up front so it's not a surprise later.
  • The LLM provider key(s) the app actually calls, if AiMode=live.

11. Database migration (run once, as the real app user, with the real env)

Run it as a transient systemd unit rather than a bare shell invocation -- this guarantees it sees exactly the same environment (user, group, EnvironmentFile) the real service will, so there's no "works when I test it, fails as a service" gap:

systemd-run --uid=<app> --gid=<app> \
  --property=EnvironmentFile=/etc/<app>/env \
  --property=WorkingDirectory=/opt/<app>/server \
  --wait --pipe --collect --unit=<app>-migrate \
  /opt/<app>/server/<App>.Server --migrate

Watch its output. A cold database retries for ~2 minutes (8 attempts, 15s apart) before giving up, so a slow first run isn't necessarily broken -- but a secret-not-found exception repeats on every retry and won't resolve itself; fix the env file and re-run. Note: for apps like Gadfly where --migrate doesn't exit afterward (it falls through to the normal web host), this transient unit ends up serving the app, which is a fine way to smoke-test it manually, but stop it before step 12 so the permanent systemd service owns the port instead of a one-off transient unit.

12. Permanent services (systemd units, one per process)

# /etc/systemd/system/<app>-server.service
[Unit]
Description=<App>.Server (web app)
After=network.target mssql-server.service
Wants=mssql-server.service

[Service]
Type=simple
User=<app>
Group=<app>
WorkingDirectory=/opt/<app>/server
ExecStart=/opt/<app>/server/<App>.Server
EnvironmentFile=/etc/<app>/env
Restart=on-failure
RestartSec=5
KillSignal=SIGTERM
TimeoutStopSec=55

[Install]
WantedBy=multi-user.target

Same shape for <app>-worker.service, pointed at /opt/<app>/worker/<App>.Worker. Then:

systemctl daemon-reload
systemctl enable --now <app>-server
systemctl enable --now <app>-worker

If the app has a Jobs:RunInWeb-style setting (anything that defaults to "the web process also runs the job queue/sweepers unless told not to" -- check the app's own docs/DEPLOY.md): once a dedicated worker unit exists, set it false in the env file and restart both. It's not a correctness bug either way (a well-built job queue claims rows atomically, so nothing double-processes) -- but on a small box, running the same sweepers twice for no benefit is pure waste. Verify the worker unit is actually listed and active (systemctl list-units --type=service --all | grep <app>) rather than assuming the web process alone is enough -- this was missed on the first Gadfly pass and only caught by an explicit audit (GAD-T868).

13. Verify end to end (don't just trust "it started")

curl -s -o /dev/null -w "HTTP %{http_code}\n" http://<public-ip>/            # through Caddy
curl -s http://<public-ip>/healthz                                           # app health
journalctl -u <app>-server --no-pager -n 40 | grep -iv 'Request (starting|finished)'

If the app logs an "AI panel: live providers" line (or equivalent), that confirms the key loaded -- but loading isn't the same as working. Prove the key itself is live with a direct, minimal call to the provider, bypassing the app entirely:

KEY=$(grep 'MindAttic__Vault__LLM__claude__apiKey' /etc/<app>/env | cut -d= -f2-)
curl -s https://api.anthropic.com/v1/messages \
  -H "x-api-key: $KEY" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' \
  -d '{"model":"claude-haiku-5-5","max_tokens":16,"messages":[{"role":"user","content":"Reply with the single word: online"}]}'

A real text response (not a 401/403) is the only real proof the key works end to end.

14. Auth defaults for every app using MindAttic.Authentication (owner policy, GAD-T860/T861, M.AUTH-T58)

Every app on this pipeline that uses the shared auth library inherits two standing decisions, not just Gadfly:

MFA is required exactly for accounts that can see secrets -- never blanket-required for every staff account. Two layers, don't confuse them:

  • Library layer (applies automatically, every app, no config needed): MfaOptions.RequireForAdmin defaults to true for the library's own MaRoles.Admin -- the single bootstrapped super-admin account every app seeds via AuthBootstrapper (step 11). This account can reach Vault-backed settings (LLM/API keys, SMTP credentials, anything else MindAttic:Vault:* exposes), so it always requires MFA. Leave this default alone; it's the "admin accounts with secrets require MFA" rule and it needs nothing app-specific to keep working on the next app.
  • App layer (per-app, a real design decision): an app's own staff/role model (organizations, tenancy, whatever it calls them) should flag a role for forced MFA only if that role can reach a page showing secrets -- an API key management page, billing/Stripe settings, member admin with password-reset powers -- not reflexively "every role above the lowest one." Gadfly's org roles are Owner, Admin, Instructor, Examiner, SecondReviewer, Student; only Owner and (org) Admin reach OrgApiKeys.razor and similar admin pages, so only those two require MFA (Gadfly.Server/Tenancy/Tenancy.cs's OrgRoles.RequiresMfa) -- Instructor/Examiner/SecondReviewer grade and review exams and never see a secret, so they sign in with just a password. When building a new app's role model, ask the same question per role: can this role see a credential, key, or payment setting? -- if no, don't force MFA on it.

The MFA enrollment page shows a real, scannable QR code, not just the raw otpauth URI as text -- fixed in MindAttic.Authentication 9.1.0 (MaMfaSetup.razor via the new QrCodeSvg.Render helper, pure-managed SVG, no System.Drawing/libgdiplus needed on the Linux host). Any app pinned below 9.1.0 asks users to type a 32-character base32 secret by hand -- bump the PackageReference when adopting this pipeline for a new app.

Reminder from the Gadfly run: do step 8's real-HTTPS setup before the first login attempt, not after -- the __Host- prefixed, SecurePolicy=Always auth cookie silently fails to store on plain HTTP with no visible error (see step 8's gotcha note). Login appearing to "do nothing" on a fresh Hetzner deploy is almost always this, not an app bug.

The library default can be turned off per app -- that's a supported override, not a bug to fix. An owner can decide a given deployment's bootstrapped admin account doesn't need MFA at all (e.g. a personal pilot server, not a multi-tenant product): set MindAttic__Auth__Mfa__RequireForAdmin=false in that app's own env file. This is the officially-supported, app-scoped way to turn the library default off (its own [Setting] doc comment says so) -- it does not mean the library's own default should change, and it does not affect any app-layer per-role MFA (the "app layer" bullet above is untouched by this). Record why on the app's own side (a ticket note is enough) when this gets flipped, since it's a deliberate, named exception to the otherwise-standing "admin accounts with secrets require MFA" rule, not a silent default change (GAD-T868).

15. What this pipeline does NOT cover yet (known gaps, tracked separately)

  • No purchased domain yet. HTTPS itself is covered (step 8, via sslip.io) -- a real domain is still a nice-to-have for a memorable URL, not a functional requirement.
  • SMTP is covered (step 10's optional add-ons) -- not a gap anymore, just opt-in per app.
  • No automated redeploy. Today, shipping an update means repeating steps 9, 11 (if schema changed) and a service restart by hand. Turning this into a one-command /publish-style flow for Hetzner-hosted apps is tracked as its own piece of work, not yet built.
  • No backups configured (Hetzner Storage Box or snapshot schedule) -- the server has none yet.
  • 2FA on the Hetzner account itself is a one-time owner step this pipeline can't do for you.
  • Multi-app sharing: this run put one app on one fresh server. Whether a second app shares this same box (one SQL Server instance, multiple databases, Caddy routing by hostname) or gets its own server is a sizing/isolation decision to make per app, not assumed here.
From MindAttic.Agency/docs/ops/hetzner-deploy-pipeline.md via MindAttic.Docs; synced automatically, so edit the repo, not this page.