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}}
-