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, `