Перенести мессенджер на PostgreSQL и сессии Redis.
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
Сообщения должны переживать рестарт, а доступ идти через Bearer, а не X-User-Id. Трек 2 сравнивает план keyset-запроса и сверяет pg_restore.
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
// Package session хранит opaque Bearer-сессии в Redis.
|
||||
//
|
||||
// PostgreSQL остаётся источником истины для пользователей и сообщений.
|
||||
// Сессия — отдельная роль: случайный токен, срок жизни SESSION_TTL_SECONDS и отзыв.
|
||||
// В Redis лежит не сам токен, а его SHA-256: дамп AOF не содержит значение,
|
||||
// которое клиент предъявляет в Authorization.
|
||||
//
|
||||
// TTL ключа равен оставшемуся сроку сессии. Рестарт API его не продлевает.
|
||||
// Рестарт Redis сессию сохраняет только потому, что включён AOF на volume.
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
)
|
||||
|
||||
// Store — клиент Redis с короткими таймаутами.
|
||||
type Store struct {
|
||||
client *redis.Client
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
// Open разбирает redis:// URL. Пароль в лог не пишется.
|
||||
func Open(redisURL string, ttl time.Duration) (*Store, error) {
|
||||
opt, err := redis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse redis url: %w", err)
|
||||
}
|
||||
opt.DialTimeout = 500 * time.Millisecond
|
||||
opt.ReadTimeout = 500 * time.Millisecond
|
||||
opt.WriteTimeout = 500 * time.Millisecond
|
||||
opt.PoolSize = 20
|
||||
client := redis.NewClient(opt)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Store{client: client, ttl: ttl}, nil
|
||||
}
|
||||
|
||||
// Close закрывает пул при остановке процесса.
|
||||
func (s *Store) Close() error {
|
||||
return s.client.Close()
|
||||
}
|
||||
|
||||
// Ping — готовность кэша сессий. Недоступный Redis не означает «анонимный доступ».
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := s.client.Ping(ctx).Err(); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Issue выпускает 256 бит случайности (32 байта) и кладёт сессию с TTL.
|
||||
// Наружу уходит hex (64 символа). В Redis — только хеш.
|
||||
func (s *Store) Issue(ctx context.Context, userID uuid.UUID) (token string, expiresAt time.Time, err error) {
|
||||
buf := make([]byte, 32)
|
||||
if _, err = rand.Read(buf); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
token = hex.EncodeToString(buf)
|
||||
expiresAt = time.Now().UTC().Add(s.ttl).Truncate(time.Millisecond)
|
||||
value := userID.String() + "|" + expiresAt.Format(time.RFC3339Nano)
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
if err = s.client.Set(ctx, key(token), value, time.Until(expiresAt)).Err(); err != nil {
|
||||
return "", time.Time{}, ErrUnavailable
|
||||
}
|
||||
return token, expiresAt, nil
|
||||
}
|
||||
|
||||
// Lookup возвращает владельца живой сессии.
|
||||
// Промах и истёкший срок — ErrUnauthorized. Сбой Redis — ErrUnavailable (HTTP 503).
|
||||
func (s *Store) Lookup(ctx context.Context, token string) (uuid.UUID, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
raw, err := s.client.Get(ctx, key(token)).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, ErrUnavailable
|
||||
}
|
||||
userPart, expPart, ok := strings.Cut(raw, "|")
|
||||
if !ok {
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
exp, err := time.Parse(time.RFC3339Nano, expPart)
|
||||
if err != nil || !exp.After(time.Now()) {
|
||||
_ = s.client.Del(ctx, key(token)).Err()
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
id, err := uuid.Parse(userPart)
|
||||
if err != nil {
|
||||
return uuid.Nil, ErrUnauthorized
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// Revoke удаляет текущую сессию. Повторный отзыв — это уже отсутствие ключа.
|
||||
func (s *Store) Revoke(ctx context.Context, token string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
n, err := s.client.Del(ctx, key(token)).Result()
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if n == 0 {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func key(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return "sess:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
Reference in New Issue
Block a user