48f3336956
gates / gates (push) Successful in 23s
The notes a background run SAVES — last night's backup line, the last error, the proof result, the restore outcome — are written in the BOX's language at the moment they are written. A household that switches sees the previous run's note in the old language until the next run rewrites it: the operator's §16 option 1, stated rather than hidden. EndRestoreOp no longer receives a Hungarian literal from anywhere. The language switch is a globe. Two text links wrapped in the sidebar footer and asked the reader to recognise "Magyar"/"English" as links; a globe is the one symbol every web user already reads as "language", so nobody has to read Hungarian to escape Hungarian. It is <details>/<summary> — a menu with no script, drawn inline because the icon sprite lives only in layout.html and the visitor pages have their own shell. Those visitor pages get the same globe, and a visitor's choice stays theirs: a display-only felhom_lang cookie that langFor reads ONLY when there is no session. A signed-in household can never inherit a language a previous visitor picked in the same browser. POST /lang is CSRF-exempt for a narrow reason written at the exemption — its only achievable effect is the language of the page the victim's own browser shows them — and safeBackPath refuses //evil.example as well as https://, because "starts with /" alone is not the test. §16 taken: a successful claim carries the cookie into the household's setting. TWO PARITY EXCEPTIONS, MEASURED: 106 fixtures compared with a real diff — exactly two change shapes (the dashboard footer, the globe in the shells) and 5 byte-identical, which are the three pages that must not change. I INTRODUCED A DEADLOCK AND THE SUITE CAUGHT IT BY HANGING. UpdateOffboxStatus holds the settings write lock while running its callback; boxLang() wants the read lock; sync.RWMutex is not reentrant. On a real box an off-site run would have hung forever HOLDING the settings lock. Fixed by resolving the language before the callback, and guarded by a test that names the file and line in a second instead of hanging for 25 minutes. MinAgent: 0.131.0 (unchanged). No hub release needed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
121 lines
4.3 KiB
Go
121 lines
4.3 KiB
Go
package web
|
|
|
|
import (
|
|
"crypto/subtle"
|
|
"fmt"
|
|
"html/template"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
const csrfFormField = "_csrf"
|
|
const csrfHeaderName = "X-CSRF-Token"
|
|
|
|
// CsrfProtect validates CSRF tokens on unsafe HTTP methods (POST, PUT, DELETE, PATCH).
|
|
// Safe methods (GET, HEAD, OPTIONS) pass through unchanged.
|
|
//
|
|
// Exempt cases:
|
|
// - Auth is disabled (no password configured)
|
|
// - Request has a valid Authorization: Bearer header (API key / hub auth)
|
|
func (s *Server) CsrfProtect(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Safe methods: no CSRF check needed
|
|
switch r.Method {
|
|
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
// Skip CSRF if auth is disabled (no password set = open access)
|
|
if !s.authEnabled() {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
// Claim/reset POSTs carry their OWN pre-auth HMAC CSRF (validated in the handler) — the
|
|
// customer resetting a claimed box has no session yet, so the session-CSRF path can't apply.
|
|
// The guest launcher share password POST (/s/<token>, v0.165.0) is the same shape: no admin
|
|
// session, own pre-auth HMAC CSRF (validShareCSRF). The admin share-management POSTs live
|
|
// under /launcher/share/* and are NOT exempted — they ride the normal session CSRF below.
|
|
if r.URL.Path == "/claim" || r.URL.Path == "/claim/request-new-code" || strings.HasPrefix(r.URL.Path, "/s/") {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
// The anonymous language switch (v0.254.0, R-557). Exempt for a narrow and checkable reason:
|
|
// the ONLY thing it can achieve is to change the language of the page the victim's own browser
|
|
// shows them. It writes one display-only cookie, reads nothing, touches no setting, and its
|
|
// redirect cannot leave this box (safeBackPath). A CSRF token here would also be unobtainable:
|
|
// the visitor has no session to mint one from. **If this handler ever gains a second effect,
|
|
// it needs CSRF that day** — the exemption is for what it does, not for where it lives.
|
|
if r.URL.Path == langCookiePath {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
// Skip CSRF for Bearer-token authenticated requests.
|
|
// Validate the token against the configured API key before skipping.
|
|
if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "Bearer ") {
|
|
token := strings.TrimPrefix(auth, "Bearer ")
|
|
apiKey := s.cfg.Hub.APIKey
|
|
if apiKey != "" && subtle.ConstantTimeCompare([]byte(token), []byte(apiKey)) == 1 {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
// Invalid Bearer token — fall through to CSRF validation
|
|
}
|
|
|
|
// Get the session's CSRF token
|
|
cookie, err := r.Cookie(sessionCookieName)
|
|
if err != nil {
|
|
s.csrfReject(w, r, "no session cookie")
|
|
return
|
|
}
|
|
expected := s.csrfTokenForSession(cookie.Value)
|
|
if expected == "" {
|
|
s.csrfReject(w, r, "invalid or expired session")
|
|
return
|
|
}
|
|
|
|
// Check form field first, then header (for fetch/AJAX calls)
|
|
submitted := r.FormValue(csrfFormField)
|
|
if submitted == "" {
|
|
submitted = r.Header.Get(csrfHeaderName)
|
|
}
|
|
|
|
if submitted == "" || subtle.ConstantTimeCompare([]byte(submitted), []byte(expected)) != 1 {
|
|
s.csrfReject(w, r, "token mismatch")
|
|
return
|
|
}
|
|
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|
|
|
|
// csrfReject sends a 403 response. Returns JSON for /api/ paths, plain text otherwise.
|
|
func (s *Server) csrfReject(w http.ResponseWriter, r *http.Request, reason string) {
|
|
s.logger.Printf("[WARN] CSRF rejected: %s %s from %s (%s)", r.Method, r.URL.Path, r.RemoteAddr, reason)
|
|
if strings.HasPrefix(r.URL.Path, "/api/") {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusForbidden)
|
|
fmt.Fprint(w, `{"ok":false,"error":"CSRF token missing or invalid"}`)
|
|
return
|
|
}
|
|
http.Error(w, "CSRF token missing or invalid. Please reload the page and try again.", http.StatusForbidden)
|
|
}
|
|
|
|
// csrfToken returns the CSRF token for the current request's session.
|
|
func (s *Server) csrfToken(r *http.Request) string {
|
|
cookie, err := r.Cookie(sessionCookieName)
|
|
if err != nil {
|
|
return ""
|
|
}
|
|
return s.csrfTokenForSession(cookie.Value)
|
|
}
|
|
|
|
// csrfField returns an HTML hidden input for embedding in forms.
|
|
func (s *Server) csrfField(r *http.Request) template.HTML {
|
|
token := s.csrfToken(r)
|
|
return template.HTML(`<input type="hidden" name="` + csrfFormField + `" value="` + template.HTMLEscapeString(token) + `">`)
|
|
}
|