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 <[email protected]>
This commit is contained in:
Paul TalandClaude Opus 5.5 committed 2026-11-24 00:56:39 +02:00
1 parent f8e851fdb9
commit 0a1d6a8927
8 files changed
+299 -32

No files matched your search

+151
View File
@@ -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"
}
+97
View File
@@ -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)
}
}
}
+12 -2
View File
@@ -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; }
</style>
{{block "head" .}}{{end}}
</head>
<body>
<header><a class="brand" href="/">pocketkv</a><a href="/openapi.yaml">API spec</a></header>
{{block "header" .}}<header>
<a class="brand" href="/">pocketkv</a>
<nav class="row" style="margin:0"><a href="/openapi.yaml">API spec</a>
<form method="post" action="/logout" class="inline"><button type="submit">Sign out</button></form>
</nav>
</header>{{end}}
<main>{{template "content" .}}</main>
</body>
</html>{{end}}
+16
View File
@@ -0,0 +1,16 @@
{{define "title"}}Sign in · pocketkv{{end}}
{{define "header"}}{{end}}
{{define "content"}}
<form class="login" method="post" action="/login">
<h1>pocketkv</h1>
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
<input type="hidden" name="next" value="{{.Next}}">
<label>Username
<input type="text" name="user" value="{{.User}}" autocomplete="username" required {{if not .User}}autofocus{{end}}>
</label>
<label>Password
<input type="password" name="password" autocomplete="current-password" required {{if .User}}autofocus{{end}}>
</label>
<button class="primary" type="submit">Sign in</button>
</form>
{{end}}
+17 -27
View File
@@ -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