Compare commits
17
Commits
2bae941f4a
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ed1176cc4f | ||
|
|
55328cf620 | ||
|
|
a03340ca37 | ||
|
|
3edfcf5656 | ||
|
|
e3d4ae696d | ||
|
|
0138dd376c | ||
|
|
114bed13ba | ||
|
|
50c61a998f | ||
|
|
a15df3f783 | ||
|
|
a6f653dd26 | ||
|
|
b0ac883818 | ||
|
|
c01332db04 | ||
|
|
8627a232e8 | ||
|
|
f8772c4397 | ||
|
|
0eb1323a44 | ||
|
|
6172de2297 | ||
|
|
65494e9b67 |
No files matched your search
@@ -7,11 +7,27 @@ Infrastructure-as-code for Commons Computing's ATProto services.
|
||||
This flake manages the following services on `asusmini`:
|
||||
|
||||
- **PDS** (Personal Data Server) - `pds.commonscomputer.com:5556`
|
||||
- **Tangled Knot** (Git forge) - `knot.commonscomputer.com:5555`
|
||||
- **Tangled Knot** (Rust Git forge) - HTTP `5555`, Git SSH `22`
|
||||
- **Tangled Spindle** (CI runner) - `spindle.commonscomputer.com:6555`
|
||||
|
||||
All services are proxied through Caddy with automatic HTTPS.
|
||||
|
||||
The supervised Go-to-Rust cutover is documented in [TANGLED-MIGRATION.md](TANGLED-MIGRATION.md).
|
||||
Do not activate the new configuration before following its backup and migration steps.
|
||||
|
||||
### Administrative SSH
|
||||
|
||||
Enable Tailscale, then connect to `asusmini` on port **2224**:
|
||||
|
||||
```bash
|
||||
ssh -p 2224 [email protected]
|
||||
```
|
||||
|
||||
This is the confirmed working admin access path. The LAN address is
|
||||
`192.168.1.249` (also port 2224). Public access to
|
||||
`pds.commonscomputer.com:2224` timed out; do not assume it is forwarded.
|
||||
Port 22 on the public hostname serves Tangled Knot's Git SSH, not an admin shell.
|
||||
|
||||
## Setup
|
||||
|
||||
### Prerequisites
|
||||
@@ -71,33 +87,53 @@ This opens your `$EDITOR` with the decrypted content. Save and close to re-encry
|
||||
|
||||
#### Manual Deployment
|
||||
|
||||
From the server:
|
||||
From an administrative root shell on the server, with a clean checkout:
|
||||
```bash
|
||||
cd /etc/nixos # or wherever this repo is cloned
|
||||
git pull
|
||||
sudo nixos-rebuild switch --flake .#asusmini
|
||||
cd /etc/commonscomputing-nix
|
||||
git pull --ff-only
|
||||
nixos-rebuild build --flake .#asusmini
|
||||
nixos-rebuild switch --flake .#asusmini
|
||||
```
|
||||
|
||||
For the first Spaces upgrade, take the offline backup described below between
|
||||
`build` and `switch`. There is no separate activation script. Do not run
|
||||
`nix flake update` unless you intend to update the pinned dependencies too.
|
||||
|
||||
#### Auto-Update
|
||||
|
||||
The timer is gated until `scripts/upgrade-knot.sh` completes the Tangled
|
||||
migration and smoke tests. It then resumes weekly updates. Tangled is pinned to
|
||||
reviewed stable `v1.20.1`, not its development branch: later Tangled releases need
|
||||
an explicit tag bump. Other flake inputs continue updating weekly.
|
||||
|
||||
A systemd timer runs weekly to:
|
||||
1. Pull latest git changes
|
||||
2. Run `nix flake update`
|
||||
3. Commit and push flake.lock changes
|
||||
4. Run `nixos-rebuild switch` with automatic rollback on failure
|
||||
3. Build, activate, and health-check the new configuration
|
||||
4. Check Knot, Spindle, SSH, and both local/public PDS health
|
||||
5. Commit and push flake.lock only after successful validation
|
||||
|
||||
Keep the server checkout's Nix files committed; uncommitted changes deliberately
|
||||
block updates. Git SSH to `git.commonscomputer.com:2222` uses the verified origin
|
||||
`205.250.24.44` through a host-specific SSH configuration because Cloudflare does
|
||||
not proxy that port. The existing deploy key remains in use.
|
||||
|
||||
**Setup required:**
|
||||
```bash
|
||||
# On the server, generate SSH key for git push
|
||||
ssh-keygen -t ed25519 -f /root/.ssh/commons-nix-deploy -N ""
|
||||
cat /root/.ssh/commons-nix-deploy.pub
|
||||
# Add the public key as a deploy key with write access to the GitHub repo
|
||||
# Add the public key as a write-enabled deploy key on our forge:
|
||||
# https://git.commonscomputer.com/aynish/commoncomputing-nix
|
||||
|
||||
# Configure git to use the key
|
||||
# If this is the chosen deploy key, configure SSH to use it:
|
||||
cat >> /root/.ssh/config <<EOF
|
||||
Host github.com
|
||||
Host git.commonscomputer.com
|
||||
IdentityFile /root/.ssh/commons-nix-deploy
|
||||
EOF
|
||||
|
||||
# Verify the existing key before generating/replacing anything on a live host:
|
||||
git -C /etc/commonscomputing-nix push --dry-run
|
||||
```
|
||||
|
||||
**Manual trigger:**
|
||||
@@ -111,6 +147,85 @@ sudo systemctl status auto-update
|
||||
sudo journalctl -u auto-update
|
||||
```
|
||||
|
||||
### Spaces Public Beta
|
||||
|
||||
The temporary PDS overlay selects published tag `v0.4.600` (runtime version
|
||||
`0.4.6000`, `@atproto/pds` 0.6.0) while nixpkgs still packages `0.4.5051`.
|
||||
When nixpkgs changes its PDS version, its package takes over automatically.
|
||||
The pinned nixpkgs already builds with a supported Node 22 runtime.
|
||||
|
||||
`PDS_SPACES_MIGRATION_JITTER_WINDOW_MS=0` matches the official production image,
|
||||
avoiding the library's default initial delay of up to 24 hours. Migration and
|
||||
PLC KEM-key publication happen automatically. Back up PDS state and its secrets
|
||||
before activation; switching Nix generations does not undo database or PLC
|
||||
changes. Do not deploy the Spaces alpha.
|
||||
|
||||
After activation, verify `/xrpc/_health` reports `0.4.6000` and inspect its
|
||||
`spacesMigration` counters. Check that hosted active PLC accounts gain an
|
||||
`#atproto_kem` verification method. These are migration checks, not a substitute
|
||||
for an authenticated Spaces application test.
|
||||
|
||||
#### One-time backup before the Spaces and Tangled stable upgrade
|
||||
|
||||
Use an administrative root shell in `/etc/commonscomputing-nix`. If needed,
|
||||
bootstrap Git/curl/jq with:
|
||||
`nix shell --inputs-from . nixpkgs#git nixpkgs#curl nixpkgs#jq --command bash`.
|
||||
The new configuration installs these tools normally. Tangled stays on stable
|
||||
`v1.20.1`; its unreleased development-branch security fixes are not included.
|
||||
Spindle keeps its existing CORS policy and unlimited cache quota rather than
|
||||
adopting the new wildcard-CORS and 5 GiB cache defaults.
|
||||
|
||||
Pause the timer and take its shared lock before updating the checkout:
|
||||
|
||||
```bash
|
||||
systemctl stop auto-update.timer
|
||||
exec 9>/run/lock/commonscomputing-update.lock
|
||||
flock --nonblock 9
|
||||
```
|
||||
|
||||
Stop if the lock is busy. The three existing server edits are duplicates of
|
||||
committed fixes; discard only those paths, then use the normal pull/build steps:
|
||||
|
||||
```bash
|
||||
git restore -- hosts/asusmini/atproto.nix hosts/asusmini/default.nix scripts/upgrade-knot.sh
|
||||
git pull --ff-only https://git.commonscomputer.com/aynish/commoncomputing-nix.git main
|
||||
nixos-rebuild build --flake .#asusmini
|
||||
```
|
||||
|
||||
Tangled `v1.20.1` also adds automatic Spindle database migrations. After a
|
||||
successful build, stop the three application services and take one consistent
|
||||
backup. Spindle may wait for running jobs to drain before it stops:
|
||||
|
||||
```bash
|
||||
umask 077
|
||||
backup=/var/backups/pds-spaces-$(date -u +%Y%m%dT%H%M%SZ)
|
||||
mkdir -p "$backup"
|
||||
readlink -f /run/current-system > "$backup/old-system"
|
||||
cp flake.lock "$backup/flake.lock"
|
||||
systemctl stop bluesky-pds knot-rs spindle
|
||||
tar --acls --xattrs --numeric-owner -C / -cpf "$backup/state.tar" var/lib/pds var/lib/knot var/lib/spindle
|
||||
tar --compare -f "$backup/state.tar" -C / var/lib/pds var/lib/knot var/lib/spindle
|
||||
cp --dereference /run/agenix/pds-env "$backup/pds-env"
|
||||
cp --dereference /run/agenix/knot-env "$backup/knot-env"
|
||||
```
|
||||
|
||||
Stop on any failure. If backup fails before activation, restart the unchanged
|
||||
services. Keep the backup root-only; it contains private keys.
|
||||
|
||||
Then use the normal `nixos-rebuild switch --flake .#asusmini` and ensure
|
||||
`systemctl start bluesky-pds knot-rs spindle` succeeds. Check PDS local and
|
||||
public health/migration counters, hosted PLC KEM keys, and Knot/Spindle/SSH health.
|
||||
Verify root's `git push --dry-run` succeeds and the checkout is clean. After all
|
||||
checks pass:
|
||||
|
||||
```bash
|
||||
systemctl reset-failed auto-update.service
|
||||
systemctl start auto-update.timer
|
||||
exec 9>&-
|
||||
```
|
||||
|
||||
Do not blindly roll back databases or PLC changes after activation has started.
|
||||
|
||||
## Development
|
||||
|
||||
### Updating Flake Inputs
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
# Tangled Upgrade
|
||||
|
||||
This runbook covers the original Go-to-Rust cutover using v1.20.0. Do not rerun
|
||||
that migration for an ordinary Rust Knot/Spindle version update.
|
||||
|
||||
The current flake pins reviewed stable `v1.20.1`, not the development branch.
|
||||
Future Tangled upgrades require an explicit stable tag bump; other flake inputs
|
||||
still update weekly. Upstream's own nixpkgs is retained for release builds.
|
||||
|
||||
## Run The Script
|
||||
|
||||
Pull the latest configuration on asusmini, then run:
|
||||
|
||||
```sh
|
||||
sudo bash /etc/commonscomputing-nix/scripts/upgrade-knot.sh
|
||||
```
|
||||
|
||||
The script rehearses first, prints the migration report, and asks you to type
|
||||
`MIGRATE` before stopping Go knot. Keep another administrative SSH session open,
|
||||
back up the master key off-host, and ask users to pause writes during cutover.
|
||||
`--yes` skips the approval prompt. Running the script authorizes migration and
|
||||
deployment, not merely a smoke test.
|
||||
|
||||
Root's Git identity must be able to fetch and push to `origin`. The script
|
||||
checks `ls-remote` and `push --dry-run` before downtime. Origin is the separate
|
||||
Gitea service on port 2222, not this knot.
|
||||
|
||||
If encrypted-secret edits prevent a fast-forward pull, preserve only those
|
||||
edits first; leave unrelated DNS changes alone:
|
||||
|
||||
```sh
|
||||
sudo git -C /etc/commonscomputing-nix stash push \
|
||||
-m 'pre-cutover encrypted secret backup' -- secrets/knot-env.age secrets/secrets.nix
|
||||
sudo git -C /etc/commonscomputing-nix pull --ff-only
|
||||
```
|
||||
|
||||
The encrypted secret is already committed; do not pop an identical stash over
|
||||
it. Its SHA-256 is
|
||||
`b26f36d098a337a98217aa4e73d2f39eb4e8864337dfcface937093f5557f0ac`.
|
||||
|
||||
## Happy Path
|
||||
|
||||
1. Lock out concurrent updates and validate the host, staging files, and Git access.
|
||||
2. Import the prebuilt system/tools if missing, after checking the archive checksum.
|
||||
3. Decrypt the persistent key into root-only runtime storage and rehearse.
|
||||
4. Obtain downtime approval; stop the timer and Go knot.
|
||||
5. Back up the database, repositories, SSH identity, and old NixOS generation.
|
||||
6. Copy-migrate repositories/access grants while preserving all original source data.
|
||||
7. Validate the imported identity/configuration and install the prebuilt system.
|
||||
8. Set ownership, check agenix supplied the same key, and start Rust knot.
|
||||
9. Check local/public APIs, service state, SSH fingerprint, and Caddy WebSocket upgrade.
|
||||
10. Mark verification complete, start the weekly timer, and request an indexer crawl.
|
||||
|
||||
Source data stays in `/home/git`; Rust state lives in `/var/lib/knot`. The
|
||||
previous rehearsal found 23 repositories, 16 members, 12 collaborator grants,
|
||||
zero skips, and no ACL/table disagreement. Check the fresh report for changes.
|
||||
|
||||
Backups are root-only under `/var/backups/knot-cutover.*`. They contain private
|
||||
key material, including `repo-signing-keys.json`; back them up encrypted off-host.
|
||||
The master key is not printed and is scoped to migration/config validation.
|
||||
The runtime plaintext file is removed on ordinary success/failure and signals;
|
||||
SIGKILL may leave it root-readable in `/run` until cleanup or reboot.
|
||||
|
||||
## Networking
|
||||
|
||||
Administrative SSH stays on **22**. Rust knot Git SSH uses **2223**, opened by
|
||||
the NixOS module. Use `100.122.40.27:2223` over Tailscale, or arrange external
|
||||
TCP 2223 forwarding to `192.168.1.249:2223`. Existing port-22 Git URLs need an
|
||||
explicit port or client SSH configuration. Public 2222 belongs to Gitea and
|
||||
must not be repurposed. The script does not change router forwarding or sshd.
|
||||
|
||||
Caddy proxies all paths and WebSocket upgrades to `192.168.1.249:5555`; Knot
|
||||
trusts forwarded addresses only from `192.168.1.11/32`. The script checks
|
||||
`/xrpc/com.atproto.sync.subscribeRepos` through Caddy. It cannot test an
|
||||
authenticated user push without their credentials: after success, test a real
|
||||
clone/push/delete of a temporary branch over port 2223.
|
||||
|
||||
## Automatic Updates
|
||||
|
||||
Both timer and service require `/var/lib/knot/.upgrade-verified`. The script
|
||||
creates it only after successful smoke tests, then starts the timer. A separate
|
||||
migration marker prevents Rust knot from initializing an empty identity.
|
||||
|
||||
Weekly updates fast-forward the configuration, update inputs, build, activate,
|
||||
and health-check **before** committing/pushing `flake.lock`. Preexisting staged
|
||||
changes, lockfile edits, or Nix configuration edits cause refusal. Unrelated
|
||||
unstaged DNS edits remain untouched. Git runs noninteractively; update and
|
||||
migration jobs share a process lock.
|
||||
|
||||
A failed build leaves the live generation unchanged and restores the script's
|
||||
own lockfile changes. After activation is attempted, failure stops the application
|
||||
services and timer and retains state/lockfile; old binaries are not automatically
|
||||
run against possibly forward-migrated data. Publication failure retains the
|
||||
healthy deployed generation and local changes; reconcile them with origin
|
||||
before the next update.
|
||||
|
||||
Future versions may compile on asusmini unless supplied by a binary cache.
|
||||
Only the initial v1.20.0 cutover is guaranteed to reuse staged binaries.
|
||||
|
||||
## Failure And Retry
|
||||
|
||||
Before activation, failed migration targets are quarantined in the backup
|
||||
directory and unchanged Go knot is restarted. After activation is attempted,
|
||||
the script stops Rust knot/updates but preserves migrated state: blind rollback
|
||||
could lose accepted writes or use an incompatible format. Investigate before
|
||||
reopening writes. Runtime timer masks do not survive reboot; do not reboot an
|
||||
old generation unattended during recovery.
|
||||
|
||||
A completed rerun verifies the live Rust service and resumes the gated timer;
|
||||
it never migrates again or reinstalls an old staged generation. An incomplete
|
||||
target without a completion marker is refused. Power loss or SIGKILL midway
|
||||
requires inspection/recovery, not a blind rerun.
|
||||
|
||||
## Staging And Tests
|
||||
|
||||
`/home/anish/tangled-v1.20.0-preflight` contains `system-path`, `tools-path`,
|
||||
`upgrade.export.gz`, and its checksum. The archive contains paths missing at
|
||||
staging time; avoid garbage collection before import. Import alone activates
|
||||
nothing. The root-authorized import accepts unsigned local products only for
|
||||
that command, without changing global Nix trust settings.
|
||||
|
||||
Local/server runtime and synthetic-migration smoke tests passed earlier. Mocked
|
||||
orchestration tests cover success, preflight refusal, migration failure,
|
||||
post-activation failure, secret cleanup, idempotence, and publication ordering.
|
||||
They do not simulate a full boot or replace the on-host checks.
|
||||
|
||||
Upstream's v1.20.0 spindle still reports hardcoded wire version `v1.16.1` in
|
||||
its describe endpoint; identify its actual package by the service store path.
|
||||
|
||||
## Upstream Guides
|
||||
|
||||
- https://tangled.org/docs/upgrading/knot-2/
|
||||
- https://tangled.org/docs/upgrading/knots-and-spindles/#upgrading-to-v1200
|
||||
Generated
+91
-196
@@ -1,36 +1,17 @@
|
||||
{
|
||||
"nodes": {
|
||||
"actor-typeahead-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1762835797,
|
||||
"narHash": "sha256-heizoWUKDdar6ymfZTnj3ytcEv/L4d4fzSmtr0HlXsQ=",
|
||||
"ref": "refs/heads/main",
|
||||
"rev": "677fe7f743050a4e7f09d4a6f87bbf1325a06f6b",
|
||||
"revCount": 6,
|
||||
"type": "git",
|
||||
"url": "https://tangled.org/@jakelazaroff.com/actor-typeahead"
|
||||
},
|
||||
"original": {
|
||||
"type": "git",
|
||||
"url": "https://tangled.org/@jakelazaroff.com/actor-typeahead"
|
||||
}
|
||||
},
|
||||
"agenix": {
|
||||
"inputs": {
|
||||
"darwin": "darwin",
|
||||
"home-manager": "home-manager",
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
],
|
||||
"systems": "systems"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1770165109,
|
||||
"narHash": "sha256-9VnK6Oqai65puVJ4WYtCTvlJeXxMzAp/69HhQuTdl/I=",
|
||||
"lastModified": 1792507013,
|
||||
"narHash": "sha256-8tKjSQajD3mUND1GaAuaWTcuyUpgcGsh5V+l4ibzC7U=",
|
||||
"owner": "ryantm",
|
||||
"repo": "agenix",
|
||||
"rev": "b027ee29d959fda4b60b57566d64c98a202e0feb",
|
||||
"rev": "5e5b88a0c8e56f291a108c2fe9934054d9745b2e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -60,28 +41,6 @@
|
||||
"url": "https://tangled.org/hyl.st/automerge-repo-nix"
|
||||
}
|
||||
},
|
||||
"darwin": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"agenix",
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1744478979,
|
||||
"narHash": "sha256-dyN+teG9G82G+m+PX/aSAagkC+vUv0SgUw3XkPhQodQ=",
|
||||
"owner": "lnl7",
|
||||
"repo": "nix-darwin",
|
||||
"rev": "43975d782b418ebf4969e9ccba82466728c2851b",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "lnl7",
|
||||
"ref": "master",
|
||||
"repo": "nix-darwin",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"fenix": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
@@ -91,11 +50,11 @@
|
||||
"rust-analyzer-src": "rust-analyzer-src"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1780397302,
|
||||
"narHash": "sha256-SQmrkj17xBdvc8lVMbsY7pIJCjKftgNh42R1keP3dLQ=",
|
||||
"lastModified": 1794750246,
|
||||
"narHash": "sha256-7Yd8fQdT8G1p76nY5thZMAO4/hMyhG9iIL42i8OfbLU=",
|
||||
"owner": "nix-community",
|
||||
"repo": "fenix",
|
||||
"rev": "f6670530f53e69cc284f7aef818eb0f08fe81905",
|
||||
"rev": "03b9a946cbd2777de45d7ba96c29157e1f7db613",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -141,7 +100,7 @@
|
||||
},
|
||||
"flake-utils": {
|
||||
"inputs": {
|
||||
"systems": "systems_2"
|
||||
"systems": "systems"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1731533236,
|
||||
@@ -159,7 +118,7 @@
|
||||
},
|
||||
"flake-utils_2": {
|
||||
"inputs": {
|
||||
"systems": "systems_3"
|
||||
"systems": "systems_2"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1731533236,
|
||||
@@ -197,61 +156,36 @@
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"hls-src": {
|
||||
"hydrant": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"narHash": "sha256-mmxgaQRXXWzRG6/OlOn5efV+NmzhvmXTQaFbODqh0b8=",
|
||||
"type": "file",
|
||||
"url": "https://cdn.jsdelivr.net/npm/[email protected]/dist/hls.min.js"
|
||||
"lastModified": 1792544679,
|
||||
"narHash": "sha256-fm0cuIyHjJTSvleJyLbT4E5KugtanuysL/oMOnGhN3I=",
|
||||
"ref": "refs/heads/main",
|
||||
"rev": "0128352f6b73d26e7ffaa5a79446ef556e452617",
|
||||
"revCount": 811,
|
||||
"type": "git",
|
||||
"url": "https://tangled.org/ptr.pet/hydrant"
|
||||
},
|
||||
"original": {
|
||||
"type": "file",
|
||||
"url": "https://cdn.jsdelivr.net/npm/[email protected]/dist/hls.min.js"
|
||||
"type": "git",
|
||||
"url": "https://tangled.org/ptr.pet/hydrant"
|
||||
}
|
||||
},
|
||||
"home-manager": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"agenix",
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1745494811,
|
||||
"narHash": "sha256-YZCh2o9Ua1n9uCvrvi5pRxtuVNml8X2a03qIFfRKpFs=",
|
||||
"owner": "nix-community",
|
||||
"repo": "home-manager",
|
||||
"rev": "abfad3d2958c9e6300a883bd443512c55dfeb1be",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-community",
|
||||
"repo": "home-manager",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"htmx-src": {
|
||||
"hydrant-dev": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"narHash": "sha256-2D8I0L0u6qb57QpeVn88RrT0xatDwQwG/lWOTjuEFPc=",
|
||||
"type": "file",
|
||||
"url": "https://cdn.jsdelivr.net/npm/[email protected]/dist/htmx.min.js"
|
||||
"lastModified": 1792544679,
|
||||
"narHash": "sha256-fm0cuIyHjJTSvleJyLbT4E5KugtanuysL/oMOnGhN3I=",
|
||||
"ref": "refs/heads/main",
|
||||
"rev": "0128352f6b73d26e7ffaa5a79446ef556e452617",
|
||||
"revCount": 811,
|
||||
"type": "git",
|
||||
"url": "https://tangled.org/ptr.pet/hydrant"
|
||||
},
|
||||
"original": {
|
||||
"type": "file",
|
||||
"url": "https://cdn.jsdelivr.net/npm/[email protected]/dist/htmx.min.js"
|
||||
}
|
||||
},
|
||||
"htmx-ws-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"narHash": "sha256-woiluaeAoxH/CyDkpk6LYNWCzxH8PHgwgnrlBFGJxgk=",
|
||||
"type": "file",
|
||||
"url": "https://cdn.jsdelivr.net/npm/[email protected]"
|
||||
},
|
||||
"original": {
|
||||
"type": "file",
|
||||
"url": "https://cdn.jsdelivr.net/npm/[email protected]"
|
||||
"type": "git",
|
||||
"url": "https://tangled.org/ptr.pet/hydrant"
|
||||
}
|
||||
},
|
||||
"ibm-plex-mono-src": {
|
||||
@@ -283,56 +217,6 @@
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"inter-fonts-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1731687360,
|
||||
"narHash": "sha256-5vdKKvHAeZi6igrfpbOdhZlDX2/5+UvzlnCQV6DdqoQ=",
|
||||
"type": "tarball",
|
||||
"url": "https://github.com/rsms/inter/releases/download/v4.1/Inter-4.1.zip"
|
||||
},
|
||||
"original": {
|
||||
"type": "tarball",
|
||||
"url": "https://github.com/rsms/inter/releases/download/v4.1/Inter-4.1.zip"
|
||||
}
|
||||
},
|
||||
"lucide-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1754044466,
|
||||
"narHash": "sha256-+exBR2OToB1iv7ZQI2S4B0lXA/QRvC9n6U99UxGpJGs=",
|
||||
"type": "tarball",
|
||||
"url": "https://github.com/lucide-icons/lucide/releases/download/0.536.0/lucide-icons-0.536.0.zip"
|
||||
},
|
||||
"original": {
|
||||
"type": "tarball",
|
||||
"url": "https://github.com/lucide-icons/lucide/releases/download/0.536.0/lucide-icons-0.536.0.zip"
|
||||
}
|
||||
},
|
||||
"mathjax-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"narHash": "sha256-eqg25bKfiDzynRMR2RfeWNfo0EefHF/eRRFafl9RnNI=",
|
||||
"type": "file",
|
||||
"url": "https://cdn.jsdelivr.net/npm/[email protected]/tex-svg.js"
|
||||
},
|
||||
"original": {
|
||||
"type": "file",
|
||||
"url": "https://cdn.jsdelivr.net/npm/[email protected]/tex-svg.js"
|
||||
}
|
||||
},
|
||||
"mermaid-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"narHash": "sha256-/YOdECG2V5c3kJ1QfGvhziTT6K/Dx/4mOk2mr3Fs/do=",
|
||||
"type": "file",
|
||||
"url": "https://cdn.jsdelivr.net/npm/[email protected]/dist/mermaid.min.js"
|
||||
},
|
||||
"original": {
|
||||
"type": "file",
|
||||
"url": "https://cdn.jsdelivr.net/npm/[email protected]/dist/mermaid.min.js"
|
||||
}
|
||||
},
|
||||
"microvm": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
@@ -357,11 +241,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1789785513,
|
||||
"narHash": "sha256-B44WL6h0XoLjJ41bUPJk0X5SDinLCII//6EcBLXKiJ0=",
|
||||
"lastModified": 1793341285,
|
||||
"narHash": "sha256-Y1CiZ4SoBUjLQyQM/pY+rS2dXD3CHLPstF0lmOc73D4=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "20b1ddd1aa5ace70c9468305030aa4f9ef79671b",
|
||||
"rev": "1c89083e451e891152365b799595cf7790a43325",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -371,6 +255,38 @@
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs-pds": {
|
||||
"locked": {
|
||||
"lastModified": 1791734076,
|
||||
"narHash": "sha256-i5qk1kLiit98rRbh1AXmWBNT9QXC/y4l5Wk/u5EdpDQ=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "7fd4004d0511991fff3a0524856a9be09e28c5f0",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nixos",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs_2": {
|
||||
"locked": {
|
||||
"lastModified": 1781216227,
|
||||
"narHash": "sha256-9mUW6gNwoN2SWc/l0fW4svPNOulXLl8ijqKyeSOGgJE=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "a0374025a863d007d98e3297f6aa46cc3141c2f0",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nixos",
|
||||
"ref": "nixos-26.05",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"agenix": "agenix",
|
||||
@@ -382,11 +298,11 @@
|
||||
"rust-analyzer-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1780337665,
|
||||
"narHash": "sha256-RS3F+/6dtBIwd5+47GVen3jAk62/KumFZ4q3RVYafDk=",
|
||||
"lastModified": 1794699679,
|
||||
"narHash": "sha256-v46dxoiIRQrRDwO/OGb9F2cBEk9aqKQyzLz7wQi9oPY=",
|
||||
"owner": "rust-lang",
|
||||
"repo": "rust-analyzer",
|
||||
"rev": "55af1774e9e840d3b28d12fcfaa72d2e2caa8ac9",
|
||||
"rev": "b664fd5c7e7055c9569960f7fe73f21c7d00c9cd",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -455,70 +371,49 @@
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"systems_3": {
|
||||
"locked": {
|
||||
"lastModified": 1681028828,
|
||||
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-systems",
|
||||
"repo": "default",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"tailwindcss-animated-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 499162500,
|
||||
"narHash": "sha256-l3esIcsAwj0PHOhnHBLWiLzzRiOo1yOk9VYEGpn6fyQ=",
|
||||
"type": "tarball",
|
||||
"url": "https://registry.npmjs.org/tailwindcss-animated/-/tailwindcss-animated-1.1.2.tgz"
|
||||
},
|
||||
"original": {
|
||||
"type": "tarball",
|
||||
"url": "https://registry.npmjs.org/tailwindcss-animated/-/tailwindcss-animated-1.1.2.tgz"
|
||||
}
|
||||
},
|
||||
"tangled": {
|
||||
"inputs": {
|
||||
"actor-typeahead-src": "actor-typeahead-src",
|
||||
"fenix": "fenix",
|
||||
"fetch-tangled": "fetch-tangled",
|
||||
"flake-compat": "flake-compat",
|
||||
"gomod2nix": "gomod2nix",
|
||||
"hls-src": "hls-src",
|
||||
"htmx-src": "htmx-src",
|
||||
"htmx-ws-src": "htmx-ws-src",
|
||||
"hydrant": "hydrant",
|
||||
"hydrant-dev": "hydrant-dev",
|
||||
"ibm-plex-mono-src": "ibm-plex-mono-src",
|
||||
"indigo": "indigo",
|
||||
"inter-fonts-src": "inter-fonts-src",
|
||||
"lucide-src": "lucide-src",
|
||||
"mathjax-src": "mathjax-src",
|
||||
"mermaid-src": "mermaid-src",
|
||||
"microvm": "microvm",
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
],
|
||||
"nixpkgs": "nixpkgs_2",
|
||||
"nixpkgs-pds": "nixpkgs-pds",
|
||||
"sqlite-lib-src": "sqlite-lib-src",
|
||||
"tailwindcss-animated-src": "tailwindcss-animated-src"
|
||||
"timeless-fonts-src": "timeless-fonts-src"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1789731405,
|
||||
"narHash": "sha256-coBPFy5y841710mAEZJ2hXetSq7nEJoyGNH+vVVxloU=",
|
||||
"ref": "refs/heads/master",
|
||||
"rev": "7fcec78848bfd98f3f6a05411efaca1958da0e8f",
|
||||
"revCount": 3226,
|
||||
"lastModified": 1794841019,
|
||||
"narHash": "sha256-G9GqopFb5msKSPs54IYLY6i6UotO1nm1T4jP9NI21K8=",
|
||||
"ref": "refs/tags/v1.20.1",
|
||||
"rev": "af4f4d69adfc252b6a06cf3394e37ddf6eb4a4e2",
|
||||
"revCount": 6544,
|
||||
"type": "git",
|
||||
"url": "https://tangled.org/@tangled.org/core"
|
||||
},
|
||||
"original": {
|
||||
"ref": "refs/tags/v1.20.1",
|
||||
"type": "git",
|
||||
"url": "https://tangled.org/@tangled.org/core"
|
||||
}
|
||||
},
|
||||
"timeless-fonts-src": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1791052084,
|
||||
"narHash": "sha256-zYpoDkE/YrICzYaHF4/NSuINczFWB41YymTxaL6KqLY=",
|
||||
"type": "tarball",
|
||||
"url": "https://media.timeless.co/type/Timeless-Type-Family-1.094.zip"
|
||||
},
|
||||
"original": {
|
||||
"type": "tarball",
|
||||
"url": "https://media.timeless.co/type/Timeless-Type-Family-1.094.zip"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
|
||||
@@ -4,8 +4,9 @@
|
||||
inputs = {
|
||||
nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
|
||||
tangled = {
|
||||
url = "git+https://tangled.org/@tangled.org/core";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
# Track reviewed stable releases, not the development branch.
|
||||
# Keep upstream's own nixpkgs so release binaries remain reusable.
|
||||
url = "git+https://tangled.org/@tangled.org/core?ref=refs/tags/v1.20.1";
|
||||
};
|
||||
agenix = {
|
||||
url = "github:ryantm/agenix";
|
||||
@@ -36,7 +37,7 @@
|
||||
system = "x86_64-linux";
|
||||
modules = [
|
||||
./hosts/asusmini
|
||||
tangled.nixosModules.knot
|
||||
tangled.nixosModules.knot-rs
|
||||
tangled.nixosModules.spindle
|
||||
agenix.nixosModules.default
|
||||
inputs."automerge-repo".nixosModules.default
|
||||
@@ -45,6 +46,23 @@
|
||||
};
|
||||
};
|
||||
|
||||
packages.x86_64-linux.knot-migration-tools =
|
||||
let
|
||||
pkgs = nixpkgs.legacyPackages.x86_64-linux;
|
||||
in
|
||||
pkgs.buildEnv {
|
||||
name = "knot-migration-tools";
|
||||
paths = [
|
||||
tangled.packages.x86_64-linux.knot-migrate
|
||||
agenix.packages.x86_64-linux.default
|
||||
pkgs.sqlite
|
||||
pkgs.openssl
|
||||
pkgs.git
|
||||
pkgs.curl
|
||||
pkgs.jq
|
||||
];
|
||||
};
|
||||
|
||||
devShells = {
|
||||
aarch64-darwin.default =
|
||||
let
|
||||
|
||||
+69
-26
@@ -1,4 +1,4 @@
|
||||
{ config, ... }:
|
||||
{ config, pkgs, ... }:
|
||||
{
|
||||
age.secrets.pds-env = {
|
||||
file = ../../secrets/pds-env.age;
|
||||
@@ -6,6 +6,12 @@
|
||||
owner = "pds";
|
||||
};
|
||||
|
||||
age.secrets.knot-env = {
|
||||
file = ../../secrets/knot-env.age;
|
||||
mode = "0400";
|
||||
owner = "root";
|
||||
};
|
||||
|
||||
services.bluesky-pds = {
|
||||
enable = true;
|
||||
environmentFiles = [ config.age.secrets.pds-env.path ];
|
||||
@@ -16,6 +22,8 @@
|
||||
# Set explicitly so the limit is visible in our config rather than
|
||||
# depending on whatever default the pinned nixpkgs module ships with.
|
||||
PDS_BLOB_UPLOAD_LIMIT = "104857600";
|
||||
# Match the production image: publish Spaces keys without a random 24h delay.
|
||||
PDS_SPACES_MIGRATION_JITTER_WINDOW_MS = "0";
|
||||
# We can set a bunch of other things too
|
||||
# PDS_BSKY_APP_VIEW_URL
|
||||
# PDS_CRAWLERS
|
||||
@@ -31,41 +39,76 @@
|
||||
# full list of options.
|
||||
services.tangled.spindle = {
|
||||
enable = true;
|
||||
keyPath = "/var/lib/spindle/key.pem";
|
||||
contact.email = "pds@email.commonscomputer.com";
|
||||
# Keep the existing unlimited cache policy rather than evicting at the new 5 GiB default.
|
||||
quota.user.cacheStorageMiB = 0;
|
||||
server = {
|
||||
hostname = "spindle.commonscomputer.com";
|
||||
owner = "did:plc:om5yygegi4yxcbay5gemn2wm";
|
||||
# Preserve the existing policy; v1.20.1 defaults to allowing every origin.
|
||||
corsOrigins = [ ];
|
||||
};
|
||||
};
|
||||
|
||||
services.tangled.knot = {
|
||||
systemd.services.spindle.preStart = ''
|
||||
# Persist the did:web identity across restarts; never put its key in the store.
|
||||
key=${config.services.tangled.spindle.keyPath}
|
||||
if [ ! -e "$key" ]; then
|
||||
umask 0077
|
||||
tmp="$(${pkgs.coreutils}/bin/mktemp "$key.XXXXXX")"
|
||||
trap '${pkgs.coreutils}/bin/rm -f "$tmp"' EXIT
|
||||
${pkgs.openssl}/bin/openssl ecparam -name prime256v1 -genkey -noout -out "$tmp"
|
||||
${pkgs.coreutils}/bin/mv "$tmp" "$key"
|
||||
trap - EXIT
|
||||
fi
|
||||
'';
|
||||
|
||||
services.tangled.knot-rs = {
|
||||
enable = true;
|
||||
server = {
|
||||
hostname = "knot.commonscomputer.com";
|
||||
owner = "did:plc:om5yygegi4yxcbay5gemn2wm";
|
||||
environmentFile = config.age.secrets.knot-env.path;
|
||||
settings = {
|
||||
server = {
|
||||
hostname = "knot.commonscomputer.com";
|
||||
admins = [ "did:plc:om5yygegi4yxcbay5gemn2wm" ];
|
||||
# Caddy is on another machine; administrative sshd uses port 2224.
|
||||
listen_addr = "0.0.0.0:5555";
|
||||
ssh_listen_addr = "0.0.0.0:22";
|
||||
};
|
||||
git.object_format = "sha1";
|
||||
atproto.plc_directory = "https://plc.directory";
|
||||
contact.email = "pds@email.commonscomputer.com";
|
||||
lfs.store_path = "/var/lib/knot/lfs";
|
||||
xrpc = {
|
||||
trusted_proxy_header = "x-forwarded-for";
|
||||
trusted_proxies = [ "192.168.1.11/32" ];
|
||||
};
|
||||
tls.http3 = false;
|
||||
};
|
||||
};
|
||||
|
||||
# Activation may create directories, but must not mint a new empty identity.
|
||||
# Create this marker only after migration and ownership checks (see runbook).
|
||||
systemd.services.knot-rs.unitConfig.ConditionPathExists = [
|
||||
"/var/lib/knot/.migration-complete"
|
||||
"/var/lib/knot/ssh_host_key"
|
||||
"/var/lib/knot/sealed-keys"
|
||||
];
|
||||
# Binding port 22 needs a capability in the host user namespace.
|
||||
systemd.services.knot-rs.serviceConfig.AmbientCapabilities = [ "CAP_NET_BIND_SERVICE" ];
|
||||
systemd.services.knot-rs.serviceConfig.PrivateUsers = false;
|
||||
systemd.services.knot-rs.serviceConfig.ExecStartPre = [
|
||||
"${pkgs.coreutils}/bin/test -s /var/lib/knot/ssh_host_key"
|
||||
"${pkgs.coreutils}/bin/test -s /var/lib/knot/sealed-keys"
|
||||
];
|
||||
|
||||
services.automerge-repo-sync-server.enable = true;
|
||||
|
||||
services.caddy = {
|
||||
enable = true;
|
||||
virtualHosts = {
|
||||
"knot.commonscomputer.com".extraConfig = ''
|
||||
reverse_proxy http://localhost:5555
|
||||
'';
|
||||
"pds.commonscomputer.com".extraConfig = ''
|
||||
reverse_proxy http://localhost:5556
|
||||
'';
|
||||
"spindle.commonscomputer.com".extraConfig = ''
|
||||
reverse_proxy http://localhost:6555
|
||||
'';
|
||||
"automerge.commonscomputer.com".extraConfig = ''
|
||||
reverse_proxy http://localhost:3030
|
||||
'';
|
||||
};
|
||||
};
|
||||
networking.firewall.allowedTCPPorts = [
|
||||
80
|
||||
443
|
||||
];
|
||||
# Public edge moved 2026-09-28: 205.250.24.44 -> pve Caddy LXC (192.168.1.11)
|
||||
# now fronts pds/knot/spindle/automerge (see cc-ansible wiki / onboard plan).
|
||||
# PL63 no longer terminates public TLS; its Caddy is removed and the four
|
||||
# vhosts are served by the edge. Services keep binding the local ports.
|
||||
# (services.caddy block removed — nothing LAN-local needs it.)
|
||||
# networking.firewall.allowedTCPPorts = [ 80 443 ]; is likewise gone;
|
||||
# 80/443 on eth0 are no longer used now that the public forwards moved.
|
||||
}
|
||||
@@ -1,58 +1,119 @@
|
||||
{ config, pkgs, ... }:
|
||||
{ pkgs, ... }:
|
||||
|
||||
{
|
||||
systemd.services.auto-update = {
|
||||
description = "Auto-update NixOS configuration";
|
||||
path = with pkgs; [
|
||||
coreutils
|
||||
curl
|
||||
git
|
||||
jq
|
||||
nix
|
||||
openssh
|
||||
util-linux
|
||||
];
|
||||
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
User = "root";
|
||||
WorkingDirectory = "/etc/commonscomputing-nix";
|
||||
TimeoutStartSec = "6h";
|
||||
};
|
||||
|
||||
restartIfChanged = false;
|
||||
unitConfig.ConditionPathExists = "/var/lib/knot/.upgrade-verified";
|
||||
unitConfig.X-StopOnRemoval = false;
|
||||
environment = {
|
||||
GIT_TERMINAL_PROMPT = "0";
|
||||
GIT_SSH_COMMAND = "${pkgs.openssh}/bin/ssh -o BatchMode=yes -o ConnectTimeout=15";
|
||||
};
|
||||
|
||||
script = ''
|
||||
set -e
|
||||
set -euo pipefail
|
||||
exec 9>/run/lock/commonscomputing-update.lock
|
||||
flock --nonblock 9 || exit 0
|
||||
|
||||
echo "Pulling latest changes..."
|
||||
git pull
|
||||
lock_snapshot="$(${pkgs.coreutils}/bin/mktemp)"
|
||||
snapshot_ready=0
|
||||
activated=0
|
||||
validated=0
|
||||
system_profile=/nix/var/nix/profiles/system
|
||||
|
||||
echo "Updating flake inputs..."
|
||||
nix flake update
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT
|
||||
set +e
|
||||
if [ "$status" -ne 0 ] && [ "$snapshot_ready" -eq 1 ] && [ "$activated" -eq 0 ]; then
|
||||
${pkgs.coreutils}/bin/cp "$lock_snapshot" flake.lock
|
||||
fi
|
||||
if [ "$status" -ne 0 ] && [ "$activated" -eq 1 ] && [ "$validated" -eq 0 ]; then
|
||||
# New binaries may already have migrated persistent state. Never
|
||||
# blindly roll back their data format or discard accepted writes.
|
||||
rm -f /var/lib/knot/.upgrade-verified
|
||||
${pkgs.systemd}/bin/systemctl stop auto-update.timer
|
||||
${pkgs.systemd}/bin/systemctl stop knot-rs.service spindle.service bluesky-pds.service
|
||||
echo "Activation/health failed: application services and updates stopped; inspect state and retained flake.lock" >&2
|
||||
elif [ "$status" -ne 0 ] && [ "$validated" -eq 1 ]; then
|
||||
echo "System is healthy, but Git publication failed; retain/reconcile the local lockfile or commit before retrying" >&2
|
||||
fi
|
||||
${pkgs.coreutils}/bin/rm -f "$lock_snapshot"
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
|
||||
# Explicitly update tangled so we always pull the latest knot/spindle
|
||||
# builds, even if other inputs are pinned or the general update is
|
||||
# later restricted. tangled.org/@tangled.org/core moves quickly and
|
||||
# we want to track master.
|
||||
nix flake update tangled
|
||||
|
||||
# Check if there are changes to commit
|
||||
if ! git diff --quiet flake.lock; then
|
||||
echo "Committing flake.lock updates..."
|
||||
git add flake.lock
|
||||
git commit -m "auto-update: flake inputs $(date -Iseconds)"
|
||||
|
||||
echo "Pushing changes..."
|
||||
git push
|
||||
else
|
||||
echo "No flake.lock changes to commit"
|
||||
fi
|
||||
|
||||
echo "Rebuilding system..."
|
||||
if ! ${config.system.build.nixos-rebuild}/bin/nixos-rebuild switch --flake .#asusmini; then
|
||||
echo "Build/switch failed, staying on current generation"
|
||||
if ! git diff --cached --quiet; then
|
||||
echo "Refusing to run with staged changes"
|
||||
exit 1
|
||||
fi
|
||||
if ! git diff --quiet -- flake.lock; then
|
||||
echo "Refusing to run with preexisting flake.lock changes"
|
||||
exit 1
|
||||
fi
|
||||
if ! git diff --quiet -- '*.nix'; then
|
||||
echo "Refusing to deploy uncommitted Nix configuration changes"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git pull --ff-only
|
||||
git push --dry-run
|
||||
${pkgs.coreutils}/bin/cp flake.lock "$lock_snapshot"
|
||||
snapshot_ready=1
|
||||
nix flake update
|
||||
|
||||
echo "Building NixOS toplevel..."
|
||||
toplevel="$(${pkgs.nix}/bin/nix build .#nixosConfigurations.asusmini.config.system.build.toplevel --no-link --print-out-paths)"
|
||||
|
||||
echo "Activating new system..."
|
||||
activated=1
|
||||
${pkgs.nix}/bin/nix-env -p "$system_profile" --set "$toplevel"
|
||||
"$toplevel/bin/switch-to-configuration" switch
|
||||
|
||||
${pkgs.systemd}/bin/systemctl is-active --quiet knot-rs
|
||||
${pkgs.systemd}/bin/systemctl is-active --quiet spindle
|
||||
${pkgs.systemd}/bin/systemctl is-active --quiet sshd
|
||||
${pkgs.systemd}/bin/systemctl is-active --quiet bluesky-pds
|
||||
${pkgs.curl}/bin/curl --fail --silent --show-error --max-time 10 --retry 5 --retry-connrefused --retry-delay 1 http://127.0.0.1:5555/xrpc/_health | jq -e '.version | length > 0'
|
||||
${pkgs.curl}/bin/curl --fail --silent --show-error --max-time 10 --retry 5 --retry-connrefused --retry-delay 1 http://127.0.0.1:6555/_health | jq -e '.status == "ok"'
|
||||
${pkgs.curl}/bin/curl --fail --silent --show-error --max-time 15 https://knot.commonscomputer.com/xrpc/org.tangled.knot.describeKnot | jq -e '.did == "did:web:knot.commonscomputer.com" and .contact.email == "pds@email.commonscomputer.com"'
|
||||
${pkgs.curl}/bin/curl --fail --silent --show-error --max-time 10 --retry 5 --retry-connrefused --retry-delay 1 http://127.0.0.1:5556/xrpc/_health | jq -e -s 'length == 1 and (.[0].version | type == "string" and length > 0)'
|
||||
${pkgs.curl}/bin/curl --fail --silent --show-error --max-time 15 https://pds.commonscomputer.com/xrpc/_health | jq -e -s 'length == 1 and (.[0].version | type == "string" and length > 0)'
|
||||
validated=1
|
||||
snapshot_ready=0
|
||||
|
||||
if ! git diff --quiet -- flake.lock; then
|
||||
git add flake.lock
|
||||
git commit -m "auto-update: flake inputs $(${pkgs.coreutils}/bin/date -Iseconds)"
|
||||
fi
|
||||
git push
|
||||
|
||||
echo "Auto-update completed successfully"
|
||||
'';
|
||||
};
|
||||
|
||||
systemd.timers.auto-update = {
|
||||
enable = true;
|
||||
description = "Auto-update timer";
|
||||
wantedBy = [ "timers.target" ];
|
||||
timerConfig = {
|
||||
@@ -60,11 +121,6 @@
|
||||
Persistent = true; # Run on boot if missed
|
||||
RandomizedDelaySec = "1h"; # Add some randomness
|
||||
};
|
||||
unitConfig.ConditionPathExists = "/var/lib/knot/.upgrade-verified";
|
||||
};
|
||||
|
||||
# TODO: Set up SSH key for git push access
|
||||
# Options:
|
||||
# 1. Deploy key with write access to the repo
|
||||
# 2. Generate SSH key on server and add to GitHub
|
||||
# Command to generate: ssh-keygen -t ed25519 -f /root/.ssh/commons-nix-deploy -N ""
|
||||
}
|
||||
@@ -54,7 +54,9 @@
|
||||
isNormalUser = true;
|
||||
description = "som";
|
||||
extraGroups = [ "networkmanager" "wheel" ];
|
||||
openssh.authorizedKeys.keys = [
|
||||
openssh.authorizedKeys.keys = [
|
||||
# Framework
|
||||
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIIQH955z6qkN3MJaSrmlkM9t/06V1Q+Cj8GFV657Gty2 anish@framework"
|
||||
# Curve
|
||||
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDM0Zvei46x/yZl/IeBCq6+IYQQ0avulzVyBysF9cPigZMCybWRV7IEU+E3k9t6JrbdbdGfJkcZIWmsWDdKS8W8mBnZpVoT0ffLynu8JQ/TKdGm4Qv6bgUeKNrGsNv0ZPs2CDaGSLj0oJfRF7Ko10tcLP0vW+yujrh+y6TH/vVzJioaV4TGvtCUpn+wEQah9ROwPQLUUofsSWdnRsDJ/gp37zXWs4l5wyjSKtP3O9RZUP7kBekbSqEgSXiTk0oUQSVqIWl9NDiP6onk/gSOjXsR/JPqsSN/XI/c/yj6gyY0f51Ru2D7iBxuMJIJcWV+rU6coIj+ULcQWLzt/7TI8jq5AOOzI/ll4zbL24Eo84Rz+TP9tvMMhDZ0VaMN22AJ8qQEjc5P09tWKsX7Jg39XelyV1jHXncE4yvIE9F4RSCHzWCeKeXakizQNuzSaxTxIExRFYHjNW5bR6+3MTGwVrEIXU+qML+0yFTR86MT+tdY5AreAJQLwbog79O1NupeXJE= anish@curve"
|
||||
# Box
|
||||
@@ -78,6 +80,9 @@
|
||||
environment.systemPackages = with pkgs; [
|
||||
vim # Do not forget to add an editor to edit configuration.nix! The Nano editor is also installed by default.
|
||||
wget
|
||||
git
|
||||
curl
|
||||
jq
|
||||
];
|
||||
|
||||
# Some programs need SUID wrappers, can be configured further or are
|
||||
@@ -93,6 +98,19 @@
|
||||
# Enable the OpenSSH daemon.
|
||||
services.openssh = {
|
||||
enable = true;
|
||||
ports = [ 2224 ];
|
||||
};
|
||||
|
||||
# Cloudflare proxies the forge's HTTPS hostname, not its SSH port 2222.
|
||||
# Route Git SSH to the verified origin while retaining the hostname's key.
|
||||
programs.ssh.extraConfig = ''
|
||||
Host git.commonscomputer.com
|
||||
HostName 205.250.24.44
|
||||
HostKeyAlias [git.commonscomputer.com]:2222
|
||||
'';
|
||||
programs.ssh.knownHosts.commons-forge = {
|
||||
hostNames = [ "[git.commonscomputer.com]:2222" ];
|
||||
publicKey = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHzlORmrVR4Ffde0JgYr2R6tWWH6lS4yednGdP+hGjtl";
|
||||
};
|
||||
|
||||
# Open ports in the firewall.
|
||||
@@ -103,7 +121,7 @@
|
||||
# the public forwards move off this box (205.250.24.44 -> pve Caddy LXC
|
||||
# .1.11), leaving LAN (Z_DMZ) + tailnet as the only ingress paths.
|
||||
# Tailnet traffic already bypasses this (tailscale0 not restricted).
|
||||
networking.firewall.allowedTCPPorts = [ 22 80 443 5555 5556 6555 3030 ];
|
||||
networking.firewall.allowedTCPPorts = [ 22 5555 5556 6555 3030 ];
|
||||
# networking.firewall.allowedUDPPorts = [ ... ];
|
||||
# Or disable the firewall altogether.
|
||||
# networking.firewall.enable = false;
|
||||
|
||||
+29
-23
@@ -1,25 +1,31 @@
|
||||
final: prev: {
|
||||
# PDS 0.4.5009 aborts in better-sqlite3 under Node 24. Node 22 satisfies
|
||||
# PDS's Node 22+ requirement and keeps its native SQLite binding stable.
|
||||
bluesky-pds = prev.bluesky-pds.overrideAttrs (old: {
|
||||
nativeBuildInputs =
|
||||
(builtins.filter (pkg: (pkg.pname or "") != "nodejs") old.nativeBuildInputs)
|
||||
++ [ prev.nodejs_22 ];
|
||||
|
||||
buildPhase = ''
|
||||
runHook preBuild
|
||||
|
||||
pushd ./node_modules/.pnpm/better-sqlite3@*/node_modules/better-sqlite3
|
||||
npm run build-release --offline --nodedir="${prev.srcOnly prev.nodejs_22}"
|
||||
find build -type f -exec remove-references-to -t "${prev.srcOnly prev.nodejs_22}" {} \;
|
||||
popd
|
||||
|
||||
makeWrapper "${prev.nodejs_22}/bin/node" "$out/bin/pds" \
|
||||
--add-flags --enable-source-maps \
|
||||
--add-flags "$out/lib/pds/index.ts" \
|
||||
--set-default NODE_ENV production
|
||||
|
||||
runHook postBuild
|
||||
'';
|
||||
});
|
||||
# Temporary Spaces beta bridge until nixpkgs updates its pre-Spaces package.
|
||||
# The published tag is v0.4.600; the service reports version 0.4.6000.
|
||||
bluesky-pds =
|
||||
if prev.bluesky-pds.version == "0.4.5051" then
|
||||
prev.bluesky-pds.overrideAttrs (
|
||||
finalAttrs: _: {
|
||||
version = "0.4.6000";
|
||||
src = prev.fetchFromGitHub {
|
||||
owner = "bluesky-social";
|
||||
repo = "pds";
|
||||
rev = "f3ce8887cbcecf7cda942d482d1c536b7e725fe1";
|
||||
hash = "sha256-scSKGKUJ3KyQTtQDZoeouwXb+2k3ez0ixv6V0lTnIE8=";
|
||||
};
|
||||
sourceRoot = "${finalAttrs.src.name}/service";
|
||||
pnpmDeps = prev.fetchPnpmDeps {
|
||||
inherit (finalAttrs)
|
||||
pname
|
||||
version
|
||||
src
|
||||
sourceRoot
|
||||
;
|
||||
pnpm = prev.pnpm_10;
|
||||
fetcherVersion = 4;
|
||||
hash = "sha256-rIy6sydaXbewdQcscn11EvsXQOemPJIKIVLLEIwiYc4=";
|
||||
};
|
||||
}
|
||||
)
|
||||
else
|
||||
prev.bluesky-pds;
|
||||
}
|
||||
Executable
+228
@@ -0,0 +1,228 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
unset KNOT_MASTER_KEY
|
||||
|
||||
# These paths are deliberately fixed to this host and its rehearsed migration.
|
||||
stage=/home/anish/tangled-v1.20.0-preflight
|
||||
repo=/etc/commonscomputing-nix
|
||||
state=/var/lib/knot
|
||||
source_dir=/home/git
|
||||
backup_dir=/var/backups
|
||||
profile=/nix/var/nix/profiles/system
|
||||
current_system=/run/current-system
|
||||
ssh_key=/etc/ssh/ssh_host_ed25519_key
|
||||
lock_file=/run/lock/commonscomputing-update.lock
|
||||
runtime_template=/run/knot-upgrade.XXXXXX
|
||||
system_root=/var/lib/knot-upgrade-system
|
||||
tools_root=/var/lib/knot-upgrade-tools
|
||||
|
||||
mkdir -p "$backup_dir"
|
||||
if [ "$(id -u)" != 0 ] || [ "$(hostname)" != asusmininix ]; then
|
||||
printf 'Run this script as root on asusmininix.\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ "$#" -gt 1 ] || { [ "$#" -eq 1 ] && [ "$1" != --yes ]; }; then
|
||||
printf 'Usage: bash scripts/upgrade-knot.sh [--yes]\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
exec 9>"$lock_file"
|
||||
flock --nonblock 9 || { printf 'Another update is running.\n' >&2; exit 1; }
|
||||
if systemctl is-active --quiet auto-update.service; then
|
||||
printf 'Wait for auto-update.service to finish before migrating.\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
system=$(<"$stage/system-path")
|
||||
tools=$(<"$stage/tools-path")
|
||||
case "$system" in /nix/store/*-nixos-system-asusmininix-*) ;; *) exit 1 ;; esac
|
||||
case "$tools" in /nix/store/*-knot-migration-tools) ;; *) exit 1 ;; esac
|
||||
if ! nix-store --check-validity "$system" "$tools"; then
|
||||
read -r expected _ < "$stage/upgrade.export.gz.sha256"
|
||||
actual=$(sha256sum "$stage/upgrade.export.gz")
|
||||
test "${actual%% *}" = "$expected"
|
||||
gzip -dc "$stage/upgrade.export.gz" | nix-store --import --option require-sigs false
|
||||
fi
|
||||
nix-store --realise "$system" --add-root "$system_root" >/dev/null
|
||||
nix-store --realise "$tools" --add-root "$tools_root" >/dev/null
|
||||
export PATH="$tools/bin:$PATH"
|
||||
test -x "$system/bin/switch-to-configuration"
|
||||
test -x "$system/sw/bin/knot-server"
|
||||
# An older staged build intentionally disabled the timer; do not install it.
|
||||
grep -Fq 'ConditionPathExists=/var/lib/knot/.upgrade-verified' \
|
||||
"$system/etc/systemd/system/auto-update.timer"
|
||||
grep -Fq 'ConditionPathExists=/var/lib/knot/.upgrade-verified' \
|
||||
"$system/etc/systemd/system/auto-update.service"
|
||||
|
||||
smoke() {
|
||||
for unit in knot-rs.service spindle.service sshd.service; do
|
||||
systemctl is-active --quiet "$unit"
|
||||
done
|
||||
curl --fail --silent --show-error --max-time 10 --retry 5 --retry-connrefused \
|
||||
--retry-delay 1 http://127.0.0.1:5555/xrpc/_health | jq -e '.version | length > 0'
|
||||
curl --fail --silent --show-error --max-time 10 --retry 5 --retry-connrefused \
|
||||
--retry-delay 1 http://127.0.0.1:6555/_health | jq -e '.status == "ok"'
|
||||
curl --fail --silent --show-error --max-time 15 \
|
||||
https://knot.commonscomputer.com/xrpc/org.tangled.knot.describeKnot \
|
||||
| jq -e '.did == "did:web:knot.commonscomputer.com" and .contact.email == "[email protected]"'
|
||||
read -r _ expected_key _ < <(ssh-keygen -lf "$ssh_key.pub")
|
||||
scanned=$(ssh-keyscan -T 5 -p 2223 -t ed25519 127.0.0.1 2>/dev/null)
|
||||
read -r _ actual_key _ < <(printf '%s\n' "$scanned" | ssh-keygen -lf -)
|
||||
test "$expected_key" = "$actual_key"
|
||||
# The upgraded endpoint is a long-lived WebSocket: timeout after the handshake.
|
||||
status=$(curl --silent --max-time 3 --output /dev/null --write-out '%{http_code}' \
|
||||
-H 'Connection: Upgrade' -H 'Upgrade: websocket' -H 'Sec-WebSocket-Version: 13' \
|
||||
-H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \
|
||||
https://knot.commonscomputer.com/xrpc/com.atproto.sync.subscribeRepos || true)
|
||||
test "$status" = 101
|
||||
}
|
||||
|
||||
export GIT_TERMINAL_PROMPT=0
|
||||
export GIT_SSH_COMMAND='ssh -o BatchMode=yes -o ConnectTimeout=15'
|
||||
git -C "$repo" ls-remote --exit-code origin HEAD >/dev/null
|
||||
git -C "$repo" push --dry-run origin HEAD:main
|
||||
git -C "$repo" var GIT_AUTHOR_IDENT >/dev/null
|
||||
if ! git -C "$repo" diff --cached --quiet || \
|
||||
! git -C "$repo" diff --quiet -- '*.nix' flake.lock; then
|
||||
printf 'Commit/stash staged changes and Nix/lockfile edits before cutover.\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -e "$state/.migration-complete" ]; then
|
||||
printf 'Migration marker already exists; checking the live Rust service only.\n'
|
||||
live_system=$(readlink -f "$current_system")
|
||||
grep -Fq 'ConditionPathExists=/var/lib/knot/.upgrade-verified' \
|
||||
"$live_system/etc/systemd/system/auto-update.timer"
|
||||
grep -Fq 'ConditionPathExists=/var/lib/knot/.upgrade-verified' \
|
||||
"$live_system/etc/systemd/system/auto-update.service"
|
||||
smoke
|
||||
touch "$state/.upgrade-verified"
|
||||
systemctl unmask --runtime auto-update.timer
|
||||
systemctl start auto-update.timer
|
||||
systemctl is-active --quiet auto-update.timer
|
||||
printf 'Already migrated; smoke tests passed and automatic updates are active.\n'
|
||||
exit 0
|
||||
fi
|
||||
if [ -e "$state" ]; then
|
||||
printf '%s exists without a completed migration. Inspect/quarantine it before retrying.\n' "$state" >&2
|
||||
exit 1
|
||||
fi
|
||||
systemctl is-active --quiet knot.service
|
||||
test -r "$source_dir/knotserver.db"
|
||||
test -s "$ssh_key"
|
||||
old_system=$(readlink -f "$current_system")
|
||||
runtime=""
|
||||
backup=""
|
||||
downtime=0
|
||||
activation_attempted=0
|
||||
migration_started=0
|
||||
verified=0
|
||||
|
||||
cleanup() {
|
||||
result=$?
|
||||
trap - EXIT INT TERM
|
||||
set +e
|
||||
if [ "$result" -ne 0 ] && [ "$downtime" -eq 1 ] && [ "$verified" -eq 0 ]; then
|
||||
systemctl stop auto-update.timer
|
||||
systemctl mask --runtime auto-update.timer
|
||||
systemctl stop knot-rs.service
|
||||
rm -f "$state/.migration-complete" "$state/.upgrade-verified"
|
||||
if [ "$activation_attempted" -eq 1 ]; then
|
||||
printf 'Activation was attempted: state may have changed. Updates/Rust knot are stopped.\n' >&2
|
||||
printf 'Do NOT blindly roll back; inspect %s and %s before reopening writes.\n' "$state" "$backup" >&2
|
||||
else
|
||||
printf 'Migration failed before activation; restarting the unchanged Go knot.\n' >&2
|
||||
if [ "$migration_started" -eq 1 ] && [ -e "$state" ]; then
|
||||
mv "$state" "$backup/failed-target"
|
||||
fi
|
||||
if ! systemctl start knot.service; then
|
||||
printf 'URGENT: Go knot could not be restarted; inspect %s.\n' "$backup" >&2
|
||||
fi
|
||||
fi
|
||||
printf 'Backups retained in %s. Timer runtime mask does not survive reboot.\n' "$backup" >&2
|
||||
fi
|
||||
if [ -n "$runtime" ]; then
|
||||
rm -f "$runtime/knot.env"
|
||||
rmdir "$runtime"
|
||||
fi
|
||||
unset master_key
|
||||
exit "$result"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
|
||||
umask 077
|
||||
runtime=$(mktemp -d "$runtime_template")
|
||||
AGENIX_RULES="$repo/secrets/secrets.nix" \
|
||||
agenix -d knot-env.age -i "$ssh_key" > "$runtime/knot.env"
|
||||
chmod 0400 "$runtime/knot.env"
|
||||
master_key=""
|
||||
export -n master_key
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
case "$line" in
|
||||
KNOT_MASTER_KEY=*) master_key=${line#KNOT_MASTER_KEY=} ;;
|
||||
''|\#*) ;;
|
||||
*) printf 'Unexpected entry in knot-env.age: expected only KNOT_MASTER_KEY.\n' >&2; exit 1 ;;
|
||||
esac
|
||||
done < "$runtime/knot.env"
|
||||
if ! [[ "$master_key" =~ ^[A-Za-z0-9+/]{43}=$ ]]; then
|
||||
printf 'KNOT_MASTER_KEY must be an unquoted base64 encoding of 32 random bytes.\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
migration_args=(
|
||||
--source-db "$source_dir/knotserver.db" --source-repos "$source_dir"
|
||||
--hostname knot.commonscomputer.com --host-key "$ssh_key"
|
||||
--plc-url https://plc.directory --contact-email [email protected]
|
||||
--master-key-env KNOT_MASTER_KEY --object-format sha1 --target "$state"
|
||||
)
|
||||
KNOT_MASTER_KEY="$master_key" knot-migrate "${migration_args[@]}" --dry-run
|
||||
printf '\nThis will stop Go knot, back it up, COPY its data, and install the staged Rust system.\n'
|
||||
printf 'Git SSH moves to port 2223; administrative SSH stays on 22. Use Tailscale or arrange WAN forwarding.\n'
|
||||
printf 'Confirm the master key is backed up off-host and keep a second administrative session open.\n'
|
||||
if [ "${1:-}" != --yes ]; then
|
||||
read -r -p 'Type MIGRATE to approve downtime: ' approval
|
||||
test "$approval" = MIGRATE
|
||||
fi
|
||||
|
||||
backup=$(mktemp -d "$backup_dir/knot-cutover.XXXXXX")
|
||||
printf '%s\n' "$old_system" > "$backup/old-system"
|
||||
nix-store --realise "$old_system" --add-root "$backup/system" >/dev/null
|
||||
systemctl stop auto-update.timer
|
||||
downtime=1
|
||||
systemctl stop knot.service
|
||||
sqlite3 "file:$source_dir/knotserver.db?mode=ro" ".backup '$backup/knotserver.db'"
|
||||
tar --acls --xattrs --numeric-owner -czf "$backup/go-knot.tar.gz" \
|
||||
"$source_dir" "$ssh_key" "$ssh_key.pub"
|
||||
migration_started=1
|
||||
KNOT_MASTER_KEY="$master_key" knot-migrate "${migration_args[@]}"
|
||||
test -f "$state/ssh_host_key" && test -s "$state/ssh_host_key"
|
||||
test -f "$state/sealed-keys" && test -s "$state/sealed-keys"
|
||||
read -r _ expected_key _ < <(ssh-keygen -lf "$ssh_key.pub")
|
||||
read -r _ imported_key _ < <(ssh-keygen -lf "$state/ssh_host_key")
|
||||
test "$expected_key" = "$imported_key"
|
||||
KNOT_MASTER_KEY="$master_key" "$system/sw/bin/knot-server" --config "$system/etc/knot/config.toml" validate
|
||||
if [ -f "$state/repo-signing-keys.json" ]; then
|
||||
mv "$state/repo-signing-keys.json" "$backup/"
|
||||
fi
|
||||
|
||||
activation_attempted=1
|
||||
nix-env --profile "$profile" --set "$system"
|
||||
"$system/bin/switch-to-configuration" switch
|
||||
chown -R knot:knot "$state"
|
||||
chmod 0600 "$state/ssh_host_key" "$state/sealed-keys"
|
||||
cmp --silent "$runtime/knot.env" /run/agenix/knot-env
|
||||
touch "$state/.migration-complete"
|
||||
systemctl start knot-rs.service
|
||||
smoke
|
||||
verified=1
|
||||
touch "$state/.upgrade-verified"
|
||||
systemctl unmask --runtime auto-update.timer
|
||||
systemctl start auto-update.timer
|
||||
systemctl is-active --quiet auto-update.timer
|
||||
if ! curl --fail --silent --show-error --max-time 15 -X POST \
|
||||
https://index.tangled.network/xrpc/com.atproto.sync.requestCrawl \
|
||||
-H 'Content-Type: application/json' -d '{"hostname":"knot.commonscomputer.com"}'; then
|
||||
printf 'Warning: request the indexer crawl again later; the local migration passed.\n' >&2
|
||||
fi
|
||||
printf '\nSUCCESS: Rust knot and spindle are healthy; weekly automatic updates are active.\n'
|
||||
printf 'Backups: %s (includes plaintext repository signing keys; back up encrypted off-host).\n' "$backup"
|
||||
printf 'Next: test an authenticated clone/push over Git SSH port 2223.\n'
|
||||
@@ -0,0 +1,19 @@
|
||||
age-encryption.org/v1
|
||||
-> ssh-ed25519 GixcEg j9ctdzN4xlfXX5Pc6yCvBGq0rus1GtNDzmjn5dF/GHk
|
||||
F9zz064IPF3gFK4V5ixj3zSlWAj/U2ySZj4R7Iv9WXU
|
||||
-> ssh-rsa POo0eA
|
||||
mCjAL56LTqiiSb83bVdMxR9xPB9F+ySL266zlgrcA1QTU1h+CzIW9e/p1Tqhwltw
|
||||
Ww3g66ODASLtAR0A/Haj0oJUpY+lNwDno9eIbsk8XuIz2RmNAouVTCn3Mf/Ugm7D
|
||||
BoFHSdYLAuoTfJBSqRyPUU0aGR+9zAyQUHyC32vOekTs3EOzmhGfGt05Fo2ClJaH
|
||||
LhSg1IkvBXOr8qJCr5fWNZvKx2TsCysM0X6eHQlEzlY2J8KBcYGX2c0CmlynbFrn
|
||||
ECpwTsB2d7o1AYHuQbvDbPx03sLAu/Q++Dq/WseD9BfZlueJhWWaAPgmj3ulqG8g
|
||||
PcE6lsjVs9JkGUezY8aJLM1zb4Zy4ENjW+dh66NVHV/FNL7CBnNPmQ/Iuw+gAfQb
|
||||
2uvLPamKrGCvVAnOnmtU6a5VwGygALpavq780EK/W/ZNZs5YC10qOjdYkwhFAUEH
|
||||
EacIVIJoMfjDyd+q6MIb4IkQidfS5RavVETOiu/XXnT8eJImTJHVtkPLG6PlxRTj
|
||||
|
||||
-> ssh-ed25519 thu/uw NYs06NaZ3okyVjYrYynNfdC9h9a9ygNx80So7Sqc/ig
|
||||
sHqd5OAdu4uLHrWl1ISkYj2FKPMRJdfUKQBSFmvXX3k
|
||||
-> ssh-ed25519 HR5c7Q NRVLLirtUASQ2uDbTvs6lXN6P7AiXpNHuhAvInJ6Njg
|
||||
5A2lVT7uI2oZAMPi5K/AWVQDU81bO3Ozdn286KOXym4
|
||||
--- W4jRPRoarq+RN5GTL2qZBXiIGxUjZJqkv/PDkKzfjCc
|
||||
^mCy…-µR„D¬÷Ã'Ç¥Ó�#Ñù6®Ô_lÇz(ƒn·¢Š®yÒ±|Kád�1«�ž®Acà<΂6]Á5t‘ÝãÌfjJÈÏöž�\1õÖgž|ü´ìj
|
||||
@@ -11,4 +11,5 @@ in
|
||||
{
|
||||
"pds-env.age".publicKeys = allKeys;
|
||||
"dns-creds.age".publicKeys = allKeys;
|
||||
"knot-env.age".publicKeys = allKeys;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@unittest.skipUnless(
|
||||
all(shutil.which(tool) for tool in ("agenix", "age", "ssh-keygen")),
|
||||
"requires agenix, age, and ssh-keygen on PATH",
|
||||
)
|
||||
class AgenixRulesTests(unittest.TestCase):
|
||||
def test_decrypt_from_outside_rules_directory(self):
|
||||
with tempfile.TemporaryDirectory(prefix="agenix-rules-test-") as raw:
|
||||
root = Path(raw)
|
||||
secrets = root / "secrets"
|
||||
secrets.mkdir()
|
||||
elsewhere = root / "elsewhere"
|
||||
elsewhere.mkdir()
|
||||
key = root / "identity"
|
||||
subprocess.run(
|
||||
["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(key)],
|
||||
check=True,
|
||||
)
|
||||
public_key = key.with_suffix(".pub").read_text().strip()
|
||||
rules = secrets / "secrets.nix"
|
||||
rules.write_text(
|
||||
'{ "knot-env.age".publicKeys = [ "' + public_key + '" ]; }\n'
|
||||
)
|
||||
plaintext = b"KNOT_MASTER_KEY=" + b"A" * 43 + b"=\n"
|
||||
encrypted = subprocess.run(
|
||||
["age", "-r", public_key], input=plaintext, capture_output=True, check=True
|
||||
)
|
||||
(secrets / "knot-env.age").write_bytes(encrypted.stdout)
|
||||
result = subprocess.run(
|
||||
["agenix", "-d", "knot-env.age", "-i", str(key)],
|
||||
cwd=elsewhere,
|
||||
env={**os.environ, "AGENIX_RULES": str(rules)},
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
self.assertEqual(result.stdout, plaintext)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,235 @@
|
||||
import re
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
NIX_FILE = ROOT / "hosts/asusmini/auto-update.nix"
|
||||
BASH = shutil.which("bash") or "/run/current-system/sw/bin/bash"
|
||||
|
||||
|
||||
FAKE = r'''#!/usr/bin/env python3
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
name = Path(sys.argv[0]).name
|
||||
args = sys.argv[1:]
|
||||
log = Path(os.environ["FAKE_LOG"])
|
||||
with log.open("a") as f:
|
||||
f.write(name + " " + " ".join(args) + "\n")
|
||||
|
||||
def fail(flag):
|
||||
return os.environ.get(flag) == "1"
|
||||
|
||||
if name == "flock":
|
||||
pass
|
||||
elif name == "mktemp":
|
||||
p = Path(os.environ["TMP_ROOT"]) / "lock-snapshot"
|
||||
p.touch()
|
||||
print(p)
|
||||
elif name == "cp":
|
||||
shutil.copyfile(args[-2], args[-1])
|
||||
elif name == "rm":
|
||||
for arg in args:
|
||||
if not arg.startswith("-"):
|
||||
Path(arg).unlink(missing_ok=True)
|
||||
elif name == "date":
|
||||
print("fixture-date")
|
||||
elif name == "git":
|
||||
operation = " ".join(args)
|
||||
if "diff --cached --quiet" in operation and fail("STAGED_CHANGES"):
|
||||
raise SystemExit(1)
|
||||
if "diff --quiet -- *.nix" in operation and fail("NIX_CHANGES"):
|
||||
raise SystemExit(1)
|
||||
if "diff --quiet -- flake.lock" in operation:
|
||||
raise SystemExit(0 if not Path("flake.lock").read_text().startswith("updated") else 1)
|
||||
if args[:1] == ["pull"]:
|
||||
if fail("PULL_FAIL"):
|
||||
raise SystemExit(1)
|
||||
Path("flake.lock").write_text("pulled lock\n")
|
||||
elif args[:1] == ["push"] and "--dry-run" not in args and fail("PUBLISH_FAIL"):
|
||||
raise SystemExit(1)
|
||||
elif args[:1] == ["commit"]:
|
||||
if fail("COMMIT_FAIL"):
|
||||
raise SystemExit(1)
|
||||
Path("flake.lock").write_text("committed lock\n")
|
||||
elif name == "nix":
|
||||
if args[:2] == ["flake", "update"]:
|
||||
Path("flake.lock").write_text("updated lock\n")
|
||||
elif args[:1] == ["build"]:
|
||||
if fail("BUILD_FAIL"):
|
||||
raise SystemExit(1)
|
||||
print(os.environ["TOPLEVEL"])
|
||||
elif name == "nix-env":
|
||||
if fail("ENV_SET_FAIL"):
|
||||
raise SystemExit(1)
|
||||
elif name == "systemctl":
|
||||
if args[:2] == ["is-active", "--quiet"] and (fail("HEALTH_FAIL") or args[-1] == os.environ.get("SERVICE_FAIL")):
|
||||
raise SystemExit(1)
|
||||
if args[:1] == ["stop"] and fail("STOP_FAIL"):
|
||||
raise SystemExit(1)
|
||||
elif name == "curl":
|
||||
if fail("HEALTH_FAIL") or args[-1] == os.environ.get("HTTP_FAIL"):
|
||||
raise SystemExit(1)
|
||||
print(args[-1])
|
||||
elif name == "jq":
|
||||
endpoint = sys.stdin.read().strip()
|
||||
if fail("HEALTH_FAIL") or endpoint == os.environ.get("JSON_FAIL"):
|
||||
raise SystemExit(1)
|
||||
else:
|
||||
Path(os.environ["UNKNOWN_LOG"]).open("a").write(name + "\n")
|
||||
raise SystemExit(127)
|
||||
'''
|
||||
|
||||
|
||||
class AutoUpdateTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = Path(tempfile.mkdtemp(prefix="auto-update-test-"))
|
||||
self.bin = self.tmp / "bin"
|
||||
self.bin.mkdir()
|
||||
self.log = self.tmp / "commands.log"
|
||||
self.unknown = self.tmp / "unknown.log"
|
||||
fake = self.bin / "fake.py"
|
||||
fake.write_text(FAKE)
|
||||
fake.chmod(fake.stat().st_mode | stat.S_IXUSR)
|
||||
for name in "flock mktemp cp rm date git nix nix-env systemctl curl jq".split():
|
||||
(self.bin / name).symlink_to(fake)
|
||||
|
||||
self.repo = self.tmp / "repo"
|
||||
self.repo.mkdir()
|
||||
(self.repo / "flake.lock").write_text("initial lock\n")
|
||||
self.toplevel = self.tmp / "toplevel"
|
||||
(self.toplevel / "bin").mkdir(parents=True)
|
||||
switch = self.toplevel / "bin" / "switch-to-configuration"
|
||||
switch.write_text("#!/bin/sh\nif [ \"${ACTIVATE_FAIL:-0}\" = 1 ]; then exit 1; fi\nexit 0\n")
|
||||
switch.chmod(0o755)
|
||||
self.state = self.tmp / "state"
|
||||
(self.state).mkdir()
|
||||
(self.state / ".upgrade-verified").touch()
|
||||
|
||||
script = NIX_FILE.read_text()
|
||||
body = script.split("script = ''", 1)[1].split("'';", 1)[0]
|
||||
body = re.sub(r"\$\{pkgs\.[^}]+\}/bin/", "", body)
|
||||
replacements = {
|
||||
"/run/lock/commonscomputing-update.lock": self.tmp / "update.lock",
|
||||
"/var/lib/knot/.upgrade-verified": self.state / ".upgrade-verified",
|
||||
"/nix/var/nix/profiles/system": self.tmp / "profile",
|
||||
}
|
||||
for old, new in replacements.items():
|
||||
body = body.replace(old, str(new))
|
||||
self.script = self.tmp / "auto-update.sh"
|
||||
self.script.write_text("#!/usr/bin/env bash\n" + body)
|
||||
self.script.chmod(0o755)
|
||||
self.env = os.environ.copy()
|
||||
self.env.update({"PATH": str(self.bin) + ":" + self.env["PATH"], "FAKE_LOG": str(self.log), "UNKNOWN_LOG": str(self.unknown), "TMP_ROOT": str(self.tmp), "TOPLEVEL": str(self.toplevel)})
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.tmp, ignore_errors=True)
|
||||
|
||||
def run_update(self, **flags):
|
||||
env = self.env.copy()
|
||||
env.update({k: str(v) for k, v in flags.items()})
|
||||
return subprocess.run([BASH, str(self.script)], cwd=self.repo, env=env, text=True, capture_output=True)
|
||||
|
||||
def commands(self):
|
||||
return self.log.read_text().splitlines() if self.log.exists() else []
|
||||
|
||||
def assert_no_unknown(self):
|
||||
self.assertFalse(self.unknown.exists(), self.unknown.read_text() if self.unknown.exists() else "")
|
||||
|
||||
def test_build_failure_restores_post_pull_lock_without_activation_or_commit(self):
|
||||
result = self.run_update(BUILD_FAIL=1)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual((self.repo / "flake.lock").read_text(), "pulled lock\n")
|
||||
commands = self.commands()
|
||||
self.assertFalse(any(x.startswith("nix-env") for x in commands))
|
||||
self.assertFalse(any(x.startswith("git commit") for x in commands))
|
||||
self.assert_no_unknown()
|
||||
|
||||
def test_activation_failure_pauses_updates_without_rollback_or_publish(self):
|
||||
result = self.run_update(ACTIVATE_FAIL=1)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
commands = self.commands()
|
||||
self.assertIn("systemctl stop auto-update.timer", commands)
|
||||
self.assertEqual(sum(x.startswith("nix-env") for x in commands), 1)
|
||||
self.assertFalse(any(x.startswith("git commit") or x == "git push" for x in commands))
|
||||
self.assertTrue((self.state / ".upgrade-verified").exists() is False)
|
||||
self.assert_no_unknown()
|
||||
|
||||
def test_health_failure_pauses_updates_without_rollback_or_publish(self):
|
||||
result = self.run_update(HEALTH_FAIL=1)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
commands = self.commands()
|
||||
self.assertIn("systemctl stop auto-update.timer", commands)
|
||||
self.assertEqual(sum(x.startswith("nix-env") for x in commands), 1)
|
||||
self.assertFalse(any(x.startswith("git commit") or x == "git push" for x in commands))
|
||||
self.assert_no_unknown()
|
||||
|
||||
def test_pds_health_failures_pause_all_updated_stateful_services(self):
|
||||
local = "http://127.0.0.1:5556/xrpc/_health"
|
||||
public = "https://pds.commonscomputer.com/xrpc/_health"
|
||||
cases = [
|
||||
{"SERVICE_FAIL": "bluesky-pds"},
|
||||
{"HTTP_FAIL": local},
|
||||
{"HTTP_FAIL": public},
|
||||
{"JSON_FAIL": local},
|
||||
{"JSON_FAIL": public},
|
||||
]
|
||||
for flags in cases:
|
||||
with self.subTest(flags=flags):
|
||||
self.log.unlink(missing_ok=True)
|
||||
(self.repo / "flake.lock").write_text("initial lock\n")
|
||||
(self.state / ".upgrade-verified").touch()
|
||||
result = self.run_update(**flags)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
commands = self.commands()
|
||||
self.assertIn("systemctl stop auto-update.timer", commands)
|
||||
self.assertIn("systemctl stop knot-rs.service spindle.service bluesky-pds.service", commands)
|
||||
self.assertFalse((self.state / ".upgrade-verified").exists())
|
||||
self.assertEqual((self.repo / "flake.lock").read_text(), "updated lock\n")
|
||||
self.assertEqual(sum(x.startswith("nix-env") for x in commands), 1)
|
||||
self.assertFalse(any(x.startswith("git commit") or x == "git push" for x in commands))
|
||||
self.assert_no_unknown()
|
||||
|
||||
def test_happy_path_commits_and_pushes_after_health(self):
|
||||
result = self.run_update()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
commands = self.commands()
|
||||
health = max(i for i, x in enumerate(commands) if x.startswith("curl "))
|
||||
commit = next(i for i, x in enumerate(commands) if x.startswith("git commit"))
|
||||
push = next(i for i, x in enumerate(commands) if x == "git push")
|
||||
self.assertLess(health, commit)
|
||||
self.assertLess(commit, push)
|
||||
for service in ("knot-rs", "spindle", "sshd", "bluesky-pds"):
|
||||
self.assertIn(f"systemctl is-active --quiet {service}", commands)
|
||||
endpoints = [x.split()[-1] for x in commands if x.startswith("curl ")]
|
||||
self.assertIn("http://127.0.0.1:5556/xrpc/_health", endpoints)
|
||||
self.assertIn("https://pds.commonscomputer.com/xrpc/_health", endpoints)
|
||||
self.assert_no_unknown()
|
||||
|
||||
def test_publication_failure_retains_deployed_lock_without_rollback(self):
|
||||
result = self.run_update(PUBLISH_FAIL=1)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual((self.repo / "flake.lock").read_text(), "committed lock\n")
|
||||
commands = self.commands()
|
||||
self.assertFalse(any(x.startswith("nix-env") and i > commands.index("git push") for i, x in enumerate(commands)))
|
||||
self.assert_no_unknown()
|
||||
|
||||
def test_staged_and_nix_edits_refuse_before_pull(self):
|
||||
for flag in ("STAGED_CHANGES", "NIX_CHANGES"):
|
||||
with self.subTest(flag=flag):
|
||||
result = self.run_update(**{flag: 1})
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse(any(x.startswith("git pull") for x in self.commands()))
|
||||
self.assert_no_unknown()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,371 @@
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SCRIPT = ROOT / "scripts" / "upgrade-knot.sh"
|
||||
BASH = shutil.which("bash") or "/run/current-system/sw/bin/bash"
|
||||
|
||||
|
||||
DISPATCHER = r'''#!/usr/bin/env python3
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
name = Path(sys.argv[0]).name
|
||||
args = sys.argv[1:]
|
||||
log = Path(os.environ["FAKE_LOG"])
|
||||
with log.open("a") as f:
|
||||
f.write(name + " " + " ".join(args) + "\n")
|
||||
if os.environ.get("KNOT_MASTER_KEY") and name not in {"knot-migrate", "knot-server"}:
|
||||
Path(os.environ["KEY_LEAK_LOG"]).write_text(name + "\n")
|
||||
|
||||
def fail(flag):
|
||||
return os.environ.get(flag) == "1"
|
||||
|
||||
if name == "id":
|
||||
print("0")
|
||||
elif name == "hostname":
|
||||
print("asusmininix")
|
||||
elif name == "flock":
|
||||
pass
|
||||
elif name == "systemctl":
|
||||
if args[:2] == ["is-active", "--quiet"]:
|
||||
unit = args[2]
|
||||
if unit == "auto-update.service":
|
||||
raise SystemExit(0 if fail("AUTO_UPDATE_ACTIVE") else 1)
|
||||
if unit == "knot-rs.service" and fail("RUST_INACTIVE"):
|
||||
raise SystemExit(1)
|
||||
raise SystemExit(0)
|
||||
if args[:1] == ["start"] and "auto-update.timer" in args and fail("TIMER_START_FAIL"):
|
||||
raise SystemExit(1)
|
||||
elif name == "nix-store":
|
||||
if args[:1] == ["--check-validity"]:
|
||||
raise SystemExit(1 if fail("INVALID_STORE") else 0)
|
||||
if args[:1] == ["--import"]:
|
||||
sys.stdin.buffer.read()
|
||||
elif name == "sha256sum":
|
||||
data = Path(args[0]).read_bytes()
|
||||
print(hashlib.sha256(data).hexdigest() + " " + args[0])
|
||||
elif name == "gzip":
|
||||
try:
|
||||
os.write(1, b"fixture export")
|
||||
except OSError:
|
||||
pass
|
||||
elif name == "grep":
|
||||
path = Path(args[-1])
|
||||
if not path.is_file() or args[1] not in path.read_text():
|
||||
raise SystemExit(1)
|
||||
if fail("LIVE_GATE_FAIL") and path.name in {"auto-update.timer", "auto-update.service"}:
|
||||
raise SystemExit(1)
|
||||
elif name == "git":
|
||||
if fail("GIT_PREFLIGHT_FAIL"):
|
||||
raise SystemExit(1)
|
||||
elif name == "curl":
|
||||
if "--write-out" in args:
|
||||
print("101")
|
||||
elif "requestCrawl" in " ".join(args) and fail("CRAWL_FAIL"):
|
||||
raise SystemExit(1)
|
||||
elif "5555" in " ".join(args) and fail("HEALTH_FAIL"):
|
||||
print("{}")
|
||||
else:
|
||||
print("{}")
|
||||
elif name == "jq":
|
||||
sys.stdin.read()
|
||||
if fail("HEALTH_FAIL") and "version" in " ".join(args):
|
||||
raise SystemExit(1)
|
||||
elif name == "ssh-keygen":
|
||||
try:
|
||||
os.write(1, b"256 TESTKEY fixture\n")
|
||||
except OSError:
|
||||
pass
|
||||
os._exit(0)
|
||||
elif name == "ssh-keyscan":
|
||||
try:
|
||||
os.write(1, b"127.0.0.1 ssh-ed25519 TESTKEY\n")
|
||||
except OSError:
|
||||
pass
|
||||
os._exit(0)
|
||||
elif name == "nix-env":
|
||||
pass
|
||||
elif name == "agenix":
|
||||
rules = os.environ.get("AGENIX_RULES", "")
|
||||
if not Path(rules).is_file() or args[:2] != ["-d", "knot-env.age"]:
|
||||
raise SystemExit("agenix needs explicit rules and a rules-relative secret name")
|
||||
value = (b"KNOT_MASTER_KEY=" + (b"B" * 43 + b"=\n" if not fail("BAD_KEY") else b"bad\n"))
|
||||
sys.stdout.buffer.write(value)
|
||||
target = os.environ.get("AGENIX_TARGET")
|
||||
if target:
|
||||
Path(target).write_bytes(value)
|
||||
elif name == "knot-migrate":
|
||||
if os.environ.get("KNOT_MASTER_KEY") != "B" * 43 + "=":
|
||||
raise SystemExit(1)
|
||||
if "--dry-run" in args:
|
||||
raise SystemExit(1 if fail("DRYRUN_FAIL") else 0)
|
||||
target = Path(args[args.index("--target") + 1])
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
(target / "ssh_host_key").write_text("fixture-key\n")
|
||||
(target / "sealed-keys").write_text("fixture-sealed\n")
|
||||
(target / "repo-signing-keys.json").write_text("{}\n")
|
||||
if fail("MIGRATION_FAIL"):
|
||||
raise SystemExit(1)
|
||||
elif name == "sqlite3" or name == "tar" or name == "chown" or name == "chmod":
|
||||
pass
|
||||
elif name == "cmp":
|
||||
if Path(args[-2]).read_bytes() != Path(args[-1]).read_bytes():
|
||||
raise SystemExit(1)
|
||||
elif name == "mktemp":
|
||||
template = args[-1]
|
||||
path = Path(template.replace("XXXXXX", "fixture"))
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if "-d" in args:
|
||||
path.mkdir(exist_ok=True)
|
||||
else:
|
||||
path.touch()
|
||||
print(path)
|
||||
elif name == "readlink":
|
||||
print(os.environ["OLD_SYSTEM"])
|
||||
elif name == "rm":
|
||||
for arg in args:
|
||||
if arg.startswith("-"):
|
||||
continue
|
||||
p = Path(arg)
|
||||
if p.is_dir():
|
||||
shutil.rmtree(p, ignore_errors=True)
|
||||
else:
|
||||
p.unlink(missing_ok=True)
|
||||
elif name == "rmdir":
|
||||
Path(args[-1]).rmdir()
|
||||
elif name == "mv":
|
||||
shutil.move(args[-2], args[-1])
|
||||
elif name == "touch":
|
||||
Path(args[-1]).touch()
|
||||
else:
|
||||
Path(os.environ["UNKNOWN_LOG"]).open("a").write(name + "\n")
|
||||
raise SystemExit(127)
|
||||
'''
|
||||
|
||||
|
||||
class UpgradeKnotTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = Path(tempfile.mkdtemp(prefix="upgrade-knot-test-"))
|
||||
self.fakebin = self.tmp / "bin"
|
||||
self.fakebin.mkdir()
|
||||
self.log = self.tmp / "commands.log"
|
||||
self.unknown = self.tmp / "unknown.log"
|
||||
self.key_scope = self.tmp / "key-scope.log"
|
||||
dispatcher = self.fakebin / "fake-command.py"
|
||||
dispatcher.write_text(DISPATCHER)
|
||||
dispatcher.chmod(dispatcher.stat().st_mode | stat.S_IXUSR)
|
||||
names = "id hostname flock systemctl nix-store sha256sum gzip grep git curl jq ssh-keygen ssh-keyscan nix-env agenix knot-migrate sqlite3 tar chown chmod cmp mktemp readlink rm rmdir mv touch".split()
|
||||
for name in names:
|
||||
(self.fakebin / name).symlink_to(dispatcher)
|
||||
|
||||
self.stage = self.tmp / "stage"
|
||||
self.stage.mkdir()
|
||||
self.store = self.tmp / "nix" / "store"
|
||||
self.system = self.store / "fixture-nixos-system-asusmininix-test"
|
||||
self.tools = self.store / "fixture-knot-migration-tools"
|
||||
(self.system / "bin").mkdir(parents=True)
|
||||
(self.system / "sw" / "bin").mkdir(parents=True)
|
||||
(self.system / "etc" / "systemd" / "system").mkdir(parents=True)
|
||||
(self.system / "etc" / "knot").mkdir()
|
||||
(self.system / "sw" / "bin" / "knot-server").write_text(
|
||||
f"#!/bin/sh\ntest \"$KNOT_MASTER_KEY\" = \"{'B' * 43}=\" || exit 1\nprintf validated > {self.key_scope}\n"
|
||||
)
|
||||
(self.system / "sw" / "bin" / "knot-server").chmod(0o755)
|
||||
switch = self.system / "bin" / "switch-to-configuration"
|
||||
switch.write_text("#!/bin/sh\nif [ \"${FAIL_ACTIVATION:-0}\" = 1 ]; then exit 1; fi\nexit 0\n")
|
||||
switch.chmod(0o755)
|
||||
gate = f"ConditionPathExists={self.state if hasattr(self, 'state') else self.tmp / 'state'}/.upgrade-verified\n"
|
||||
(self.system / "etc" / "systemd" / "system" / "auto-update.timer").write_text(gate)
|
||||
(self.system / "etc" / "systemd" / "system" / "auto-update.service").write_text(gate)
|
||||
(self.tools / "bin").mkdir(parents=True)
|
||||
(self.stage / "system-path").write_text(str(self.system) + "\n")
|
||||
(self.stage / "tools-path").write_text(str(self.tools) + "\n")
|
||||
export = self.stage / "upgrade.export.gz"
|
||||
export.write_bytes(b"fixture export")
|
||||
(self.stage / "upgrade.export.gz.sha256").write_text(hashlib.sha256(export.read_bytes()).hexdigest() + " upgrade.export.gz\n")
|
||||
|
||||
self.repo = self.tmp / "repo"
|
||||
(self.repo / "secrets").mkdir(parents=True)
|
||||
(self.repo / "secrets" / "knot-env.age").write_text("not a secret used by fixture\n")
|
||||
(self.repo / "secrets" / "secrets.nix").write_text("{}\n")
|
||||
self.source = self.tmp / "git"
|
||||
self.source.mkdir()
|
||||
(self.source / "knotserver.db").write_text("fixture db\n")
|
||||
self.ssh = self.tmp / "ssh_host_ed25519_key"
|
||||
self.ssh.write_text("fixture private key\n")
|
||||
(self.ssh.parent / (self.ssh.name + ".pub")).write_text("fixture public key\n")
|
||||
self.state = self.tmp / "state"
|
||||
self.agenix_target = self.tmp / "agenix" / "knot-env"
|
||||
self.agenix_target.parent.mkdir()
|
||||
self.agenix_target.write_text("KNOT_MASTER_KEY=" + "B" * 43 + "=\n")
|
||||
self.old = self.store / "old-system"
|
||||
(self.old / "bin").mkdir(parents=True)
|
||||
(self.old / "bin" / "switch-to-configuration").write_text("#!/bin/sh\nexit 0\n")
|
||||
(self.old / "bin" / "switch-to-configuration").chmod(0o755)
|
||||
(self.old / "etc" / "systemd" / "system").mkdir(parents=True)
|
||||
(self.old / "etc" / "systemd" / "system" / "auto-update.timer").write_text(
|
||||
f"ConditionPathExists={self.state}/.upgrade-verified\n"
|
||||
)
|
||||
(self.old / "etc" / "systemd" / "system" / "auto-update.service").write_text(
|
||||
f"ConditionPathExists={self.state}/.upgrade-verified\n"
|
||||
)
|
||||
current = self.tmp / "current-system"
|
||||
current.symlink_to(self.old)
|
||||
|
||||
replacements = {
|
||||
"/nix/store": self.store,
|
||||
"/home/anish/tangled-v1.20.0-preflight": self.stage,
|
||||
"/etc/commonscomputing-nix": self.repo,
|
||||
"/var/lib/knot": self.state,
|
||||
"/home/git": self.source,
|
||||
"/var/backups": self.tmp / "backups",
|
||||
"/nix/var/nix/profiles/system": self.tmp / "profile",
|
||||
"/run/current-system": current,
|
||||
"/etc/ssh/ssh_host_ed25519_key": self.ssh,
|
||||
"/run/lock/commonscomputing-update.lock": self.tmp / "lock",
|
||||
"/run/knot-upgrade.XXXXXX": self.tmp / "runtime.XXXXXX",
|
||||
"/var/lib/knot-upgrade-system": self.tmp / "system-root",
|
||||
"/var/lib/knot-upgrade-tools": self.tmp / "tools-root",
|
||||
"/run/agenix/knot-env": self.agenix_target,
|
||||
}
|
||||
text = SCRIPT.read_text()
|
||||
for old, new in replacements.items():
|
||||
text = text.replace(old, str(new))
|
||||
self.script = self.tmp / "upgrade-knot.sh"
|
||||
self.script.write_text(text)
|
||||
self.env = os.environ.copy()
|
||||
self.key_leak = self.tmp / "key-leak.log"
|
||||
self.env.update({"PATH": str(self.fakebin) + ":" + self.env["PATH"], "FAKE_LOG": str(self.log), "UNKNOWN_LOG": str(self.unknown), "KEY_LEAK_LOG": str(self.key_leak), "OLD_SYSTEM": str(self.old), "AGENIX_TARGET": str(self.agenix_target)})
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.tmp, ignore_errors=True)
|
||||
|
||||
def run_upgrade(self, *args, **flags):
|
||||
env = self.env.copy()
|
||||
env.update({k: str(v) for k, v in flags.items()})
|
||||
return subprocess.run([BASH, str(self.script), *args], text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
|
||||
|
||||
def commands(self):
|
||||
return self.log.read_text().splitlines() if self.log.exists() else []
|
||||
|
||||
def assert_no_unknown_tools(self):
|
||||
self.assertFalse(self.unknown.exists(), self.unknown.read_text() if self.unknown.exists() else "")
|
||||
|
||||
def test_happy_path_order_and_secret_cleanup(self):
|
||||
result = self.run_upgrade("--yes")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
commands = self.commands()
|
||||
self.assertLess(next(i for i, x in enumerate(commands) if x.startswith("systemctl stop auto-update.timer")), next(i for i, x in enumerate(commands) if x.startswith("knot-migrate ") and "--dry-run" not in x))
|
||||
timer_start = next(i for i, x in enumerate(commands) if x == "systemctl start auto-update.timer")
|
||||
health_end = max(i for i, x in enumerate(commands) if x.startswith("curl ") and i < timer_start)
|
||||
self.assertGreater(timer_start, health_end)
|
||||
self.assertTrue((self.state / ".migration-complete").exists())
|
||||
self.assertFalse(self.tmp.joinpath("runtime.fixture", "knot.env").exists())
|
||||
self.assertFalse(self.key_leak.exists())
|
||||
self.assertTrue(self.key_scope.exists())
|
||||
self.assert_no_unknown_tools()
|
||||
|
||||
def test_dryrun_failure_does_not_stop_go_or_timer(self):
|
||||
result = self.run_upgrade("--yes", DRYRUN_FAIL=1)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
commands = self.commands()
|
||||
self.assertFalse(any(x == "systemctl stop knot.service" for x in commands))
|
||||
self.assertFalse(any(x == "systemctl stop auto-update.timer" for x in commands))
|
||||
self.assertFalse(self.tmp.joinpath("runtime.fixture", "knot.env").exists())
|
||||
self.assert_no_unknown_tools()
|
||||
|
||||
def test_migration_failure_quarantines_target_and_restarts_go(self):
|
||||
result = self.run_upgrade("--yes", MIGRATION_FAIL=1)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertTrue((self.tmp / "backups" / "knot-cutover.fixture" / "failed-target").exists())
|
||||
self.assertFalse(self.tmp.joinpath("runtime.fixture", "knot.env").exists())
|
||||
commands = self.commands()
|
||||
self.assertIn("systemctl start knot.service", commands)
|
||||
self.assert_no_unknown_tools()
|
||||
|
||||
def test_activation_failure_keeps_new_state_and_stops_services(self):
|
||||
result = self.run_upgrade("--yes", FAIL_ACTIVATION=1)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
commands = self.commands()
|
||||
sets = [x for x in commands if x.startswith("nix-env --profile")]
|
||||
self.assertEqual(len(sets), 1)
|
||||
self.assertFalse(any(x == "systemctl start knot.service" for x in commands))
|
||||
self.assertIn("systemctl stop auto-update.timer", commands)
|
||||
self.assertTrue(self.state.exists())
|
||||
self.assertFalse((self.state / ".migration-complete").exists())
|
||||
self.assert_no_unknown_tools()
|
||||
|
||||
def test_health_failure_keeps_new_state_and_stops_services(self):
|
||||
result = self.run_upgrade("--yes", HEALTH_FAIL=1)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
commands = self.commands()
|
||||
self.assertEqual(sum(x.startswith("nix-env --profile") for x in commands), 1)
|
||||
self.assertNotIn("systemctl start knot.service", commands)
|
||||
self.assertIn("systemctl stop knot-rs.service", commands)
|
||||
self.assertTrue(self.state.exists())
|
||||
self.assert_no_unknown_tools()
|
||||
|
||||
def test_completed_marker_skips_migration(self):
|
||||
self.state.mkdir()
|
||||
(self.state / ".migration-complete").touch()
|
||||
result = self.run_upgrade()
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertFalse(any(x.startswith("knot-migrate") for x in self.commands()))
|
||||
self.assertTrue(any(x == "systemctl start auto-update.timer" for x in self.commands()))
|
||||
self.assert_no_unknown_tools()
|
||||
|
||||
def test_completed_marker_rejects_mismatched_live_gate_without_touching_state(self):
|
||||
self.state.mkdir()
|
||||
(self.state / ".migration-complete").touch()
|
||||
before = (self.state / ".upgrade-verified").exists()
|
||||
result = self.run_upgrade(LIVE_GATE_FAIL=1)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertEqual((self.state / ".upgrade-verified").exists(), before)
|
||||
self.assertFalse(any(x == "systemctl start auto-update.timer" for x in self.commands()))
|
||||
self.assert_no_unknown_tools()
|
||||
|
||||
def test_invalid_key_fails_before_downtime(self):
|
||||
result = self.run_upgrade("--yes", BAD_KEY=1)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
commands = self.commands()
|
||||
self.assertFalse(any(x == "systemctl stop knot.service" for x in commands))
|
||||
self.assertFalse(any(x == "systemctl stop auto-update.timer" for x in commands))
|
||||
self.assert_no_unknown_tools()
|
||||
|
||||
def test_missing_staged_service_gate_fails_before_downtime(self):
|
||||
service = self.system / "etc" / "systemd" / "system" / "auto-update.service"
|
||||
service.write_text("[Unit]\n")
|
||||
result = self.run_upgrade("--yes")
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertFalse(any(x == "systemctl stop knot.service" for x in self.commands()))
|
||||
self.assertFalse(self.state.exists())
|
||||
self.assert_no_unknown_tools()
|
||||
|
||||
def test_git_preflight_failure_has_no_downtime(self):
|
||||
result = self.run_upgrade("--yes", GIT_PREFLIGHT_FAIL=1)
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
commands = self.commands()
|
||||
self.assertFalse(any(x == "systemctl stop knot.service" for x in commands))
|
||||
self.assertFalse(any(x == "systemctl stop auto-update.timer" for x in commands))
|
||||
self.assert_no_unknown_tools()
|
||||
|
||||
def test_invalid_store_imports_export(self):
|
||||
result = self.run_upgrade("--yes", INVALID_STORE=1)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertTrue(any(x.startswith("nix-store --import") for x in self.commands()))
|
||||
self.assert_no_unknown_tools()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user