From 0a1d6a89273666b9bf3b7b28672ba522890b35a7 Mon Sep 17 00:00:00 2001 From: Paul Tal <2018.tpg@gmail.com> Date: Tue, 24 Nov 2026 00:56:39 +0200 Subject: [PATCH] Replace HTTP Basic Auth with a login page and session cookie - /login form checks DASHBOARD_USER / DASHBOARD_PASSWORD from .env in constant time; failed attempts are serialized with a 1s delay - Sessions are random tokens kept in memory for 30 days, in an HttpOnly, SameSite=Lax cookie (Secure behind HTTPS); sign out ends them server-side - Signed-out requests redirect to /login and return to the page afterwards, with redirects limited to local paths - Dashboard pages send no-store and X-Frame-Options: DENY - Tests for the login flow and redirect safety; docs updated Co-Authored-By: Claude Opus 5.5 --- .env.example | 2 +- .gitignore | 1 + README.md | 6 +- internal/web/auth.go | 151 +++++++++++++++++++++++++++++ internal/web/auth_test.go | 97 ++++++++++++++++++ internal/web/templates/layout.html | 14 ++- internal/web/templates/login.html | 16 +++ internal/web/web.go | 44 ++++----- 8 files changed, 299 insertions(+), 32 deletions(-) create mode 100644 internal/web/auth.go create mode 100644 internal/web/auth_test.go create mode 100644 internal/web/templates/login.html diff --git a/.env.example b/.env.example index f7d652a..87db085 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,4 @@ -# Dashboard login (HTTP Basic Auth). Both are required. Don't use quotes. +# Dashboard login. Both are required. Don't use quotes. DASHBOARD_USER=admin DASHBOARD_PASSWORD=change-me diff --git a/.gitignore b/.gitignore index 6b35931..6e5cb74 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ .env data/ /pocketkv +.DS_Store diff --git a/README.md b/README.md index cdaf3ed..18af1fe 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Simple minimal self hostable kv datastore you can use to serve dynamic read-only values to static sites. -- **Dashboard** (HTTP Basic Auth): create stores, edit JSON values in a code editor, create read-only API keys. +- **Dashboard** (login page, credentials from `.env`): create stores, edit JSON values in a code editor, create read-only API keys. - **API** (read-only, CORS `*`): read one value or all values of a store with an API key. Keys are safe to embed in static sites. - Go standard library only. All data lives in one JSON file. @@ -25,7 +25,9 @@ Open http://localhost:8080. Real environment variables take precedence over `.env`. Back up by copying `DATA_FILE`. -Basic Auth sends the password with every request, so put the dashboard behind HTTPS (e.g. a reverse proxy) if it is reachable from outside your network. +Sign in at `/login` with the credentials from `.env`. Sessions last 30 days, or until you sign out or the server restarts. Wrong passwords are slowed to about one try per second. + +Without HTTPS, the password and session cookie travel unencrypted, so put the dashboard behind HTTPS (e.g. a reverse proxy) if it is reachable from outside your network. ## Deploy with Docker diff --git a/internal/web/auth.go b/internal/web/auth.go new file mode 100644 index 0000000..fe1b3ad --- /dev/null +++ b/internal/web/auth.go @@ -0,0 +1,151 @@ +package web + +import ( + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "net/http" + "net/url" + "strings" + "sync" + "time" +) + +const ( + sessionCookie = "pocketkv_session" + sessionTTL = 30 * 24 * time.Hour + failedDelay = time.Second // slows down password guessing +) + +// auth checks the dashboard credentials and keeps signed-in sessions in +// memory. Restarting the server signs everyone out. +type auth struct { + userHash, passHash [32]byte + + mu sync.Mutex + sessions map[string]time.Time // session token -> expiry + + loginMu sync.Mutex // serializes login attempts so failures can't run in parallel +} + +func newAuth(user, password string) *auth { + return &auth{ + userHash: sha256.Sum256([]byte(user)), + passHash: sha256.Sum256([]byte(password)), + sessions: map[string]time.Time{}, + } +} + +// check compares credentials in constant time. A wrong guess holds the login +// lock for failedDelay, which limits guessing to about one try per second. +func (a *auth) check(user, password string) bool { + a.loginMu.Lock() + defer a.loginMu.Unlock() + u, p := sha256.Sum256([]byte(user)), sha256.Sum256([]byte(password)) + ok := subtle.ConstantTimeCompare(u[:], a.userHash[:])&subtle.ConstantTimeCompare(p[:], a.passHash[:]) == 1 + if !ok { + time.Sleep(failedDelay) + } + return ok +} + +func (a *auth) newSession() string { + token := rand.Text() + now := time.Now() + a.mu.Lock() + defer a.mu.Unlock() + for t, exp := range a.sessions { + if now.After(exp) { + delete(a.sessions, t) + } + } + a.sessions[token] = now.Add(sessionTTL) + return token +} + +func (a *auth) valid(r *http.Request) bool { + c, err := r.Cookie(sessionCookie) + if err != nil { + return false + } + a.mu.Lock() + defer a.mu.Unlock() + exp, ok := a.sessions[c.Value] + return ok && time.Now().Before(exp) +} + +func (a *auth) endSession(r *http.Request) { + if c, err := r.Cookie(sessionCookie); err == nil { + a.mu.Lock() + delete(a.sessions, c.Value) + a.mu.Unlock() + } +} + +// require sends visitors without a valid session to the login page. +func (a *auth) require(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !a.valid(r) { + to := "/login" + if r.Method == http.MethodGet && r.URL.RequestURI() != "/" { + to += "?next=" + url.QueryEscape(r.URL.RequestURI()) + } + http.Redirect(w, r, to, http.StatusSeeOther) + return + } + next.ServeHTTP(w, r) + }) +} + +// --- handlers --- + +type loginData struct { + User string + Next string + Error string +} + +func (s *server) loginPage(w http.ResponseWriter, r *http.Request) { + next := safeNext(r.URL.Query().Get("next")) + if s.auth.valid(r) { + redirect(w, r, next) + return + } + s.render(w, http.StatusOK, "login", loginData{Next: next}) +} + +func (s *server) login(w http.ResponseWriter, r *http.Request) { + user, next := r.FormValue("user"), safeNext(r.FormValue("next")) + if !s.auth.check(user, r.FormValue("password")) { + s.render(w, http.StatusUnauthorized, "login", loginData{User: user, Next: next, Error: "Wrong username or password."}) + return + } + http.SetCookie(w, &http.Cookie{ + Name: sessionCookie, + Value: s.auth.newSession(), + Path: "/", + MaxAge: int(sessionTTL.Seconds()), + HttpOnly: true, + Secure: isHTTPS(r), + SameSite: http.SameSiteLaxMode, + }) + redirect(w, r, next) +} + +func (s *server) logout(w http.ResponseWriter, r *http.Request) { + s.auth.endSession(r) + http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: "", Path: "/", MaxAge: -1, HttpOnly: true, Secure: isHTTPS(r), SameSite: http.SameSiteLaxMode}) + redirect(w, r, "/login") +} + +// safeNext only allows redirects to local paths, never to another site. +func safeNext(next string) string { + if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.HasPrefix(next, "/\\") { + return "/" + } + return next +} + +func isHTTPS(r *http.Request) bool { + return r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" +} diff --git a/internal/web/auth_test.go b/internal/web/auth_test.go new file mode 100644 index 0000000..188d88a --- /dev/null +++ b/internal/web/auth_test.go @@ -0,0 +1,97 @@ +package web + +import ( + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "strings" + "testing" + + "github.com/katistix/pocketkv/internal/store" +) + +func newTestServer(t *testing.T) http.Handler { + db, err := store.Open(filepath.Join(t.TempDir(), "db.json")) + if err != nil { + t.Fatal(err) + } + return New(db, "admin", "secret") +} + +func do(h http.Handler, method, path string, form url.Values, cookie *http.Cookie) *httptest.ResponseRecorder { + var body *strings.Reader + if form != nil { + body = strings.NewReader(form.Encode()) + } else { + body = strings.NewReader("") + } + req := httptest.NewRequest(method, path, body) + if form != nil { + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + if cookie != nil { + req.AddCookie(cookie) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec +} + +func TestLoginFlow(t *testing.T) { + h := newTestServer(t) + + // Signed out: pages redirect to the login page, keeping the target. + rec := do(h, "GET", "/stores/x", nil, nil) + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/login?next=%2Fstores%2Fx" { + t.Fatalf("signed out GET: %d %s", rec.Code, rec.Header().Get("Location")) + } + if rec := do(h, "POST", "/stores", url.Values{"name": {"s"}}, nil); rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/login" { + t.Fatalf("signed out POST: %d %s", rec.Code, rec.Header().Get("Location")) + } + if rec := do(h, "GET", "/login", nil, nil); rec.Code != http.StatusOK { + t.Fatalf("login page: %d", rec.Code) + } + + // Wrong password. + rec = do(h, "POST", "/login", url.Values{"user": {"admin"}, "password": {"nope"}}, nil) + if rec.Code != http.StatusUnauthorized || len(rec.Result().Cookies()) != 0 { + t.Fatalf("wrong password: %d", rec.Code) + } + + // Right password: cookie set, redirected to next. + rec = do(h, "POST", "/login", url.Values{"user": {"admin"}, "password": {"secret"}, "next": {"/stores/x"}}, nil) + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/stores/x" { + t.Fatalf("login: %d %s", rec.Code, rec.Header().Get("Location")) + } + cookie := rec.Result().Cookies()[0] + if !cookie.HttpOnly || cookie.SameSite != http.SameSiteLaxMode { + t.Fatalf("cookie flags: %+v", cookie) + } + if rec := do(h, "GET", "/", nil, cookie); rec.Code != http.StatusOK { + t.Fatalf("signed in GET: %d", rec.Code) + } + if rec := do(h, "POST", "/stores", url.Values{"name": {"s"}}, cookie); rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/stores/s" { + t.Fatalf("signed in POST: %d %s", rec.Code, rec.Header().Get("Location")) + } + + // Logout invalidates the session server-side. + do(h, "POST", "/logout", nil, cookie) + if rec := do(h, "GET", "/", nil, cookie); rec.Code != http.StatusSeeOther { + t.Fatalf("after logout: %d", rec.Code) + } +} + +func TestSafeNext(t *testing.T) { + for in, want := range map[string]string{ + "": "/", + "/stores/x": "/stores/x", + "//evil.com": "/", + "/\\evil.com": "/", + "https://evil.com": "/", + } { + if got := safeNext(in); got != want { + t.Errorf("safeNext(%q) = %q, want %q", in, got, want) + } + } +} diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 60c594c..35d5849 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -23,7 +23,7 @@ .preview { color:var(--muted); max-width:420px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } form.inline { display:inline; } .row { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin:12px 0; } - input[type=text] { padding:7px 9px; border:1px solid var(--line); border-radius:6px; background:var(--bg); color:var(--fg); font:inherit; min-width:240px; } + input[type=text], input[type=password] { padding:7px 9px; border:1px solid var(--line); border-radius:6px; background:var(--bg); color:var(--fg); font:inherit; min-width:240px; } button, .button { padding:7px 14px; border:1px solid var(--line); border-radius:6px; background:var(--code); color:var(--fg); font:inherit; cursor:pointer; text-decoration:none; display:inline-block; } button.primary, .button.primary { background:var(--accent); border-color:var(--accent); color:#fff; } button.danger { color:var(--danger); background:none; border-color:transparent; padding:4px 8px; } @@ -34,12 +34,22 @@ .tablist button[aria-selected=true] { color:var(--fg); border-bottom-color:var(--accent); } .tablist .copy { margin-left:auto; } .tabs pre { margin-top:0; border-top-left-radius:0; border-top-right-radius:0; } + .login { max-width:340px; margin:12vh auto 0; } + .login h1 { text-align:center; margin-bottom:24px; } + .login label { display:block; margin-bottom:14px; font-size:.9rem; color:var(--muted); } + .login input { display:block; width:100%; min-width:0; margin-top:4px; color:var(--fg); } + .login button { width:100%; padding:9px; margin-top:6px; } .crumbs { color:var(--muted); margin:0 0 8px; } {{block "head" .}}{{end}} -
pocketkvAPI spec
+{{block "header" .}}
+ pocketkv + +
{{end}}
{{template "content" .}}
{{end}} diff --git a/internal/web/templates/login.html b/internal/web/templates/login.html new file mode 100644 index 0000000..e9a24d6 --- /dev/null +++ b/internal/web/templates/login.html @@ -0,0 +1,16 @@ +{{define "title"}}Sign in ยท pocketkv{{end}} +{{define "header"}}{{end}} +{{define "content"}} +
+

