diff --git a/README.md b/README.md index ec5f8a9..082750c 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,55 @@ mux.Handle("/webui-static/", layout.StaticHandler("/webui-static/")) See `yetano/yasta` for a full worked example (the pilot migration of this module). +## Flash messages (v0.3.0) + +A message after a form POST travels in the query parameters `flash` and +`flashKind` (owner decision 2026-10-31): no server state, and it works +behind a base path and through the Verse relay. The text lands in the +browser history, so it never carries a secret. + +```go +layout.RedirectFlash(w, r, basePath+"/services", layout.FlashOK, "service a started") // 303 +... +hdr.ApplyFlash(r) // fills Flash/FlashKind; an unknown kind shows as an error +``` + +`FlashKind` is `FlashOK` (green), `FlashInfo` (blue) or `FlashError` +(red). `ApplyAppearance` drops the flash parameters from +`AppearanceBack` (`WithoutFlash`), so switching the theme does not show +the message again. + +## HTTP hardening: package `httpsec` (v0.3.0) + +`teruna.dev/yetano/yetano-webui-template/httpsec`, net/http only. Owner +decisions of 2026-10-31 are built in. + +- `Headers(h, HeaderOptions{...})` -- outermost wrapper. Default set: + `Content-Security-Policy` `DefaultCSP` (`default-src 'self'; img-src + 'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors + 'none'; form-action 'self'`), `nosniff`, `X-Frame-Options: DENY`, + `Referrer-Policy: same-origin`, `Cross-Origin-Opener-Policy: + same-origin`, `Cache-Control: no-store` except below + `CacheablePrefixes`, HSTS only with `TLS: true`. `CSP` overrides the + policy for a UI that needs more. +- Host gate against DNS rebinding: `Gate(h, allowed, "")` + answers 421. `HostAllowed` accepts IP addresses, `localhost`, + `*.localhost` and the configured hosts (add a public URL's host with + `HostOf`); an **empty Host is rejected**. `GateActive(loginOn, + allowed)` is the family rule for when to install it: **always without + a login, with a login only once hosts are configured**. +- `SafeNext(next, basePath, "/login", "/logout")` -- the target after a + login or a "back" link: a local path inside the UI, else + `basePath + "/"`. +- `CookiePath(basePath)` (`basePath + "/"`, `/` at the root) and + `SecureCookies(r, publicURL)` (TLS or an https public URL). + +Cross-origin protection stays `http.NewCrossOriginProtection()` from +the standard library, wrapped inside `Headers`. + +Order: `Headers(Gate(cop.Handler(app)))` -- the headers also reach a 421 +or 403. + ## Migration status Eight projects use it, all on `v0.2.5` and all with the built-in theme diff --git a/appearance.go b/appearance.go index 5538506..e6dab2c 100644 --- a/appearance.go +++ b/appearance.go @@ -4,6 +4,8 @@ import ( "net/http" "net/url" "strings" + + "teruna.dev/yetano/yetano-webui-template/httpsec" ) // Values for PageHeader.Palette; each has its own block in @@ -78,7 +80,7 @@ func (h *PageHeader) ApplyAppearance(r *http.Request) { path = "/" } back := url.URL{Path: path, RawQuery: r.URL.RawQuery} - h.AppearanceBack = back.String() + h.AppearanceBack = WithoutFlash(back.String()) } // AppearanceHandler stores a theme and/or palette choice from a POST @@ -103,7 +105,7 @@ func AppearanceHandler(basePath string) http.Handler { return } set := func(name, value string) { - http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: basePath + "/", + http.SetCookie(w, &http.Cookie{Name: name, Value: value, Path: httpsec.CookiePath(basePath), MaxAge: 365 * 24 * 3600, HttpOnly: true, SameSite: http.SameSiteLaxMode}) } if theme != "" { @@ -112,22 +114,10 @@ func AppearanceHandler(basePath string) http.Handler { if palette != "" { set(PaletteCookie, palette) } - http.Redirect(w, r, basePath+localPath(r.FormValue("back")), http.StatusSeeOther) + http.Redirect(w, r, basePath+httpsec.SafeNext(r.FormValue("back"), ""), http.StatusSeeOther) }) } -// localPath returns back if it is a path (with query) inside this UI, -// otherwise "/". -func localPath(back string) string { - u, err := url.Parse(back) - if err != nil || u.Scheme != "" || u.Host != "" || u.User != nil || - !strings.HasPrefix(back, "/") || strings.HasPrefix(back, "//") || - strings.ContainsAny(back, "\\\r\n") { - return "/" - } - return back -} - // AppearanceItem is one button of the rendered appearance menu. type AppearanceItem struct { ID, Label, Symbol string diff --git a/flash.go b/flash.go new file mode 100644 index 0000000..f93bd07 --- /dev/null +++ b/flash.go @@ -0,0 +1,77 @@ +package layout + +import ( + "net/http" + "net/url" +) + +// Values for PageHeader.FlashKind. +const ( + FlashOK = "ok" + FlashError = "error" + FlashInfo = "info" +) + +// Query parameters a flash message travels in across a redirect: no +// server state, and it works behind a base path or a relay. The text +// ends up in the browser history, so it never carries a secret. +const ( + FlashParam = "flash" + FlashKindParam = "flashKind" +) + +// FlashURL adds a flash message of kind (FlashOK, FlashError, FlashInfo) +// to target's query, replacing one that is already there. +func FlashURL(target, kind, msg string) string { + u, err := url.Parse(target) + if err != nil { + return target + } + q := u.Query() + q.Set(FlashParam, msg) + q.Set(FlashKindParam, kind) + u.RawQuery = q.Encode() + return u.String() +} + +// RedirectFlash answers a form POST with 303 See Other to target (a +// path the handler has already made local, e.g. with httpsec.SafeNext), +// carrying a flash message. +func RedirectFlash(w http.ResponseWriter, r *http.Request, target, kind, msg string) { + http.Redirect(w, r, FlashURL(target, kind, msg), http.StatusSeeOther) +} + +// ApplyFlash fills h.Flash and h.FlashKind from r's query. An unknown +// kind is shown as an error, the way the base template renders it. +func (h *PageHeader) ApplyFlash(r *http.Request) { + q := r.URL.Query() + h.Flash = q.Get(FlashParam) + if h.Flash == "" { + h.FlashKind = "" + return + } + switch kind := q.Get(FlashKindParam); kind { + case FlashOK, FlashInfo: + h.FlashKind = kind + default: + h.FlashKind = FlashError + } +} + +// WithoutFlash removes the flash parameters from a (relative) URL, so a +// link back to the current page -- e.g. AppearanceBack -- does not show +// the message again. +func WithoutFlash(target string) string { + u, err := url.Parse(target) + if err != nil || u.RawQuery == "" { + return target + } + q := u.Query() + if !q.Has(FlashParam) && !q.Has(FlashKindParam) { + return target + } + q.Del(FlashParam) + q.Del(FlashKindParam) + u.RawQuery = q.Encode() + return u.String() +} diff --git a/flash_test.go b/flash_test.go new file mode 100644 index 0000000..29ae0c8 --- /dev/null +++ b/flash_test.go @@ -0,0 +1,46 @@ +package layout + +import ( + "net/http/httptest" + "testing" +) + +func TestFlashRoundTrip(t *testing.T) { + u := FlashURL("/services?x=1", FlashOK, "service a started") + var h PageHeader + h.ApplyFlash(httptest.NewRequest("GET", u, nil)) + if h.Flash != "service a started" || h.FlashKind != FlashOK { + t.Fatalf("ApplyFlash(%q) = %q/%q", u, h.Flash, h.FlashKind) + } + if got := WithoutFlash(u); got != "/services?x=1" { + t.Errorf("WithoutFlash = %q", got) + } + if WithoutFlash("/a?b=c") != "/a?b=c" || WithoutFlash("/a") != "/a" { + t.Error("WithoutFlash changed a URL without flash") + } + + h.ApplyFlash(httptest.NewRequest("GET", "/?flash=x&flashKind=bogus", nil)) + if h.FlashKind != FlashError { + t.Errorf("unknown kind = %q", h.FlashKind) + } + h.ApplyFlash(httptest.NewRequest("GET", "/", nil)) + if h.Flash != "" || h.FlashKind != "" { + t.Errorf("no flash = %q/%q", h.Flash, h.FlashKind) + } +} + +func TestRedirectFlash(t *testing.T) { + rec := httptest.NewRecorder() + RedirectFlash(rec, httptest.NewRequest("POST", "/x", nil), "/ui/repos", FlashInfo, "nothing to do") + if rec.Code != 303 || rec.Header().Get("Location") != "/ui/repos?flash=nothing+to+do&flashKind=info" { + t.Fatalf("%d %q", rec.Code, rec.Header().Get("Location")) + } +} + +func TestApplyAppearanceDropsFlash(t *testing.T) { + h := PageHeader{BasePath: "/ui"} + h.ApplyAppearance(httptest.NewRequest("GET", "/ui/repos?flash=done&flashKind=ok&page=2", nil)) + if h.AppearanceBack != "/repos?page=2" { + t.Fatalf("AppearanceBack = %q", h.AppearanceBack) + } +} diff --git a/httpsec/httpsec.go b/httpsec/httpsec.go new file mode 100644 index 0000000..5356005 --- /dev/null +++ b/httpsec/httpsec.go @@ -0,0 +1,176 @@ +// Package httpsec holds the HTTP hardening every Yetano/Yak/Yamase web +// UI shares: security headers, the Host gate against DNS rebinding, +// open-redirect-safe "next" targets and the cookie scope for a UI served +// under a base path. It only builds on net/http; cross-origin protection +// stays the standard library's http.CrossOriginProtection. +package httpsec + +import ( + "net" + "net/http" + "net/url" + "strings" +) + +// DefaultCSP allows the UI's own scripts, styles and images (plus data: +// images, e.g. the template's favicon) and nothing else: no plugins, no +// rewriting, no framing, forms only to the UI itself. +const DefaultCSP = "default-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'" + +// HeaderOptions configures Headers. The zero value is the default set. +type HeaderOptions struct { + // CSP replaces DefaultCSP, e.g. for a UI that still needs inline + // scripts or a WebSocket to another origin. + CSP string + // TLS adds Strict-Transport-Security. Set it only when the UI itself + // serves HTTPS (or is only ever reached through an HTTPS proxy): + // browsers remember it for a year. + TLS bool + // CacheablePrefixes are path prefixes (as the handler sees them) whose + // responses may be cached, e.g. "/static/", "/webui-static/"; + // everything else gets Cache-Control: no-store, so pages with + // session data never land in a shared or back-button cache. + CacheablePrefixes []string +} + +// Headers sets the security headers on every response of next. Put it +// outermost, so even a 421 from the Host gate or a 403 from cross-origin +// protection carries them. +func Headers(next http.Handler, opts HeaderOptions) http.Handler { + csp := opts.CSP + if csp == "" { + csp = DefaultCSP + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h := w.Header() + h.Set("Content-Security-Policy", csp) + h.Set("X-Content-Type-Options", "nosniff") + h.Set("X-Frame-Options", "DENY") + h.Set("Referrer-Policy", "same-origin") + h.Set("Cross-Origin-Opener-Policy", "same-origin") + if opts.TLS { + h.Set("Strict-Transport-Security", "max-age=31536000") + } + cacheable := false + for _, p := range opts.CacheablePrefixes { + if strings.HasPrefix(r.URL.Path, p) { + cacheable = true + break + } + } + if !cacheable { + h.Set("Cache-Control", "no-store") + } + next.ServeHTTP(w, r) + }) +} + +// GateActive is the family's rule for when the Host gate runs: always +// when the UI has no login (anyone who can make a browser send requests +// to it could otherwise drive it through a rebound DNS name), and also +// with a login once hosts are configured explicitly. A UI behind a +// domain with a login keeps working without extra configuration. +func GateActive(loginOn bool, allowed []string) bool { + return !loginOn || len(allowed) > 0 +} + +// HostAllowed reports whether a request's Host header names this UI: an +// IP address, localhost or a *.localhost name, or one of allowed +// (compared case-insensitively, a trailing dot ignored). A port is +// ignored. An empty Host is rejected -- every browser sends one, so only +// a hand-made request lacks it. +func HostAllowed(host string, allowed []string) bool { + if h, _, err := net.SplitHostPort(host); err == nil { + host = h + } + host = strings.TrimSuffix(strings.ToLower(strings.Trim(host, "[]")), ".") + if host == "" { + return false + } + if net.ParseIP(host) != nil || host == "localhost" || strings.HasSuffix(host, ".localhost") { + return true + } + for _, a := range allowed { + if strings.TrimSuffix(strings.ToLower(a), ".") == host { + return true + } + } + return false +} + +// HostOf returns the host of a public URL (e.g. a configured external +// address), for adding it to the allowed list; "" if there is none. +func HostOf(publicURL string) string { + u, err := url.Parse(publicURL) + if err != nil { + return "" + } + return u.Hostname() +} + +// Gate answers 421 Misdirected Request for a Host HostAllowed rejects, +// naming setting (the configuration key that lists allowed hosts, e.g. +// "settings.webUI.allowedHosts") so the operator knows what to change. +func Gate(next http.Handler, allowed []string, setting string) http.Handler { + msg := "unknown host" + if setting != "" { + msg += " (see " + setting + ")" + } + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !HostAllowed(r.Host, allowed) { + http.Error(w, msg, http.StatusMisdirectedRequest) + return + } + next.ServeHTTP(w, r) + }) +} + +// SafeNext returns next if it is a local target inside the UI at +// basePath ("" for a UI at the root) -- a path, optionally with query, +// that cannot leave the host: no scheme, host or user, no "//" or "/\" +// start, no backslash or control character -- and none of the +// basePath-relative paths in exclude (e.g. "/login", "/logout", so a +// login never returns to itself). Otherwise it returns basePath + "/". +func SafeNext(next, basePath string, exclude ...string) string { + fallback := basePath + "/" + if next == "" || !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") { + return fallback + } + for _, c := range next { + if c < 0x20 || c == 0x7f || c == '\\' { + return fallback + } + } + u, err := url.Parse(next) + if err != nil || u.Scheme != "" || u.Host != "" || u.User != nil || u.Opaque != "" { + return fallback + } + rel := u.Path + if basePath != "" { + if rel != basePath && !strings.HasPrefix(rel, basePath+"/") { + return fallback + } + rel = strings.TrimPrefix(rel, basePath) + } + for _, x := range exclude { + if rel == x { + return fallback + } + } + return next +} + +// CookiePath is the Path for cookies of a UI at basePath: basePath + "/" +// ("/" at the root), so two UIs on one host keep separate sessions and +// "/app" never matches "/application". (A "__Host-" cookie needs Path +// "/" and therefore a UI at the root.) +func CookiePath(basePath string) string { + return strings.TrimSuffix(basePath, "/") + "/" +} + +// SecureCookies reports whether cookies for r should carry Secure: when +// the request came over TLS, or the UI's public URL is https (it then +// sits behind a TLS-terminating proxy). +func SecureCookies(r *http.Request, publicURL string) bool { + return r.TLS != nil || strings.HasPrefix(strings.ToLower(publicURL), "https://") +} diff --git a/httpsec/httpsec_test.go b/httpsec/httpsec_test.go new file mode 100644 index 0000000..92d902b --- /dev/null +++ b/httpsec/httpsec_test.go @@ -0,0 +1,134 @@ +package httpsec + +import ( + "crypto/tls" + "net/http" + "net/http/httptest" + "testing" +) + +var ok = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) + +func TestHeaders(t *testing.T) { + h := Headers(ok, HeaderOptions{CacheablePrefixes: []string{"/static/"}}) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("GET", "/page", nil)) + for k, want := range map[string]string{ + "Content-Security-Policy": DefaultCSP, + "X-Content-Type-Options": "nosniff", + "X-Frame-Options": "DENY", + "Referrer-Policy": "same-origin", + "Cross-Origin-Opener-Policy": "same-origin", + "Cache-Control": "no-store", + "Strict-Transport-Security": "", + } { + if got := rec.Header().Get(k); got != want { + t.Errorf("%s = %q, want %q", k, got, want) + } + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("GET", "/static/app.css", nil)) + if got := rec.Header().Get("Cache-Control"); got != "" { + t.Errorf("static Cache-Control = %q", got) + } + + rec = httptest.NewRecorder() + Headers(ok, HeaderOptions{CSP: "default-src 'none'", TLS: true}).ServeHTTP(rec, httptest.NewRequest("GET", "/", nil)) + if rec.Header().Get("Content-Security-Policy") != "default-src 'none'" || rec.Header().Get("Strict-Transport-Security") == "" { + t.Errorf("options ignored: %v", rec.Header()) + } +} + +func TestGateActive(t *testing.T) { + if !GateActive(false, nil) || GateActive(true, nil) || !GateActive(true, []string{"a.example"}) { + t.Fatal("GateActive rule") + } +} + +func TestHostAllowed(t *testing.T) { + allowed := []string{"Ops.Example.", "b.example"} + for host, want := range map[string]bool{ + "": false, + ":8080": false, + "127.0.0.1:8080": true, + "[::1]:8080": true, + "::1": true, + "localhost": true, + "LOCALHOST:1": true, + "app.localhost": true, + "ops.example": true, + "ops.example.:443": true, + "b.example": true, + "evil.example": false, + "localhost.evil.com": false, + } { + if got := HostAllowed(host, allowed); got != want { + t.Errorf("HostAllowed(%q) = %v, want %v", host, got, want) + } + } +} + +func TestGate(t *testing.T) { + g := Gate(ok, nil, "web.allowed_hosts") + for host, code := range map[string]int{"localhost": 200, "evil.example": 421, "": 421} { + r := httptest.NewRequest("GET", "/", nil) + r.Host = host + rec := httptest.NewRecorder() + g.ServeHTTP(rec, r) + if rec.Code != code { + t.Errorf("Host %q: %d, want %d", host, rec.Code, code) + } + if code == 421 && rec.Body.String() != "unknown host (see web.allowed_hosts)\n" { + t.Errorf("body %q", rec.Body.String()) + } + } +} + +func TestHostOf(t *testing.T) { + if HostOf("https://ops.example:8443/ui") != "ops.example" || HostOf("") != "" { + t.Fatal("HostOf") + } +} + +func TestSafeNext(t *testing.T) { + for _, tc := range []struct{ next, base, want string }{ + {"/services?x=1", "", "/services?x=1"}, + {"", "", "/"}, + {"services", "", "/"}, + {"//evil.example", "", "/"}, + {"/\\evil.example", "", "/"}, + {"/a\\b", "", "/"}, + {"/a\nb", "", "/"}, + {"/a\x7f", "", "/"}, + {"https://evil.example/", "", "/"}, + {"/login", "", "/"}, + {"/logout", "", "/"}, + {"/login/help", "", "/login/help"}, + {"/ui/repos", "/ui", "/ui/repos"}, + {"/ui", "/ui", "/ui"}, + {"/other", "/ui", "/ui/"}, + {"/uix", "/ui", "/ui/"}, + {"/ui/login", "/ui", "/ui/"}, + } { + if got := SafeNext(tc.next, tc.base, "/login", "/logout"); got != tc.want { + t.Errorf("SafeNext(%q, %q) = %q, want %q", tc.next, tc.base, got, tc.want) + } + } +} + +func TestCookiePath(t *testing.T) { + if CookiePath("") != "/" || CookiePath("/ui") != "/ui/" || CookiePath("/ui/") != "/ui/" { + t.Fatal("CookiePath") + } +} + +func TestSecureCookies(t *testing.T) { + r := httptest.NewRequest("GET", "/", nil) + if SecureCookies(r, "") || !SecureCookies(r, "HTTPS://ops.example") { + t.Fatal("public URL") + } + r.TLS = &tls.ConnectionState{} + if !SecureCookies(r, "") { + t.Fatal("TLS") + } +} diff --git a/layout.go b/layout.go index f52af6b..3f61e17 100644 --- a/layout.go +++ b/layout.go @@ -86,7 +86,7 @@ type PageHeader struct { NavItems []NavItem ActiveNav string Flash string - FlashKind string // "ok" or "error"; meaningless if Flash == "" + FlashKind string // FlashOK, FlashError or FlashInfo (flash.go); meaningless if Flash == "" Username string LogoutPath string // BasePath-relative, e.g. "/logout"; rendered as a POST form (never a GET link); "" hides it NavbarBeforeBrand template.HTML // extra markup rendered before the brand link, e.g. a mobile sidebar toggle diff --git a/templates/layout/base.html.tmpl b/templates/layout/base.html.tmpl index be1e419..2bf6df5 100644 --- a/templates/layout/base.html.tmpl +++ b/templates/layout/base.html.tmpl @@ -18,7 +18,7 @@ {{template "sidebar" .}}
-{{if .Flash}}
{{.Flash}}
{{end}} +{{if .Flash}}
{{.Flash}}
{{end}} {{template "content" .}}