- router.dnsProviders: named accounts at DNS providers, used by dynamic DNS and certificates (ddclient and lego provider lists in pkgs/router-webui/providers.json). Schema 2 migrates router.ddns. - router.acme: a Let's Encrypt certificate for the web UI via security.acme (DNS-01, resolver 1.1.1.1), served and reloaded by the web UI; Certificate page. - Web UI: password change (web UI and root), reboot button, HTTP to HTTPS redirect (router.webui.httpPort), grouped menu. - Latest kernel (linuxPackages_latest); 7.3 and 7.3.0 are the same kernel for the reboot hint. - SPECS.md: wanted later (REST API, GraphQL, MCP). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AeFqV9dZrK6nipHkPfyM4F
255 lines
9.6 KiB
Go
255 lines
9.6 KiB
Go
package main
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func newTestApp(t *testing.T) (*app, System) {
|
|
t.Helper()
|
|
dir := t.TempDir()
|
|
sys := System{ConfigDir: filepath.Join(dir, "config"), StateDir: dir}
|
|
os.MkdirAll(sys.ConfigDir, 0o700)
|
|
os.WriteFile(sys.settingsPath(), []byte(sample), 0o600)
|
|
h, _ := hashPassword("hunter2hunter2")
|
|
os.WriteFile(sys.passwordPath(), []byte(h), 0o600)
|
|
return newApp(sys, newCollector(sys, filepath.Join(dir, "leases")), false), sys
|
|
}
|
|
|
|
func do(h http.Handler, method, path string, form url.Values, cookie *http.Cookie) *httptest.ResponseRecorder {
|
|
var req *http.Request
|
|
if form != nil {
|
|
req = httptest.NewRequest(method, path, strings.NewReader(form.Encode()))
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
} else {
|
|
req = httptest.NewRequest(method, path, nil)
|
|
}
|
|
if cookie != nil {
|
|
req.AddCookie(cookie)
|
|
}
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, req)
|
|
return rec
|
|
}
|
|
|
|
func TestLoginAndSave(t *testing.T) {
|
|
a, sys := newTestApp(t)
|
|
h := a.routes()
|
|
|
|
if rec := do(h, "GET", "/network", nil, nil); rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("unauthenticated access: %d", rec.Code)
|
|
}
|
|
if rec := do(h, "POST", "/login", url.Values{"password": {"nope"}}, nil); rec.Code != http.StatusUnauthorized {
|
|
t.Fatalf("wrong password: %d", rec.Code)
|
|
}
|
|
// What Firefox and Chrome send for a same-origin form post (seen as 403).
|
|
req := httptest.NewRequest("POST", "https://192.168.1.1/login", strings.NewReader("password=hunter2hunter2"))
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
req.Header.Set("Origin", "null")
|
|
req.Header.Set("Sec-Fetch-Site", "same-origin")
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusSeeOther || len(rec.Result().Cookies()) == 0 {
|
|
t.Fatalf("browser login: %d", rec.Code)
|
|
}
|
|
req = httptest.NewRequest("POST", "https://192.168.1.1/login", strings.NewReader("password=hunter2hunter2"))
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
req.Header.Set("Sec-Fetch-Site", "cross-site")
|
|
rec = httptest.NewRecorder()
|
|
h.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusForbidden {
|
|
t.Fatalf("cross-site login: %d", rec.Code)
|
|
}
|
|
|
|
rec = do(h, "POST", "/login", url.Values{"password": {"hunter2hunter2"}}, nil)
|
|
if rec.Code != http.StatusSeeOther || len(rec.Result().Cookies()) == 0 {
|
|
t.Fatalf("login failed: %d", rec.Code)
|
|
}
|
|
cookie := rec.Result().Cookies()[0]
|
|
|
|
page := do(h, "GET", "/network", nil, cookie).Body.String()
|
|
m := regexp.MustCompile(`name="csrf" value="([^"]+)"`).FindStringSubmatch(page)
|
|
if m == nil {
|
|
t.Fatalf("no CSRF token in:\n%s", page)
|
|
}
|
|
form := url.Values{
|
|
"hostName": {"gw"}, "wan.interface": {"eth1"}, "wan.type": {"dhcp"},
|
|
"lans": {"1"}, "lan.0.name": {"main"}, "lan.0.interface": {"eth2"},
|
|
"lan.0.address": {"192.168.10.1"}, "lan.0.internet": {"on"}, "lan.0.dhcp": {"on"},
|
|
"lan.0.poolStart": {"192.168.10.100"}, "lan.0.poolEnd": {"192.168.10.120"},
|
|
}
|
|
if rec := do(h, "POST", "/network", form, cookie); rec.Code != http.StatusForbidden {
|
|
t.Fatalf("POST without CSRF token: %d", rec.Code)
|
|
}
|
|
form.Set("csrf", m[1])
|
|
if rec := do(h, "POST", "/network", form, cookie); rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("save: %d\n%s", rec.Code, rec.Body)
|
|
}
|
|
s, _ := loadSettings(sys.settingsPath())
|
|
if str(s, "system", "hostName") != "gw" || str(s, "router", "lans", "main", "dhcp", "pool", "end") != "192.168.10.120" {
|
|
t.Fatalf("not saved: %v", s)
|
|
}
|
|
if str(s, "router", "lans", "main", "dhcp", "reservations", "nas", "address") != "192.168.10.5" {
|
|
t.Fatal("the form dropped the reservation")
|
|
}
|
|
|
|
req = httptest.NewRequest("POST", "/advanced", strings.NewReader(url.Values{"csrf": {m[1]}, "settings": {"{}"}}.Encode()))
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
req.Header.Set("Origin", "https://evil.example")
|
|
req.AddCookie(cookie)
|
|
rec = httptest.NewRecorder()
|
|
h.ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusForbidden {
|
|
t.Fatalf("cross-origin POST: %d", rec.Code)
|
|
}
|
|
}
|
|
|
|
func TestAdvancedPageHasRebootButton(t *testing.T) {
|
|
a, _ := newTestApp(t)
|
|
h := a.routes()
|
|
cookie := do(h, "POST", "/login", url.Values{"password": {"hunter2hunter2"}}, nil).Result().Cookies()[0]
|
|
if body := do(h, "GET", "/advanced", nil, cookie).Body.String(); !strings.Contains(body, `action="/reboot"`) {
|
|
t.Fatalf("no reboot button:\n%s", body)
|
|
}
|
|
}
|
|
|
|
func TestPasswordChange(t *testing.T) {
|
|
a, sys := newTestApp(t)
|
|
var root string
|
|
setRootPassword = func(_ System, pw string) error { root = pw; return nil }
|
|
t.Cleanup(func() { setRootPassword = (func(System, string) error)(nil) })
|
|
h := a.routes()
|
|
cookie := do(h, "POST", "/login", url.Values{"password": {"hunter2hunter2"}}, nil).Result().Cookies()[0]
|
|
body := do(h, "GET", "/advanced", nil, cookie).Body.String()
|
|
token := regexp.MustCompile(`name="csrf" value="([^"]+)"`).FindStringSubmatch(body)[1]
|
|
try := func(cur, next, confirm string) string {
|
|
rec := do(h, "POST", "/password", url.Values{"csrf": {token}, "current": {cur}, "new": {next}, "confirm": {confirm}}, cookie)
|
|
return rec.Header().Get("Location")
|
|
}
|
|
for name, loc := range map[string]string{
|
|
"wrong": try("nope", "newpassword1", "newpassword1"),
|
|
"short": try("hunter2hunter2", "short", "short"),
|
|
"mismatch": try("hunter2hunter2", "newpassword1", "newpassword2"),
|
|
} {
|
|
if root != "" || !strings.Contains(loc, "msg=") {
|
|
t.Fatalf("%s: root=%q location=%q", name, root, loc)
|
|
}
|
|
}
|
|
if stored, _ := os.ReadFile(sys.passwordPath()); func() bool { ok, _ := checkPassword(string(stored), "hunter2hunter2"); return !ok }() {
|
|
t.Fatal("a refused change altered the password")
|
|
}
|
|
if loc := try("hunter2hunter2", "newpassword1", "newpassword1"); !strings.Contains(loc, "Password+changed") {
|
|
t.Fatalf("location %q", loc)
|
|
}
|
|
stored, _ := os.ReadFile(sys.passwordPath())
|
|
if ok, _ := checkPassword(string(stored), "newpassword1"); !ok || root != "newpassword1" {
|
|
t.Errorf("web UI password not changed or root=%q", root)
|
|
}
|
|
}
|
|
|
|
func TestRedirectToHTTPS(t *testing.T) {
|
|
for _, c := range []struct{ addr, host, want string }{
|
|
{":443", "192.168.10.1", "https://192.168.10.1/login?x=1"},
|
|
{":443", "router.home:80", "https://router.home/login?x=1"},
|
|
{":8443", "router.home", "https://router.home:8443/login?x=1"},
|
|
{":443", "[fd00::1]:80", "https://[fd00::1]/login?x=1"},
|
|
} {
|
|
req := httptest.NewRequest("GET", "http://"+c.host+"/login?x=1", nil)
|
|
rec := httptest.NewRecorder()
|
|
redirectToHTTPS(c.addr).ServeHTTP(rec, req)
|
|
if rec.Code != http.StatusPermanentRedirect || rec.Header().Get("Location") != c.want {
|
|
t.Errorf("%s %s: %d %q, want %q", c.addr, c.host, rec.Code, rec.Header().Get("Location"), c.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestACMEIsChecked(t *testing.T) {
|
|
good := ACMEForm{Enabled: true, Provider: "cf", Domains: "router.example.org\n*.home.example.org", Email: "me@example.org", Staging: true, Agree: true}
|
|
mk := func() Settings {
|
|
return withProvider(withProvider(mustParse(t), "cf", "cloudflare"), "dyn", "dyndns2")
|
|
}
|
|
if err := mk().applyACME(good); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for name, mod := range map[string]func(*ACMEForm){
|
|
"provider": func(f *ACMEForm) { f.Provider = "dyn" }, // cannot do DNS-01
|
|
"domains": func(f *ACMEForm) { f.Domains = "" },
|
|
"email": func(f *ACMEForm) { f.Email = "" },
|
|
"agree": func(f *ACMEForm) { f.Agree = false },
|
|
} {
|
|
f := good
|
|
mod(&f)
|
|
if err := mk().applyACME(f); err == nil || err.(FormErrors)[name] == "" {
|
|
t.Errorf("%s accepted: %v", name, err)
|
|
}
|
|
}
|
|
if err := mk().applyACME(ACMEForm{}); err != nil {
|
|
t.Errorf("disabled and empty: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestCertificatePage(t *testing.T) {
|
|
a, sys := newTestApp(t)
|
|
s, _ := loadSettings(sys.settingsPath())
|
|
withProvider(s, "cf", "cloudflare")
|
|
if err := s.save(sys.settingsPath()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
h := a.routes()
|
|
cookie := do(h, "POST", "/login", url.Values{"password": {"hunter2hunter2"}}, nil).Result().Cookies()[0]
|
|
body := do(h, "GET", "/certificate", nil, cookie).Body.String()
|
|
if !strings.Contains(body, `<option value="cf"`) {
|
|
t.Fatalf("the account is not offered:\n%s", body)
|
|
}
|
|
token := regexp.MustCompile(`name="csrf" value="([^"]+)"`).FindStringSubmatch(body)[1]
|
|
form := url.Values{"csrf": {token}, "enabled": {"on"}, "provider": {"cf"}, "domains": {"router.example.org"}, "email": {"a@example.org"}}
|
|
if rec := do(h, "POST", "/certificate", form, cookie); rec.Code != http.StatusUnprocessableEntity {
|
|
t.Fatalf("without the agreement: %d", rec.Code)
|
|
}
|
|
form.Set("agree", "on")
|
|
if rec := do(h, "POST", "/certificate", form, cookie); rec.Code != http.StatusSeeOther {
|
|
t.Fatalf("save: %d\n%s", rec.Code, rec.Body)
|
|
}
|
|
s, _ = loadSettings(sys.settingsPath())
|
|
if f := s.acme(); !f.Enabled || f.Provider != "cf" || !f.Agree || f.Staging {
|
|
t.Fatalf("not saved: %+v", f)
|
|
}
|
|
}
|
|
|
|
func TestCertSource(t *testing.T) {
|
|
self, err := loadOrCreateCert(t.TempDir())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
dir := t.TempDir()
|
|
c := &certSource{fallback: self, dir: dir}
|
|
got, _ := c.get(nil)
|
|
if got != &c.fallback {
|
|
t.Fatal("served something else without files")
|
|
}
|
|
other := t.TempDir()
|
|
if _, err := loadOrCreateCert(other); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for from, to := range map[string]string{"cert.pem": "fullchain.pem", "key.pem": "key.pem"} {
|
|
data, _ := os.ReadFile(filepath.Join(other, from))
|
|
os.WriteFile(filepath.Join(dir, to), data, 0o600)
|
|
}
|
|
if got, _ = c.get(nil); got == &c.fallback || string(got.Certificate[0]) == string(self.Certificate[0]) {
|
|
t.Fatal("did not pick up the certificate")
|
|
}
|
|
os.WriteFile(filepath.Join(dir, "key.pem"), []byte("junk"), 0o600)
|
|
future := time.Now().Add(time.Hour)
|
|
os.Chtimes(filepath.Join(dir, "key.pem"), future, future)
|
|
if got, _ = c.get(nil); got != &c.fallback {
|
|
t.Fatal("served a broken pair")
|
|
}
|
|
}
|