Update from a git repository

router.update.repository names a public repository whose tags vX.Y.Z are
releases. router-update check (daily, and from the Updates page) looks for a
newer one and the Overview says so; router-update --git builds the router
from a tag like a bundle update: the settings are migrated, the new version
must be confirmed, the nixpkgs pin stays. The flake of such a router comes
from the release's config-flake.nix. The global flake registry is off.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 08:57:00 +01:00
co-authored by Claude Sonnet 5.5
parent a2dbeb5dea
commit 3fc54e678e
13 changed files with 589 additions and 26 deletions
+4 -4
View File
@@ -290,10 +290,10 @@ Package upgrades (see above)
- **Real package changes in tests**: the upgrade tests use an identical nixpkgs copy, so no real version change is ever exercised. - **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: - **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). 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. `router.update.repository` (a git URL). A daily check (`git ls-remote --tags`, newest `vX.Y.Z`) shows "0.x.y is available" on the Overview, like the release notice. 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.
3. Preview and apply lock the configuration flake to the tag (`--override-input nixos-router git+<url>?rev=…`) next to the nixpkgs pin, evaluate once and show the package changes, download and builds of both together; the serial guard and the settings migration run as for bundles. 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. A release is a tag on the commit (`router-release` can still write a bundle for offline routers and the installer). The nixpkgs in the repository's `flake.lock` must be a revision of a channel (`git-revision`), so cache.nixos.org has its packages. 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.
5. VM test with a git server in the client VM (`git+http://`), as `channelServer` stands in for channels.nixos.org. 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). Bundles and `--url` stay (offline, installer, gitea down).
Web UI polish (list of 2026-11-24) Web UI polish (list of 2026-11-24)
+22
View File
@@ -0,0 +1,22 @@
# 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
# 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.
#
# The release (version, commit time, settings schema) is the flake's own: an
# input from git has its commit, unlike the `path:` input of a bundle's flake.
#
# This is a contract between the updater that is installed and the release it
# installs: change it only in a way every earlier updater can still write.
{
inputs.nixos-router.url = "@SOURCE@";
outputs =
{ nixos-router, ... }:
{
nixosConfigurations.router = nixos-router.lib.mkRouterSystem {
settings = ./settings.json;
modules = if builtins.pathExists ./local.nix then [ ./local.nix ] else [ ];
};
};
}
+14
View File
@@ -440,6 +440,20 @@ 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 { update.channel = mkOption {
type = types.nullOr (types.strMatching "unstable|[0-9]{2}\\.[0-9]{2}"); type = types.nullOr (types.strMatching "unstable|[0-9]{2}\\.[0-9]{2}");
default = null; default = null;
+131 -13
View File
@@ -55,12 +55,16 @@ let
migrate migrate
pkgs.coreutils pkgs.coreutils
pkgs.curl pkgs.curl
pkgs.git
pkgs.gawk
pkgs.jq pkgs.jq
pkgs.util-linux pkgs.util-linux
]; ];
text = '' text = ''
usage() { usage() {
echo "usage: router-update [--force] (--request | --bundle FILE | --url URL) [timeout]" >&2 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 " --bundle FILE a bundle made by router-release" >&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 " --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 echo " --request what the web UI asked for (${updateDir}/request.json)" >&2
@@ -72,9 +76,11 @@ let
force=0 mode="" arg="" timeout="" force=0 mode="" arg="" timeout=""
while [ $# -gt 0 ]; do while [ $# -gt 0 ]; do
case $1 in case $1 in
check) mode=check ;;
--force) force=1 ;; --force) force=1 ;;
--bundle) shift; [ $# -gt 0 ] || usage; mode=bundle arg=$1 ;; --bundle) shift; [ $# -gt 0 ] || usage; mode=bundle arg=$1 ;;
--url) shift; [ $# -gt 0 ] || usage; mode=url arg=$1 ;; --url) shift; [ $# -gt 0 ] || usage; mode=url arg=$1 ;;
--git) shift; [ $# -gt 0 ] || usage; mode=git arg=$1 ;;
--request) --request)
req=${updateDir}/request.json req=${updateDir}/request.json
[ -r "$req" ] || die "no request" [ -r "$req" ] || die "no request"
@@ -88,11 +94,60 @@ let
done done
[ -n "$mode" ] || usage [ -n "$mode" ] || usage
[ "$(id -u)" -eq 0 ] || die "must run as root" [ "$(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 exec 9>/run/router-update.lock
flock -n 9 || die "another update is running" flock -n 9 || die "another update is running"
trusted=$(tr '\n' ' ' < /etc/router-update-keys) # Bundles and servers are signed; a git repository is trusted as it is.
[ -n "''${trusted// /}" ] || die "this router has no update key" trusted=""
if [ "$mode" != git ]; then
trusted=$(tr '\n' ' ' < /etc/router-update-keys)
[ -n "''${trusted// /}" ] || die "this router has no update key"
fi
staged=${updateDir}/staged staged=${updateDir}/staged
case $mode in case $mode in
@@ -109,20 +164,56 @@ let
base=''${arg%/} base=''${arg%/}
store="$base/cache" store="$base/cache"
latest=$(curl -fsS --max-time 30 "$base/latest") ;; latest=$(curl -fsS --max-time 30 "$base/latest") ;;
git) ;;
*) usage ;; *) usage ;;
esac esac
release=$(jq -er .release <<<"$latest") || die "the update has no release" if [ "$mode" = git ]; then
[[ $release =~ ^/nix/store/[0-9a-z]{32}-[A-Za-z0-9+._-]+$ ]] || die "not a store path: $release" 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"
# Nothing is trusted until every path of the closure is signed by our key. # Nothing is trusted until every path of the closure is signed by our key.
echo "router-update: verifying $release" echo "router-update: verifying $release"
nix --option trusted-public-keys "$trusted" store verify \ nix --option trusted-public-keys "$trusted" store verify \
--store "$store" --no-contents --sigs-needed 1 -r "$release" \ --store "$store" --no-contents --sigs-needed 1 -r "$release" \
|| die "the update is not signed with this router's update key" || die "the update is not signed with this router's update key"
echo "router-update: importing it" echo "router-update: importing it"
nix --option trusted-public-keys "$trusted" copy --from "$store" "$release" nix --option trusted-public-keys "$trusted" copy --from "$store" "$release"
rm -rf "$staged" rm -rf "$staged"
fi
new_version=$(cat "$release/version") new_version=$(cat "$release/version")
new_serial=$(cat "$release/serial") new_serial=$(cat "$release/serial")
@@ -214,6 +305,28 @@ in
router.rollback.onRollback = "${restore}/bin/router-update-restore"; router.rollback.onRollback = "${restore}/bin/router-update-restore";
router.rollback.onConfirm = "rm -rf ${snapshot}"; 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 = { systemd.services.router-update = {
description = "Install a router update"; description = "Install a router update";
restartIfChanged = false; restartIfChanged = false;
@@ -226,6 +339,11 @@ in
}; };
}; };
# The router's flakes name their inputs in full; nix would otherwise try to
# download the global registry (channels.nixos.org) for a git input and
# fail, slowly, without the internet.
nix.settings.flake-registry = lib.mkDefault "";
# Old generations (and the updates' leftovers) would fill the disk. # Old generations (and the updates' leftovers) would fill the disk.
nix.gc = { nix.gc = {
automatic = true; automatic = true;
+115
View File
@@ -0,0 +1,115 @@
package main
import (
"net/http"
"net/url"
"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.
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"`
}
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).
func (a *app) newRouterVersion() string {
s, err := loadSettings(a.sys.settingsPath())
if err != nil {
return ""
}
if c := a.gitCheck(s.repository()); c != nil && c.Newer {
return c.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.")
}
+102
View File
@@ -0,0 +1,102 @@
package main
import (
"encoding/json"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
)
func TestUpdatesFromGit(t *testing.T) {
a, sys := newTestApp(t)
sys.ReleaseFile = filepath.Join(t.TempDir(), "router-release")
os.WriteFile(sys.ReleaseFile, []byte(`{"version":"1.0.0","serial":1000}`), 0o600)
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)
}
}
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 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())
}
// 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)
}
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)
}
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)
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)
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)
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)
}
}
+5 -1
View File
@@ -341,6 +341,9 @@ func (a *app) routes() http.Handler {
mux.HandleFunc("POST /update/url", a.auth(a.updateSaveURL)) mux.HandleFunc("POST /update/url", a.auth(a.updateSaveURL))
mux.HandleFunc("POST /update/check", a.auth(a.updateCheck)) mux.HandleFunc("POST /update/check", a.auth(a.updateCheck))
mux.HandleFunc("POST /update/install", a.auth(a.updateInstall)) 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("POST /update/upload", a.updateUpload)
mux.HandleFunc("GET /upgrade", a.auth(upgradeRedirect)) mux.HandleFunc("GET /upgrade", a.auth(upgradeRedirect))
mux.HandleFunc("POST /upgrade/channel", a.auth(a.upgradeChannel)) mux.HandleFunc("POST /upgrade/channel", a.auth(a.upgradeChannel))
@@ -491,12 +494,13 @@ type overviewData struct {
Status Status Status Status
Dashboard dashboard Dashboard dashboard
NewRelease string // a stable NixOS release newer than the followed channel exists NewRelease string // a stable NixOS release newer than the followed channel exists
NewRouter string // a release of nixos-router is out in the repository
} }
func (a *app) overview(w http.ResponseWriter, r *http.Request, sess session) { func (a *app) overview(w http.ResponseWriter, r *http.Request, sess session) {
st := a.sys.Status() st := a.sys.Status()
p := page{Title: "Overview", CSRF: sess.csrf, LoggedIn: true, Flash: r.URL.Query().Get("msg"), p := page{Title: "Overview", CSRF: sess.csrf, LoggedIn: true, Flash: r.URL.Query().Get("msg"),
Data: overviewData{Status: st, Dashboard: a.dashboardData(r.URL.Query().Get("range")), NewRelease: a.releaseNotice()}} Data: overviewData{Status: st, Dashboard: a.dashboardData(r.URL.Query().Get("range")), NewRelease: a.releaseNotice(), NewRouter: a.newRouterVersion()}}
switch { switch {
case st.Applying || st.ConfirmRunning: case st.Applying || st.ConfirmRunning:
p.Live = 2 p.Live = 2
@@ -22,6 +22,9 @@
</div> </div>
</section> </section>
{{end}} {{end}}
{{with .Data.NewRouter}}
<section class="notice"><p>nixos-router {{.}} is out. <a href="/update">Look at it on the Updates page</a>.</p></section>
{{end}}
{{with .Data.NewRelease}} {{with .Data.NewRelease}}
<section class="notice"><p>NixOS {{.}} is out. <a href="/update#packages">See what it would change</a>.</p></section> <section class="notice"><p>NixOS {{.}} is out. <a href="/update#packages">See what it would change</a>.</p></section>
{{end}} {{end}}
+35
View File
@@ -38,6 +38,41 @@
</dl> </dl>
</section> </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> <section>
<h2>Install a bundle</h2> <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 <p>A <code>.bundle</code> file made with <code>nix run .#release</code>. It is installed only if it is signed with
+11 -1
View File
@@ -251,6 +251,7 @@ func updateProgress(log string) (int, string) {
pct int pct int
what string what string
}{ }{
{"router-update: fetching", 10, "Fetching the release from the repository"},
{"router-update: verifying", 10, "Verifying the signature"}, {"router-update: verifying", 10, "Verifying the signature"},
{"router-update: importing", 30, "Importing the release"}, {"router-update: importing", 30, "Importing the release"},
{"router-update: installed", 50, "Checking the version"}, {"router-update: installed", 50, "Checking the version"},
@@ -275,6 +276,10 @@ type updateData struct {
Offer *Available Offer *Available
OfferErr string OfferErr string
Pending bool // an update waits for confirmation 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 { func (a *app) updateData() updateData {
@@ -284,6 +289,11 @@ func (a *app) updateData() updateData {
Status: a.sys.UpdateStatus(), Status: a.sys.UpdateStatus(),
URL: a.sys.updateURL(), URL: a.sys.updateURL(),
Pending: st.RollbackIn > 0, 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) d.Progress, d.Step = updateProgress(d.Status.Log)
return d return d
@@ -303,7 +313,7 @@ func (a *app) updatesData() updatesData {
func (a *app) updatePage(w http.ResponseWriter, r *http.Request, sess session) { func (a *app) updatePage(w http.ResponseWriter, r *http.Request, sess session) {
d := a.updatesData() d := a.updatesData()
p := page{Title: "Updates", CSRF: sess.csrf, LoggedIn: true, Data: d, Flash: r.URL.Query().Get("msg")} 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 { if d.Update.Status.Running || d.Upgrade.Run.Running || d.Update.GitRun.Running {
p.Live = 3 p.Live = 3
} }
a.render(w, "update", p) a.render(w, "update", p)
+7 -4
View File
@@ -93,7 +93,10 @@ func (s Settings) channel() string { return str(s, "router", "update", "channel"
// setChannel changes router.update.channel in settings.json and, since it takes // setChannel changes router.update.channel in settings.json and, since it takes
// effect when upgrading rather than when applying, in the confirmed settings // effect when upgrading rather than when applying, in the confirmed settings
// too, so it does not show up as an unapplied change. // too, so it does not show up as an unapplied change.
func (sys System) setChannel(channel string) error { func (sys System) setChannel(channel string) error { return sys.setUpdateField("channel", channel) }
// setUpdateField does that for a key of router.update ("" removes it).
func (sys System) setUpdateField(key, value string) error {
set := func(path string, required bool) error { set := func(path string, required bool) error {
s, err := loadSettings(path) s, err := loadSettings(path)
if err != nil { if err != nil {
@@ -103,15 +106,15 @@ func (sys System) setChannel(channel string) error {
return err return err
} }
router := obj(s, "router") router := obj(s, "router")
if channel == "" { if value == "" {
if u, ok := router["update"].(map[string]any); ok { if u, ok := router["update"].(map[string]any); ok {
delete(u, "channel") delete(u, key)
if len(u) == 0 { if len(u) == 0 {
delete(router, "update") delete(router, "update")
} }
} }
} else { } else {
obj(router, "update")["channel"] = channel obj(router, "update")[key] = value
} }
return s.save(path) return s.save(path)
} }
+46
View File
@@ -39,6 +39,52 @@
http.server.ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever() http.server.ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
''; '';
# A git server over (smart) HTTP: `git http-backend` for the repositories under
# the directory in argv[1], on the port in argv[2]. Enough for ls-remote and fetch.
gitServer =
pkgs:
pkgs.writeScript "git-server.py" ''
#!${pkgs.python3}/bin/python3
import http.server, os, subprocess, sys
root, port = sys.argv[1], int(sys.argv[2])
class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.cgi()
def do_POST(self):
self.cgi()
def cgi(self):
path, _, query = self.path.partition("?")
body = self.rfile.read(int(self.headers.get("Content-Length") or 0))
env = dict(os.environ, GIT_PROJECT_ROOT=root, GIT_HTTP_EXPORT_ALL="1", PATH_INFO=path,
QUERY_STRING=query, REQUEST_METHOD=self.command, REMOTE_ADDR=self.client_address[0],
CONTENT_TYPE=self.headers.get("Content-Type", ""), CONTENT_LENGTH=str(len(body)),
HTTP_CONTENT_ENCODING=self.headers.get("Content-Encoding", ""))
done = subprocess.run(["${pkgs.git}/bin/git", "http-backend"], input=body, env=env, capture_output=True)
head, _, out = done.stdout.partition(b"\r\n\r\n")
status, headers = 200, []
for line in head.split(b"\r\n"):
name, _, value = line.decode().partition(": ")
if name.lower() == "status":
status = int(value.split()[0])
elif name:
headers.append((name, value))
self.send_response(status)
for name, value in headers:
self.send_header(name, value)
self.send_header("Content-Length", str(len(out)))
self.end_headers()
self.wfile.write(out)
def log_message(self, *args):
pass
http.server.ThreadingHTTPServer(("0.0.0.0", port), Handler).serve_forever()
'';
# `driverInteractive` uses the full QEMU, which would open a window per VM; # `driverInteractive` uses the full QEMU, which would open a window per VM;
# `nix run .#lab` wants the consoles in the terminal instead. # `nix run .#lab` wants the consoles in the terminal instead.
interactiveDefaults.virtualisation.qemu.options = [ interactiveDefaults.virtualisation.qemu.options = [
+94 -3
View File
@@ -64,6 +64,18 @@ let
''; '';
}; };
# Version 3 is only a source tree: the builder serves it from a git repository.
v3 = mkVersion {
name = "v3";
version = "3.0.0";
serial = 3000;
extra = ''
rm $out/migrations/*.jq
echo '.system.timeZone = "Europe/Berlin"' > $out/migrations/1.jq
echo '.system.timeZone = "Europe/Paris"' > $out/migrations/2.jq
'';
};
release = release =
v: v:
v.lib.mkRelease { v.lib.mkRelease {
@@ -186,12 +198,17 @@ pkgs.testers.runNixOSTest {
} }
]; ];
networking.firewall.enable = false; networking.firewall.enable = false;
environment.systemPackages = [ pkgs.python3 ]; environment.systemPackages = [
pkgs.python3
pkgs.git
];
virtualisation.additionalPaths = [ virtualisation.additionalPaths = [
release1 release1
release2 release2
v3.src
]; ];
environment.etc."channels.py".source = common.channelServer pkgs; environment.etc."channels.py".source = common.channelServer pkgs;
environment.etc."git-server.py".source = common.gitServer pkgs;
environment.etc."keys/good.sec".source = "${keys}/good.sec"; environment.etc."keys/good.sec".source = "${keys}/good.sec";
environment.etc."keys/evil.sec".source = "${keys}/evil.sec"; environment.etc."keys/evil.sec".source = "${keys}/evil.sec";
}; };
@@ -234,9 +251,12 @@ pkgs.testers.runNixOSTest {
def csrf_from_query(path): def csrf_from_query(path):
return builder.succeed(f"curl -sk -b /tmp/jar {ui}{path} | grep -o 'upload?csrf=[^\"]*' | head -1 | cut -d= -f2").strip() return builder.succeed(f"curl -sk -b /tmp/jar {ui}{path} | grep -o 'upload?csrf=[^\"]*' | head -1 | cut -d= -f2").strip()
def update_finished(): def update_finished():
# Stops at a failed update rather than waiting for one that will not come.
target.wait_until_succeeds( target.wait_until_succeeds(
"test $(systemctl show -p ActiveState --value router-update.service) = inactive" "state=$(systemctl show -p ActiveState --value router-update.service);"
" && test $(systemctl show -p Result --value router-update.service) = success", timeout=900) " test $state = inactive -o $state = failed", timeout=300)
result = target.succeed("systemctl show -p Result --value router-update.service").strip()
assert result == "success", (result, target.succeed("journalctl -u router-update.service --no-pager | tail -30"))
v1_flake = flake_source() v1_flake = flake_source()
@@ -359,5 +379,76 @@ pkgs.testers.runNixOSTest {
rc, out = update_from(8003) rc, out = update_from(8003)
assert rc != 0 and "not newer" in out, out assert rc != 0 and "not newer" in out, out
assert version() == "2.0.0" assert version() == "2.0.0"
with subtest("a release in a git repository is found, built and installed like a bundle"):
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"
" && git -c user.name=test -c user.email=test@example.org commit -q -m 'version 3' && git tag v3.0.0")
commit = builder.succeed("git -C /root/v3 rev-parse HEAD").strip()
builder.succeed("mkdir -p /srv/git && git clone -q --bare /root/v3 /srv/git/router.git")
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")
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/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 "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")
# 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"
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"
login()
token = csrf("/update")
assert form("/update/gitinstall", "--data-urlencode tag=v3.0.0") == "303"
update_finished()
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
lock = json.loads(target.succeed("cat /var/lib/router/config/flake.lock"))
locked = lock["nodes"][lock["nodes"]["root"]["inputs"]["nixos-router"]]["locked"]
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()
token = csrf("/")
builder.succeed(f"curl -sk -b /tmp/jar -o /dev/null --data-urlencode csrf={token} {ui}/confirm")
target.wait_until_fails("systemctl is-active router-rollback.timer", timeout=60)
target.wait_until_succeeds("test $(systemctl show -p ActiveState --value router-confirm.service) = inactive")
assert target.succeed("readlink /etc/localtime").strip().endswith("Europe/Paris")
with subtest("the router built from git rebuilds to exactly itself without the repository, and is up to date"):
builder.succeed("systemctl stop git-server")
out = target.succeed("router-apply 2>&1")
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
''; '';
} }