Refs #41, #45 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
253 lines
6.8 KiB
Go
253 lines
6.8 KiB
Go
// Package auth implements sessions, password and TOTP verification, rate
|
|
// limiting and CSRF protection.
|
|
package auth
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
// ErrNoSession is returned for unknown, expired or malformed sessions.
|
|
var ErrNoSession = errors.New("auth: no session")
|
|
|
|
// Session is a signed-in browser. Token is the cookie value and never
|
|
// stored server side.
|
|
type Session struct {
|
|
Token string
|
|
UserID uuid.UUID
|
|
OrgID uuid.UUID
|
|
Locale string
|
|
Method Method
|
|
// SSOOrg is the organization whose identity provider authenticated the
|
|
// session, if Method is MethodSSO.
|
|
SSOOrg uuid.UUID
|
|
CSRF string
|
|
CreatedAt time.Time
|
|
}
|
|
|
|
// Method records how a session was authenticated. Organization policies
|
|
// that require TOTP or SSO are checked against it.
|
|
type Method string
|
|
|
|
// Authentication methods. Sessions from before methods were recorded have
|
|
// the empty Method and count as the weakest.
|
|
const (
|
|
MethodPassword Method = "password"
|
|
MethodPasswordTOTP Method = "password+totp"
|
|
MethodSSO Method = "sso"
|
|
)
|
|
|
|
// NewSession describes a session to create. OrgID, Locale and SSOOrg may be
|
|
// empty.
|
|
type NewSession struct {
|
|
UserID uuid.UUID
|
|
OrgID uuid.UUID
|
|
Locale string
|
|
Method Method
|
|
SSOOrg uuid.UUID
|
|
}
|
|
|
|
// CheckCSRF compares token with the session's CSRF token in constant time.
|
|
func (s *Session) CheckCSRF(token string) bool {
|
|
return token != "" && subtle.ConstantTimeCompare([]byte(token), []byte(s.CSRF)) == 1
|
|
}
|
|
|
|
// Sessions stores sessions in Redis so any API replica can serve any request.
|
|
type Sessions struct {
|
|
rdb redis.UniversalClient
|
|
idle time.Duration
|
|
absolute time.Duration
|
|
now func() time.Time
|
|
}
|
|
|
|
// NewSessions returns a store whose sessions expire after idle without use
|
|
// and after absolute regardless of use.
|
|
func NewSessions(rdb redis.UniversalClient, idle, absolute time.Duration) *Sessions {
|
|
return &Sessions{rdb: rdb, idle: idle, absolute: absolute, now: time.Now}
|
|
}
|
|
|
|
// Only the hash of the token is stored, so a leaked Redis dump does not
|
|
// contain usable session cookies.
|
|
func key(token string) string {
|
|
sum := sha256.Sum256([]byte(token))
|
|
return "session:" + hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
func userIndex(id uuid.UUID) string { return "user_sessions:" + id.String() }
|
|
|
|
// RandomToken returns 256 bits of randomness, URL-safe encoded.
|
|
func RandomToken() string {
|
|
b := make([]byte, 32)
|
|
_, _ = rand.Read(b)
|
|
return base64.RawURLEncoding.EncodeToString(b)
|
|
}
|
|
|
|
// Create starts a session.
|
|
func (s *Sessions) Create(ctx context.Context, n NewSession) (*Session, error) {
|
|
sess := &Session{
|
|
Token: RandomToken(),
|
|
UserID: n.UserID,
|
|
OrgID: n.OrgID,
|
|
Locale: n.Locale,
|
|
Method: n.Method,
|
|
SSOOrg: n.SSOOrg,
|
|
CSRF: RandomToken(),
|
|
CreatedAt: s.now(),
|
|
}
|
|
user := n.UserID
|
|
k := key(sess.Token)
|
|
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
|
p.HSet(ctx, k, map[string]any{
|
|
"user": sess.UserID.String(),
|
|
"org": orgString(n.OrgID),
|
|
"locale": n.Locale,
|
|
"method": string(n.Method),
|
|
"sso_org": orgString(n.SSOOrg),
|
|
"csrf": sess.CSRF,
|
|
"created": sess.CreatedAt.Unix(),
|
|
})
|
|
p.Expire(ctx, k, s.idle)
|
|
p.SAdd(ctx, userIndex(user), k)
|
|
p.Expire(ctx, userIndex(user), s.absolute)
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("auth: create session: %w", err)
|
|
}
|
|
return sess, nil
|
|
}
|
|
|
|
// Get loads the session for token and extends its idle expiry.
|
|
func (s *Sessions) Get(ctx context.Context, token string) (*Session, error) {
|
|
if token == "" {
|
|
return nil, ErrNoSession
|
|
}
|
|
k := key(token)
|
|
vals, err := s.rdb.HGetAll(ctx, k).Result()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("auth: load session: %w", err)
|
|
}
|
|
if len(vals) == 0 {
|
|
return nil, ErrNoSession
|
|
}
|
|
sess, err := decode(token, vals)
|
|
if err != nil {
|
|
_ = s.rdb.Del(ctx, k).Err()
|
|
return nil, ErrNoSession
|
|
}
|
|
if s.now().Sub(sess.CreatedAt) > s.absolute {
|
|
_ = s.Delete(ctx, sess)
|
|
return nil, ErrNoSession
|
|
}
|
|
// Sliding expiry, but never beyond the absolute lifetime.
|
|
remaining := s.absolute - s.now().Sub(sess.CreatedAt)
|
|
if err := s.rdb.Expire(ctx, k, min(s.idle, remaining)).Err(); err != nil {
|
|
return nil, fmt.Errorf("auth: touch session: %w", err)
|
|
}
|
|
return sess, nil
|
|
}
|
|
|
|
// SwitchOrg changes the active organization. Membership must be checked
|
|
// by the caller.
|
|
func (s *Sessions) SwitchOrg(ctx context.Context, sess *Session, org uuid.UUID) error {
|
|
if err := s.rdb.HSet(ctx, key(sess.Token), "org", orgString(org)).Err(); err != nil {
|
|
return fmt.Errorf("auth: switch org: %w", err)
|
|
}
|
|
sess.OrgID = org
|
|
return nil
|
|
}
|
|
|
|
// SetMethod records a stronger authentication, e.g. after the user proved
|
|
// possession of a TOTP device in this session.
|
|
func (s *Sessions) SetMethod(ctx context.Context, sess *Session, m Method) error {
|
|
if err := s.rdb.HSet(ctx, key(sess.Token), "method", string(m)).Err(); err != nil {
|
|
return fmt.Errorf("auth: set method: %w", err)
|
|
}
|
|
sess.Method = m
|
|
return nil
|
|
}
|
|
|
|
// SetLocale changes the session language.
|
|
func (s *Sessions) SetLocale(ctx context.Context, sess *Session, locale string) error {
|
|
if err := s.rdb.HSet(ctx, key(sess.Token), "locale", locale).Err(); err != nil {
|
|
return fmt.Errorf("auth: set locale: %w", err)
|
|
}
|
|
sess.Locale = locale
|
|
return nil
|
|
}
|
|
|
|
// Delete ends sess.
|
|
func (s *Sessions) Delete(ctx context.Context, sess *Session) error {
|
|
k := key(sess.Token)
|
|
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
|
p.Del(ctx, k)
|
|
p.SRem(ctx, userIndex(sess.UserID), k)
|
|
return nil
|
|
})
|
|
return err
|
|
}
|
|
|
|
// DeleteAllForUser ends every session of a user, e.g. after a password change
|
|
// or when an admin disables the account.
|
|
func (s *Sessions) DeleteAllForUser(ctx context.Context, user uuid.UUID) error {
|
|
idx := userIndex(user)
|
|
keys, err := s.rdb.SMembers(ctx, idx).Result()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
_, err = s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
|
|
if len(keys) > 0 {
|
|
p.Del(ctx, keys...)
|
|
}
|
|
p.Del(ctx, idx)
|
|
return nil
|
|
})
|
|
return err
|
|
}
|
|
|
|
func decode(token string, v map[string]string) (*Session, error) {
|
|
user, err := uuid.Parse(v["user"])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var org uuid.UUID
|
|
if v["org"] != "" {
|
|
if org, err = uuid.Parse(v["org"]); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
created, err := strconv.ParseInt(v["created"], 10, 64)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var ssoOrg uuid.UUID
|
|
if v["sso_org"] != "" {
|
|
if ssoOrg, err = uuid.Parse(v["sso_org"]); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return &Session{
|
|
Token: token, UserID: user, OrgID: org, Locale: v["locale"],
|
|
Method: Method(v["method"]), SSOOrg: ssoOrg,
|
|
CSRF: v["csrf"], CreatedAt: time.Unix(created, 0),
|
|
}, nil
|
|
}
|
|
|
|
func orgString(id uuid.UUID) string {
|
|
if id == uuid.Nil {
|
|
return ""
|
|
}
|
|
return id.String()
|
|
}
|