forked from mtusi2026/mtusi2026lab2
Реализовать лабораторную 2: PostgreSQL, Bearer-сессии и Valkey
Переносит минимум lab1 на PostgreSQL, добавляет Argon2id, Basic-вход, opaque Bearer-сессии в Valkey с TTL и AOF, строгую валидацию JSON, keyset-пагинацию по индексу, миграции, compose-стенд и собственные проверки уровня 3/4. Трек 5 — план запроса и восстановление.
This commit is contained in:
@@ -0,0 +1,151 @@
|
||||
// Package session stores opaque server-side sessions in Valkey. The token is
|
||||
// never persisted: only its SHA-256 hash is used as the cache key, so a cache
|
||||
// dump does not contain credentials that can be replayed against the API.
|
||||
//
|
||||
// Valkey is the source of truth for sessions. It is configured with AOF
|
||||
// persistence and a named volume, so valid sessions survive both the API
|
||||
// process and the Valkey process restarting with volumes kept.
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi.ru/messenger-lab2/internal/auth"
|
||||
)
|
||||
|
||||
const keyPrefix = "mtusi:lab2:session:"
|
||||
|
||||
var (
|
||||
// ErrInvalid means the token is unknown, expired or malformed.
|
||||
ErrInvalid = errors.New("invalid session")
|
||||
// ErrUnavailable means Valkey is not answering; the API must return a
|
||||
// bounded 503 instead of trusting the bearer token.
|
||||
ErrUnavailable = errors.New("session store unavailable")
|
||||
)
|
||||
|
||||
type record struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
// Options bound every network operation and the connection pool.
|
||||
type Options struct {
|
||||
PoolSize int
|
||||
DialTimeout time.Duration
|
||||
IOTimeout time.Duration
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
// Store is a thin, timeout-aware wrapper around go-redis.
|
||||
type Store struct {
|
||||
client *redis.Client
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
// Open parses CACHE_URL (redis:// or rediss://) without echoing it in errors.
|
||||
// It does not require Valkey to be reachable at startup: /health/ready and
|
||||
// login report the outage as 503.
|
||||
func Open(rawURL string, options Options) (*Store, error) {
|
||||
parsed, err := redis.ParseURL(rawURL)
|
||||
if err != nil {
|
||||
return nil, errors.New("CACHE_URL is not a valid Redis/Valkey URL")
|
||||
}
|
||||
if options.PoolSize <= 0 {
|
||||
options.PoolSize = 8
|
||||
}
|
||||
if options.DialTimeout <= 0 {
|
||||
options.DialTimeout = 2 * time.Second
|
||||
}
|
||||
if options.IOTimeout <= 0 {
|
||||
options.IOTimeout = 2 * time.Second
|
||||
}
|
||||
if options.TTL <= 0 {
|
||||
options.TTL = time.Hour
|
||||
}
|
||||
parsed.PoolSize = options.PoolSize
|
||||
parsed.DialTimeout = options.DialTimeout
|
||||
parsed.ReadTimeout = options.IOTimeout
|
||||
parsed.WriteTimeout = options.IOTimeout
|
||||
// One retry keeps a transient blip invisible while bounding the worst-case
|
||||
// time a handler spends waiting for the cache.
|
||||
parsed.MaxRetries = 1
|
||||
parsed.MinRetryBackoff = 20 * time.Millisecond
|
||||
parsed.MaxRetryBackoff = 100 * time.Millisecond
|
||||
return &Store{client: redis.NewClient(parsed), ttl: options.TTL}, nil
|
||||
}
|
||||
|
||||
// TTL exposes the configured session lifetime (used by tests and startup logs).
|
||||
func (s *Store) TTL() time.Duration { return s.ttl }
|
||||
|
||||
// Create issues a new opaque token and stores the session with a TTL. The
|
||||
// returned expiry is the absolute instant the client must treat as the end of
|
||||
// the session; restarting a process does not extend it.
|
||||
func (s *Store) Create(ctx context.Context, userID string) (token string, expiresAt time.Time, err error) {
|
||||
token, err = auth.NewToken()
|
||||
if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("generate session token: %w", err)
|
||||
}
|
||||
// A whole number of microseconds keeps the value parseable by the
|
||||
// Python 3.9 public client (its fromisoformat accepts 3 or 6 fractional
|
||||
// digits, not Go's trimmed nanosecond form) while staying RFC 3339.
|
||||
expiresAt = time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond)
|
||||
payload, err := json.Marshal(record{UserID: userID, ExpiresAt: expiresAt})
|
||||
if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("encode session: %w", err)
|
||||
}
|
||||
if err := s.client.Set(ctx, key(auth.TokenHash(token)), payload, s.ttl).Err(); err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return token, expiresAt, nil
|
||||
}
|
||||
|
||||
// Get resolves a token to a user id. Unknown, expired and corrupt records are
|
||||
// all ErrInvalid; a transport failure is ErrUnavailable.
|
||||
func (s *Store) Get(ctx context.Context, token string) (string, error) {
|
||||
raw, err := s.client.Get(ctx, key(auth.TokenHash(token))).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
var value record
|
||||
if err := json.Unmarshal(raw, &value); err != nil || value.UserID == "" {
|
||||
return "", ErrInvalid
|
||||
}
|
||||
if !value.ExpiresAt.After(time.Now()) {
|
||||
// TTL should already have removed the key; this also covers a clock
|
||||
// adjustment or an externally imported record.
|
||||
_ = s.client.Del(ctx, key(auth.TokenHash(token))).Err()
|
||||
return "", ErrInvalid
|
||||
}
|
||||
return value.UserID, nil
|
||||
}
|
||||
|
||||
// Delete revokes the session. Missing keys are not an error here: the caller
|
||||
// has already authenticated the token, and a concurrent logout is harmless.
|
||||
func (s *Store) Delete(ctx context.Context, token string) error {
|
||||
if err := s.client.Del(ctx, key(auth.TokenHash(token))).Err(); err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ping is used by /health/ready and the startup log.
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
if err := s.client.Ping(ctx).Err(); err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrUnavailable, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close releases the connection pool.
|
||||
func (s *Store) Close() error { return s.client.Close() }
|
||||
|
||||
func key(tokenHash string) string { return keyPrefix + tokenHash }
|
||||
Reference in New Issue
Block a user