pocketkv

+ {{if .Error}}

{{.Error}}

{{end}} + + + + +
+{{end}} diff --git a/internal/web/web.go b/internal/web/web.go index a18b32b..9602fa5 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -1,11 +1,9 @@ // Package web serves the dashboard: server-rendered html/template pages -// behind HTTP Basic Auth. +// behind a login page with a session cookie. package web import ( "bytes" - "crypto/sha256" - "crypto/subtle" "embed" "encoding/json" "errors" @@ -25,14 +23,15 @@ const maxFormBytes = 5 << 20 // 5 MiB per request type server struct { db *store.DB + auth *auth pages map[string]*template.Template } -// New returns the dashboard handler, protected by Basic Auth and by -// cross-origin request protection on every non-GET request. +// New returns the dashboard handler. Every page except /login needs a +// signed-in session, and every non-GET request gets cross-origin protection. func New(db *store.DB, user, password string) http.Handler { - s := &server{db: db, pages: map[string]*template.Template{}} - for _, p := range []string{"index", "store", "value"} { + s := &server{db: db, auth: newAuth(user, password), pages: map[string]*template.Template{}} + for _, p := range []string{"login", "index", "store", "value"} { s.pages[p] = template.Must(template.ParseFS(templateFS, "templates/layout.html", "templates/"+p+".html")) } @@ -46,27 +45,16 @@ func New(db *store.DB, user, password string) http.Handler { mux.HandleFunc("POST /stores/{store}/value/delete", s.deleteValue) mux.HandleFunc("POST /stores/{store}/keys", s.createAPIKey) mux.HandleFunc("POST /stores/{store}/keys/delete", s.deleteAPIKey) + mux.HandleFunc("POST /logout", s.logout) - var h http.Handler = mux + root := http.NewServeMux() + root.HandleFunc("GET /login", s.loginPage) + root.HandleFunc("POST /login", s.login) + root.Handle("/", s.auth.require(mux)) + + var h http.Handler = root h = http.NewCrossOriginProtection().Handler(h) - h = http.MaxBytesHandler(h, maxFormBytes) - return basicAuth(user, password, h) -} - -func basicAuth(user, password string, next http.Handler) http.Handler { - wantUser, wantPass := sha256.Sum256([]byte(user)), sha256.Sum256([]byte(password)) - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - u, p, ok := r.BasicAuth() - gotUser, gotPass := sha256.Sum256([]byte(u)), sha256.Sum256([]byte(p)) - userOK := subtle.ConstantTimeCompare(gotUser[:], wantUser[:]) == 1 - passOK := subtle.ConstantTimeCompare(gotPass[:], wantPass[:]) == 1 - if !ok || !userOK || !passOK { - w.Header().Set("WWW-Authenticate", `Basic realm="pocketkv", charset="UTF-8"`) - http.Error(w, "Unauthorized", http.StatusUnauthorized) - return - } - next.ServeHTTP(w, r) - }) + return http.MaxBytesHandler(h, maxFormBytes) } // --- pages --- @@ -222,6 +210,8 @@ func (s *server) render(w http.ResponseWriter, status int, page string, data any return } w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("X-Frame-Options", "DENY") w.WriteHeader(status) buf.WriteTo(w) } @@ -241,7 +231,7 @@ func redirect(w http.ResponseWriter, r *http.Request, to string) { func baseURL(r *http.Request) string { scheme := "http" - if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" { + if isHTTPS(r) { scheme = "https" } return scheme + "://" + r.Host