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
+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/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))
@@ -491,12 +494,13 @@ type overviewData struct {
Status Status
Dashboard dashboard
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) {
st := a.sys.Status()
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 {
case st.Applying || st.ConfirmRunning:
p.Live = 2
@@ -22,6 +22,9 @@
</div>
</section>
{{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}}
<section class="notice"><p>NixOS {{.}} is out. <a href="/update#packages">See what it would change</a>.</p></section>
{{end}}
+35
View File
@@ -38,6 +38,41 @@
</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
+11 -1
View File
@@ -251,6 +251,7 @@ 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"},
@@ -275,6 +276,10 @@ type updateData struct {
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 {
@@ -284,6 +289,11 @@ func (a *app) updateData() updateData {
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
@@ -303,7 +313,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 {
if d.Update.Status.Running || d.Upgrade.Run.Running || d.Update.GitRun.Running {
p.Live = 3
}
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
// effect when upgrading rather than when applying, in the confirmed settings
// 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 {
s, err := loadSettings(path)
if err != nil {
@@ -103,15 +106,15 @@ func (sys System) setChannel(channel string) error {
return err
}
router := obj(s, "router")
if channel == "" {
if value == "" {
if u, ok := router["update"].(map[string]any); ok {
delete(u, "channel")
delete(u, key)
if len(u) == 0 {
delete(router, "update")
}
}
} else {
obj(router, "update")["channel"] = channel
obj(router, "update")[key] = value
}
return s.save(path)
}