Stage 1: backend foundation (Postgres, sessions, accounts, OTel)
- internal/postgres: pgx-over-database/sql pool (otelsql), embedded goose
migrations into schema 'backend', committed go-jet code + cmd/jetgen tool.
- internal/account: durable accounts + unified telegram/email identities
(UUIDv7 keys), find-or-create provisioning with unique-conflict handling.
- internal/session: opaque 256-bit tokens stored as a SHA-256 hash, revoke-only
(no TTL); write-through cache gating /readyz; store + service.
- internal/telemetry: OTel tracer/meter providers (none/stdout) + request-timing
middleware; internal/config gains Postgres + OTel env loading.
- internal/server: /api/v1 {public,user,internal,admin} skeleton + X-User-ID
middleware; /readyz checks DB ping + cache; main wires
telemetry -> db+migrate -> warm cache -> server.
- Tests: unit + integration (build tag 'integration', testcontainers
postgres:17) for migrations, accounts, sessions, readyz; new integration.yaml.
- Docs: ARCHITECTURE, TESTING, PLAN refinements, root + backend READMEs.
Session/account REST handlers deferred to Stage 6 (gateway); OTLP + dashboards
to Stage 11.
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// Cache is the in-memory write-through projection of the active rows in
|
||||
// backend.sessions, keyed by token hash so Resolve avoids a database round-trip
|
||||
// on the hot path. Reads are RLocked; writes are Locked. Callers commit the
|
||||
// corresponding database write before invoking Add or Remove so the cache stays
|
||||
// consistent with the persisted state.
|
||||
type Cache struct {
|
||||
mu sync.RWMutex
|
||||
byHash map[string]Session
|
||||
ready atomic.Bool
|
||||
}
|
||||
|
||||
// NewCache constructs an empty Cache. It reports Ready() == false until Warm
|
||||
// completes successfully.
|
||||
func NewCache() *Cache {
|
||||
return &Cache{byHash: make(map[string]Session)}
|
||||
}
|
||||
|
||||
// Warm replaces the cache contents with every active session loaded from store.
|
||||
// It is intended to run once at process boot before the listener accepts
|
||||
// traffic; success flips Ready to true. Re-warming is supported (useful in
|
||||
// tests).
|
||||
func (c *Cache) Warm(ctx context.Context, store *Store) error {
|
||||
sessions, err := store.ListActive(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.byHash = make(map[string]Session, len(sessions))
|
||||
for _, s := range sessions {
|
||||
c.byHash[s.TokenHash] = s
|
||||
}
|
||||
c.ready.Store(true)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Ready reports whether Warm has completed at least once. The /readyz probe
|
||||
// wires through this so the backend only reports ready once sessions are
|
||||
// hydrated.
|
||||
func (c *Cache) Ready() bool {
|
||||
if c == nil {
|
||||
return false
|
||||
}
|
||||
return c.ready.Load()
|
||||
}
|
||||
|
||||
// Size returns the number of cached active sessions, for startup logs and tests.
|
||||
func (c *Cache) Size() int {
|
||||
if c == nil {
|
||||
return 0
|
||||
}
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
return len(c.byHash)
|
||||
}
|
||||
|
||||
// Get returns the session for tokenHash and a presence flag. A miss returns the
|
||||
// zero Session and false.
|
||||
func (c *Cache) Get(tokenHash string) (Session, bool) {
|
||||
if c == nil {
|
||||
return Session{}, false
|
||||
}
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
s, ok := c.byHash[tokenHash]
|
||||
return s, ok
|
||||
}
|
||||
|
||||
// Add stores s under its token hash. It is safe to call on an existing entry.
|
||||
func (c *Cache) Add(s Session) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.byHash[s.TokenHash] = s
|
||||
}
|
||||
|
||||
// Remove evicts the entry for tokenHash. Removing a missing entry is a no-op.
|
||||
func (c *Cache) Remove(tokenHash string) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
delete(c.byHash, tokenHash)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// TestCache exercises the write-through cache's add/get/remove/size/ready cycle.
|
||||
func TestCache(t *testing.T) {
|
||||
c := NewCache()
|
||||
if c.Ready() {
|
||||
t.Error("a fresh cache must not report ready")
|
||||
}
|
||||
if _, ok := c.Get("h1"); ok {
|
||||
t.Error("get on empty cache must miss")
|
||||
}
|
||||
|
||||
s := Session{ID: uuid.New(), AccountID: uuid.New(), TokenHash: "h1", Status: StatusActive}
|
||||
c.Add(s)
|
||||
if got, ok := c.Get("h1"); !ok || got.ID != s.ID {
|
||||
t.Fatalf("get after add: got %v ok=%v", got.ID, ok)
|
||||
}
|
||||
if c.Size() != 1 {
|
||||
t.Errorf("size = %d, want 1", c.Size())
|
||||
}
|
||||
|
||||
c.Remove("h1")
|
||||
if _, ok := c.Get("h1"); ok {
|
||||
t.Error("get after remove must miss")
|
||||
}
|
||||
if c.Size() != 0 {
|
||||
t.Errorf("size = %d, want 0", c.Size())
|
||||
}
|
||||
}
|
||||
|
||||
// TestCacheNilSafe checks that the cache methods are safe on a nil receiver,
|
||||
// which the readiness probe relies on before the cache is constructed.
|
||||
func TestCacheNilSafe(t *testing.T) {
|
||||
var c *Cache
|
||||
if c.Ready() {
|
||||
t.Error("nil cache must not be ready")
|
||||
}
|
||||
if _, ok := c.Get("x"); ok {
|
||||
t.Error("nil cache get must miss")
|
||||
}
|
||||
if c.Size() != 0 {
|
||||
t.Error("nil cache size must be 0")
|
||||
}
|
||||
c.Add(Session{TokenHash: "x"}) // must not panic
|
||||
c.Remove("x") // must not panic
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Service mints, resolves, and revokes sessions over the store and the
|
||||
// write-through cache. The gateway is its only caller (from a later stage); the
|
||||
// HTTP surface is wired then.
|
||||
type Service struct {
|
||||
store *Store
|
||||
cache *Cache
|
||||
}
|
||||
|
||||
// NewService constructs a Service over store and cache.
|
||||
func NewService(store *Store, cache *Cache) *Service {
|
||||
return &Service{store: store, cache: cache}
|
||||
}
|
||||
|
||||
// Warm hydrates the cache from the store. Call once before serving traffic.
|
||||
func (svc *Service) Warm(ctx context.Context) error {
|
||||
return svc.cache.Warm(ctx, svc.store)
|
||||
}
|
||||
|
||||
// Ready reports whether the session cache has been warmed.
|
||||
func (svc *Service) Ready() bool {
|
||||
return svc.cache.Ready()
|
||||
}
|
||||
|
||||
// Create mints a new active session for accountID and returns the plaintext
|
||||
// token (shown to the caller once) together with the persisted session.
|
||||
func (svc *Service) Create(ctx context.Context, accountID uuid.UUID) (string, Session, error) {
|
||||
token, tokenHash, err := GenerateToken()
|
||||
if err != nil {
|
||||
return "", Session{}, err
|
||||
}
|
||||
sess, err := svc.store.Insert(ctx, accountID, tokenHash)
|
||||
if err != nil {
|
||||
return "", Session{}, err
|
||||
}
|
||||
svc.cache.Add(sess)
|
||||
return token, sess, nil
|
||||
}
|
||||
|
||||
// Resolve maps a presented token to its active session, consulting the cache
|
||||
// first and falling back to the store (repopulating the cache on a hit).
|
||||
// Returns ErrNotFound when no active session matches.
|
||||
func (svc *Service) Resolve(ctx context.Context, token string) (Session, error) {
|
||||
hash := HashToken(token)
|
||||
if sess, ok := svc.cache.Get(hash); ok {
|
||||
return sess, nil
|
||||
}
|
||||
sess, err := svc.store.FindActiveByTokenHash(ctx, hash)
|
||||
if err != nil {
|
||||
return Session{}, err
|
||||
}
|
||||
svc.cache.Add(sess)
|
||||
return sess, nil
|
||||
}
|
||||
|
||||
// Revoke revokes the session for the presented token. It is idempotent:
|
||||
// revoking an unknown or already-revoked token returns nil.
|
||||
func (svc *Service) Revoke(ctx context.Context, token string) error {
|
||||
hash := HashToken(token)
|
||||
if _, _, err := svc.store.RevokeByTokenHash(ctx, hash, time.Now().UTC()); err != nil {
|
||||
return err
|
||||
}
|
||||
svc.cache.Remove(hash)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/go-jet/jet/v2/postgres"
|
||||
"github.com/go-jet/jet/v2/qrm"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"scrabble/backend/internal/postgres/jet/backend/model"
|
||||
"scrabble/backend/internal/postgres/jet/backend/table"
|
||||
)
|
||||
|
||||
// Session lifecycle statuses persisted in the status column.
|
||||
const (
|
||||
StatusActive = "active"
|
||||
StatusRevoked = "revoked"
|
||||
)
|
||||
|
||||
// ErrNotFound is returned when no active session matches the lookup.
|
||||
var ErrNotFound = errors.New("session: not found")
|
||||
|
||||
// Session mirrors a row in backend.sessions. TokenHash is the hex-encoded
|
||||
// SHA-256 of the bearer token.
|
||||
type Session struct {
|
||||
ID uuid.UUID
|
||||
AccountID uuid.UUID
|
||||
TokenHash string
|
||||
Status string
|
||||
CreatedAt time.Time
|
||||
LastSeenAt *time.Time
|
||||
RevokedAt *time.Time
|
||||
}
|
||||
|
||||
// Store is the Postgres-backed query surface for backend.sessions.
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
// NewStore constructs a Store wrapping db.
|
||||
func NewStore(db *sql.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
|
||||
// Insert persists a new active session for accountID carrying tokenHash and
|
||||
// returns the persisted row.
|
||||
func (s *Store) Insert(ctx context.Context, accountID uuid.UUID, tokenHash string) (Session, error) {
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return Session{}, fmt.Errorf("session: new id: %w", err)
|
||||
}
|
||||
stmt := table.Sessions.INSERT(
|
||||
table.Sessions.SessionID,
|
||||
table.Sessions.AccountID,
|
||||
table.Sessions.TokenHash,
|
||||
).VALUES(id, accountID, tokenHash).RETURNING(table.Sessions.AllColumns)
|
||||
|
||||
var row model.Sessions
|
||||
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
|
||||
return Session{}, fmt.Errorf("session: insert: %w", err)
|
||||
}
|
||||
return modelToSession(row), nil
|
||||
}
|
||||
|
||||
// FindActiveByTokenHash returns the active session matching tokenHash, or
|
||||
// ErrNotFound.
|
||||
func (s *Store) FindActiveByTokenHash(ctx context.Context, tokenHash string) (Session, error) {
|
||||
stmt := postgres.SELECT(table.Sessions.AllColumns).
|
||||
FROM(table.Sessions).
|
||||
WHERE(
|
||||
table.Sessions.TokenHash.EQ(postgres.String(tokenHash)).
|
||||
AND(table.Sessions.Status.EQ(postgres.String(StatusActive))),
|
||||
).
|
||||
LIMIT(1)
|
||||
|
||||
var row model.Sessions
|
||||
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
|
||||
if errors.Is(err, qrm.ErrNoRows) {
|
||||
return Session{}, ErrNotFound
|
||||
}
|
||||
return Session{}, fmt.Errorf("session: find by token hash: %w", err)
|
||||
}
|
||||
return modelToSession(row), nil
|
||||
}
|
||||
|
||||
// RevokeByTokenHash transitions the active session for tokenHash to revoked and
|
||||
// returns the post-update row. ok is false with a nil error when no active
|
||||
// session matched, so revocation is idempotent.
|
||||
func (s *Store) RevokeByTokenHash(ctx context.Context, tokenHash string, at time.Time) (Session, bool, error) {
|
||||
stmt := table.Sessions.
|
||||
UPDATE(table.Sessions.Status, table.Sessions.RevokedAt).
|
||||
SET(postgres.String(StatusRevoked), postgres.TimestampzT(at)).
|
||||
WHERE(
|
||||
table.Sessions.TokenHash.EQ(postgres.String(tokenHash)).
|
||||
AND(table.Sessions.Status.EQ(postgres.String(StatusActive))),
|
||||
).
|
||||
RETURNING(table.Sessions.AllColumns)
|
||||
|
||||
var row model.Sessions
|
||||
if err := stmt.QueryContext(ctx, s.db, &row); err != nil {
|
||||
if errors.Is(err, qrm.ErrNoRows) {
|
||||
return Session{}, false, nil
|
||||
}
|
||||
return Session{}, false, fmt.Errorf("session: revoke by token hash: %w", err)
|
||||
}
|
||||
return modelToSession(row), true, nil
|
||||
}
|
||||
|
||||
// ListActive loads every active session. Cache.Warm calls this at boot.
|
||||
func (s *Store) ListActive(ctx context.Context) ([]Session, error) {
|
||||
stmt := postgres.SELECT(table.Sessions.AllColumns).
|
||||
FROM(table.Sessions).
|
||||
WHERE(table.Sessions.Status.EQ(postgres.String(StatusActive)))
|
||||
|
||||
var rows []model.Sessions
|
||||
if err := stmt.QueryContext(ctx, s.db, &rows); err != nil {
|
||||
return nil, fmt.Errorf("session: list active: %w", err)
|
||||
}
|
||||
out := make([]Session, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
out = append(out, modelToSession(row))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// modelToSession projects a generated model row into the public Session struct,
|
||||
// copying pointer fields so callers cannot mutate the scan buffer.
|
||||
func modelToSession(row model.Sessions) Session {
|
||||
s := Session{
|
||||
ID: row.SessionID,
|
||||
AccountID: row.AccountID,
|
||||
TokenHash: row.TokenHash,
|
||||
Status: row.Status,
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
if row.LastSeenAt != nil {
|
||||
t := *row.LastSeenAt
|
||||
s.LastSeenAt = &t
|
||||
}
|
||||
if row.RevokedAt != nil {
|
||||
t := *row.RevokedAt
|
||||
s.RevokedAt = &t
|
||||
}
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// Package session owns opaque server sessions: minting bearer tokens, resolving
|
||||
// them to accounts through a write-through in-memory cache, and revoking them.
|
||||
// Only the SHA-256 hash of a token is persisted; the plaintext is returned to
|
||||
// the caller once and never stored. Sessions are revoke-only (no TTL).
|
||||
package session
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// tokenBytes is the entropy of an opaque session token: 256 bits.
|
||||
const tokenBytes = 32
|
||||
|
||||
// GenerateToken returns a fresh random opaque token (URL-safe base64, 256-bit)
|
||||
// together with its hex-encoded SHA-256 hash for storage. The plaintext token
|
||||
// is handed to the caller once and is never persisted.
|
||||
func GenerateToken() (token, tokenHash string, err error) {
|
||||
buf := make([]byte, tokenBytes)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", "", fmt.Errorf("session: read random token: %w", err)
|
||||
}
|
||||
token = base64.RawURLEncoding.EncodeToString(buf)
|
||||
return token, HashToken(token), nil
|
||||
}
|
||||
|
||||
// HashToken returns the hex-encoded SHA-256 of token. Lookups hash the presented
|
||||
// token and compare against the stored hash.
|
||||
func HashToken(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package session
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestGenerateTokenUniqueAndHashed checks that tokens are unique, the stored
|
||||
// value is the hash (not the plaintext), and the hash is a 64-char SHA-256 hex.
|
||||
func TestGenerateTokenUniqueAndHashed(t *testing.T) {
|
||||
tok1, hash1, err := GenerateToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateToken: %v", err)
|
||||
}
|
||||
tok2, hash2, err := GenerateToken()
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateToken: %v", err)
|
||||
}
|
||||
|
||||
if tok1 == tok2 {
|
||||
t.Error("tokens must be unique")
|
||||
}
|
||||
if hash1 == hash2 {
|
||||
t.Error("hashes must differ for distinct tokens")
|
||||
}
|
||||
if hash1 != HashToken(tok1) {
|
||||
t.Error("stored hash must equal HashToken(token)")
|
||||
}
|
||||
if tok1 == hash1 {
|
||||
t.Error("stored hash must not equal the plaintext token")
|
||||
}
|
||||
if len(hash1) != 64 {
|
||||
t.Errorf("hash length = %d, want 64 (sha256 hex)", len(hash1))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHashTokenDeterministic checks that hashing is stable for a given token.
|
||||
func TestHashTokenDeterministic(t *testing.T) {
|
||||
first := HashToken("alpha")
|
||||
second := HashToken("alpha")
|
||||
if first != second {
|
||||
t.Error("HashToken must be deterministic")
|
||||
}
|
||||
if first == HashToken("beta") {
|
||||
t.Error("distinct tokens must hash differently")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user