feat(auth): store sessions in redis with sliding and absolute expiry
Tokens are only kept as SHA-256 hashes. A per-user index allows ending all sessions of an account at once. Closes #1 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
ccc0fe58b8
commit
dae55d8c18
2 files changed
+274
No files matched your search
@@ -0,0 +1,174 @@
|
|||||||
|
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"
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrNoSession = errors.New("auth: no session")
|
||||||
|
|
||||||
|
type Session struct {
|
||||||
|
Token string
|
||||||
|
UserID uuid.UUID
|
||||||
|
OrgID uuid.UUID
|
||||||
|
CSRF string
|
||||||
|
CreatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Session) CheckCSRF(token string) bool {
|
||||||
|
return token != "" && subtle.ConstantTimeCompare([]byte(token), []byte(s.CSRF)) == 1
|
||||||
|
}
|
||||||
|
|
||||||
|
type Sessions struct {
|
||||||
|
rdb redis.UniversalClient
|
||||||
|
idle time.Duration
|
||||||
|
absolute time.Duration
|
||||||
|
now func() time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
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() }
|
||||||
|
|
||||||
|
func randomToken() string {
|
||||||
|
b := make([]byte, 32)
|
||||||
|
_, _ = rand.Read(b)
|
||||||
|
return base64.RawURLEncoding.EncodeToString(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Sessions) Create(ctx context.Context, user, org uuid.UUID) (*Session, error) {
|
||||||
|
sess := &Session{
|
||||||
|
Token: randomToken(),
|
||||||
|
UserID: user,
|
||||||
|
OrgID: org,
|
||||||
|
CSRF: randomToken(),
|
||||||
|
CreatedAt: s.now(),
|
||||||
|
}
|
||||||
|
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(org),
|
||||||
|
"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
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
return &Session{Token: token, UserID: user, OrgID: org, CSRF: v["csrf"], CreatedAt: time.Unix(created, 0)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func orgString(id uuid.UUID) string {
|
||||||
|
if id == uuid.Nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return id.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
|
)
|
||||||
|
|
||||||
|
func testSessions(t *testing.T) (*Sessions, *time.Time) {
|
||||||
|
t.Helper()
|
||||||
|
url := os.Getenv("UPTIME_TEST_REDIS_URL")
|
||||||
|
if url == "" {
|
||||||
|
t.Skip("UPTIME_TEST_REDIS_URL not set")
|
||||||
|
}
|
||||||
|
opts, err := redis.ParseURL(url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
rdb := redis.NewClient(opts)
|
||||||
|
t.Cleanup(func() { _ = rdb.Close() })
|
||||||
|
now := time.Now()
|
||||||
|
s := NewSessions(rdb, time.Hour, 24*time.Hour)
|
||||||
|
s.now = func() time.Time { return now }
|
||||||
|
return s, &now
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionRoundTrip(t *testing.T) {
|
||||||
|
s, _ := testSessions(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
user, org := uuid.New(), uuid.New()
|
||||||
|
|
||||||
|
created, err := s.Create(ctx, user, org)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, err := s.Get(ctx, created.Token)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got.UserID != user || got.OrgID != org || got.CSRF != created.CSRF {
|
||||||
|
t.Fatalf("mismatch: %+v vs %+v", got, created)
|
||||||
|
}
|
||||||
|
if !got.CheckCSRF(created.CSRF) || got.CheckCSRF("") || got.CheckCSRF("x") {
|
||||||
|
t.Fatal("csrf check wrong")
|
||||||
|
}
|
||||||
|
if err := s.Delete(ctx, got); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := s.Get(ctx, created.Token); !errors.Is(err, ErrNoSession) {
|
||||||
|
t.Fatalf("deleted session still valid: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionAbsoluteLifetime(t *testing.T) {
|
||||||
|
s, now := testSessions(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
sess, err := s.Create(ctx, uuid.New(), uuid.Nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
*now = now.Add(25 * time.Hour)
|
||||||
|
if _, err := s.Get(ctx, sess.Token); !errors.Is(err, ErrNoSession) {
|
||||||
|
t.Fatalf("expired session accepted: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDeleteAllForUser(t *testing.T) {
|
||||||
|
s, _ := testSessions(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
user := uuid.New()
|
||||||
|
a, _ := s.Create(ctx, user, uuid.Nil)
|
||||||
|
b, _ := s.Create(ctx, user, uuid.Nil)
|
||||||
|
other, _ := s.Create(ctx, uuid.New(), uuid.Nil)
|
||||||
|
|
||||||
|
if err := s.DeleteAllForUser(ctx, user); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, tok := range []string{a.Token, b.Token} {
|
||||||
|
if _, err := s.Get(ctx, tok); !errors.Is(err, ErrNoSession) {
|
||||||
|
t.Fatal("session survived DeleteAllForUser")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := s.Get(ctx, other.Token); err != nil {
|
||||||
|
t.Fatalf("unrelated session removed: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTokenNotStoredInPlain(t *testing.T) {
|
||||||
|
s, _ := testSessions(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
sess, _ := s.Create(ctx, uuid.New(), uuid.Nil)
|
||||||
|
if n, _ := s.rdb.Exists(ctx, "session:"+sess.Token).Result(); n != 0 {
|
||||||
|
t.Fatal("raw token used as redis key")
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user