8 Commits
Author SHA1 Message Date
nilsandClaude Sonnet 5.5 b1d181a1dd Release 0.13.7
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 11:49:57 +01:00
nilsandClaude Sonnet 5.5 2b7cd86e98 One upgrade for nixos-router and the packages
Check, preview and apply look at the repository's release tags and the
channel together; the new nixos-router is a highlighted row in the
preview table. The update server section and the separate git update
are gone; bundles stay.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 11:49:57 +01:00
nilsandClaude Sonnet 5.5 3e6eee0b9c Release 0.13.6
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 10:46:55 +01:00
nilsandClaude Sonnet 5.5 da206a5237 Cover the page while looking at the repository
The look for a newer release shows the same box as an update, and the page
reloads when it is done.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 10:46:55 +01:00
nilsandClaude Sonnet 5.5 3881c623cf Release 0.13.5
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 10:37:14 +01:00
nilsandClaude Sonnet 5.5 83343f7a18 Tag releases, and name the version on the Overview
nix run .#release ends by creating the annotated tag vX.Y.Z on the released
commit (the tags routers that update from the repository look for); it
refuses a HEAD of another version and does nothing outside a checkout. The
System card on the Overview says which nixos-router and NixOS run.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 10:37:14 +01:00
nilsandClaude Sonnet 5.5 3afd7ed4cc Release 0.13.4
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 10:05:08 +01:00
nilsandClaude Sonnet 5.5 ad9de15344 Hardcode the repository releases come from
routerUpdate.repository (a module option beside the update keys, not a
router.* setting) defaults to the project's repository; the Updates page names
it but no longer has a field for it. Forks and tests set it in a module.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-25 10:05:08 +01:00
23 changed files with 473 additions and 706 deletions
+4 -4
View File
@@ -289,12 +289,12 @@ Package upgrades (see above)
- **Reset**: go back to the nixpkgs that came with the release (`channel = null` and remove the pin).
- **Real package changes in tests**: the upgrade tests use an identical nixpkgs copy, so no real version change is ever exercised.
- **Merge the Update and Packages pages, and take releases from git** (decided 2026-11-24, not built). The repository is public, so no key is needed on the router; trusting the git server (TLS and the tag) is enough, so no signatures on this path; the packages come from cache.nixos.org and the small parts of nixos-router are built on the router; gitea has to be reachable to update this way. Plan:
1. **Done (0.13.2):** one "Updates" page with the parts "Router software" and "Packages", one overlay and one confirmation banner, both logs. Still to do for it: one check, one preview and one apply for both (needs step 3).
2. **Done (0.13.3):** `router.update.repository` (an http(s) address, no credentials or query; saved like the channel, in the confirmed settings too, so it is no unapplied change). `router-update check` (daily timer `router-update-check`, and the page's button) lists the repository's tags with `git ls-remote`, takes the newest `vX.Y.Z` (other tags are ignored) and writes `update/check.json` (repository, time, installed, newest tag/version/revision, newer). The Overview and the Updates page show it while it is about this repository and the installed version.
1. **Done (0.13.2):** one "Updates" page with the parts "Router software" and "Packages", one overlay and one confirmation banner, both logs. One check, one preview and one apply for both: see "Unified upgrade" below.
2. **Done (0.13.3, fixed in 0.13.4):** the repository is hardcoded: the module option `routerUpdate.repository` (beside `routerUpdate.publicKeys`; not a `router.*` setting, so it is not in the settings, the options listing or the web UI) defaults to `https://git.stinnesbeck.com/nils/nixos-router`, is baked into `router-update` and written to `/etc/router-update-repository` for the web UI, and the page only names it (no field: a fork or a test sets the option in a module; a moved repository needs a bundle update). `router-update check` (daily timer `router-update-check`, and the page's button) lists the repository's tags with `git ls-remote`, takes the newest `vX.Y.Z` (other tags are ignored) and writes `update/check.json` (repository, time, installed, newest tag/version/revision, newer). The Overview and the Updates page show it while it is about this repository and the installed version.
3. **Done (0.13.3), without a preview:** `router-update --git TAG|latest` (the web UI's "Install"): `nix flake prefetch` of `git+<repo>?ref=refs/tags/<tag>&rev=<commit>`, then the steps of a bundle update from the serial guard on (snapshot, flake, nixpkgs pin, migration, `router-apply` with commit-confirm, rollback). The flake is the source's `config-flake.nix` with `@SOURCE@` replaced by that address, so `flake.lock` and `flake.nix` agree and nothing moves by itself (this file is a contract with every updater already installed: change it only compatibly). The release data (version, serial = the commit's time, schema = the number of `migrations/*.jq`) is read from the fetched source. No signature is checked. Still to do: preview (package changes, download and builds of both inputs), and the nixpkgs-pin interplay for a pin chosen later.
4. Still to do: a release is a tag `vX.Y.Z` on the release commit (`router-release` tags it, still writes a bundle for the installer and offline routers) and refuses a `flake.lock` whose nixpkgs is not a channel revision (`git-revision`), so cache.nixos.org has its packages.
4. **Tag: done (0.13.5).** A release is a tag `vX.Y.Z` on the release commit: `nix run .#release` (which still writes the bundle for the installer and offline routers) ends by creating the annotated tag, locally (push it with the branch; `--no-tag` skips it). It refuses when HEAD's `VERSION` is another version or the tag is on another commit, does nothing outside a git checkout (the VM tests), and tags last so a failed release leaves no tag. Still to do: refuse a `flake.lock` whose nixpkgs is not a channel revision (`git-revision`), so cache.nixos.org has its packages.
5. **Done:** the `update` VM test serves a repository from the builder (`common.gitServer`: `git http-backend` over HTTP) and covers the check, tags that are no releases, refused tags, install through the web UI with migration, confirm, the rebuild without the server, and "not newer".
Bundles and `--url` stay (offline, installer, gitea down).
6. **Unified upgrade (decided 2026-11-26).** nixos-router is a flake input like nixpkgs, so it is part of `router-upgrade`, not a separate update: `router-update check`, `router-update --git`, the unit `router-update-check` and the page's "Releases from git" are gone (steps 2 and 3 above describe where it started). `router-upgrade check` reads the channel's newest nixpkgs revision *and* the repository's newest tag (a repository that cannot be read is a warning; with no channel the packages are skipped) and writes both to `upgrade/check.json` (`router: {repository, installed, newest, newer}`, `packagesUpToDate`, `upToDate` = both); the daily timer (`router-upgrade-notice`) runs `router-upgrade daily` and feeds the Overview notices. `preview` fetches the tag, builds what a release carries (version, serial, schema, migrations, and the flake from `config-flake.nix`), puts the new flake and the migrated settings into a copy of the configuration, locks it (the nixpkgs override as before; without a channel an earlier pin stays), and writes the usual package diff to `preview.json` plus `router: {from, to, tag, rev}`; the page shows one table with the nixos-router row highlighted, and one "Upgrade" button. `apply` refuses when `flake.nix` (or, with a new router, `settings.json`) changed since the preview, and otherwise snapshots, copies flake, migrated settings and lock, writes the pin only when a channel override was used, and runs `router-apply` with commit-confirm as before. The page has no "Update server" any more (it was a setting nobody needs after the hardcoded repository); `router-update` keeps `--url`, `--bundle` and uploads (offline, installer, gitea down), and the page keeps "Install a bundle". Tested in the `update` VM test (check, ignored non-release tags, preview with the router row, apply, confirm, rebuild without the server) and the Go tests.
Web UI polish (list of 2026-11-24)
- Folds inside panels (Packages "What is built here", WireGuard) may jump like the certificate log did.
+1 -1
View File
@@ -1 +1 @@
0.13.3
0.13.7
+2 -2
View File
@@ -1,6 +1,6 @@
# The flake.nix of an installed router's configuration directory when its
# nixos-router comes from a git repository (router.update.repository).
# `router-update --git` writes it with @SOURCE@ replaced by the address of the
# nixos-router comes from a git repository (routerUpdate.repository).
# `router-upgrade` writes it with @SOURCE@ replaced by the address of the
# release it installs (git+URL?ref=refs/tags/vX.Y.Z&rev=COMMIT), so the lock
# file and this file always agree and nothing moves to a newer commit by itself.
#
+1
View File
@@ -222,6 +222,7 @@
name = "router-release";
runtimeInputs = with pkgs; [
nix
git
gnutar
coreutils
jq
-14
View File
@@ -440,20 +440,6 @@ in
'';
};
update.repository = mkOption {
type = types.nullOr (types.strMatching "https?://[A-Za-z0-9.-]+(:[0-9]+)?(/[A-Za-z0-9._~/-]*)?");
default = null;
example = "https://git.example.org/me/nixos-router";
description = ''
A public git repository of nixos-router whose tags `vX.Y.Z` are releases.
`router-update check` (daily, and in the web UI) looks for a newer tag,
and `router-update --git` builds the router from it, like an update from
a bundle: the settings are migrated and the new version must be
confirmed. The repository is trusted (TLS and the tag), nothing is
signed on this path. null: updates come from bundles and update servers.
'';
};
update.channel = mkOption {
type = types.nullOr (types.strMatching "unstable|[0-9]{2}\\.[0-9]{2}");
default = null;
+30 -125
View File
@@ -55,16 +55,14 @@ let
migrate
pkgs.coreutils
pkgs.curl
pkgs.git
pkgs.gawk
pkgs.jq
pkgs.util-linux
];
text = ''
# (A release from the git repository is not installed here but by
# router-upgrade, with the packages: this is for signed bundles.)
usage() {
echo "usage: router-update check | [--force] (--request | --bundle FILE | --url URL | --git TAG|latest) [timeout]" >&2
echo " check the newest release tag of router.update.repository, against the installed version" >&2
echo " --git TAG build the release from a tag (vX.Y.Z, or latest) of router.update.repository" >&2
echo "usage: router-update [--force] (--request | --bundle FILE | --url URL) [timeout]" >&2
echo " --bundle FILE a bundle made by router-release" >&2
echo " --url URL a server with the release's latest and cache/ (HTTP or HTTPS)" >&2
echo " --request what the web UI asked for (${updateDir}/request.json)" >&2
@@ -76,11 +74,9 @@ let
force=0 mode="" arg="" timeout=""
while [ $# -gt 0 ]; do
case $1 in
check) mode=check ;;
--force) force=1 ;;
--bundle) shift; [ $# -gt 0 ] || usage; mode=bundle arg=$1 ;;
--url) shift; [ $# -gt 0 ] || usage; mode=url arg=$1 ;;
--git) shift; [ $# -gt 0 ] || usage; mode=git arg=$1 ;;
--request)
req=${updateDir}/request.json
[ -r "$req" ] || die "no request"
@@ -94,60 +90,12 @@ let
done
[ -n "$mode" ] || usage
[ "$(id -u)" -eq 0 ] || die "must run as root"
config=${cfg.directory}
# The release tags of the repository, "TAG REVISION" per line (an
# annotated tag counts with the commit it points to).
repository() { jq -r '.router.update.repository // empty' "$config/settings.json"; }
git_tags() {
git ls-remote --tags "$1" 'refs/tags/v*' | awk '
{ n = $2; sub("^refs/tags/", "", n); peeled = (n ~ /\^\{\}$/); sub(/\^\{\}$/, "", n)
if (n !~ /^v[0-9]+\.[0-9]+\.[0-9]+$/) next
if (peeled) p[n] = $1; else d[n] = $1
seen[n] = 1 }
END { for (n in seen) print n, (n in p ? p[n] : d[n]) }' | sort -V
}
if [ "$mode" = check ]; then
# Only looks: no lock, so it runs beside an update.
repo=$(repository)
if [ -z "$repo" ]; then
echo "router-update: no repository (router.update.repository): nothing to look at"
exit 0
fi
tags=$(git_tags "$repo") || die "cannot read the tags of $repo"
[ -n "$tags" ] || die "$repo has no release tags (vX.Y.Z)"
read -r tag rev <<<"$(tail -n 1 <<<"$tags")"
version=''${tag#v}
installed=$(jq -r '.version // "unknown"' /etc/router-release)
newer=false
if [ "$version" != "$installed" ] && [ "$(printf '%s\n%s\n' "$installed" "$version" | sort -V | tail -n 1)" = "$version" ]; then
newer=true
fi
mkdir -p ${updateDir}
jq -n --arg repo "$repo" --arg time "$(date -u +%FT%TZ)" --arg installed "$installed" \
--arg tag "$tag" --arg version "$version" --arg rev "$rev" --argjson newer "$newer" \
'{repository: $repo, time: $time, installed: $installed, newest: {tag: $tag, version: $version, rev: $rev}, newer: $newer}' \
> ${updateDir}/check.json.new
chmod 0644 ${updateDir}/check.json.new
mv ${updateDir}/check.json.new ${updateDir}/check.json
if [ "$newer" = true ]; then
echo "router-update: $version is available (installed: $installed)"
else
echo "router-update: up to date ($installed; the repository's newest is $version)"
fi
exit 0
fi
exec 9>/run/router-update.lock
flock -n 9 || die "another update is running"
# Bundles and servers are signed; a git repository is trusted as it is.
trusted=""
if [ "$mode" != git ]; then
trusted=$(tr '\n' ' ' < /etc/router-update-keys)
[ -n "''${trusted// /}" ] || die "this router has no update key"
fi
trusted=$(tr '\n' ' ' < /etc/router-update-keys)
[ -n "''${trusted// /}" ] || die "this router has no update key"
staged=${updateDir}/staged
case $mode in
@@ -164,56 +112,20 @@ let
base=''${arg%/}
store="$base/cache"
latest=$(curl -fsS --max-time 30 "$base/latest") ;;
git) ;;
*) usage ;;
esac
if [ "$mode" = git ]; then
repo=$(repository)
[ -n "$repo" ] || die "no repository: set router.update.repository"
tags=$(git_tags "$repo") || die "cannot read the tags of $repo"
if [ -z "$arg" ] || [ "$arg" = latest ]; then
found=$(tail -n 1 <<<"$tags")
else
[[ $arg =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "not a release tag: $arg"
found=$(awk -v t="$arg" '$1 == t' <<<"$tags")
fi
[ -n "$found" ] || die "$repo has no such release tag"
read -r tag rev <<<"$found"
src="git+$repo?ref=refs/tags/$tag&rev=$rev"
echo "router-update: fetching $tag ($rev) from $repo"
# (No registry: the address is complete, and the global one is a download.)
meta=$(nix --option flake-registry "" flake prefetch --json "$src") || die "cannot fetch $src"
tree=$(jq -er .storePath <<<"$meta")
if [ ! -r "$tree/config-flake.nix" ] || [ ! -r "$tree/VERSION" ]; then
die "$tag is not a release this updater can build (no config-flake.nix or VERSION)"
fi
# What a release carries, made from the source: the files that the rest
# of the update reads (the flake that points at the source, its version,
# its commit time, its settings migrations).
release=${updateDir}/git-release
rm -rf "$release"
mkdir -p "$release/migrations"
tr -d '\n' < "$tree/VERSION" > "$release/version"
jq -er .locked.lastModified <<<"$meta" | tr -d '\n' > "$release/serial"
printf %s "$rev" > "$release/rev"
find "$tree/migrations" -name '*.jq' -exec cp {} "$release/migrations/" \;
find "$release/migrations" -name '*.jq' | wc -l | tr -d '\n' > "$release/schema"
# (jq, not a shell substitution: the address has a & in it.)
jq -rRs --arg source "$src" 'gsub("@SOURCE@"; $source)' "$tree/config-flake.nix" > "$release/flake.nix"
else
release=$(jq -er .release <<<"$latest") || die "the update has no release"
[[ $release =~ ^/nix/store/[0-9a-z]{32}-[A-Za-z0-9+._-]+$ ]] || die "not a store path: $release"
release=$(jq -er .release <<<"$latest") || die "the update has no release"
[[ $release =~ ^/nix/store/[0-9a-z]{32}-[A-Za-z0-9+._-]+$ ]] || die "not a store path: $release"
# Nothing is trusted until every path of the closure is signed by our key.
echo "router-update: verifying $release"
nix --option trusted-public-keys "$trusted" store verify \
--store "$store" --no-contents --sigs-needed 1 -r "$release" \
|| die "the update is not signed with this router's update key"
echo "router-update: importing it"
nix --option trusted-public-keys "$trusted" copy --from "$store" "$release"
rm -rf "$staged"
fi
# Nothing is trusted until every path of the closure is signed by our key.
echo "router-update: verifying $release"
nix --option trusted-public-keys "$trusted" store verify \
--store "$store" --no-contents --sigs-needed 1 -r "$release" \
|| die "the update is not signed with this router's update key"
echo "router-update: importing it"
nix --option trusted-public-keys "$trusted" copy --from "$store" "$release"
rm -rf "$staged"
new_version=$(cat "$release/version")
new_serial=$(cat "$release/serial")
@@ -268,6 +180,19 @@ in
default = null;
description = "Version, serial, revision and settings schema of this nixos-router (`/etc/router-release`).";
};
routerUpdate.repository = lib.mkOption {
type = lib.types.nullOr (lib.types.strMatching "https?://[A-Za-z0-9.-]+(:[0-9]+)?(/[A-Za-z0-9._~/-]*)?");
default = "https://git.stinnesbeck.com/nils/nixos-router";
example = "https://git.example.org/me/nixos-router";
description = ''
The public git repository of nixos-router whose tags `vX.Y.Z` are
releases. `router-upgrade` (daily, and in the web UI) looks for a newer
tag and, with the packages, locks the configuration flake to it. The
repository is trusted (TLS and the tag), nothing is signed on this path.
It belongs to the installed version, not to the settings: a fork or a
test sets it in a module. null: updates come from bundles only.
'';
};
routerUpdate.publicKeys = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
@@ -284,6 +209,8 @@ in
if config.routerSettings.release == null then { } else config.routerSettings.release
);
environment.etc."router-update-keys".text = lib.concatLines keys;
# For the web UI.
environment.etc."router-update-repository".text = toString config.routerUpdate.repository;
environment.systemPackages = [
update
restore
@@ -305,28 +232,6 @@ in
router.rollback.onRollback = "${restore}/bin/router-update-restore";
router.rollback.onConfirm = "rm -rf ${snapshot}";
# Is there a newer release in router.update.repository? Once a day, and when
# the web UI asks. It only reads the repository's tag list.
systemd.services.router-update-check = {
description = "Look for a newer release of nixos-router";
restartIfChanged = false;
stopIfChanged = false;
path = [ "/run/current-system/sw" ];
serviceConfig = {
Type = "oneshot";
ExecStart = "${lib.getExe update} check";
TimeoutStartSec = "5min";
};
};
systemd.timers.router-update-check = {
wantedBy = [ "timers.target" ];
timerConfig = {
OnCalendar = "daily";
RandomizedDelaySec = "1h";
Persistent = true;
};
};
systemd.services.router-update = {
description = "Install a router update";
restartIfChanged = false;
+162 -40
View File
@@ -30,23 +30,29 @@ let
up = cfg.upgrade;
snapshot = "${cfg.stateDirectory}/config.pre-update";
dir = "${cfg.stateDirectory}/upgrade";
migrate = pkgs.callPackage ../../pkgs/router-migrate.nix { };
repository = toString config.routerUpdate.repository;
upgrade = pkgs.writeShellApplication {
name = "router-upgrade";
runtimeInputs = [
config.nix.package
config.systemd.package
migrate
pkgs.coreutils
pkgs.curl
pkgs.gawk
pkgs.git
pkgs.jq
pkgs.util-linux
];
text = ''
usage() {
echo "usage: router-upgrade check | releases | preview [--force] [--downgrade] | download | apply [timeout] | --request" >&2
echo " check the newest revision of router.update.channel, against the running one" >&2
echo " releases which stable NixOS releases the channel server has (a timer runs it daily)" >&2
echo " preview the packages that change and the size of the download (nothing is fetched)" >&2
echo "usage: router-upgrade check | daily | releases | preview [--force] [--downgrade] | download | apply [timeout] | --request" >&2
echo " check the newest nixpkgs revision of router.update.channel and the newest release tag of nixos-router, against the running ones" >&2
echo " daily check, quietly (a timer runs it)" >&2
echo " releases which stable NixOS releases the channel server has" >&2
echo " preview the new nixos-router and the packages that change, and the size of the download (nothing is fetched)" >&2
echo " download fetch and build what was previewed, without activating it" >&2
echo " apply activate what was previewed (fetching it if need be), with commit-confirm" >&2
exit 2
@@ -78,12 +84,15 @@ let
config=${cfg.directory}
mkdir -p ${dir}
# nixos-router comes from this repository (its tags vX.Y.Z); the packages
# (nixpkgs) from the channel, if one is followed. Both are inputs of the
# configuration flake, and one lock moves them together.
repository=${lib.escapeShellArg repository}
channel=""
branch=""
if [ "$cmd" != releases ]; then
channel=$(jq -r '.router.update.channel // empty' "$config/settings.json")
[ -n "$channel" ] || die "no channel: set router.update.channel (unstable, or a release like 26.05)"
if [ "$channel" = unstable ]; then branch=nixos-unstable; else branch="nixos-$channel"; fi
if [ "$channel" = unstable ]; then branch=nixos-unstable; elif [ -n "$channel" ]; then branch="nixos-$channel"; fi
fi
running_rev=$(/run/current-system/sw/bin/nixos-version --revision || true)
@@ -121,20 +130,64 @@ let
echo "releases on the channel server: ''${found[*]:-none}"
}
# The release tags of the repository, "TAG REVISION" per line, oldest first (an
# annotated tag counts with the commit it points to).
git_tags() {
git ls-remote --tags "$1" 'refs/tags/v*' | awk '
{ n = $2; sub("^refs/tags/", "", n); peeled = (n ~ /\^\{\}$/); sub(/\^\{\}$/, "", n)
if (n !~ /^v[0-9]+\.[0-9]+\.[0-9]+$/) next
if (peeled) p[n] = $1; else d[n] = $1
seen[n] = 1 }
END { for (n in seen) print n, (n in p ? p[n] : d[n]) }' | sort -V
}
installed_router=$(jq -r '.version // "unknown"' /etc/router-release 2>/dev/null || echo unknown)
r_tag="" r_rev="" r_version="" r_newer=false
check() {
releases || true
newest=$(newest_rev)
if [ "$newest" = "$running_rev" ]; then same=true; else same=false; fi
local packages_same=true router_json=null tags
newest=""
if [ -n "$channel" ]; then
newest=$(newest_rev)
if [ "$newest" != "$running_rev" ]; then packages_same=false; fi
fi
if [ -n "$repository" ]; then
# (Not fatal: the packages can still be looked at.)
if tags=$(git_tags "$repository" 2>/dev/null) && [ -n "$tags" ]; then
read -r r_tag r_rev <<<"$(tail -n 1 <<<"$tags")"
r_version=''${r_tag#v}
if [ "$r_version" != "$installed_router" ] \
&& [ "$(printf '%s\n%s\n' "$installed_router" "$r_version" | sort -V | tail -n 1)" = "$r_version" ]; then
r_newer=true
fi
router_json=$(jq -n --arg repo "$repository" --arg installed "$installed_router" --arg tag "$r_tag" \
--arg version "$r_version" --arg rev "$r_rev" --argjson newer "$r_newer" \
'{repository: $repo, installed: $installed, newest: {tag: $tag, version: $version, rev: $rev}, newer: $newer}')
else
echo "router-upgrade: cannot read the release tags of $repository" >&2
fi
fi
[ -n "$channel" ] || [ "$router_json" != null ] \
|| die "nothing to look at: no channel is set (router.update.channel: unstable, or a release like 26.05) and the repository cannot be read"
if [ "$packages_same" = true ] && [ "$r_newer" = false ]; then same=true; else same=false; fi
jq -n --arg channel "$channel" --arg branch "$branch" --arg time "$(date -u +%FT%TZ)" \
--arg running "$running_rev" --arg version "$running_version" --arg newest "$newest" \
--argjson upToDate "$same" \
--argjson packagesUpToDate "$packages_same" --argjson upToDate "$same" --argjson router "$router_json" \
'{channel: $channel, branch: $branch, time: $time, running: {rev: $running, version: $version},
newest: {rev: $newest}, upToDate: $upToDate}' > ${dir}/check.json.new
newest: {rev: $newest}, packagesUpToDate: $packagesUpToDate, upToDate: $upToDate, router: $router}' > ${dir}/check.json.new
mv ${dir}/check.json.new ${dir}/check.json
echo "channel $channel ($branch)"
echo " running $running_version"
echo " newest $(short "$newest")"
if [ "$same" = true ]; then echo "up to date"; else echo "a newer revision is available"; fi
if [ "$router_json" != null ]; then
echo "nixos-router ($repository)"
echo " installed $installed_router"
echo " newest $r_version"
fi
if [ -n "$channel" ]; then
echo "channel $channel ($branch)"
echo " running $running_version"
echo " newest $(short "$newest")"
fi
if [ "$same" = true ]; then echo "up to date"; else echo "a newer version is available"; fi
}
# The names (with versions) of store paths, one per line.
@@ -171,24 +224,71 @@ let
esac
done
check
rm -rf ${dir}/preview.json ${dir}/flake ${dir}/result
rm -rf ${dir}/preview.json ${dir}/flake ${dir}/base ${dir}/git-release ${dir}/result
if [ "$same" = true ] && [ "$force" -eq 0 ]; then return 0; fi
mkdir ${dir}/flake
mkdir ${dir}/flake ${dir}/base
for f in flake.nix settings.json local.nix flake.lock; do
if [ -e "$config/$f" ]; then cp "$config/$f" ${dir}/flake/; fi
done
ref="${up.nixpkgsRef}"
ref=''${ref//%rev%/$newest}
echo "router-upgrade: locking nixpkgs to $(short "$newest")"
nix flake lock --override-input nixos-router/nixpkgs "$ref" "path:${dir}/flake"
node=$(jq -r '.nodes[.nodes[.root].inputs["nixos-router"]].inputs.nixpkgs' ${dir}/flake/flake.lock)
hash=$(jq -er --arg n "$node" '.nodes[$n].locked.narHash' ${dir}/flake/flake.lock)
case $ref in
*narHash=*) pin=$ref ;;
*\?*) pin="$ref&narHash=$hash" ;;
*) pin="$ref?narHash=$hash" ;;
esac
# What the directory was like: apply refuses to go on when it changed.
cp "$config/flake.nix" "$config/settings.json" ${dir}/base/
# A newer nixos-router is one more input to lock: its source, from the tag, and
# the flake it brings, which names that source (config-flake.nix, with the
# address filled in), and the settings migrated to its schema.
router_new=false
if [ "$r_newer" = true ]; then
src="git+$repository?ref=refs/tags/$r_tag&rev=$r_rev"
echo "router-upgrade: fetching nixos-router $r_version ($(short "$r_rev"))"
# (No registry: the address is complete, and the global one is a download.)
meta=$(nix --option flake-registry "" flake prefetch --json "$src") || die "cannot fetch $src"
tree=$(jq -er .storePath <<<"$meta")
if [ ! -r "$tree/config-flake.nix" ] || [ ! -r "$tree/VERSION" ]; then
die "$r_tag is not a release this updater can build (no config-flake.nix or VERSION)"
fi
# What a release carries, made from the source: what the migration reads.
rel=${dir}/git-release
mkdir -p "$rel/migrations"
tr -d '\n' < "$tree/VERSION" > "$rel/version"
jq -er .locked.lastModified <<<"$meta" | tr -d '\n' > "$rel/serial"
printf %s "$r_rev" > "$rel/rev"
find "$tree/migrations" -name '*.jq' -exec cp {} "$rel/migrations/" \;
find "$rel/migrations" -name '*.jq' | wc -l | tr -d '\n' > "$rel/schema"
# (jq, not a shell substitution: the address has a & in it.)
jq -rRs --arg source "$src" 'gsub("@SOURCE@"; $source)' "$tree/config-flake.nix" > ${dir}/flake/flake.nix
rm -f ${dir}/flake/flake.lock
router-migrate-settings "$rel" ${dir}/flake/settings.json || die "migrating the settings to nixos-router $r_version failed"
router_new=true
fi
# The packages: the channel's revision; without a channel the one an earlier
# upgrade chose stays, else the nixos-router's own.
ref=""
pin=""
if [ -n "$channel" ]; then
ref="${up.nixpkgsRef}"
ref=''${ref//%rev%/$newest}
elif [ -r "$config/nixpkgs-pin.json" ]; then
ref=$(jq -r .ref "$config/nixpkgs-pin.json")
fi
lock=(nix flake lock)
if [ -n "$ref" ]; then lock+=(--override-input nixos-router/nixpkgs "$ref"); fi
if [ "$router_new" = true ]; then
echo "router-upgrade: locking nixos-router $r_version and the packages"
else
echo "router-upgrade: locking the packages''${newest:+ to $(short "$newest")}"
fi
"''${lock[@]}" "path:${dir}/flake"
if [ -n "$channel" ]; then
node=$(jq -r '.nodes[.nodes[.root].inputs["nixos-router"]].inputs.nixpkgs' ${dir}/flake/flake.lock)
hash=$(jq -er --arg n "$node" '.nodes[$n].locked.narHash' ${dir}/flake/flake.lock)
case $ref in
*narHash=*) pin=$ref ;;
*\?*) pin="$ref&narHash=$hash" ;;
*) pin="$ref?narHash=$hash" ;;
esac
fi
attr="path:${dir}/flake#nixosConfigurations.router.config.system"
echo "router-upgrade: evaluating the new system"
@@ -224,13 +324,19 @@ let
sed 's/^/ /' ${dir}/builds.txt | head -n 60
if [ "$(wc -l < ${dir}/builds.txt)" -gt 60 ]; then echo " ... and $(( $(wc -l < ${dir}/builds.txt) - 60 )) more"; fi
release_version=$(jq -r '.version // ""' /etc/router-release 2>/dev/null || true)
jq -n --arg channel "$channel" --arg release "$release_version" --arg rev "$newest" --arg ref "$pin" --arg version "$new_version" \
--arg time "$(date -u +%FT%TZ)" --arg download "$download" --argjson builds "$builds" \
# What changes in nixos-router itself, if it does: shown above the packages.
router_change=null
if [ "$router_new" = true ]; then
router_change=$(jq -n --arg from "$installed_router" --arg to "$r_version" --arg tag "$r_tag" --arg rev "$r_rev" \
'{from: $from, to: $to, tag: $tag, rev: $rev}')
echo " nixos-router: $installed_router -> $r_version"
fi
jq -n --arg channel "$channel" --arg release "$installed_router" --arg rev "$newest" --arg ref "$pin" --arg version "$new_version" \
--arg time "$(date -u +%FT%TZ)" --arg download "$download" --argjson builds "$builds" --argjson router "$router_change" \
--argjson reboot "$reboot" --slurpfile changes ${dir}/changes.json --rawfile buildNames ${dir}/builds.txt \
'{channel: $channel, release: $release, rev: $rev, ref: $ref, version: $version, time: $time, download: $download,
builds: $builds, buildNames: ($buildNames | split("\n") | map(select(. != "")) | .[:300]),
rebootNeeded: $reboot, changes: $changes[0]}' > ${dir}/preview.json
rebootNeeded: $reboot, router: $router, changes: $changes[0]}' > ${dir}/preview.json
rm -f ${dir}/builds.txt
echo "$new_version$([ "$reboot" = false ] || echo ' (a new kernel runs after a reboot)'): router-upgrade apply activates it"
}
@@ -251,18 +357,31 @@ let
exec 9>/run/router-update.lock
flock -n 9 || die "an update or upgrade is running"
[ ! -d ${snapshot} ] || die "an earlier update or upgrade is not confirmed yet"
cmp -s "$config/flake.nix" ${dir}/flake/flake.nix \
cmp -s "$config/flake.nix" ${dir}/base/flake.nix \
|| die "the configuration flake changed since it was previewed: preview again"
# A new nixos-router brings migrated settings: they are taken over whole.
router_to=$(jq -r '.router.to // ""' ${dir}/preview.json)
if [ -n "$router_to" ]; then
cmp -s "$config/settings.json" ${dir}/base/settings.json \
|| die "the settings changed since the upgrade was previewed: preview again"
fi
cp -a "$config" ${snapshot}
fail() {
echo "router-upgrade: $*" >&2
/run/current-system/sw/bin/router-update-restore
exit 1
}
if [ -n "$router_to" ]; then
cp ${dir}/flake/flake.nix "$config/flake.nix"
cp ${dir}/flake/settings.json "$config/settings.json"
fi
cp ${dir}/flake/flake.lock "$config/flake.lock"
jq '{channel, rev, ref}' ${dir}/preview.json > "$config/nixpkgs-pin.json"
# The packages that were chosen stay chosen when nixos-router is updated later.
if [ -n "$(jq -r '.ref // ""' ${dir}/preview.json)" ]; then
jq '{channel, rev, ref}' ${dir}/preview.json > "$config/nixpkgs-pin.json"
fi
echo "router-upgrade: building and activating $(jq -r .version ${dir}/preview.json)"
echo "router-upgrade: building and activating ''${router_to:+nixos-router $router_to on }$(jq -r .version ${dir}/preview.json)"
if ! router-apply ''${timeout:+"$timeout"}; then
if systemctl is-active --quiet router-rollback.timer; then
# Activation failed half way: the rollback restores the configuration.
@@ -271,7 +390,7 @@ let
fi
fail "the upgrade failed; the previous system is back"
fi
rm -rf ${dir}/preview.json ${dir}/flake ${dir}/result
rm -rf ${dir}/preview.json ${dir}/flake ${dir}/base ${dir}/git-release ${dir}/result
if systemctl is-active --quiet router-rollback.timer; then
echo "router-upgrade: active; confirm it (router-confirm, or in the web UI) or the previous system comes back"
else
@@ -281,6 +400,8 @@ let
case $cmd in
check) check ;;
# For the timer: a router with nothing to look at, or no internet, is no failure.
daily) check || echo "router-upgrade: nothing was looked at" >&2 ;;
releases) releases ;;
preview) preview "$@" ;;
download) download ;;
@@ -310,15 +431,16 @@ in
# The web UI starts this rather than running anything itself, so a switch
# that restarts the UI does not cut an upgrade short; a switch must not
# restart or stop it either (router-apply is what runs the switch).
# Which stable releases exist, once a day: the web UI says when a newer one than
# the followed channel appears. It only asks the channel server and writes a small
# file, so it is a unit of its own that never holds up an upgrade.
# Is there something newer (a nixos-router release, a nixpkgs revision of the
# channel, a NixOS release), once a day: the web UI says so on the Overview. It
# only asks the servers and writes small files, so it is a unit of its own that
# never holds up an upgrade.
systemd.services.router-upgrade-notice = {
description = "Look for new NixOS releases";
description = "Look for newer versions of nixos-router and NixOS";
path = [ "/run/current-system/sw" ];
serviceConfig = {
Type = "oneshot";
ExecStart = "${lib.getExe upgrade} releases";
ExecStart = "${lib.getExe upgrade} daily";
TimeoutStartSec = "5min";
};
};
+4 -1
View File
@@ -319,6 +319,8 @@ type dashboard struct {
Events []Event
Charts []Chart
Prefs Prefs
Version string // the installed release of nixos-router
NixOS string // the NixOS it runs on
}
func (a *app) dashboardData(rangeName string) dashboard {
@@ -326,7 +328,8 @@ func (a *app) dashboardData(rangeName string) dashboard {
now := time.Now()
s, _ := loadSettings(a.sys.settingsPath())
f := s.form()
d := dashboard{Range: rg.Name, Interval: 5, Snap: a.metrics.Snapshot(), Prefs: a.sys.loadPrefs()}
d := dashboard{Range: rg.Name, Interval: 5, Snap: a.metrics.Snapshot(), Prefs: a.sys.loadPrefs(),
Version: a.sys.installedRelease().Version, NixOS: a.sys.runningVersion()}
// Newest first, the last few.
ev := d.Snap.Uplink.Events
d.Events = make([]Event, 0, 10)
+19
View File
@@ -155,6 +155,25 @@ func TestDashboardRenders(t *testing.T) {
}
}
func TestDashboardNamesTheVersion(t *testing.T) {
a, sys := newTestApp(t)
dir := t.TempDir()
sys.ReleaseFile = filepath.Join(dir, "router-release")
sys.VersionFile = filepath.Join(dir, "nixos-version")
os.WriteFile(sys.ReleaseFile, []byte(`{"version":"4.5.6"}`), 0o600)
os.WriteFile(sys.VersionFile, []byte("26.11.20261113.d5cc683\n"), 0o600)
a.sys = sys
h := a.routes()
cookie := login(t, h)
// The page and the fragment that refreshes it say what runs.
for _, path := range []string{"/", "/dashboard?range=24h"} {
body := do(h, "GET", path, nil, cookie).Body.String()
if !strings.Contains(body, "nixos-router 4.5.6") || !strings.Contains(body, "NixOS 26.11.20261113.d5cc683") {
t.Errorf("%s does not name the version:\n%s", path, body)
}
}
}
func TestBackup(t *testing.T) {
a, sys := newTestApp(t)
h := a.routes()
+20 -99
View File
@@ -1,115 +1,36 @@
package main
import (
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
)
// Updates from a git repository (router.update.repository): router-update
// check looks at the repository's release tags (vX.Y.Z) once a day and when the
// page asks, and writes what it found to update/check.json; installing builds
// the router from a tag, like an update from a bundle.
// nixos-router is an input of the configuration flake like nixpkgs, and comes
// from a git repository whose tags vX.Y.Z are releases. Looking for it and
// locking it is router-upgrade's, with the packages (check.json has both). The
// repository is part of the installed version (routerUpdate.repository,
// written to /etc/router-update-repository), not something the page sets.
var (
// The same shape the option accepts: no credentials, no query.
repositoryRe = regexp.MustCompile(`^https?://[A-Za-z0-9.-]+(:[0-9]+)?(/[A-Za-z0-9._~/-]*)?$`)
releaseTagRe = regexp.MustCompile(`^v[0-9]+\.[0-9]+\.[0-9]+$`)
)
// GitCheck is update/check.json: the newest release tag of the repository.
type GitCheck struct {
Repository string `json:"repository"`
Time string `json:"time"`
Installed string `json:"installed"`
Newest struct {
Tag string `json:"tag"`
Version string `json:"version"`
Rev string `json:"rev"`
} `json:"newest"`
Newer bool `json:"newer"`
// repository is where releases come from ("" if the router has none).
func (s System) repository() string {
path := s.RepositoryFile
if path == "" {
path = "/etc/router-update-repository"
}
data, _ := os.ReadFile(path)
return strings.TrimSpace(string(data))
}
func (s Settings) repository() string { return str(s, "router", "update", "repository") }
const gitCheckUnit = "router-update-check.service"
// gitCheck is what the last check found, if it is still about this repository
// and this installed version.
func (a *app) gitCheck(repository string) *GitCheck {
var c GitCheck
if repository == "" || !readUpgradeFile(filepath.Join(a.sys.updateDir(), "check.json"), &c) {
return nil
}
if c.Repository != repository || c.Installed != a.sys.installedRelease().Version || c.Newest.Tag == "" {
return nil
}
return &c
}
// newRouterVersion is the version of a release that is out and not installed,
// for the Overview ("" if there is none or nothing was checked).
// newRouterVersion is the version of a release of nixos-router that is out and
// not installed, for the Overview ("" if there is none or nothing was checked).
func (a *app) newRouterVersion() string {
s, err := loadSettings(a.sys.settingsPath())
if err != nil {
var c UpgradeCheck
if !readUpgradeFile(filepath.Join(a.sys.upgradeDir(), "check.json"), &c) {
return ""
}
if c := a.gitCheck(s.repository()); c != nil && c.Newer {
return c.Newest.Version
if r := c.Router; r != nil && r.Newer && r.Installed == a.sys.installedRelease().Version {
return r.Newest.Version
}
return ""
}
func (a *app) updateSaveRepository(w http.ResponseWriter, r *http.Request, _ session) {
v := strings.TrimRight(strings.TrimSpace(r.PostFormValue("repository")), "/")
if !r.PostForm.Has("repository") {
a.updateBack(w, r, "Not saved: no address was sent.")
return
}
if v != "" && !repositoryRe.MatchString(v) {
a.updateBack(w, r, "Not saved: an http:// or https:// address of a public repository, without credentials or a query.")
return
}
if err := a.sys.setUpdateField("repository", v); err != nil {
a.updateBack(w, r, "Not saved: "+err.Error())
return
}
a.updateBack(w, r, "Saved.")
}
func (a *app) updateGitCheck(w http.ResponseWriter, r *http.Request, _ session) {
s, err := loadSettings(a.sys.settingsPath())
if err != nil || s.repository() == "" {
a.updateBack(w, r, "Set the repository first.")
return
}
if err := startUnit(gitCheckUnit); err != nil {
a.updateBack(w, r, "Could not look: "+err.Error())
return
}
a.updateBack(w, r, "Looking at the repository.")
}
func (a *app) updateGitInstall(w http.ResponseWriter, r *http.Request, _ session) {
if a.busy() {
a.updateBack(w, r, "Another change is in progress or waiting for confirmation.")
return
}
tag := r.PostFormValue("tag")
if tag != "" && !releaseTagRe.MatchString(tag) {
a.updateBack(w, r, "Not a release tag: "+url.QueryEscape(tag))
return
}
s, err := loadSettings(a.sys.settingsPath())
if err != nil || s.repository() == "" {
a.updateBack(w, r, "Set the repository first.")
return
}
if err := a.sys.requestUpdate("git", tag, r.PostFormValue("force") == "on"); err != nil {
a.updateBack(w, r, "Could not start the update: "+err.Error())
return
}
a.updateBack(w, r, "Updating.")
}
+37 -64
View File
@@ -9,94 +9,67 @@ import (
"testing"
)
func TestUpdatesFromGit(t *testing.T) {
const testRepository = "https://git.example.org/me/nixos-router"
// One check, one preview: the page shows nixos-router and the packages
// together, and the preview marks the router's own row.
func TestUpgradeShowsRouterAndPackages(t *testing.T) {
a, sys := newTestApp(t)
sys.ReleaseFile = filepath.Join(t.TempDir(), "router-release")
dir := t.TempDir()
sys.ReleaseFile = filepath.Join(dir, "router-release")
sys.RepositoryFile = filepath.Join(dir, "router-update-repository")
os.WriteFile(sys.ReleaseFile, []byte(`{"version":"1.0.0","serial":1000}`), 0o600)
os.WriteFile(sys.RepositoryFile, []byte(testRepository+"\n"), 0o644)
a.sys = sys
orig := startUnit
var started []string
startUnit = func(unit string) error { started = append(started, unit); return nil }
defer func() { startUnit = orig }()
h := a.routes()
cookie := login(t, h)
token := csrfFrom(t, do(h, "GET", "/update", nil, cookie).Body.String())
post := func(path string, form url.Values) string {
form.Set("csrf", token)
return do(h, "POST", path, form, cookie).Header().Get("Location")
}
// The repository: an address of a public repository, nothing else.
for _, bad := range []string{"git@git.example.org:me/r.git", "https://user:pw@git.example.org/r", "https://git.example.org/r?x=1", "file:///etc", "https://git.example.org/a b"} {
if loc := post("/update/repository", url.Values{"repository": {bad}}); !strings.Contains(loc, "Not+saved") {
t.Errorf("%q was accepted: %s", bad, loc)
body := do(h, "GET", "/update", nil, cookie).Body.String()
for _, want := range []string{testRepository, "Check for upgrades"} {
if !strings.Contains(body, want) {
t.Fatalf("the page lacks %q:\n%s", want, body)
}
}
if loc := post("/update/gitcheck", url.Values{}); !strings.Contains(loc, "Set+the+repository") || len(started) != 0 {
t.Fatalf("a check without a repository: %q %v", loc, started)
if strings.Contains(body, `name="repository"`) {
t.Fatalf("the page has a field for the repository:\n%s", body)
}
if loc := post("/update/gitinstall", url.Values{"tag": {"v1.1.0"}}); !strings.Contains(loc, "Set+the+repository") {
t.Fatalf("an install without a repository: %q", loc)
}
post("/update/repository", url.Values{"repository": {"https://git.example.org/me/nixos-router/"}})
s, _ := loadSettings(sys.settingsPath())
if got := s.repository(); got != "https://git.example.org/me/nixos-router" {
t.Fatalf("repository: %q", got)
}
// It takes effect when updating, so it is no unapplied change.
if c, err := loadSettings(sys.confirmedPath()); err == nil && c.repository() != "" {
t.Logf("confirmed settings carry it: %q", c.repository())
if rec := do(h, "POST", "/update/repository", nil, cookie); rec.Code != 404 && rec.Code != 405 {
t.Fatalf("the repository can be set from the page: %d", rec.Code)
}
// Looking starts the unit; what it found is shown while it is about this repository and version.
post("/update/gitcheck", url.Values{})
if len(started) != 1 || started[0] != "router-update-check.service" {
t.Fatalf("started %v", started)
}
if body := do(h, "GET", "/update", nil, cookie).Body.String(); !strings.Contains(body, "Not looked yet") {
t.Fatalf("a result before any look:\n%s", body)
}
token := csrfFrom(t, body)
do(h, "POST", "/upgrade/channel", url.Values{"csrf": {token}, "channel": {"26.05"}}, cookie)
write := func(repo, installed string, newer bool) {
os.MkdirAll(sys.updateDir(), 0o755)
data, _ := json.Marshal(map[string]any{"repository": repo, "time": "2026-11-26T08:00:00Z", "installed": installed,
"newest": map[string]string{"tag": "v1.1.0", "version": "1.1.0", "rev": "0123456789abcdef0123456789abcdef01234567"}, "newer": newer})
os.WriteFile(filepath.Join(sys.updateDir(), "check.json"), data, 0o644)
os.MkdirAll(sys.upgradeDir(), 0o755)
data, _ := json.Marshal(map[string]any{"channel": "26.05", "running": map[string]string{"version": a.sys.runningVersion()}, "time": "2026-11-26T08:00:00Z", "upToDate": !newer, "packagesUpToDate": true,
"router": map[string]any{"repository": repo, "installed": installed, "newer": newer,
"newest": map[string]string{"tag": "v1.1.0", "version": "1.1.0", "rev": "0123456789abcdef0123456789abcdef01234567"}}})
os.WriteFile(filepath.Join(sys.upgradeDir(), "check.json"), data, 0o644)
}
write("https://git.example.org/someone-else/nixos-router", "1.0.0", true)
if body := do(h, "GET", "/", nil, cookie).Body.String(); strings.Contains(body, "is out") {
t.Fatalf("a notice from another repository:\n%s", body)
}
write("https://git.example.org/me/nixos-router", "0.9.0", true)
write(testRepository, "0.9.0", true)
if body := do(h, "GET", "/", nil, cookie).Body.String(); strings.Contains(body, "is out") {
t.Fatalf("a notice from before the last update:\n%s", body)
}
write("https://git.example.org/me/nixos-router", "1.0.0", true)
write(testRepository, "1.0.0", true)
for _, path := range []string{"/", "/update"} {
if body := do(h, "GET", path, nil, cookie).Body.String(); !strings.Contains(body, "1.1.0") || (path == "/" && !strings.Contains(body, "nixos-router 1.1.0 is out")) {
t.Fatalf("%s lacks the release:\n%s", path, body)
}
}
write("https://git.example.org/me/nixos-router", "1.0.0", false)
write(testRepository, "1.0.0", false)
if body := do(h, "GET", "/", nil, cookie).Body.String(); strings.Contains(body, "nixos-router 1.1.0 is out") {
t.Fatalf("a notice when up to date")
}
// Installing asks the update unit to build the tag, and only a release tag.
if loc := post("/update/gitinstall", url.Values{"tag": {"v1.1.0; reboot"}}); !strings.Contains(loc, "Not+a+release+tag") {
t.Fatalf("a bad tag: %q", loc)
}
started = nil
post("/update/gitinstall", url.Values{"tag": {"v1.1.0"}, "force": {"on"}})
var req struct {
Mode string `json:"mode"`
URL string `json:"url"`
Force bool `json:"force"`
}
data, _ := os.ReadFile(filepath.Join(sys.updateDir(), "request.json"))
if err := json.Unmarshal(data, &req); err != nil || req.Mode != "git" || req.URL != "v1.1.0" || !req.Force {
t.Fatalf("request: %s", data)
}
if len(started) != 1 || started[0] != "router-update.service" {
t.Fatalf("started %v", started)
// A preview that includes the router: one table, the router's row marked.
preview, _ := json.Marshal(map[string]any{"channel": "26.05", "release": "1.0.0", "rev": "", "version": "26.05", "time": "t",
"router": map[string]string{"from": "1.0.0", "to": "1.1.0", "tag": "v1.1.0", "rev": "abc"},
"changes": []map[string]string{{"name": "curl", "from": "8.0", "to": "8.1"}}})
os.WriteFile(filepath.Join(sys.upgradeDir(), "preview.json"), preview, 0o644)
body = do(h, "GET", "/update", nil, cookie).Body.String()
for _, want := range []string{`class="highlight"`, "<td>nixos-router</td>", "<td>curl</td>", "Upgrade nixos-router to 1.1.0 and"} {
if !strings.Contains(body, want) {
t.Fatalf("the preview lacks %q:\n%s", want, body)
}
}
}
-6
View File
@@ -338,12 +338,6 @@ func (a *app) routes() http.Handler {
mux.HandleFunc("POST /prefs", a.auth(a.savePrefs))
mux.HandleFunc("POST /backup", a.auth(a.backup))
mux.HandleFunc("GET /update", a.auth(a.updatePage))
mux.HandleFunc("POST /update/url", a.auth(a.updateSaveURL))
mux.HandleFunc("POST /update/check", a.auth(a.updateCheck))
mux.HandleFunc("POST /update/install", a.auth(a.updateInstall))
mux.HandleFunc("POST /update/repository", a.auth(a.updateSaveRepository))
mux.HandleFunc("POST /update/gitcheck", a.auth(a.updateGitCheck))
mux.HandleFunc("POST /update/gitinstall", a.auth(a.updateGitInstall))
mux.HandleFunc("POST /update/upload", a.updateUpload)
mux.HandleFunc("GET /upgrade", a.auth(upgradeRedirect))
mux.HandleFunc("POST /upgrade/channel", a.auth(a.upgradeChannel))
+1
View File
@@ -152,6 +152,7 @@ table { border-collapse: collapse; }
th { text-align: left; font-size: .82rem; font-weight: 600; color: var(--muted); padding: 0 .45rem .35rem; white-space: nowrap; border-bottom: 1px solid var(--line); }
td { padding: .3rem .45rem; }
table tr:nth-child(even) td { background: var(--zebra); }
table tr.highlight td { font-weight: 600; background: var(--zebra); border-left: 3px solid var(--tick); }
pre.log { background: var(--code); padding: .85rem 1rem; border-radius: var(--radius); overflow-x: auto; font-size: 12.5px; max-height: 30rem; }
code { font-size: .88em; overflow-wrap: anywhere; background: var(--code); padding: .1em .35em; border-radius: 3px; }
pre code { background: none; padding: 0; }
+4 -1
View File
@@ -21,6 +21,8 @@ type System struct {
StateDir string // /var/lib/router: secrets, UI state
// ReleaseFile describes the installed nixos-router; /etc/router-release if empty.
ReleaseFile string
// RepositoryFile holds the git repository releases come from; /etc/router-update-repository if empty.
RepositoryFile string
// VersionFile holds the running NixOS version; /run/current-system/nixos-version if empty.
VersionFile string
// LeasesDNSDir is where leases-dns leaves its status; /run/router-leases-dns if empty.
@@ -47,7 +49,8 @@ func command(name string, args ...string) (string, error) {
return strings.TrimSpace(string(out)), err
}
func unitProperty(unit, prop string) string {
// unitProperty is a property of a systemd unit (replaced in tests).
var unitProperty = func(unit, prop string) string {
out, _ := command("systemctl", "show", "--value", "-p", prop, unit)
return out
}
@@ -32,6 +32,7 @@
<section class="card">
<h2>System</h2>
<dl>
{{if $d.Version}}<dt>Version</dt><dd>nixos-router {{$d.Version}}{{if $d.NixOS}} <span class="muted">on NixOS {{$d.NixOS}}</span>{{end}}</dd>{{end}}
<dt>Uptime</dt><dd>{{age $sys.Uptime}}</dd>
{{if $sys.Kernel}}<dt>Kernel</dt><dd>{{$sys.Kernel}}{{if $sys.KernelNext}} <span class="bad">reboot to run {{$sys.KernelNext}}</span> <button type="button" class="link" data-dialog="Reboot the router now? Routing stops for a minute or two." data-dialog-ok="Reboot" data-post="/reboot">Reboot</button>{{end}}</dd>{{end}}
{{if $sys.BootPending}}<dt>Reboot</dt><dd><span class="bad">a new configuration starts at the next reboot</span> <button type="button" class="link" data-dialog="Reboot the router now? Routing stops for a minute or two." data-dialog-ok="Reboot" data-post="/reboot">Reboot</button></dd>{{end}}
+36 -103
View File
@@ -28,90 +28,6 @@
previous one.</p></section>
{{end}}
<h2 class="part">Router software</h2>
<section>
<h2>Installed</h2>
<dl>
<dt>Version</dt><dd>{{or $u.Installed.Version "unknown"}}{{if $u.Installed.Rev}} <span class="muted">{{$u.Installed.Rev}}</span>{{end}}</dd>
<dt>Settings schema</dt><dd>{{$u.Installed.Schema}}</dd>
</dl>
</section>
<section>
<h2>Releases from git</h2>
<p>The router looks once a day at the release tags (<code>vX.Y.Z</code>) of a public repository and says here and on the
Overview when a newer one exists. Installing builds it on the router, like a bundle: the settings are kept (and
migrated), and the new version must be confirmed afterwards, or the router goes back. The repository is trusted
as it is: nothing is signed on this path.</p>
<form method="post" action="/update/repository" class="actions">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<label>Repository <input name="repository" value="{{$u.Repository}}" size="44" placeholder="https://git.example.org/me/nixos-router"></label>
<button class="secondary">Save</button>
</form>
{{if $u.Repository}}
<form method="post" action="/update/gitcheck" class="actions">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<button class="secondary"{{if $u.GitRun.Running}} disabled{{end}}>{{if $u.GitRun.Running}}Looking…{{else}}Look for a newer release{{end}}</button>
</form>
{{if and $u.GitRun.Result (ne $u.GitRun.Result "success")}}<p class="error">The last look failed:</p><pre class="log">{{$u.GitRun.Log}}</pre>{{end}}
{{with $u.Git}}
<dl>
<dt>Installed</dt><dd>{{.Installed}}</dd>
<dt>Newest</dt><dd>{{.Newest.Version}} <span class="muted">{{printf "%.7s" .Newest.Rev}}, looked {{.Time}}</span></dd>
</dl>
<form method="post" action="/update/gitinstall">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<input type="hidden" name="tag" value="{{.Newest.Tag}}">
{{if .Newer}}<p>A newer release is available.</p>
{{else}}<p>Up to date.</p><p><label><input type="checkbox" name="force"> install it anyway</label></p>{{end}}
<button{{if $u.Pending}} disabled{{end}}>{{if .Newer}}Install {{.Newest.Version}}{{else}}Install {{.Newest.Version}} again{{end}}</button>
</form>
{{else}}
<p class="hint">Not looked yet.</p>
{{end}}
{{end}}
</section>
<section>
<h2>Install a bundle</h2>
<p>A <code>.bundle</code> file made with <code>nix run .#release</code>. It is installed only if it is signed with
this router's update key. The settings are kept (and migrated if the new version needs it); the new version
must be confirmed afterwards, or the router goes back.</p>
<form method="post" action="/update/upload?csrf={{.CSRF}}" enctype="multipart/form-data" data-upload>
<p><label><input type="checkbox" name="force"> also install a version that is not newer</label></p>
<p><input type="file" name="bundle" required> <button>Upload and install</button></p>
</form>
</section>
<section>
<h2>Update server</h2>
<form method="post" action="/update/url" class="actions">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<label>Address <input name="url" value="{{$u.URL}}" size="40" placeholder="https://updates.example.com/router"></label>
<button class="secondary">Save</button>
</form>
{{if $u.URL}}
<form method="post" action="/update/check" class="actions">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<button class="secondary">Check for updates</button>
</form>
{{end}}
{{if $u.OfferErr}}<p class="error">Could not check: {{$u.OfferErr}}</p>{{end}}
{{with $u.Offer}}
<p>{{if .Newer}}Available: <strong>{{.Version}}</strong>{{if .Rev}} <span class="muted">{{.Rev}}</span>{{end}}.{{else}}Nothing newer: the server has {{.Version}}.{{end}}</p>
<form method="post" action="/update/install">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
{{if not .Newer}}<p><label><input type="checkbox" name="force"> install it anyway</label></p>{{end}}
<button>{{if .Newer}}Install {{.Version}}{{else}}Install{{end}}</button>
</form>
{{end}}
<p class="hint">The server only has to serve static files: the <code>latest</code> file and <code>cache/</code> that
<code>nix run .#release</code> writes. The data is signed, so plain HTTP works too.</p>
</section>
<h2 class="part" id="packages">Packages</h2>
{{with $g.NewerRelease}}
<section class="notice">
<h2>NixOS {{.}} is out</h2>
@@ -125,14 +41,16 @@
</section>
{{end}}
<section>
<h2>Channel</h2>
<p>Upgrades the kernel and all programs (NixOS) without a new release of nixos-router. Nothing is downloaded until
you ask for it, and an upgrade is activated like a settings change: unless you confirm it in time, the router
goes back to the previous system.</p>
<section id="packages">
<h2>Installed</h2>
<dl>
<dt>Running</dt><dd>{{or $g.Version "unknown"}}</dd>
<dt>nixos-router</dt><dd>{{or $g.Router.Version "unknown"}}{{if $g.Router.Rev}} <span class="muted">{{printf "%.7s" $g.Router.Rev}}</span>{{end}}</dd>
<dt>Settings schema</dt><dd>{{$g.Router.Schema}}</dd>
<dt>NixOS</dt><dd>{{or $g.Version "unknown"}}</dd>
</dl>
<p>An upgrade brings the newest nixos-router{{if $g.Repository}} (from <code>{{$g.Repository}}</code>){{end}} and the packages
(the kernel and all programs) of the channel you follow. Nothing is downloaded until you ask for it, and an upgrade is
activated like a settings change: unless you confirm it in time, the router goes back to the previous system.</p>
<form method="post" action="/upgrade/channel" class="actions">
<input type="hidden" name="csrf" value="{{.CSRF}}">
<label>Follow
@@ -143,12 +61,12 @@
<button class="secondary">Save</button>
</form>
{{if $g.ReleasesSeen}}<p class="hint">Stable releases as the channel server listed them on {{$g.ReleasesSeen}}; Check for upgrades asks again.</p>{{end}}
<p class="hint">The channel only chooses what an upgrade offers; saving it changes nothing on the router. Going back to an older release
<p class="hint">The channel only chooses which packages an upgrade offers; saving it changes nothing on the router. Going back to an older release
(unstable to 26.05) is refused unless you tick "downgrade anyway" when previewing; state written by the newer
release may not work with the older one.</p>
</section>
{{if $g.Channel}}
{{if or $g.Channel $g.Repository}}
<section>
<h2>Check</h2>
<form method="post" action="/upgrade/check" class="actions">
@@ -157,11 +75,11 @@
</form>
{{with $g.Check}}
<dl>
<dt>Channel</dt><dd>{{.Branch}}</dd>
<dt>Running</dt><dd>{{.Running.Version}}</dd>
<dt>Newest</dt><dd>{{printf "%.7s" .Newest.Rev}} <span class="muted">checked {{.Time}}</span></dd>
{{with .Router}}<dt>nixos-router</dt><dd>{{.Installed}}{{if .Newer}} → <strong>{{.Newest.Version}}</strong>{{else}} <span class="muted">(the newest)</span>{{end}}</dd>{{end}}
{{if .Channel}}<dt>Packages</dt><dd>{{.Channel}}: {{printf "%.7s" .Newest.Rev}}{{if .PackagesUpToDate}} <span class="muted">(what runs)</span>{{else}} <strong>newer than the running {{printf "%.7s" .Running.Rev}}</strong>{{end}}</dd>{{end}}
<dt>Checked</dt><dd>{{.Time}}</dd>
</dl>
{{if .UpToDate}}<p>Up to date.</p>{{else}}<p>A newer revision is available.</p>{{end}}
{{if .UpToDate}}<p>Up to date.</p>{{else}}<p>A newer version is available.</p>{{end}}
{{end}}
</section>
@@ -173,15 +91,19 @@
<label><input type="checkbox" name="downgrade"> downgrade anyway</label>
<button class="secondary"{{if or $g.Run.Running $g.Updating}} disabled{{end}}>Preview</button>
</form>
<p class="hint">Works it out from the new revision's description: no package is downloaded.</p>
<p class="hint">Works it out from the new versions' descriptions: no package is downloaded.</p>
{{with $g.Preview}}
<p>{{$g.Version}} → <strong>{{.Version}}</strong> <span class="muted">{{printf "%.7s" .Rev}}, previewed {{.Time}}</span></p>
{{if .Changes}}
<p>{{$g.Version}} → <strong>{{.Version}}</strong> <span class="muted">{{if .Rev}}{{printf "%.7s" .Rev}}, {{end}}previewed {{.Time}}</span></p>
{{if or .Router .Changes}}
<table>
<thead><tr><th>Package</th><th>Now</th><th></th><th>New</th></tr></thead>
<tbody>{{range .Changes}}<tr><td>{{.Name}}</td><td>{{.From}}</td><td>→</td><td>{{.To}}</td></tr>{{end}}</tbody>
<tbody>
{{with .Router}}<tr class="highlight" title="This upgrade also installs a new version of nixos-router itself, and migrates the settings to it if it needs that."><td>nixos-router</td><td>{{.From}}</td><td>→</td><td>{{.To}}</td></tr>{{end}}
{{range .Changes}}<tr><td>{{.Name}}</td><td>{{.From}}</td><td>→</td><td>{{.To}}</td></tr>{{end}}
</tbody>
</table>
{{else}}<p>No package changes.</p>{{end}}
{{if .Router}}<p class="hint">The highlighted row is the router software itself: this upgrade installs it too.</p>{{end}}
<p class="hint">The list shows the versions of programs the router runs; a program that is only rebuilt does not appear.</p>
<dl>
<dt>To download</dt><dd>{{or .Download "nothing, or the package cache cannot be reached"}}</dd>
@@ -203,7 +125,7 @@
</form>
<form method="post" action="/upgrade/apply">
<input type="hidden" name="csrf" value="{{$.CSRF}}">
<button{{if or $g.Run.Running $g.Updating $g.Pending}} disabled{{end}}>Upgrade to {{.Version}}</button>
<button{{if or $g.Run.Running $g.Updating $g.Pending}} disabled{{end}}>Upgrade{{with .Router}} nixos-router to {{.To}} and{{end}} to {{.Version}}</button>
</form>
</div>
<p class="hint">Downloading first lets you start the upgrade later without needing the internet. Upgrading
@@ -214,16 +136,27 @@
<section><p>Choose a channel to look for upgrades.</p></section>
{{end}}
<section>
<h2>Install a bundle</h2>
<p>For a router without a route to the repository, or when it is down: a <code>.bundle</code> file made with
<code>nix run .#release</code>. It is installed only if it is signed with this router's update key. The settings are kept
(and migrated if the new version needs it); the new version must be confirmed afterwards, or the router goes back.</p>
<form method="post" action="/update/upload?csrf={{.CSRF}}" enctype="multipart/form-data" data-upload>
<p><label><input type="checkbox" name="force"> also install a version that is not newer</label></p>
<p><input type="file" name="bundle" required> <button>Upload and install</button></p>
</form>
</section>
{{if and $u.Status.Log (not $u.Status.Running)}}
<section>
<h2>Last update{{if $u.Status.Result}} — {{if eq $u.Status.Result "success"}}succeeded{{else}}failed ({{$u.Status.Result}}){{end}}{{end}}</h2>
<h2>Last bundle update{{if $u.Status.Result}} — {{if eq $u.Status.Result "success"}}succeeded{{else}}failed ({{$u.Status.Result}}){{end}}{{end}}</h2>
<pre class="log">{{$u.Status.Log}}</pre>
</section>
{{end}}
{{if and $g.Run.Log (not $g.Run.Running)}}
<section>
<h2>Last package run{{if $g.Run.Result}} — {{if eq $g.Run.Result "success"}}succeeded{{else}}failed ({{$g.Run.Result}}){{end}}{{end}}</h2>
<h2>Last upgrade run{{if $g.Run.Result}} — {{if eq $g.Run.Result "success"}}succeeded{{else}}failed ({{$g.Run.Result}}){{end}}{{end}}</h2>
<pre class="log">{{$g.Run.Log}}</pre>
</section>
{{end}}
+4 -126
View File
@@ -14,7 +14,6 @@ import (
"path/filepath"
"regexp"
"strings"
"time"
)
// Updates arrive as a tar of a signed binary cache (see lib.mkRelease):
@@ -142,67 +141,10 @@ func (s System) installedRelease() Release {
return r
}
func (s System) updateDir() string { return filepath.Join(s.StateDir, "update") }
func (s System) updateURLPath() string { return filepath.Join(s.StateDir, "webui", "update.json") }
func (s System) updateDir() string { return filepath.Join(s.StateDir, "update") }
func (s System) updateURL() string {
var v struct {
URL string `json:"url"`
}
if data, err := os.ReadFile(s.updateURLPath()); err == nil {
json.Unmarshal(data, &v)
}
return v.URL
}
func (s System) saveUpdateURL(u string) error {
data, _ := json.Marshal(struct {
URL string `json:"url"`
}{u})
if err := os.MkdirAll(filepath.Dir(s.updateURLPath()), 0o700); err != nil {
return err
}
return writeFileAtomic(s.updateURLPath(), data, 0o600)
}
// parseUpdateURL accepts the base of an update server: http or https, no
// credentials, no query. The data is signed, so plain HTTP is no risk to the
// router; it only lets an attacker withhold updates.
func parseUpdateURL(v string) (string, error) {
v = strings.TrimRight(strings.TrimSpace(v), "/")
u, err := url.Parse(v)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil ||
u.RawQuery != "" || u.Fragment != "" {
return "", errors.New("an http:// or https:// address without credentials")
}
return v, nil
}
// Available is what the update server offers.
type Available struct {
Release
Newer bool
}
func (s System) checkUpdate(base string) (Available, error) {
client := &http.Client{Timeout: 15 * time.Second}
resp, err := client.Get(base + "/latest")
if err != nil {
return Available{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return Available{}, fmt.Errorf("the server answered %s", resp.Status)
}
var a Available
if err := json.NewDecoder(io.LimitReader(resp.Body, maxLatest)).Decode(&a); err != nil || a.Version == "" {
return Available{}, errors.New("the server's latest file is not an update description")
}
a.Newer = a.Serial > s.installedRelease().Serial
return a, nil
}
// request asks the router-update unit to install; it reads this file.
// requestUpdate asks the router-update unit to install what is staged; it
// reads this file. (Updates from the repository are router-upgrade's.)
func (s System) requestUpdate(mode, url string, force bool) error {
data, _ := json.Marshal(map[string]any{"mode": mode, "url": url, "force": force})
if err := os.MkdirAll(s.updateDir(), 0o700); err != nil {
@@ -251,7 +193,6 @@ func updateProgress(log string) (int, string) {
pct int
what string
}{
{"router-update: fetching", 10, "Fetching the release from the repository"},
{"router-update: verifying", 10, "Verifying the signature"},
{"router-update: importing", 30, "Importing the release"},
{"router-update: installed", 50, "Checking the version"},
@@ -272,14 +213,7 @@ type updateData struct {
Progress int // percent, while updating
Step string // what it does now
Status UpdateStatus
URL string
Offer *Available
OfferErr string
Pending bool // an update waits for confirmation
Repository string // router.update.repository
Git *GitCheck // what the last look at it found
GitRun UpdateStatus // the look that is running or ran last
}
func (a *app) updateData() updateData {
@@ -287,13 +221,7 @@ func (a *app) updateData() updateData {
d := updateData{
Installed: a.sys.installedRelease(),
Status: a.sys.UpdateStatus(),
URL: a.sys.updateURL(),
Pending: st.RollbackIn > 0,
GitRun: unitRun(gitCheckUnit),
}
if s, err := loadSettings(a.sys.settingsPath()); err == nil {
d.Repository = s.repository()
d.Git = a.gitCheck(d.Repository)
}
d.Progress, d.Step = updateProgress(d.Status.Log)
return d
@@ -313,7 +241,7 @@ func (a *app) updatesData() updatesData {
func (a *app) updatePage(w http.ResponseWriter, r *http.Request, sess session) {
d := a.updatesData()
p := page{Title: "Updates", CSRF: sess.csrf, LoggedIn: true, Data: d, Flash: r.URL.Query().Get("msg")}
if d.Update.Status.Running || d.Upgrade.Run.Running || d.Update.GitRun.Running {
if d.Update.Status.Running || d.Upgrade.Run.Running {
p.Live = 3
}
a.render(w, "update", p)
@@ -333,56 +261,6 @@ func (a *app) busy() bool {
return st.Applying || st.ConfirmRunning || st.RollbackIn > 0 || a.sys.UpdateStatus().Running || a.sys.UpgradeStatus().Running
}
func (a *app) updateSaveURL(w http.ResponseWriter, r *http.Request, _ session) {
v := strings.TrimSpace(r.PostFormValue("url"))
if v != "" {
var err error
if v, err = parseUpdateURL(v); err != nil {
a.updateBack(w, r, "Not saved: "+err.Error())
return
}
}
if err := a.sys.saveUpdateURL(v); err != nil {
a.updateBack(w, r, "Not saved: "+err.Error())
return
}
a.updateBack(w, r, "Saved.")
}
func (a *app) updateCheck(w http.ResponseWriter, r *http.Request, sess session) {
d := a.updatesData()
p := page{Title: "Updates", CSRF: sess.csrf, LoggedIn: true}
if d.Update.URL == "" {
a.updateBack(w, r, "Set the update server first.")
return
}
offer, err := a.sys.checkUpdate(d.Update.URL)
if err != nil {
d.Update.OfferErr = err.Error()
} else {
d.Update.Offer = &offer
}
p.Data = d
a.render(w, "update", p)
}
func (a *app) updateInstall(w http.ResponseWriter, r *http.Request, _ session) {
if a.busy() {
a.updateBack(w, r, "Another change is in progress or waiting for confirmation.")
return
}
u := a.sys.updateURL()
if u == "" {
a.updateBack(w, r, "Set the update server first.")
return
}
if err := a.sys.requestUpdate("url", u, r.PostFormValue("force") == "on"); err != nil {
a.updateBack(w, r, "Could not start the update: "+err.Error())
return
}
a.updateBack(w, r, "Updating.")
}
// updateUpload takes a bundle as multipart/form-data and streams it into the
// staging directory; a bundle is hundreds of megabytes. The CSRF token is in
// the query string, since the body must not be read before it is checked.
+5 -62
View File
@@ -116,53 +116,6 @@ func TestUnbundleRefusesHostileBundles(t *testing.T) {
}
}
func TestParseUpdateURL(t *testing.T) {
for in, want := range map[string]string{
"https://updates.example.com/router/": "https://updates.example.com/router",
" http://192.168.1.5:8000 ": "http://192.168.1.5:8000",
} {
if got, err := parseUpdateURL(in); err != nil || got != want {
t.Errorf("%q: %q %v", in, got, err)
}
}
for _, in := range []string{"", "ftp://x/y", "file:///etc", "https://user:pw@host/x", "https://host/x?y=1", "updates.example.com", "https://"} {
if _, err := parseUpdateURL(in); err == nil {
t.Errorf("%q accepted", in)
}
}
}
func TestCheckUpdate(t *testing.T) {
a, sys := newTestApp(t)
_ = a
sys.ReleaseFile = filepath.Join(t.TempDir(), "router-release")
os.WriteFile(sys.ReleaseFile, []byte(`{"version":"0.2.0","serial":1000,"schema":0}`), 0o600)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/new/latest":
w.Write([]byte(`{"release":"/nix/store/x","version":"0.3.0","serial":2000,"schema":1}`))
case "/same/latest":
w.Write([]byte(`{"version":"0.2.0","serial":1000}`))
case "/junk/latest":
w.Write([]byte(`hello`))
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
if o, err := sys.checkUpdate(srv.URL + "/new"); err != nil || !o.Newer || o.Version != "0.3.0" {
t.Fatalf("new: %+v %v", o, err)
}
if o, err := sys.checkUpdate(srv.URL + "/same"); err != nil || o.Newer {
t.Fatalf("same: %+v %v", o, err)
}
for _, p := range []string{"/junk", "/missing"} {
if _, err := sys.checkUpdate(srv.URL + p); err == nil {
t.Fatalf("%s: no error", p)
}
}
}
func upload(t *testing.T, h http.Handler, token string, cookie *http.Cookie, bundle []byte, force bool) *httptest.ResponseRecorder {
t.Helper()
var body bytes.Buffer
@@ -227,21 +180,11 @@ func TestUpdateUploadAndInstall(t *testing.T) {
t.Fatalf("not staged: %v", err)
}
// Pulling: the saved server, through install.
if rec := do(h, "POST", "/update/url", url.Values{"csrf": {token}, "url": {"ftp://nope"}}, cookie); !strings.Contains(rec.Header().Get("Location"), "Not+saved") {
t.Fatalf("bad url: %q", rec.Header().Get("Location"))
}
do(h, "POST", "/update/url", url.Values{"csrf": {token}, "url": {"http://192.168.10.60:8000/"}}, cookie)
if sys.updateURL() != "http://192.168.10.60:8000" {
t.Fatalf("url: %q", sys.updateURL())
}
do(h, "POST", "/update/install", url.Values{"csrf": {token}}, cookie)
data, _ = os.ReadFile(filepath.Join(sys.updateDir(), "request.json"))
if !strings.Contains(string(data), `"mode":"url"`) || !strings.Contains(string(data), "192.168.10.60:8000") {
t.Fatalf("request: %s", data)
}
if page := do(h, "GET", "/update", nil, cookie).Body.String(); !strings.Contains(page, "192.168.10.60:8000") {
t.Fatalf("the page lacks the saved server:\n%s", page)
// The page has no update server any more.
for _, p := range []string{"/update/url", "/update/install", "/update/check"} {
if rec := do(h, "POST", p, url.Values{"csrf": {token}}, cookie); rec.Code != 404 && rec.Code != 405 {
t.Fatalf("%s still exists: %d", p, rec.Code)
}
}
}
+43 -14
View File
@@ -43,9 +43,23 @@ var (
// releaseOf is the release (26.11) of a version like 26.11.20261027.31ecbac.
func releaseOf(version string) string { return releaseRe.FindString(version) }
// UpgradeCheck is check.json: the channel's newest revision against the running one.
// RouterCheck is what the repository has: its newest release tag against the
// installed version of nixos-router.
type RouterCheck struct {
Repository string `json:"repository"`
Installed string `json:"installed"`
Newest struct {
Tag string `json:"tag"`
Version string `json:"version"`
Rev string `json:"rev"`
} `json:"newest"`
Newer bool `json:"newer"`
}
// UpgradeCheck is check.json: the newest nixos-router and the channel's newest
// nixpkgs revision, against the installed and the running ones.
type UpgradeCheck struct {
Channel string `json:"channel"`
Channel string `json:"channel"` // "" if no channel is followed
Branch string `json:"branch"`
Time string `json:"time"`
Running struct {
@@ -55,7 +69,17 @@ type UpgradeCheck struct {
Newest struct {
Rev string `json:"rev"`
} `json:"newest"`
UpToDate bool `json:"upToDate"`
PackagesUpToDate bool `json:"packagesUpToDate"`
UpToDate bool `json:"upToDate"` // both
Router *RouterCheck `json:"router"` // nil if the repository could not be read
}
// RouterChange is the update of nixos-router that a preview includes.
type RouterChange struct {
From string `json:"from"`
To string `json:"to"`
Tag string `json:"tag"`
Rev string `json:"rev"`
}
// UpgradeChange is a package that has another version in the new system.
@@ -76,6 +100,7 @@ type UpgradePreview struct {
Builds int `json:"builds"`
BuildNames []string `json:"buildNames"` // what would be built here
RebootNeeded bool `json:"rebootNeeded"`
Router *RouterChange `json:"router"` // nixos-router changes too
Changes []UpgradeChange `json:"changes"`
}
@@ -154,13 +179,15 @@ var upgradeTitles = map[string]string{
type channelChoice struct{ Value, Label string }
type upgradeData struct {
Version string // the running NixOS version
Channel string
Choices []channelChoice
Check *UpgradeCheck
Preview *UpgradePreview
Run UpgradeRun
Title string // what the running step does
Router Release // the installed nixos-router
Repository string // where its releases come from
Version string // the running NixOS version
Channel string
Choices []channelChoice
Check *UpgradeCheck
Preview *UpgradePreview
Run UpgradeRun
Title string // what the running step does
NewerRelease string // a stable release newer than the followed channel exists
ReleasesSeen string // when the channel server was last asked which exist
@@ -263,7 +290,8 @@ func channelChoices(current string, stable []string) []channelChoice {
}
func (a *app) upgradeData() upgradeData {
d := upgradeData{Version: a.sys.runningVersion(), Run: a.sys.UpgradeStatus()}
d := upgradeData{Version: a.sys.runningVersion(), Run: a.sys.UpgradeStatus(),
Router: a.sys.installedRelease(), Repository: a.sys.repository()}
d.Updating = a.sys.UpdateStatus().Running
d.Pending = a.sys.Status().RollbackIn > 0
if s, err := loadSettings(a.sys.settingsPath()); err == nil {
@@ -287,7 +315,8 @@ func (a *app) upgradeData() upgradeData {
// What was checked before another channel was chosen or before the last
// upgrade says nothing about now; nor does a preview that another
// nixos-router made (it may list packages differently).
if readUpgradeFile(filepath.Join(a.sys.upgradeDir(), "check.json"), &c) && c.Channel == d.Channel && c.Running.Version == d.Version {
if readUpgradeFile(filepath.Join(a.sys.upgradeDir(), "check.json"), &c) && c.Channel == d.Channel && c.Running.Version == d.Version &&
(c.Router == nil || c.Router.Installed == a.sys.installedRelease().Version) {
d.Check = &c
}
var p UpgradePreview
@@ -344,8 +373,8 @@ func (a *app) upgradeStep(w http.ResponseWriter, r *http.Request, _ session) {
return
}
d := a.upgradeData()
if d.Channel == "" {
a.upgradeBack(w, r, "Choose a channel first.")
if d.Channel == "" && d.Repository == "" {
a.upgradeBack(w, r, "Choose a channel first: this router has no repository to look at either.")
return
}
if (action == "download" || action == "apply") && d.Preview == nil {
+9 -4
View File
@@ -46,11 +46,16 @@ func TestOneUpdatesPage(t *testing.T) {
t.Fatalf("/upgrade: %d %q", rec.Code, rec.Header().Get("Location"))
}
body := do(h, "GET", "/update", nil, cookie).Body.String()
for _, want := range []string{"Router software", "Install a bundle", "Update server", `id="packages"`, "Choose a channel", `aria-current="page">Updates`} {
for _, want := range []string{"Install a bundle", `id="packages"`, "Choose a channel", `aria-current="page">Updates`} {
if !strings.Contains(body, want) {
t.Errorf("the page lacks %q", want)
}
}
for _, not := range []string{"Update server", "Releases from git", "Look for a newer release"} {
if strings.Contains(body, not) {
t.Errorf("the page still has %q", not)
}
}
if strings.Contains(body, `href="/upgrade"`) {
t.Error("the menu still links /upgrade")
}
@@ -245,7 +250,7 @@ func TestUpgradePage(t *testing.T) {
t.Run("the last run's output is shown", func(t *testing.T) {
os.WriteFile(filepath.Join(a.sys.upgradeDir(), "last.log"), []byte("channel 26.11 (nixos-26.11)\nup to date\n"), 0o600)
if body := page(); !strings.Contains(body, "Last package run") || !strings.Contains(body, "nixos-26.11)") {
if body := page(); !strings.Contains(body, "Last upgrade run") || !strings.Contains(body, "nixos-26.11)") {
t.Fatalf("no log:\n%s", body)
}
if got := tail("a\nbb\nccc\n", 6); got != "ccc\n" {
@@ -280,11 +285,11 @@ func TestUpgradePage(t *testing.T) {
post("/upgrade/channel", url.Values{"channel": {"26.05"}})
check := `{"channel":"26.05","branch":"nixos-26.05","time":"2026-11-09T10:00:00Z","running":{"rev":"aaa","version":"%s"},"newest":{"rev":"0123456789abcdef"},"upToDate":false}`
os.WriteFile(filepath.Join(a.sys.upgradeDir(), "check.json"), []byte(strings.Replace(check, "%s", "26.11.20261001.old", 1)), 0o600)
if strings.Contains(page(), "A newer revision is available") {
if strings.Contains(page(), "A newer version is available") {
t.Fatal("an outdated check is shown")
}
os.WriteFile(filepath.Join(a.sys.upgradeDir(), "check.json"), []byte(strings.Replace(check, "%s", "26.11.20261027.31ecbac", 1)), 0o600)
if body := page(); !strings.Contains(body, "A newer revision is available") || !strings.Contains(body, "0123456") {
if body := page(); !strings.Contains(body, "A newer version is available") || !strings.Contains(body, "0123456") {
t.Fatalf("the current check is not shown:\n%s", body)
}
})
+36 -2
View File
@@ -1,16 +1,23 @@
# Signs $release (a store path) as a binary cache and writes, into --out:
# router-update-<version>.bundle one file to upload in the web UI
# latest, cache/ the same, laid out for `router pulls from a URL`
# usage: router-release --key KEYFILE [--out DIR] [--compression zstd|none]
#
# Run in a git checkout it also tags the commit that was released (vX.Y.Z, the
# tags routers that update from the repository look for). The tag is local: it
# has to be pushed with the branch. It is made last, so a release that fails
# leaves no tag.
# usage: router-release --key KEYFILE [--out DIR] [--compression zstd|none] [--no-tag]
key=""
out=dist
compression=zstd
tag=1
while [ $# -gt 0 ]; do
case $1 in
--key) key=$2; shift ;;
--out) out=$2; shift ;;
--compression) compression=$2; shift ;;
*) echo "usage: router-release --key KEYFILE [--out DIR] [--compression zstd|none]" >&2; exit 2 ;;
--no-tag) tag=0 ;;
*) echo "usage: router-release --key KEYFILE [--out DIR] [--compression zstd|none] [--no-tag]" >&2; exit 2 ;;
esac
shift
done
@@ -28,3 +35,30 @@ tar -C "$out" -cf "$out/router-update-$version.bundle" latest cache
echo "release $version ($(du -h "$out/router-update-$version.bundle" | cut -f1)):"
echo " upload $out/router-update-$version.bundle in the router's web UI (Update)"
echo " or serve $out over HTTP(S) and give the router that URL"
if [ "$tag" -eq 1 ]; then
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo " tag none: not in a git repository"
else
head_version=$(git show HEAD:VERSION 2>/dev/null | tr -d '\n' || true)
if [ "$head_version" != "$version" ]; then
echo "router-release: the commit at HEAD is version '$head_version', not $version: not tagged" >&2
echo " (commit the version, then: git tag -a v$version -m 'Release $version')" >&2
exit 1
fi
head=$(git rev-parse HEAD)
if git rev-parse -q --verify "refs/tags/v$version" >/dev/null; then
if [ "$(git rev-parse "v$version^{commit}")" != "$head" ]; then
echo "router-release: v$version is already a tag of another commit" >&2
exit 1
fi
echo " tag v$version exists"
else
git tag -a "v$version" -m "Release $version"
echo " tag v$version on ${head:0:7}: push it with the branch (git push origin v$version)"
fi
if [ "$(cat "$release/rev")" != "$head" ]; then
echo " note the release was built from a tree that differs from HEAD (uncommitted changes)"
fi
fi
fi
+5 -3
View File
@@ -47,6 +47,8 @@ let
{ modulesPath, ... }:
{
imports = [ (modulesPath + "/testing/test-instrumentation.nix") ];
# No release repository: this test is about the packages (update.nix has one).
routerUpdate.repository = null;
routerSettings.upgrade = {
channelsUrl = "http://192.168.10.50:8080";
nixpkgsRef = "path:/var/lib/newer-nixpkgs?lastModified=${toString self.inputs.nixpkgs.lastModified}&rev=%rev%";
@@ -352,7 +354,7 @@ pkgs.testers.runNixOSTest {
rev = "0123456789abcdef0123456789abcdef01234567"
channel(rev)
out = target.succeed("router-upgrade check 2>&1")
assert "a newer revision is available" in out, out
assert "a newer version is available" in out, out
assert json.loads(target.succeed("cat /var/lib/router/upgrade/check.json"))["upToDate"] is False
channel(running_rev)
out = target.succeed("router-upgrade check 2>&1")
@@ -448,7 +450,7 @@ pkgs.testers.runNixOSTest {
assert curl(f"-o /dev/null -w '%{{redirect_url}}' {ui}/upgrade").endswith("/update#packages")
page = curl(f"{ui}/update")
assert "Packages" in page and "Router software" in page and 'value="26.05" selected' in page and target.succeed("cat /run/current-system/nixos-version").strip() in page, page
assert "Check for upgrades" in page and "Install a bundle" in page and 'value="26.05" selected' in page and target.succeed("cat /run/current-system/nixos-version").strip() in page, page
assert curl(f"-o /dev/null -w '%{{http_code}}' -d csrf={csrf('/update')} -d 'channel=nixos-26.05%3Bx' {ui}/upgrade/channel") == "303"
assert "26.05" in target.succeed("jq -r .router.update.channel /var/lib/router/config/settings.json")
assert curl(f"-o /dev/null -w '%{{http_code}}' -d csrf=wrong {ui}/upgrade/check") == "403"
@@ -461,6 +463,6 @@ pkgs.testers.runNixOSTest {
step("apply")
assert "Upgrade to" not in curl(f"{ui}/update")
assert json.loads(target.succeed("cat /var/lib/router/config/nixpkgs-pin.json"))["rev"] == running_rev
assert "Last package run" in curl(f"{ui}/update")
assert "Last upgrade run" in curl(f"{ui}/update")
'';
}
+49 -35
View File
@@ -125,6 +125,8 @@ let
{
imports = [ (modulesPath + "/testing/test-instrumentation.nix") ];
router.rollback.timeout = "90s";
# Releases from git: the builder's repository, not the real one.
routerUpdate.repository = "http://${builderIp}:8005/router.git";
routerSettings.upgrade = {
channelsUrl = "http://192.168.10.60:8080";
nixpkgsRef = "path:/var/lib/newer-nixpkgs?lastModified=${toString self.inputs.nixpkgs.lastModified}&rev=%rev%";
@@ -349,14 +351,15 @@ pkgs.testers.runNixOSTest {
pinned()
target.wait_for_unit("router-webui.service")
with subtest("the same update, pulled from a server in the web UI, can be confirmed"):
with subtest("the same update, pulled from a server, can be confirmed in the web UI"):
login()
token = csrf("/update")
form = lambda path, data: builder.succeed(
f"curl -sk -b /tmp/jar -o /tmp/out -w '%{{http_code}}' --data-urlencode csrf={token} {data} {ui}{path}").strip()
assert form("/update/url", "--data-urlencode url=http://${builderIp}:8004/") == "303"
assert "Available: <strong>2.0.0</strong>" in (form("/update/check", "") and builder.succeed("cat /tmp/out"))
assert form("/update/install", "") == "303"
# The page has no update server to set any more; the command line still pulls.
page = builder.succeed(f"curl -sk -b /tmp/jar {ui}/update")
assert "Update server" not in page, page
# (As the unit, like the web UI starts it: the switch restarts the web UI.)
target.succeed("mkdir -p /var/lib/router/update"
" && echo '{\"mode\":\"url\",\"url\":\"http://${builderIp}:8004\",\"force\":false}' > /var/lib/router/update/request.json"
" && systemctl start --no-block router-update.service")
update_finished()
assert version() == "2.0.0"
target.succeed("systemctl is-active router-rollback.timer")
@@ -380,7 +383,14 @@ pkgs.testers.runNixOSTest {
assert rc != 0 and "not newer" in out, out
assert version() == "2.0.0"
with subtest("a release in a git repository is found, built and installed like a bundle"):
def upgrade_finished():
target.wait_until_succeeds(
"state=$(systemctl show -p ActiveState --value router-upgrade.service);"
" test $state = inactive -o $state = failed", timeout=300)
result = target.succeed("systemctl show -p Result --value router-upgrade.service").strip()
assert result == "success", (result, target.succeed("journalctl -u router-upgrade.service --no-pager | tail -30"))
with subtest("a release in a git repository is found with the packages, previewed and installed like any upgrade"):
repo = "http://${builderIp}:8005/router.git"
builder.succeed("cp -r ${v3.src} /root/v3 && chmod -R u+w /root/v3")
builder.succeed("cd /root/v3 && git init -q -b main && git add -A"
@@ -390,37 +400,42 @@ pkgs.testers.runNixOSTest {
builder.succeed("systemd-run --unit=git-server /etc/git-server.py /srv/git 8005")
builder.wait_for_open_port(8005, "${builderIp}")
# Nothing to look at until a repository is named.
assert "no repository" in target.succeed("router-update check 2>&1")
# The repository is part of the installed version; the page names it and has no field for it.
assert target.succeed("cat /etc/router-update-repository").strip() == repo
login()
token = csrf("/update")
page = builder.succeed(f"curl -sk -b /tmp/jar {ui}/update")
assert repo in page and 'name="repository"' not in page, page
form = lambda path, data: builder.succeed(
f"curl -sk -b /tmp/jar -o /tmp/out -w '%{{http_code}}' --data-urlencode csrf={token} {data} {ui}{path}").strip()
assert form("/update/repository", f"--data-urlencode repository={repo}/") == "303"
assert form("/update/gitcheck", "") == "303"
target.wait_until_succeeds(
"test $(systemctl show -p ActiveState --value router-update-check.service) = inactive"
" && test $(systemctl show -p Result --value router-update-check.service) = success", timeout=120)
check = json.loads(target.succeed("cat /var/lib/router/update/check.json"))
assert check["newer"] is True and check["newest"] == {"tag": "v3.0.0", "version": "3.0.0", "rev": commit} and check["installed"] == "2.0.0", check
assert form("/update/repository", f"--data-urlencode repository={repo}") in ("404", "405")
assert form("/update/gitcheck", "") in ("404", "405")
# One check looks at both: the repository and the channel.
assert form("/upgrade/check", "") == "303"
upgrade_finished()
check = json.loads(target.succeed("cat /var/lib/router/upgrade/check.json"))
assert check["router"]["newer"] is True and check["router"]["newest"] == {"tag": "v3.0.0", "version": "3.0.0", "rev": commit}, check
assert check["router"]["installed"] == "2.0.0" and check["packagesUpToDate"] is True and check["upToDate"] is False, check
assert "nixos-router 3.0.0 is out" in builder.succeed(f"curl -sk -b /tmp/jar {ui}/")
assert "Install 3.0.0" in builder.succeed(f"curl -sk -b /tmp/jar {ui}/update")
page = builder.succeed(f"curl -sk -b /tmp/jar {ui}/update")
assert "<strong>3.0.0</strong>" in page and "A newer version is available" in page, page
# Only tags that are versions are releases; a newer tag of another kind is ignored.
builder.succeed("cd /root/v3 && git tag nightly && git tag v4.0 && git push -q /srv/git/router.git nightly v4.0")
target.succeed("router-update check >&2")
assert json.loads(target.succeed("cat /var/lib/router/update/check.json"))["newest"]["tag"] == "v3.0.0"
target.succeed("router-upgrade check >&2")
assert json.loads(target.succeed("cat /var/lib/router/upgrade/check.json"))["router"]["newest"]["tag"] == "v3.0.0"
rc, out = target.execute("router-update --git v9.9.9 2>&1")
assert rc != 0 and "no such release tag" in out, out
rc, out = target.execute("router-update --git 'v3.0.0; reboot' 2>&1")
assert rc != 0 and "not a release tag" in out, out
assert version() == "2.0.0"
# The preview names the router's own update, in the table with the packages.
assert form("/upgrade/preview", "") == "303"
upgrade_finished()
preview = json.loads(target.succeed("cat /var/lib/router/upgrade/preview.json"))
assert preview["router"]["from"] == "2.0.0" and preview["router"]["to"] == "3.0.0", preview
page = builder.succeed(f"curl -sk -b /tmp/jar {ui}/update")
assert 'class="highlight"' in page and "<td>nixos-router</td>" in page and "Upgrade nixos-router to 3.0.0 and" in page, page
# Nothing has changed on the router until the upgrade is applied.
assert version() == "2.0.0" and "v3.0.0" not in target.succeed("cat /var/lib/router/config/flake.nix")
login()
token = csrf("/update")
assert form("/update/gitinstall", "--data-urlencode tag=v3.0.0") == "303"
update_finished()
target.succeed("router-upgrade apply 5min >&2")
assert version() == "3.0.0", release_json()
flake = target.succeed("cat /var/lib/router/config/flake.nix")
assert f"git+{repo}?ref=refs/tags/v3.0.0&rev={commit}" in flake, flake
@@ -429,7 +444,6 @@ pkgs.testers.runNixOSTest {
assert locked["type"] == "git" and locked["rev"] == commit, locked
settings = target.succeed("cat /var/lib/router/config/settings.json")
assert '"version": 2' in settings and "Europe/Paris" in settings, settings
assert "router-update-check" not in settings
pinned()
target.succeed("systemctl is-active router-rollback.timer")
login()
@@ -445,10 +459,10 @@ pkgs.testers.runNixOSTest {
assert "no changes" in out, out
builder.succeed("systemd-run --unit=git-server-again /etc/git-server.py /srv/git 8005")
builder.wait_for_open_port(8005, "${builderIp}")
target.succeed("router-update check >&2")
check = json.loads(target.succeed("cat /var/lib/router/update/check.json"))
assert check["newer"] is False and check["installed"] == "3.0.0", check
rc, out = target.execute("router-update --git latest 2>&1")
assert rc != 0 and "not newer" in out, out
target.succeed("router-upgrade check >&2")
check = json.loads(target.succeed("cat /var/lib/router/upgrade/check.json"))
assert check["router"]["newer"] is False and check["router"]["installed"] == "3.0.0" and check["upToDate"] is True, check
out = target.succeed("router-upgrade preview 2>&1")
assert "up to date" in out, out
'';
}