Files
pixa/internal/session/session.go
sneak cb9e14eee7
All checks were successful
check / check (push) Successful in 1m48s
refactor: drop the ignored secure toggle parameter from session.NewManager
Per review on PR #48: pre-1.0 there is no installed base to keep
compiling against, so remove the dead parameter in one pass instead of
deferring. NewManager now takes only the signing key. Update the
handlers.go call site and its stale comment, mechanically update the
NewManager call shapes in the session tests (assertions unchanged),
collapse the now-meaningless constructor-argument loop in the cookie
attributes test, and drop the moot P1 Future Step from TODO.md.

Reviewer-directed test call-site updates; cookie behavior is unchanged
from the previous commit (always Secure/HttpOnly/SameSite=Strict).
2026-08-07 22:24:15 +07:00

146 lines
3.5 KiB
Go

// Package session provides encrypted session cookie management.
package session
import (
"errors"
"net/http"
"time"
"github.com/gorilla/securecookie"
"sneak.berlin/go/pixa/internal/seal"
)
// Session configuration constants.
const (
CookieName = "pixa_session"
SessionTTL = 30 * 24 * time.Hour // 30 days
// HKDF salts for key derivation
hashKeySalt = "pixa-session-hash-v1"
blockKeySalt = "pixa-session-block-v1"
)
// Errors returned by session operations.
var (
ErrInvalidSession = errors.New("invalid or expired session")
ErrNoSession = errors.New("no session cookie present")
)
// Data contains the session payload stored in the encrypted cookie.
type Data struct {
Authenticated bool `json:"auth"`
CreatedAt time.Time `json:"created"`
ExpiresAt time.Time `json:"expires"`
}
// Manager handles session creation and validation using encrypted cookies.
type Manager struct {
sc *securecookie.SecureCookie
}
// NewManager creates a session manager with keys derived from the signing key.
//
// Session cookies always carry the Secure, HttpOnly, and SameSite=Strict
// attributes; this cannot be configured. Browsers treat http://localhost as a
// trustworthy origin and accept Secure cookies there, so local development
// keeps working.
func NewManager(signingKey string) (*Manager, error) {
masterKey := []byte(signingKey)
// Derive separate keys for HMAC (hash) and encryption (block)
hashKey, err := seal.DeriveKey(masterKey, hashKeySalt)
if err != nil {
return nil, err
}
blockKey, err := seal.DeriveKey(masterKey, blockKeySalt)
if err != nil {
return nil, err
}
sc := securecookie.New(hashKey[:], blockKey[:])
sc.MaxAge(int(SessionTTL.Seconds()))
return &Manager{
sc: sc,
}, nil
}
// CreateSession creates a new authenticated session and sets the cookie.
func (m *Manager) CreateSession(w http.ResponseWriter) error {
now := time.Now()
data := &Data{
Authenticated: true,
CreatedAt: now,
ExpiresAt: now.Add(SessionTTL),
}
encoded, err := m.sc.Encode(CookieName, data)
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: CookieName,
Value: encoded,
Path: "/",
MaxAge: int(SessionTTL.Seconds()),
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
})
return nil
}
// ValidateSession checks if the request has a valid session cookie.
// Returns the session data if valid, or an error if invalid/missing.
func (m *Manager) ValidateSession(r *http.Request) (*Data, error) {
cookie, err := r.Cookie(CookieName)
if err != nil {
if errors.Is(err, http.ErrNoCookie) {
return nil, ErrNoSession
}
return nil, err
}
var data Data
if err := m.sc.Decode(CookieName, cookie.Value, &data); err != nil {
return nil, ErrInvalidSession
}
// Check if session has expired (defense in depth - cookie MaxAge should handle this)
if time.Now().After(data.ExpiresAt) {
return nil, ErrInvalidSession
}
if !data.Authenticated {
return nil, ErrInvalidSession
}
return &data, nil
}
// ClearSession removes the session cookie.
func (m *Manager) ClearSession(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: CookieName,
Value: "",
Path: "/",
MaxAge: -1, // Delete immediately
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
})
}
// IsAuthenticated is a convenience method that returns true if the request
// has a valid authenticated session.
func (m *Manager) IsAuthenticated(r *http.Request) bool {
data, err := m.ValidateSession(r)
return err == nil && data != nil && data.Authenticated
}