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>
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||
|
||||
"bountyboard/internal/domain"
|
||||
)
|
||||
|
||||
func (s *Store) sessions() *mongo.Collection { return s.DB.Collection("sessions") }
|
||||
|
||||
func (s *Store) CreateSession(ctx context.Context, sess *domain.Session) error {
|
||||
if _, err := s.sessions().InsertOne(ctx, sess); err != nil {
|
||||
return fmt.Errorf("insert session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SessionByToken returns a live session. Expired-but-not-yet-reaped rows
|
||||
// (Mongo TTL sweeps roughly once a minute) are treated as absent.
|
||||
func (s *Store) SessionByToken(ctx context.Context, token string) (*domain.Session, error) {
|
||||
var sess domain.Session
|
||||
err := s.sessions().FindOne(ctx, bson.M{
|
||||
"_id": token,
|
||||
"expiresAt": bson.M{"$gt": time.Now().UTC()},
|
||||
}).Decode(&sess)
|
||||
if errors.Is(err, mongo.ErrNoDocuments) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("find session: %w", err)
|
||||
}
|
||||
return &sess, nil
|
||||
}
|
||||
|
||||
// RefreshSession slides the expiry window (§7: 30-day sliding expiry).
|
||||
func (s *Store) RefreshSession(ctx context.Context, token string) error {
|
||||
now := time.Now().UTC()
|
||||
_, err := s.sessions().UpdateOne(ctx, bson.M{"_id": token}, bson.M{
|
||||
"$set": bson.M{"expiresAt": now.Add(domain.SessionTTL), "refreshedAt": now},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("refresh session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) DeleteSession(ctx context.Context, token string) error {
|
||||
if _, err := s.sessions().DeleteOne(ctx, bson.M{"_id": token}); err != nil {
|
||||
return fmt.Errorf("delete session: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteUserSessions revokes every session of a user (logout-all, disable,
|
||||
// password change).
|
||||
func (s *Store) DeleteUserSessions(ctx context.Context, userID string) (int64, error) {
|
||||
res, err := s.sessions().DeleteMany(ctx, bson.M{"userId": userID})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("delete user sessions: %w", err)
|
||||
}
|
||||
return res.DeletedCount, nil
|
||||
}
|
||||
|
||||
// DeleteUserSessionsExcept revokes all sessions of a user except one (used
|
||||
// after a password change to keep the current session alive).
|
||||
func (s *Store) DeleteUserSessionsExcept(ctx context.Context, userID, keepToken string) (int64, error) {
|
||||
res, err := s.sessions().DeleteMany(ctx, bson.M{
|
||||
"userId": userID,
|
||||
"_id": bson.M{"$ne": keepToken},
|
||||
})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("delete user sessions: %w", err)
|
||||
}
|
||||
return res.DeletedCount, nil
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
"go.mongodb.org/mongo-driver/v2/mongo"
|
||||
|
||||
"bountyboard/internal/domain"
|
||||
)
|
||||
|
||||
// ErrDuplicate is returned when a unique index rejects an insert/update
|
||||
// (e.g. email already registered).
|
||||
var ErrDuplicate = errors.New("duplicate value")
|
||||
|
||||
func (s *Store) users() *mongo.Collection { return s.DB.Collection("users") }
|
||||
|
||||
// NormalizeEmail is the canonical form stored and queried everywhere.
|
||||
func NormalizeEmail(email string) string {
|
||||
return strings.ToLower(strings.TrimSpace(email))
|
||||
}
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, u *domain.User) error {
|
||||
now := time.Now().UTC()
|
||||
u.Email = NormalizeEmail(u.Email)
|
||||
u.CreatedAt, u.UpdatedAt, u.Version = now, now, 1
|
||||
if u.LastSeenAt.IsZero() {
|
||||
u.LastSeenAt = now
|
||||
}
|
||||
if _, err := s.users().InsertOne(ctx, u); err != nil {
|
||||
if mongo.IsDuplicateKeyError(err) {
|
||||
return fmt.Errorf("user %s: %w", u.Email, ErrDuplicate)
|
||||
}
|
||||
return fmt.Errorf("insert user: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) userBy(ctx context.Context, filter bson.M) (*domain.User, error) {
|
||||
var u domain.User
|
||||
err := s.users().FindOne(ctx, filter).Decode(&u)
|
||||
if errors.Is(err, mongo.ErrNoDocuments) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("find user: %w", err)
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (s *Store) UserByID(ctx context.Context, id string) (*domain.User, error) {
|
||||
return s.userBy(ctx, bson.M{"_id": id})
|
||||
}
|
||||
|
||||
func (s *Store) UserByEmail(ctx context.Context, email string) (*domain.User, error) {
|
||||
return s.userBy(ctx, bson.M{"email": NormalizeEmail(email)})
|
||||
}
|
||||
|
||||
func (s *Store) UserByOIDC(ctx context.Context, issuer, subject string) (*domain.User, error) {
|
||||
return s.userBy(ctx, bson.M{"auth.oidc.issuer": issuer, "auth.oidc.subject": subject})
|
||||
}
|
||||
|
||||
func (s *Store) CountUsers(ctx context.Context) (int64, error) {
|
||||
n, err := s.users().CountDocuments(ctx, bson.M{})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("count users: %w", err)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// SetPassword replaces the local credential and clears/sets the forced
|
||||
// change flag. Not version-checked: password changes must never lose to a
|
||||
// concurrent profile edit.
|
||||
func (s *Store) SetPassword(ctx context.Context, userID, hash string, mustChange bool) error {
|
||||
res, err := s.users().UpdateOne(ctx, bson.M{"_id": userID}, bson.M{
|
||||
"$set": bson.M{
|
||||
"auth.local.passwordHash": hash,
|
||||
"auth.local.mustChange": mustChange,
|
||||
"updatedAt": time.Now().UTC(),
|
||||
},
|
||||
"$inc": bson.M{"version": 1},
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("set password: %w", err)
|
||||
}
|
||||
if res.MatchedCount == 0 {
|
||||
return fmt.Errorf("user %s: %w", userID, ErrNotFound)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LinkOIDC attaches an OIDC identity to an existing account (login linking
|
||||
// by verified email, §7).
|
||||
func (s *Store) LinkOIDC(ctx context.Context, userID, issuer, subject string) error {
|
||||
res, err := s.users().UpdateOne(ctx, bson.M{"_id": userID}, bson.M{
|
||||
"$set": bson.M{
|
||||
"auth.oidc": domain.OIDCAuth{Issuer: issuer, Subject: subject},
|
||||
"updatedAt": time.Now().UTC(),
|
||||
},
|
||||
"$inc": bson.M{"version": 1},
|
||||
})
|
||||
if err != nil {
|
||||
if mongo.IsDuplicateKeyError(err) {
|
||||
return fmt.Errorf("oidc identity: %w", ErrDuplicate)
|
||||
}
|
||||
return fmt.Errorf("link oidc: %w", err)
|
||||
}
|
||||
if res.MatchedCount == 0 {
|
||||
return fmt.Errorf("user %s: %w", userID, ErrNotFound)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// TouchLastSeen updates lastSeenAt without bumping version (pure telemetry).
|
||||
func (s *Store) TouchLastSeen(ctx context.Context, userID string) error {
|
||||
_, err := s.users().UpdateOne(ctx, bson.M{"_id": userID},
|
||||
bson.M{"$set": bson.M{"lastSeenAt": time.Now().UTC()}})
|
||||
if err != nil {
|
||||
return fmt.Errorf("touch lastSeenAt: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user