Phase 1.2: session login + empty HTMX dashboard

- Session login for the single user Sam: server-side session store with an
  HMAC-signed session cookie, POST /login, POST /logout, and double-submit
  CSRF on every form post. Unauthenticated requests to / and /partials/*
  redirect to /login?next=...
- Empty dashboard shell in the Family Home Lab design system: left nav
  (category and folder placeholders), centre list, right detail pane.
- Copy tokens.css and the self-hosted Inter fonts from the family-home-lab
  design system into web/static; vendor htmx 2.0.4. No cross-project imports
  at runtime.
- Dark mode via prefers-color-scheme plus a persisted toggle; phone-first
  layout with 44px touch targets, hairline borders, 8px grid, pill CTAs.
- Config: EMAIL_AGENT_PASSWORD for the login password, falling back to
  EMAIL_AGENT_SESSION_SECRET so one configured secret is enough.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
2026-10-11 19:58:25 +11:00
parent 1dc755a740
commit 3c0030c9a3
21 changed files with 1423 additions and 80 deletions

View File

@@ -42,6 +42,10 @@ type Config struct {
// service has a single configuration surface.
SessionSecret string
// Password is the single-user login password. When it is empty the service
// falls back to SessionSecret so one configured secret is enough. Secret.
Password string
// LogLevel controls slog verbosity: debug, info, warn, error.
LogLevel string
@@ -75,6 +79,7 @@ func Load() (*Config, error) {
c := &Config{
Env: getenvDefault("EMAIL_AGENT_ENV", DefaultEnv),
SessionSecret: os.Getenv("EMAIL_AGENT_SESSION_SECRET"),
Password: os.Getenv("EMAIL_AGENT_PASSWORD"),
LogLevel: strings.ToLower(getenvDefault("EMAIL_AGENT_LOG_LEVEL", "info")),
PublicBaseURL: strings.TrimRight(getenvDefault("EMAIL_AGENT_PUBLIC_BASE_URL", "http://localhost:8790"), "/"),
JEVBaseURL: strings.TrimRight(os.Getenv("JEV_BASE_URL"), "/"),

284
internal/server/auth.go Normal file
View File

@@ -0,0 +1,284 @@
package server
import (
"context"
"crypto/subtle"
"net/http"
"net/url"
"strings"
"time"
"gitea.lab.audasmedia.com.au/sam/email_agent/internal/session"
"gitea.lab.audasmedia.com.au/sam/email_agent/internal/version"
)
const (
// csrfCookieName holds the double-submit CSRF token. It is independent of
// the session so the login form (which has no session yet) is protected too.
csrfCookieName = "email_agent_csrf"
sessionTTL = session.DefaultTTL
)
// ctxKey is the private context key type for request-scoped values.
type ctxKey int
const sessionCtxKey ctxKey = iota
// requireAuth redirects unauthenticated requests to the login screen and
// otherwise puts the session on the request context.
func (s *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
sess, ok := s.currentSession(r)
if !ok {
target := "/login?next=" + url.QueryEscape(r.URL.RequestURI())
http.Redirect(w, r, target, http.StatusSeeOther)
return
}
next(w, r.WithContext(context.WithValue(r.Context(), sessionCtxKey, sess)))
}
}
func (s *Server) currentSession(r *http.Request) (session.Session, bool) {
c, err := r.Cookie(session.CookieName)
if err != nil || c.Value == "" {
return session.Session{}, false
}
return s.sessions.Lookup(c.Value)
}
func sessionFrom(r *http.Request) session.Session {
sess, _ := r.Context().Value(sessionCtxKey).(session.Session)
return sess
}
// loginSecret is the password the single user must supply. EMAIL_AGENT_PASSWORD
// wins; otherwise the session secret doubles as the password so a single
// configured secret is enough.
func (s *Server) loginSecret() string {
if s.cfg.Password != "" {
return s.cfg.Password
}
return s.cfg.SessionSecret
}
// csrfToken returns the current double-submit token, minting one when absent.
func (s *Server) csrfToken(w http.ResponseWriter, r *http.Request) string {
if c, err := r.Cookie(csrfCookieName); err == nil && c.Value != "" {
return c.Value
}
tok, err := session.RandomToken(32)
if err != nil {
// crypto/rand failing is fatal for security; surface it rather than
// issuing an unprotected form.
s.logger.Error("csrf token generation failed", "error", err)
return ""
}
http.SetCookie(w, &http.Cookie{
Name: csrfCookieName,
Value: tok,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Secure: s.cfg.IsProduction(),
MaxAge: int(sessionTTL.Seconds()),
})
return tok
}
// csrfOK verifies the double-submit token from the form or the X-CSRF-Token
// header.
func (s *Server) csrfOK(r *http.Request) bool {
c, err := r.Cookie(csrfCookieName)
if err != nil || c.Value == "" {
return false
}
tok := r.FormValue("csrf")
if tok == "" {
tok = r.Header.Get("X-CSRF-Token")
}
return subtle.ConstantTimeCompare([]byte(tok), []byte(c.Value)) == 1
}
func (s *Server) setSessionCookie(w http.ResponseWriter, value string, expires time.Time) {
http.SetCookie(w, &http.Cookie{
Name: session.CookieName,
Value: value,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Secure: s.cfg.IsProduction(),
Expires: expires,
MaxAge: int(sessionTTL.Seconds()),
})
}
func (s *Server) clearSessionCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: session.CookieName,
Value: "",
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteLaxMode,
Secure: s.cfg.IsProduction(),
MaxAge: -1,
})
}
type loginData struct {
PartOfDay string
Error string
Next string
CSRFToken string
Configured bool
}
func (s *Server) renderLogin(w http.ResponseWriter, r *http.Request, code int, errMsg, next string) {
// Mint the CSRF cookie before the status line, or Set-Cookie is dropped.
csrf := s.csrfToken(w, r)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(code)
data := loginData{
PartOfDay: partOfDay(time.Now()),
Error: errMsg,
Next: next,
CSRFToken: csrf,
Configured: s.loginSecret() != "",
}
if err := s.tmpl.ExecuteTemplate(w, "login.html", data); err != nil {
s.logger.Error("render login", "error", err)
}
}
// handleLoginGet renders the sign-in form.
func (s *Server) handleLoginGet(w http.ResponseWriter, r *http.Request) {
if _, ok := s.currentSession(r); ok {
http.Redirect(w, r, cleanNext(r.URL.Query().Get("next")), http.StatusSeeOther)
return
}
s.renderLogin(w, r, http.StatusOK, "", cleanNext(r.URL.Query().Get("next")))
}
// handleLoginPost validates the CSRF token and password, then starts a session.
// POST (not GET) means the password is never placed in the URL or browser
// history.
func (s *Server) handleLoginPost(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
s.renderLogin(w, r, http.StatusBadRequest, "Could not read the sign-in form.", "/")
return
}
next := cleanNext(r.FormValue("next"))
if !s.csrfOK(r) {
s.renderLogin(w, r, http.StatusForbidden, "Your sign-in page expired. Please try again.", next)
return
}
secret := s.loginSecret()
if secret == "" {
s.renderLogin(w, r, http.StatusServiceUnavailable, "Login is not configured yet.", next)
return
}
if subtle.ConstantTimeCompare([]byte(r.FormValue("password")), []byte(secret)) != 1 {
s.logger.Warn("login failed", "remote", r.RemoteAddr)
s.renderLogin(w, r, http.StatusUnauthorized, "Incorrect password.", next)
return
}
sess, cookie, err := s.sessions.New("Sam")
if err != nil {
s.logger.Error("create session", "error", err)
http.Error(w, "could not start a session", http.StatusInternalServerError)
return
}
s.setSessionCookie(w, cookie, sess.ExpiresAt)
s.logger.Info("login ok", "user", sess.User, "remote", r.RemoteAddr)
http.Redirect(w, r, next, http.StatusSeeOther)
}
// handleLogout destroys the session and returns to the login screen.
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
_ = r.ParseForm()
if !s.csrfOK(r) {
http.Error(w, "invalid CSRF token", http.StatusForbidden)
return
}
if c, err := r.Cookie(session.CookieName); err == nil && c.Value != "" {
s.sessions.Destroy(c.Value)
}
s.clearSessionCookie(w)
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
type navItem struct {
Name string
Color string
}
type dashboardData struct {
Greeting string
User string
CSRFToken string
Version string
Categories []navItem
Folders []navItem
}
// handleDashboard renders the empty inbox shell.
func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) {
sess := sessionFrom(r)
data := dashboardData{
Greeting: partOfDay(time.Now()),
User: sess.User,
CSRFToken: s.csrfToken(w, r),
Version: version.Version,
// Placeholders until FR-14 (editable categories) and FR-9 (folders)
// land. Colours are the design system's decorative sticker palette.
Categories: []navItem{
{Name: "Action", Color: "var(--primary)"},
{Name: "Important", Color: "var(--sticker-orange)"},
{Name: "Info", Color: "var(--sticker-sky)"},
{Name: "Spam", Color: "var(--sticker-red)"},
{Name: "Newsletter", Color: "var(--sticker-purple)"},
{Name: "Auto-reply", Color: "var(--sticker-teal)"},
},
Folders: []navItem{
{Name: "Replied-to", Color: "var(--sticker-green)"},
{Name: "Delete", Color: "var(--sticker-red)"},
{Name: "Saved", Color: "var(--sticker-teal)"},
},
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := s.tmpl.ExecuteTemplate(w, "dashboard.html", data); err != nil {
s.logger.Error("render dashboard", "error", err)
}
}
// handleInboxPartial is the HTMX fragment for the centre list. Phase 1.2 has no
// mail yet, so it renders the empty state.
func (s *Server) handleInboxPartial(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := s.tmpl.ExecuteTemplate(w, "inbox.html", nil); err != nil {
s.logger.Error("render inbox partial", "error", err)
}
}
// cleanNext only allows same-site, absolute-path redirects.
func cleanNext(next string) string {
if next == "" || !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") {
return "/"
}
return next
}
// partOfDay returns the time-aware greeting prefix.
func partOfDay(t time.Time) string {
switch h := t.Hour(); {
case h < 12:
return "Good morning"
case h < 18:
return "Good afternoon"
default:
return "Good evening"
}
}

View File

@@ -1,45 +1,66 @@
// Package server wires the HTTP surface of the Email Agent.
//
// Phase 1 exposes liveness/readiness endpoints and a placeholder dashboard.
// Login and the real HTMX screens arrive in Phase 1.2.
// Phase 1.2 exposes a session login and an empty HTMX dashboard shell in the
// Family Home Lab design system. Mail fetch arrives in Phase 2.
package server
import (
"context"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"html/template"
"io/fs"
"log/slog"
"mime"
"net/http"
"time"
"gitea.lab.audasmedia.com.au/sam/email_agent/internal/config"
"gitea.lab.audasmedia.com.au/sam/email_agent/internal/session"
"gitea.lab.audasmedia.com.au/sam/email_agent/internal/store"
"gitea.lab.audasmedia.com.au/sam/email_agent/internal/version"
"gitea.lab.audasmedia.com.au/sam/email_agent/web"
)
func init() {
// Go's mime table has no woff2 entry; the self-hosted Inter fonts need it.
_ = mime.AddExtensionType(".woff2", "font/woff2")
}
// Server holds the HTTP dependencies.
type Server struct {
cfg *config.Config
store *store.Store
logger *slog.Logger
http *http.Server
index *template.Template
cfg *config.Config
store *store.Store
logger *slog.Logger
http *http.Server
tmpl *template.Template
sessions *session.Manager
}
// New builds a Server. It does not start listening.
func New(cfg *config.Config, st *store.Store, logger *slog.Logger) (*Server, error) {
index, err := template.New("index").Parse(indexHTML)
tmpl, err := template.ParseFS(web.TemplateFS, "templates/*.html")
if err != nil {
return nil, fmt.Errorf("parse index template: %w", err)
return nil, fmt.Errorf("parse templates: %w", err)
}
key, err := sessionKey(cfg, logger)
if err != nil {
return nil, fmt.Errorf("session key: %w", err)
}
sessions, err := session.NewManager(key, session.DefaultTTL)
if err != nil {
return nil, fmt.Errorf("session manager: %w", err)
}
s := &Server{
cfg: cfg,
store: st,
logger: logger,
index: index,
cfg: cfg,
store: st,
logger: logger,
tmpl: tmpl,
sessions: sessions,
}
s.http = &http.Server{
Addr: cfg.Addr,
@@ -52,12 +73,43 @@ func New(cfg *config.Config, st *store.Store, logger *slog.Logger) (*Server, err
return s, nil
}
// sessionKey returns the cookie signing key. In production it comes from
// EMAIL_AGENT_SESSION_SECRET; with no secret configured the service still
// starts with an ephemeral key so it is usable, but sessions do not survive a
// restart and the operator sees a warning.
func sessionKey(cfg *config.Config, logger *slog.Logger) ([]byte, error) {
if cfg.SessionSecret != "" {
return []byte(cfg.SessionSecret), nil
}
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
return nil, err
}
logger.Warn("EMAIL_AGENT_SESSION_SECRET is not set; using an ephemeral session key (sessions reset on restart)")
return key, nil
}
// Handler returns the root HTTP handler with middleware applied.
func (s *Server) Handler() http.Handler {
staticFS, err := fs.Sub(web.StaticFS, "static")
if err != nil {
// web.StaticFS is a compile-time constant; this cannot fail at runtime.
panic(fmt.Sprintf("static assets: %v", err))
}
static := http.StripPrefix("/static/", http.FileServer(http.FS(staticFS)))
mux := http.NewServeMux()
mux.HandleFunc("GET /health", s.handleHealth)
mux.HandleFunc("GET /readyz", s.handleReady)
mux.HandleFunc("GET /{$}", s.handleIndex)
mux.Handle("GET /static/", static)
mux.HandleFunc("GET /login", s.handleLoginGet)
mux.HandleFunc("POST /login", s.handleLoginPost)
mux.HandleFunc("POST /logout", s.handleLogout)
mux.HandleFunc("GET /{$}", s.requireAuth(s.handleDashboard))
mux.HandleFunc("GET /partials/inbox", s.requireAuth(s.handleInboxPartial))
return s.recoverPanic(s.logRequests(mux))
}
@@ -138,19 +190,6 @@ func (s *Server) handleReady(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ready"})
}
// handleIndex renders a placeholder dashboard. The real login + inbox screens
// are Phase 1.2.
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
data := struct {
Version string
Env string
}{Version: version.Version, Env: s.cfg.Env}
if err := s.index.Execute(w, data); err != nil {
s.logger.Error("render index", "error", err)
}
}
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
@@ -195,34 +234,3 @@ func (r *statusRecorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
const indexHTML = `<!doctype html>
<html lang="en" data-theme="light">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Email Agent</title>
<style>
:root { color-scheme: light dark; }
body { font-family: Inter, -apple-system, system-ui, "Segoe UI", Helvetica, Arial, sans-serif;
background: #f6f5f4; color: #31302e; margin: 0; }
@media (prefers-color-scheme: dark) { body { background: #141518; color: #dcdee2; } }
main { max-width: 640px; margin: 12vh auto; padding: 0 24px; }
.band { background: #213183; color: #fff; border-radius: 12px; padding: 24px; }
h1 { font-size: 32px; line-height: 1.1; margin: 0 0 8px; }
p { font-size: 15px; line-height: 1.5; }
code { background: rgba(127,127,127,.15); padding: 2px 6px; border-radius: 4px; }
</style>
</head>
<body>
<main>
<div class="band">
<h1>Email Agent</h1>
<p>Phase 1 skeleton is running. Version <code>{{.Version}}</code> ({{.Env}}).</p>
</div>
<p>Login and the inbox arrive in Phase 1.2. Liveness is at
<a href="/health">/health</a>.</p>
</main>
</body>
</html>
`

View File

@@ -6,20 +6,28 @@ import (
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"regexp"
"strings"
"testing"
"gitea.lab.audasmedia.com.au/sam/email_agent/internal/config"
"gitea.lab.audasmedia.com.au/sam/email_agent/internal/session"
"gitea.lab.audasmedia.com.au/sam/email_agent/internal/store"
)
const testPassword = "test-password"
func newTestServer(t *testing.T) *Server {
t.Helper()
cfg := &config.Config{
Env: "test",
Addr: ":0",
DBPath: filepath.Join(t.TempDir(), "email_agent.db"),
LogLevel: "error",
Env: "test",
Addr: ":0",
DBPath: filepath.Join(t.TempDir(), "email_agent.db"),
LogLevel: "error",
SessionSecret: "test-session-secret",
Password: testPassword,
}
st, err := store.Open(context.Background(), cfg.DBPath)
if err != nil {
@@ -65,9 +73,9 @@ func TestReadyz(t *testing.T) {
}
}
func TestIndexRendersHTML(t *testing.T) {
func TestStaticTokensServed(t *testing.T) {
srv := newTestServer(t)
req := httptest.NewRequest(http.MethodGet, "/", nil)
req := httptest.NewRequest(http.MethodGet, "/static/tokens.css", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
@@ -75,7 +83,180 @@ func TestIndexRendersHTML(t *testing.T) {
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
if ct := rec.Header().Get("Content-Type"); ct == "" {
t.Error("Content-Type header is empty")
if !strings.Contains(rec.Body.String(), "--canvas-soft") {
t.Error("tokens.css does not contain the design tokens")
}
}
func TestUnauthenticatedRedirectsToLogin(t *testing.T) {
srv := newTestServer(t)
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusSeeOther {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusSeeOther)
}
if loc := rec.Header().Get("Location"); !strings.HasPrefix(loc, "/login") {
t.Errorf("Location = %q, want /login…", loc)
}
}
func TestLoginPageRenders(t *testing.T) {
srv := newTestServer(t)
req := httptest.NewRequest(http.MethodGet, "/login", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
body := rec.Body.String()
if !strings.Contains(body, "Sign in") || !strings.Contains(body, `name="csrf"`) {
t.Error("login page is missing the form or CSRF field")
}
if findCookie(t, rec.Result().Cookies(), csrfCookieName) == nil {
t.Error("login page did not set the CSRF cookie")
}
}
func TestLoginFlowAndDashboard(t *testing.T) {
srv := newTestServer(t)
h := srv.Handler()
// 1. Load the login page to obtain the CSRF token.
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/login", nil))
csrf := csrfFromBody(t, rec.Body.String())
csrfCookie := findCookie(t, rec.Result().Cookies(), csrfCookieName)
// 2. Sign in with the right password.
rec = httptest.NewRecorder()
h.ServeHTTP(rec, loginRequest(csrf, testPassword, csrfCookie))
if rec.Code != http.StatusSeeOther {
t.Fatalf("login status = %d, want %d (body: %s)", rec.Code, http.StatusSeeOther, rec.Body.String())
}
sessionCookie := findCookie(t, rec.Result().Cookies(), session.CookieName)
if sessionCookie == nil {
t.Fatal("login did not set the session cookie")
}
// 3. The dashboard renders with the session cookie.
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.AddCookie(sessionCookie)
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("dashboard status = %d, want %d", rec.Code, http.StatusOK)
}
body := rec.Body.String()
for _, want := range []string{"Good ", "Inbox", "Categories", "Folders", "Log out"} {
if !strings.Contains(body, want) {
t.Errorf("dashboard body missing %q", want)
}
}
}
func TestLoginWrongPassword(t *testing.T) {
srv := newTestServer(t)
h := srv.Handler()
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/login", nil))
csrf := csrfFromBody(t, rec.Body.String())
csrfCookie := findCookie(t, rec.Result().Cookies(), csrfCookieName)
rec = httptest.NewRecorder()
h.ServeHTTP(rec, loginRequest(csrf, "wrong-password", csrfCookie))
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusUnauthorized)
}
if findCookie(t, rec.Result().Cookies(), session.CookieName) != nil {
t.Error("a session cookie was issued for a failed login")
}
}
func TestLoginRejectsMissingCSRF(t *testing.T) {
srv := newTestServer(t)
form := url.Values{"password": {testPassword}}
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusForbidden)
}
}
func TestLogoutDestroysSession(t *testing.T) {
srv := newTestServer(t)
h := srv.Handler()
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/login", nil))
csrf := csrfFromBody(t, rec.Body.String())
csrfCookie := findCookie(t, rec.Result().Cookies(), csrfCookieName)
rec = httptest.NewRecorder()
h.ServeHTTP(rec, loginRequest(csrf, testPassword, csrfCookie))
sessionCookie := findCookie(t, rec.Result().Cookies(), session.CookieName)
if sessionCookie == nil {
t.Fatal("login did not set the session cookie")
}
// Log out, carrying both the CSRF and session cookies.
form := url.Values{"csrf": {csrf}}
req := httptest.NewRequest(http.MethodPost, "/logout", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.AddCookie(csrfCookie)
req.AddCookie(sessionCookie)
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusSeeOther {
t.Fatalf("logout status = %d, want %d", rec.Code, http.StatusSeeOther)
}
// The old session no longer reaches the dashboard.
req = httptest.NewRequest(http.MethodGet, "/", nil)
req.AddCookie(sessionCookie)
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusSeeOther {
t.Fatalf("dashboard after logout = %d, want %d", rec.Code, http.StatusSeeOther)
}
}
func loginRequest(csrf, password string, csrfCookie *http.Cookie) *http.Request {
form := url.Values{"password": {password}, "csrf": {csrf}}
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if csrfCookie != nil {
req.AddCookie(csrfCookie)
}
return req
}
var csrfFieldRE = regexp.MustCompile(`name="csrf" value="([^"]*)"`)
func csrfFromBody(t *testing.T, body string) string {
t.Helper()
m := csrfFieldRE.FindStringSubmatch(body)
if len(m) < 2 || m[1] == "" {
t.Fatalf("no CSRF token in body")
}
return m[1]
}
func findCookie(t *testing.T, cookies []*http.Cookie, name string) *http.Cookie {
t.Helper()
for _, c := range cookies {
if c.Name == name && c.Value != "" {
return c
}
}
return nil
}

196
internal/session/session.go Normal file
View File

@@ -0,0 +1,196 @@
// Package session implements the Email Agent's server-side session store and
// the signed cookie format used to reference a session.
//
// Sessions live in the process (there is one user and one container), so the
// cookie only ever carries an opaque, HMAC-signed identifier. Nothing about the
// user or the session state is stored client-side.
package session
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"strings"
"sync"
"time"
)
// CookieName is the name of the session cookie.
const CookieName = "email_agent_session"
// DefaultTTL is how long a session stays valid.
const DefaultTTL = 30 * 24 * time.Hour
// Session is a single logged-in session.
type Session struct {
ID string
User string
CreatedAt time.Time
ExpiresAt time.Time
}
// Store is an in-memory, concurrency-safe session store with lazy expiry.
type Store struct {
mu sync.Mutex
sessions map[string]Session
ttl time.Duration
now func() time.Time
}
// NewStore returns an empty store. A non-positive ttl falls back to DefaultTTL.
func NewStore(ttl time.Duration) *Store {
if ttl <= 0 {
ttl = DefaultTTL
}
return &Store{
sessions: make(map[string]Session),
ttl: ttl,
now: time.Now,
}
}
// Create makes a new session for user and returns it.
func (s *Store) Create(user string) (Session, error) {
id, err := RandomToken(32)
if err != nil {
return Session{}, err
}
now := s.now()
sess := Session{
ID: id,
User: user,
CreatedAt: now,
ExpiresAt: now.Add(s.ttl),
}
s.mu.Lock()
defer s.mu.Unlock()
s.gcLocked()
s.sessions[id] = sess
return sess, nil
}
// Get returns the session for id if it exists and has not expired.
func (s *Store) Get(id string) (Session, bool) {
s.mu.Lock()
defer s.mu.Unlock()
sess, ok := s.sessions[id]
if !ok {
return Session{}, false
}
if s.now().After(sess.ExpiresAt) {
delete(s.sessions, id)
return Session{}, false
}
return sess, true
}
// Delete removes a session.
func (s *Store) Delete(id string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.sessions, id)
}
// Len returns the number of live (not-yet-swept) sessions.
func (s *Store) Len() int {
s.mu.Lock()
defer s.mu.Unlock()
return len(s.sessions)
}
func (s *Store) gcLocked() {
now := s.now()
for id, sess := range s.sessions {
if now.After(sess.ExpiresAt) {
delete(s.sessions, id)
}
}
}
// Manager pairs a session store with the HMAC key that signs cookie values.
type Manager struct {
store *Store
key []byte
}
// NewManager builds a Manager. An empty key is replaced with a random key so
// the manager is always safe to use; the caller should normally supply one.
func NewManager(key []byte, ttl time.Duration) (*Manager, error) {
if len(key) == 0 {
k, err := randomBytes(32)
if err != nil {
return nil, err
}
key = k
}
return &Manager{store: NewStore(ttl), key: key}, nil
}
// New creates a session and returns it with the signed cookie value to set.
func (m *Manager) New(user string) (Session, string, error) {
sess, err := m.store.Create(user)
if err != nil {
return Session{}, "", err
}
return sess, m.sign(sess.ID), nil
}
// Lookup resolves a signed cookie value to a live session.
func (m *Manager) Lookup(cookieValue string) (Session, bool) {
id, ok := m.verify(cookieValue)
if !ok {
return Session{}, false
}
return m.store.Get(id)
}
// Destroy deletes the session referenced by a signed cookie value.
func (m *Manager) Destroy(cookieValue string) {
if id, ok := m.verify(cookieValue); ok {
m.store.Delete(id)
}
}
func (m *Manager) sign(id string) string {
mac := hmac.New(sha256.New, m.key)
mac.Write([]byte(id))
return id + "." + hex.EncodeToString(mac.Sum(nil))
}
func (m *Manager) verify(value string) (string, bool) {
i := strings.LastIndexByte(value, '.')
if i <= 0 || i == len(value)-1 {
return "", false
}
id, sigHex := value[:i], value[i+1:]
sig, err := hex.DecodeString(sigHex)
if err != nil {
return "", false
}
mac := hmac.New(sha256.New, m.key)
mac.Write([]byte(id))
if subtle.ConstantTimeCompare(sig, mac.Sum(nil)) != 1 {
return "", false
}
return id, true
}
// RandomToken returns a URL-safe random string carrying n bytes of entropy.
func RandomToken(n int) (string, error) {
b, err := randomBytes(n)
if err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
func randomBytes(n int) ([]byte, error) {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
return nil, err
}
return b, nil
}

View File

@@ -0,0 +1,78 @@
package session
import (
"testing"
"time"
)
func TestManagerRoundTrip(t *testing.T) {
m, err := NewManager([]byte("test-key"), time.Hour)
if err != nil {
t.Fatalf("NewManager() error = %v", err)
}
sess, cookie, err := m.New("Sam")
if err != nil {
t.Fatalf("New() error = %v", err)
}
if sess.User != "Sam" {
t.Errorf("User = %q, want Sam", sess.User)
}
got, ok := m.Lookup(cookie)
if !ok {
t.Fatal("Lookup() = not ok, want a live session")
}
if got.ID != sess.ID {
t.Errorf("Lookup ID = %q, want %q", got.ID, sess.ID)
}
m.Destroy(cookie)
if _, ok := m.Lookup(cookie); ok {
t.Error("Lookup() after Destroy() = ok, want expired")
}
}
func TestManagerRejectsTamperedCookie(t *testing.T) {
m, err := NewManager([]byte("key-a"), time.Hour)
if err != nil {
t.Fatalf("NewManager() error = %v", err)
}
_, cookie, err := m.New("Sam")
if err != nil {
t.Fatalf("New() error = %v", err)
}
other, err := NewManager([]byte("key-b"), time.Hour)
if err != nil {
t.Fatalf("NewManager() error = %v", err)
}
if _, ok := other.Lookup(cookie); ok {
t.Error("Lookup() with a different key = ok, want rejected")
}
for _, bad := range []string{"", "garbage", "abc.", ".abc", "a.b.c", cookie + "x"} {
if _, ok := m.Lookup(bad); ok {
t.Errorf("Lookup(%q) = ok, want rejected", bad)
}
}
}
func TestStoreExpiry(t *testing.T) {
st := NewStore(time.Minute)
base := time.Now()
st.now = func() time.Time { return base }
sess, err := st.Create("Sam")
if err != nil {
t.Fatalf("Create() error = %v", err)
}
if _, ok := st.Get(sess.ID); !ok {
t.Fatal("Get() = not ok before expiry")
}
st.now = func() time.Time { return base.Add(2 * time.Minute) }
if _, ok := st.Get(sess.ID); ok {
t.Error("Get() = ok after expiry, want expired")
}
}