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>
This commit is contained in:
2026-11-25 11:49:57 +01:00
co-authored by Claude Sonnet 5.5
parent 3e6eee0b9c
commit 2b7cd86e98
15 changed files with 372 additions and 695 deletions
+13 -77
View File
@@ -1,35 +1,16 @@
package main
import (
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
)
// Updates from a git 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. The repository is part of the
// installed version (routerUpdate.repository, written to
// /etc/router-update-repository), not something the page sets.
var 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"`
}
// 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.
// repository is where releases come from ("" if the router has none).
func (s System) repository() string {
@@ -41,60 +22,15 @@ func (s System) repository() string {
return strings.TrimSpace(string(data))
}
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() *GitCheck {
var c GitCheck
repository := a.sys.repository()
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 {
if c := a.gitCheck(); c != nil && c.Newer {
return c.Newest.Version
var c UpgradeCheck
if !readUpgradeFile(filepath.Join(a.sys.upgradeDir(), "check.json"), &c) {
return ""
}
if r := c.Router; r != nil && r.Newer && r.Installed == a.sys.installedRelease().Version {
return r.Newest.Version
}
return ""
}
func (a *app) updateGitCheck(w http.ResponseWriter, r *http.Request, _ session) {
if a.sys.repository() == "" {
a.updateBack(w, r, "This router has no repository to look at.")
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
}
if a.sys.repository() == "" {
a.updateBack(w, r, "This router has no repository to update from.")
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.")
}
+29 -92
View File
@@ -11,96 +11,40 @@ import (
const testRepository = "https://git.example.org/me/nixos-router"
// While the look at the repository runs, the page is covered by the same kind
// of box as an update, and keeps asking for itself until it is done.
func TestLookingAtTheRepositoryShowsABox(t *testing.T) {
a, sys := newTestApp(t)
sys.RepositoryFile = filepath.Join(t.TempDir(), "router-update-repository")
os.WriteFile(sys.RepositoryFile, []byte(testRepository), 0o644)
a.sys = sys
orig := unitProperty
state := "inactive"
unitProperty = func(unit, prop string) string {
if unit == gitCheckUnit && prop == "ActiveState" {
return state
}
return ""
}
defer func() { unitProperty = orig }()
h := a.routes()
cookie := login(t, h)
body := do(h, "GET", "/update", nil, cookie).Body.String()
if strings.Contains(body, "Looking at the repository…") || strings.Contains(body, "data-live") {
t.Fatalf("a box with nothing running:\n%s", body)
}
if !strings.Contains(body, "Look for a newer release") {
t.Fatalf("no button:\n%s", body)
}
state = "activating"
body = do(h, "GET", "/update", nil, cookie).Body.String()
if !strings.Contains(body, "Looking at the repository…") || !strings.Contains(body, `class="upload-overlay"`) || !strings.Contains(body, "data-live") {
t.Fatalf("no box while looking:\n%s", body)
}
if !strings.Contains(body, testRepository) {
t.Fatalf("the box does not say where it looks:\n%s", body)
}
}
func TestUpdatesFromGit(t *testing.T) {
// 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)
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")
}
// A router without a repository has nothing to look at.
if loc := post("/update/gitcheck", url.Values{}); !strings.Contains(loc, "no+repository") || len(started) != 0 {
t.Fatalf("a check without a repository: %q %v", loc, started)
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/gitinstall", url.Values{"tag": {"v1.1.0"}}); !strings.Contains(loc, "no+repository") {
t.Fatalf("an install without a repository: %q", loc)
}
if rec := do(h, "POST", "/update/repository", url.Values{"csrf": {token}, "repository": {"https://evil.example.org/r"}}, cookie); rec.Code != 404 && rec.Code != 405 {
t.Fatalf("the repository can be set from the page: %d", rec.Code)
}
if body := do(h, "GET", "/update", nil, cookie).Body.String(); strings.Contains(body, `name="repository"`) {
if strings.Contains(body, `name="repository"`) {
t.Fatalf("the page has a field for the repository:\n%s", body)
}
// The repository is the installed version's; the page names it.
os.WriteFile(sys.RepositoryFile, []byte(testRepository+"\n"), 0o644)
if body := do(h, "GET", "/update", nil, cookie).Body.String(); !strings.Contains(body, testRepository) || !strings.Contains(body, "Not looked yet") {
t.Fatalf("the page does not say which repository:\n%s", body)
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)
}
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)
}
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)
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(testRepository, "0.9.0", true)
if body := do(h, "GET", "/", nil, cookie).Body.String(); strings.Contains(body, "is out") {
@@ -117,22 +61,15 @@ func TestUpdatesFromGit(t *testing.T) {
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)
}
}
}
-5
View File
@@ -338,11 +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/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; }
+36 -108
View File
@@ -22,101 +22,12 @@
<p class="muted">The page reloads when it is done. The web UI restarts when an upgrade is switched on, and you log in again.</p>
</div>
</div>
{{else if $u.GitRun.Running}}
<div class="upload-overlay" role="dialog" aria-modal="true">
<div class="upload-card wide">
<h2>Looking at the repository…</h2>
<progress max="100"></progress>
<p>Reading the release tags of <code>{{$u.Repository}}</code>.</p>
{{if $u.GitRun.Log}}<pre class="log">{{$u.GitRun.Log}}</pre>{{end}}
<p class="muted">The page reloads when it is done.</p>
</div>
</div>
{{else if $u.Pending}}
<section class="pending"><h2>Waiting for confirmation</h2>
<p>A new system is active and not confirmed yet. Confirm it on the <a href="/">Overview</a>, or the router goes back to the
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 <code>{{or $u.Repository "no repository"}}</code>
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>
{{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>
@@ -130,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
@@ -148,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">
@@ -162,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>
@@ -178,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>
@@ -208,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
@@ -219,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 -124
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 // routerUpdate.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,12 +221,8 @@ 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),
}
d.Repository = a.sys.repository()
d.Git = a.gitCheck()
d.Progress, d.Step = updateProgress(d.Status.Log)
return d
}
@@ -311,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)
@@ -331,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)
}
})