Files
BountyBoard/internal/http/auth.go
T
etalon c1cc781279 feat: authentication with local accounts, sessions, CSRF, RBAC, and OIDC PKCE (phase 3)
- argon2id (t=3, m=64MiB, p=2) PHC hashing honoring embedded params
- token-bucket rate limiting (10/15min per IP+email) on login/register
- opaque 32B session tokens in Mongo, 30-day sliding expiry, logout-all
- CSRF double-submit cookie/header on authenticated mutations
- bootstrap admin from env with forced first-login password change
- requireAuth/requireRole middleware with disabled-account enforcement
- OIDC code flow with PKCE: lazy discovery, account linking only on
  verified email, auto-created developer accounts
- unit tests (RBAC matrix, CSRF, password, rate limiter) + integration
  suite covering the full auth matrix incl. an in-test fake IdP

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 18:31:25 +02:00

259 lines
7.8 KiB
Go

package httpx
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/mail"
"strings"
"time"
"bountyboard/internal/auth"
"bountyboard/internal/domain"
"bountyboard/internal/store"
"bountyboard/internal/ulid"
)
func (s *Server) routesAuth(mux *http.ServeMux) {
mux.HandleFunc("POST /api/v1/auth/register", s.handleRegister)
mux.HandleFunc("POST /api/v1/auth/login", s.handleLogin)
mux.Handle("POST /api/v1/auth/logout", s.authed(s.handleLogout))
mux.Handle("POST /api/v1/auth/logout-all", s.authed(s.handleLogoutAll))
mux.Handle("POST /api/v1/auth/change-password", s.authed(s.handleChangePassword))
mux.Handle("GET /api/v1/auth/me", s.requireAuth(http.HandlerFunc(s.handleMe)))
mux.HandleFunc("GET /api/v1/auth/oidc/login", s.handleOIDCLogin)
mux.HandleFunc("GET /api/v1/auth/oidc/callback", s.handleOIDCCallback)
}
// decodeJSON reads a bounded JSON body into dst, rejecting unknown fields.
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
writeError(w, http.StatusBadRequest, "bad_request", "invalid JSON body: "+err.Error())
return false
}
return true
}
func validEmail(email string) bool {
a, err := mail.ParseAddress(email)
return err == nil && a.Address == email
}
func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) {
var req struct {
Email string `json:"email"`
Name string `json:"name"`
Password string `json:"password"`
}
if !decodeJSON(w, r, &req) {
return
}
req.Email = store.NormalizeEmail(req.Email)
req.Name = strings.TrimSpace(req.Name)
switch {
case !validEmail(req.Email):
writeError(w, http.StatusBadRequest, "invalid_email", "a valid email address is required")
return
case req.Name == "":
writeError(w, http.StatusBadRequest, "invalid_name", "name is required")
return
case len(req.Password) < auth.MinPasswordLen:
writeError(w, http.StatusBadRequest, "weak_password",
fmt.Sprintf("password must be at least %d characters", auth.MinPasswordLen))
return
}
if !s.loginLimiter.Allow("register|" + ClientIP(r.Context()).String()) {
writeError(w, http.StatusTooManyRequests, "rate_limited", "too many attempts, try again later")
return
}
hash, err := auth.HashPassword(req.Password)
if err != nil {
s.internalError(w, r, "hash password", err)
return
}
u := &domain.User{
ID: ulid.New(),
Email: req.Email,
Name: req.Name,
// Open self-registration always creates a developer account (§3).
Roles: domain.Roles{Developer: true},
Auth: domain.Auth{Local: &domain.LocalAuth{PasswordHash: hash}},
Settings: domain.UserSettings{
Theme: "light",
Notifications: domain.NotificationPrefs{Email: true, InApp: true},
},
}
if err := s.store.CreateUser(r.Context(), u); err != nil {
if errors.Is(err, store.ErrDuplicate) {
writeError(w, http.StatusConflict, "email_taken", "an account with this email already exists")
return
}
s.internalError(w, r, "create user", err)
return
}
s.metrics.Inc("auth_registrations_total", 1)
s.startSession(w, r, u, http.StatusCreated)
}
func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) {
var req struct {
Email string `json:"email"`
Password string `json:"password"`
}
if !decodeJSON(w, r, &req) {
return
}
req.Email = store.NormalizeEmail(req.Email)
if !s.loginLimiter.Allow(ClientIP(r.Context()).String() + "|" + req.Email) {
s.metrics.Inc("auth_rate_limited_total", 1)
writeError(w, http.StatusTooManyRequests, "rate_limited", "too many attempts, try again later")
return
}
denyInvalid := func() {
s.metrics.Inc("auth_login_failures_total", 1)
writeError(w, http.StatusUnauthorized, "invalid_credentials", "invalid email or password")
}
u, err := s.store.UserByEmail(r.Context(), req.Email)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
denyInvalid()
return
}
s.internalError(w, r, "find user", err)
return
}
if u.Auth.Local == nil {
denyInvalid()
return
}
ok, err := auth.VerifyPassword(req.Password, u.Auth.Local.PasswordHash)
if err != nil {
s.internalError(w, r, "verify password", err)
return
}
if !ok {
denyInvalid()
return
}
if u.Disabled {
writeError(w, http.StatusForbidden, "account_disabled", "account is disabled")
return
}
s.startSession(w, r, u, http.StatusOK)
}
// newSessionFor persists a fresh session for u and returns it with a new
// CSRF token.
func (s *Server) newSessionFor(r *http.Request, u *domain.User) (*domain.Session, string, error) {
now := time.Now().UTC()
sess := &domain.Session{
Token: auth.NewToken(),
UserID: u.ID,
CreatedAt: now,
ExpiresAt: now.Add(domain.SessionTTL),
RefreshedAt: now,
IP: ClientIP(r.Context()).String(),
UA: r.UserAgent(),
}
if err := s.store.CreateSession(r.Context(), sess); err != nil {
return nil, "", err
}
if err := s.store.TouchLastSeen(r.Context(), u.ID); err != nil {
s.log.Warn("touch lastSeenAt", "err", err)
}
s.metrics.Inc("auth_logins_total", 1)
return sess, auth.NewToken(), nil
}
// startSession mints session + CSRF cookies and writes the login response.
func (s *Server) startSession(w http.ResponseWriter, r *http.Request, u *domain.User, status int) {
sess, csrf, err := s.newSessionFor(r, u)
if err != nil {
s.internalError(w, r, "create session", err)
return
}
s.setAuthCookies(w, sess.Token, csrf)
writeJSON(w, status, map[string]any{
"user": u,
"mustChangePassword": u.MustChangePassword(),
})
}
func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) {
if err := s.store.DeleteSession(r.Context(), CurrentSession(r.Context()).Token); err != nil {
s.internalError(w, r, "delete session", err)
return
}
s.clearAuthCookies(w)
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleLogoutAll(w http.ResponseWriter, r *http.Request) {
n, err := s.store.DeleteUserSessions(r.Context(), CurrentUser(r.Context()).ID)
if err != nil {
s.internalError(w, r, "delete sessions", err)
return
}
s.clearAuthCookies(w)
writeJSON(w, http.StatusOK, map[string]any{"revoked": n})
}
func (s *Server) handleChangePassword(w http.ResponseWriter, r *http.Request) {
var req struct {
CurrentPassword string `json:"currentPassword"`
NewPassword string `json:"newPassword"`
}
if !decodeJSON(w, r, &req) {
return
}
u := CurrentUser(r.Context())
if u.Auth.Local == nil {
writeError(w, http.StatusBadRequest, "no_local_auth",
"this account signs in via SSO and has no password")
return
}
if len(req.NewPassword) < auth.MinPasswordLen {
writeError(w, http.StatusBadRequest, "weak_password",
fmt.Sprintf("password must be at least %d characters", auth.MinPasswordLen))
return
}
ok, err := auth.VerifyPassword(req.CurrentPassword, u.Auth.Local.PasswordHash)
if err != nil {
s.internalError(w, r, "verify password", err)
return
}
if !ok {
writeError(w, http.StatusUnauthorized, "invalid_credentials", "current password is incorrect")
return
}
hash, err := auth.HashPassword(req.NewPassword)
if err != nil {
s.internalError(w, r, "hash password", err)
return
}
if err := s.store.SetPassword(r.Context(), u.ID, hash, false); err != nil {
s.internalError(w, r, "set password", err)
return
}
// Revoke every other session: a password change is the recovery action
// after credential leak.
if _, err := s.store.DeleteUserSessionsExcept(r.Context(), u.ID, CurrentSession(r.Context()).Token); err != nil {
s.log.Warn("revoke other sessions", "err", err)
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) {
u := CurrentUser(r.Context())
writeJSON(w, http.StatusOK, map[string]any{
"user": u,
"mustChangePassword": u.MustChangePassword(),
"oidcEnabled": s.cfg.OIDC.Enabled(),
})
}