Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(server/auth): cache auth token lookups in Redis with 10m TTL

Bohan Jiang86e7de3e4187
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index f384d2caa5..e4a0e98b6e 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -5,6 +5,7 @@ import (
"net/http"
"os"
"strings"
+ "time"
"github.com/go-chi/chi/v5"
chimw "github.com/go-chi/chi/v5/middleware"
@@ -108,6 +109,15 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
h.LocalSkillListStore = handler.NewRedisLocalSkillListStore(rdb)
h.LocalSkillImportStore = handler.NewRedisLocalSkillImportStore(rdb)
}
+ // Auth caches: PAT cache is shared between the regular Auth middleware,
+ // the DaemonAuth fallback (mul_) path, and the revoke handler
+ // (invalidate). DaemonTokenCache backs the DaemonAuth mdt_ path. Both
+ // constructors return nil when rdb is nil — every consumer handles that
+ // as "no cache, always hit DB".
+ patCache := auth.NewPATCache(rdb)
+ daemonTokenCache := auth.NewDaemonTokenCache(rdb)
+ h.PATCache = patCache
+ h.DaemonTokenCache = daemonTokenCache
health := newServerHealth(pool)
r := chi.NewRouter()
@@ -152,7 +162,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// WebSocket
mc := &membershipChecker{queries: queries}
- pr := &patResolver{queries: queries}
+ pr := &patResolver{queries: queries, cache: patCache}
slugResolver := realtime.SlugResolver(func(ctx context.Context, slug string) (string, error) {
ws, err := queries.GetWorkspaceBySlug(ctx, slug)
if err != nil {
@@ -183,7 +193,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Daemon API routes (require daemon token or valid user token)
r.Route("/api/daemon", func(r chi.Router) {
- r.Use(middleware.DaemonAuth(queries))
+ r.Use(middleware.DaemonAuth(queries, patCache, daemonTokenCache))
r.Post("/register", h.DaemonRegister)
r.Post("/deregister", h.DaemonDeregister)
@@ -215,7 +225,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Protected API routes
r.Group(func(r chi.Router) {
- r.Use(middleware.Auth(queries))
+ r.Use(middleware.Auth(queries, patCache))
r.Use(middleware.RefreshCloudFrontCookies(cfSigner))
// --- User-scoped routes (no workspace context required) ---
@@ -493,19 +503,39 @@ func (mc *membershipChecker) IsMember(ctx context.Context, userID, workspaceID s
}
// patResolver implements realtime.PATResolver using database queries.
+// patCache is shared with the Auth and DaemonAuth middlewares so a token
+// revoke through any path invalidates the cache for all of them. Nil
+// cache is supported and degrades to direct DB lookups.
type patResolver struct {
queries *db.Queries
+ cache *auth.PATCache
}
func (pr *patResolver) ResolveToken(ctx context.Context, token string) (string, bool) {
hash := auth.HashToken(token)
+
+ if userID, ok := pr.cache.Get(ctx, hash); ok {
+ return userID, true
+ }
+
pat, err := pr.queries.GetPersonalAccessTokenByHash(ctx, hash)
if err != nil {
return "", false
}
- // Best-effort: update last_used_at
+
+ userID := util.UUIDToString(pat.UserID)
+
+ var expiresAt time.Time
+ if pat.ExpiresAt.Valid {
+ expiresAt = pat.ExpiresAt.Time
+ }
+ pr.cache.Set(ctx, hash, userID, auth.TTLForExpiry(time.Now(), expiresAt))
+
+ // Cache miss = first WS auth in this TTL window. Refresh last_used_at;
+ // subsequent connects within the window skip the write.
go pr.queries.UpdatePersonalAccessTokenLastUsed(context.Background(), pat.ID)
- return util.UUIDToString(pat.UserID), true
+
+ return userID, true
}
// parseUUID is a thin alias for util.MustParseUUID. Call sites here are all
diff --git a/server/internal/auth/daemon_token_cache.go b/server/internal/auth/daemon_token_cache.go
new file mode 100644
index 0000000000..31b3c3820d
--- /dev/null
+++ b/server/internal/auth/daemon_token_cache.go
@@ -0,0 +1,99 @@
+package auth
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+// daemonTokenCachePrefix namespaces daemon-token cache keys separately
+// from PAT (mul:auth:pat:*) so the two key spaces can't collide and an
+// invalidation on one kind of token doesn't accidentally hit the other.
+const daemonTokenCachePrefix = "mul:auth:daemon:"
+
+// DaemonTokenIdentity is what DaemonAuth needs from the cached lookup —
+// the workspace_id and daemon_id that the middleware injects into the
+// request context. We deliberately omit token_hash, expires_at, and the
+// row id; cache entries should leak the minimum.
+type DaemonTokenIdentity struct {
+ WorkspaceID string `json:"w"`
+ DaemonID string `json:"d"`
+}
+
+// DaemonTokenCache caches resolved daemon-token (mdt_) lookups in Redis.
+// A nil *DaemonTokenCache is safe to use — every method becomes a no-op
+// or reports a cache miss, so single-node dev / tests with no REDIS_URL
+// degrade cleanly to direct DB lookups.
+type DaemonTokenCache struct {
+ rdb *redis.Client
+}
+
+// NewDaemonTokenCache returns a cache backed by rdb. Pass nil to disable
+// caching; the returned *DaemonTokenCache is safe to call but never hits
+// Redis.
+func NewDaemonTokenCache(rdb *redis.Client) *DaemonTokenCache {
+ if rdb == nil {
+ return nil
+ }
+ return &DaemonTokenCache{rdb: rdb}
+}
+
+func daemonTokenCacheKey(hash string) string { return daemonTokenCachePrefix + hash }
+
+// Get returns the cached identity for a token hash. ok=false on cache
+// miss or any Redis / decode error — a dead Redis must not take down
+// auth.
+func (c *DaemonTokenCache) Get(ctx context.Context, hash string) (DaemonTokenIdentity, bool) {
+ if c == nil {
+ return DaemonTokenIdentity{}, false
+ }
+ raw, err := c.rdb.Get(ctx, daemonTokenCacheKey(hash)).Bytes()
+ if err != nil {
+ if !errors.Is(err, redis.Nil) {
+ slog.Warn("daemon_token_cache: get failed; falling back to DB", "error", err)
+ }
+ return DaemonTokenIdentity{}, false
+ }
+ var id DaemonTokenIdentity
+ if err := json.Unmarshal(raw, &id); err != nil {
+ slog.Warn("daemon_token_cache: malformed entry; falling back to DB", "error", err)
+ return DaemonTokenIdentity{}, false
+ }
+ return id, true
+}
+
+// Set populates the cache with the given TTL. Use TTLForExpiry to clamp
+// the TTL to the token's remaining lifetime so a daemon token expiring
+// in <AuthCacheTTL can't outlive its expires_at on a cache hit.
+//
+// Errors are logged and swallowed — a cache write failure is not a
+// request failure.
+func (c *DaemonTokenCache) Set(ctx context.Context, hash string, id DaemonTokenIdentity, ttl time.Duration) {
+ if c == nil || ttl <= 0 {
+ return
+ }
+ raw, err := json.Marshal(id)
+ if err != nil {
+ slog.Warn("daemon_token_cache: marshal failed", "error", err)
+ return
+ }
+ if err := c.rdb.Set(ctx, daemonTokenCacheKey(hash), raw, ttl).Err(); err != nil {
+ slog.Warn("daemon_token_cache: set failed", "error", err)
+ }
+}
+
+// Invalidate removes the entry for hash. Called when a daemon token is
+// deleted so the deletion takes effect immediately rather than waiting
+// for the TTL.
+func (c *DaemonTokenCache) Invalidate(ctx context.Context, hash string) {
+ if c == nil {
+ return
+ }
+ if err := c.rdb.Del(ctx, daemonTokenCacheKey(hash)).Err(); err != nil {
+ slog.Warn("daemon_token_cache: invalidate failed; entry will expire on TTL", "error", err)
+ }
+}
diff --git a/server/internal/auth/daemon_token_cache_test.go b/server/internal/auth/daemon_token_cache_test.go
new file mode 100644
index 0000000000..d622042bc6
--- /dev/null
+++ b/server/internal/auth/daemon_token_cache_test.go
@@ -0,0 +1,93 @@
+package auth
+
+import (
+ "context"
+ "testing"
+ "time"
+)
+
+func TestDaemonTokenCache_NilSafe(t *testing.T) {
+ var c *DaemonTokenCache // nil
+ ctx := context.Background()
+
+ if id, ok := c.Get(ctx, "any-hash"); ok || id != (DaemonTokenIdentity{}) {
+ t.Fatalf("nil cache must miss; got (%+v, %v)", id, ok)
+ }
+ c.Set(ctx, "any-hash", DaemonTokenIdentity{WorkspaceID: "w", DaemonID: "d"}, AuthCacheTTL)
+ c.Invalidate(ctx, "any-hash")
+}
+
+func TestNewDaemonTokenCache_NilRedisReturnsNil(t *testing.T) {
+ if c := NewDaemonTokenCache(nil); c != nil {
+ t.Fatalf("NewDaemonTokenCache(nil) must return nil, got %#v", c)
+ }
+}
+
+func TestDaemonTokenCache_SetGetInvalidate(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ c := NewDaemonTokenCache(rdb)
+ if c == nil {
+ t.Fatal("NewDaemonTokenCache returned nil")
+ }
+ ctx := context.Background()
+
+ if _, ok := c.Get(ctx, "missing"); ok {
+ t.Fatal("expected miss before set")
+ }
+
+ want := DaemonTokenIdentity{WorkspaceID: "ws-uuid", DaemonID: "daemon-1"}
+ c.Set(ctx, "hash-D", want, AuthCacheTTL)
+ if got, ok := c.Get(ctx, "hash-D"); !ok || got != want {
+ t.Fatalf("expected hit %+v, got (%+v, %v)", want, got, ok)
+ }
+
+ c.Invalidate(ctx, "hash-D")
+ if _, ok := c.Get(ctx, "hash-D"); ok {
+ t.Fatal("expected miss after invalidate")
+ }
+}
+
+func TestDaemonTokenCache_TTL(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ c := NewDaemonTokenCache(rdb)
+ if c == nil {
+ t.Fatal("NewDaemonTokenCache returned nil")
+ }
+ ctx := context.Background()
+
+ c.Set(ctx, "hash-T", DaemonTokenIdentity{WorkspaceID: "w", DaemonID: "d"}, AuthCacheTTL)
+ ttl, err := rdb.TTL(ctx, daemonTokenCacheKey("hash-T")).Result()
+ if err != nil {
+ t.Fatalf("TTL: %v", err)
+ }
+ if ttl <= 0 || ttl > AuthCacheTTL+time.Second {
+ t.Fatalf("unexpected TTL %v (want ~%v)", ttl, AuthCacheTTL)
+ }
+}
+
+func TestDaemonTokenCache_Set_RespectsClampedTTL(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ c := NewDaemonTokenCache(rdb)
+ if c == nil {
+ t.Fatal("NewDaemonTokenCache returned nil")
+ }
+ ctx := context.Background()
+
+ c.Set(ctx, "hash-short", DaemonTokenIdentity{WorkspaceID: "w", DaemonID: "d"}, 5*time.Second)
+ ttl, err := rdb.TTL(ctx, daemonTokenCacheKey("hash-short")).Result()
+ if err != nil {
+ t.Fatalf("TTL: %v", err)
+ }
+ if ttl <= 0 || ttl > 5*time.Second+time.Second {
+ t.Fatalf("expected clamped TTL ~5s, got %v", ttl)
+ }
+
+ c.Set(ctx, "hash-zero", DaemonTokenIdentity{WorkspaceID: "w", DaemonID: "d"}, 0)
+ if _, ok := c.Get(ctx, "hash-zero"); ok {
+ t.Fatal("zero-TTL Set must not cache")
+ }
+ c.Set(ctx, "hash-neg", DaemonTokenIdentity{WorkspaceID: "w", DaemonID: "d"}, -time.Second)
+ if _, ok := c.Get(ctx, "hash-neg"); ok {
+ t.Fatal("negative-TTL Set must not cache")
+ }
+}
diff --git a/server/internal/auth/pat_cache.go b/server/internal/auth/pat_cache.go
new file mode 100644
index 0000000000..15652e1fc3
--- /dev/null
+++ b/server/internal/auth/pat_cache.go
@@ -0,0 +1,108 @@
+package auth
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+// AuthCacheTTL bounds how long a token-hash lookup stays cached before
+// the auth middleware goes back to Postgres. Shared by PATCache and
+// DaemonTokenCache so both kinds of token follow the same revocation
+// latency contract. Short enough that revocation lag from a missed
+// invalidation is bounded; long enough that a high-frequency client
+// (CLI, daemon) collapses from one DB round-trip per request to one
+// per TTL window.
+const AuthCacheTTL = 10 * time.Minute
+
+// patCachePrefix namespaces auth-cache keys away from the realtime relay
+// (ws:*) and local-skill (mul:local_skill:*) keys.
+const patCachePrefix = "mul:auth:pat:"
+
+// PATCache caches resolved PAT lookups in Redis. A nil *PATCache is safe
+// to use — every method becomes a no-op or reports a cache miss, and the
+// auth middleware degrades to direct DB lookups.
+type PATCache struct {
+ rdb *redis.Client
+}
+
+// NewPATCache returns a cache backed by rdb. Pass nil to disable caching;
+// the returned *PATCache is safe to call but never hits Redis.
+func NewPATCache(rdb *redis.Client) *PATCache {
+ if rdb == nil {
+ return nil
+ }
+ return &PATCache{rdb: rdb}
+}
+
+func patCacheKey(hash string) string { return patCachePrefix + hash }
+
+// Get returns the cached user_id for a token hash. ok=false on cache miss
+// or any Redis error — a dead Redis must not take down auth.
+func (c *PATCache) Get(ctx context.Context, hash string) (userID string, ok bool) {
+ if c == nil {
+ return "", false
+ }
+ v, err := c.rdb.Get(ctx, patCacheKey(hash)).Result()
+ if err != nil {
+ if !errors.Is(err, redis.Nil) {
+ slog.Warn("pat_cache: get failed; falling back to DB", "error", err)
+ }
+ return "", false
+ }
+ return v, true
+}
+
+// Set populates the cache with the given TTL. Callers MUST pass a TTL no
+// longer than the token's remaining lifetime — otherwise an entry could
+// outlive the PAT's expires_at and let an expired token pass auth on
+// cache hit. Use TTLForExpiry to compute it from a token's expires_at.
+//
+// Errors are logged and swallowed — a cache write failure is not a
+// request failure.
+func (c *PATCache) Set(ctx context.Context, hash, userID string, ttl time.Duration) {
+ if c == nil || ttl <= 0 {
+ return
+ }
+ if err := c.rdb.Set(ctx, patCacheKey(hash), userID, ttl).Err(); err != nil {
+ slog.Warn("pat_cache: set failed", "error", err)
+ }
+}
+
+// TTLForExpiry returns the cache TTL for a token given its expires_at.
+// - Zero expiresAt (token never expires) → full AuthCacheTTL.
+// - expiresAt in the future → min(AuthCacheTTL, time until expiry).
+// - expiresAt at or before now → 0 (caller should skip caching; the
+// middleware shouldn't reach here because the SELECT already
+// filters expired tokens, but a TOCTOU between SELECT and Set is
+// possible).
+//
+// Pass time.Time{} when the token has no expiry (pgtype.Timestamptz with
+// Valid=false maps to a zero Time).
+func TTLForExpiry(now, expiresAt time.Time) time.Duration {
+ if expiresAt.IsZero() {
+ return AuthCacheTTL
+ }
+ remaining := expiresAt.Sub(now)
+ if remaining <= 0 {
+ return 0
+ }
+ if remaining < AuthCacheTTL {
+ return remaining
+ }
+ return AuthCacheTTL
+}
+
+// Invalidate removes the entry for hash. Called on PAT revocation so the
+// revoke takes effect immediately rather than waiting for the TTL.
+func (c *PATCache) Invalidate(ctx context.Context, hash string) {
+ if c == nil {
+ return
+ }
+ if err := c.rdb.Del(ctx, patCacheKey(hash)).Err(); err != nil {
+ slog.Warn("pat_cache: invalidate failed; entry will expire on TTL", "error", err)
+ }
+}
diff --git a/server/internal/auth/pat_cache_test.go b/server/internal/auth/pat_cache_test.go
new file mode 100644
index 0000000000..d3a6a57c9e
--- /dev/null
+++ b/server/internal/auth/pat_cache_test.go
@@ -0,0 +1,167 @@
+package auth
+
+import (
+ "context"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/redis/go-redis/v9"
+)
+
+// newRedisTestClient mirrors the helper in the handler package: connect to
+// REDIS_TEST_URL, flush, and skip when unset so `go test ./...` works on a
+// stock laptop without a Redis instance running.
+func newRedisTestClient(t *testing.T) *redis.Client {
+ t.Helper()
+ url := os.Getenv("REDIS_TEST_URL")
+ if url == "" {
+ t.Skip("REDIS_TEST_URL not set")
+ }
+ opts, err := redis.ParseURL(url)
+ if err != nil {
+ t.Fatalf("parse REDIS_TEST_URL: %v", err)
+ }
+ rdb := redis.NewClient(opts)
+ ctx := context.Background()
+ if err := rdb.Ping(ctx).Err(); err != nil {
+ t.Skipf("REDIS_TEST_URL unreachable: %v", err)
+ }
+ if err := rdb.FlushDB(ctx).Err(); err != nil {
+ t.Fatalf("flushdb: %v", err)
+ }
+ t.Cleanup(func() {
+ rdb.FlushDB(context.Background())
+ rdb.Close()
+ })
+ return rdb
+}
+
+func TestPATCache_NilSafe(t *testing.T) {
+ var c *PATCache // nil
+ ctx := context.Background()
+
+ if v, ok := c.Get(ctx, "any-hash"); ok || v != "" {
+ t.Fatalf("nil cache must miss; got (%q, %v)", v, ok)
+ }
+ c.Set(ctx, "any-hash", "user-1", AuthCacheTTL) // no panic
+ c.Invalidate(ctx, "any-hash") // no panic
+}
+
+func TestNewPATCache_NilRedisReturnsNil(t *testing.T) {
+ if c := NewPATCache(nil); c != nil {
+ t.Fatalf("NewPATCache(nil) must return nil, got %#v", c)
+ }
+}
+
+func TestPATCache_SetGetInvalidate(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ c := NewPATCache(rdb)
+ if c == nil {
+ t.Fatal("NewPATCache returned nil")
+ }
+ ctx := context.Background()
+
+ if _, ok := c.Get(ctx, "missing"); ok {
+ t.Fatal("expected miss before set")
+ }
+
+ c.Set(ctx, "hash-A", "user-A", AuthCacheTTL)
+ if v, ok := c.Get(ctx, "hash-A"); !ok || v != "user-A" {
+ t.Fatalf("expected hit user-A, got (%q, %v)", v, ok)
+ }
+
+ c.Invalidate(ctx, "hash-A")
+ if v, ok := c.Get(ctx, "hash-A"); ok {
+ t.Fatalf("expected miss after invalidate, got (%q, %v)", v, ok)
+ }
+}
+
+// TestPATCache_TTL pins the contract that entries expire on AuthCacheTTL so
+// the auth middleware refreshes last_used_at at most once per window.
+//
+// We don't sleep AuthCacheTTL (60s); instead we assert the TTL is what the
+// constructor set, which is the property the middleware actually depends
+// on.
+func TestPATCache_TTL(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ c := NewPATCache(rdb)
+ if c == nil {
+ t.Fatal("NewPATCache returned nil")
+ }
+ ctx := context.Background()
+
+ c.Set(ctx, "hash-T", "user-T", AuthCacheTTL)
+ ttl, err := rdb.TTL(ctx, patCacheKey("hash-T")).Result()
+ if err != nil {
+ t.Fatalf("TTL: %v", err)
+ }
+ // Redis returns the remaining TTL; allow a small skew for rounding.
+ if ttl <= 0 || ttl > AuthCacheTTL+time.Second {
+ t.Fatalf("unexpected TTL %v (want ~%v)", ttl, AuthCacheTTL)
+ }
+}
+
+func TestTTLForExpiry(t *testing.T) {
+ now := time.Date(2026, 4, 29, 12, 0, 0, 0, time.UTC)
+
+ // No expiry set → full AuthCacheTTL.
+ if got := TTLForExpiry(now, time.Time{}); got != AuthCacheTTL {
+ t.Fatalf("zero expires_at: got %v, want %v", got, AuthCacheTTL)
+ }
+
+ // Far-future expiry → full AuthCacheTTL.
+ far := now.Add(24 * time.Hour)
+ if got := TTLForExpiry(now, far); got != AuthCacheTTL {
+ t.Fatalf("far-future expires_at: got %v, want %v", got, AuthCacheTTL)
+ }
+
+ // Sooner-than-TTL expiry → clamped to remaining lifetime.
+ soon := now.Add(10 * time.Second)
+ if got := TTLForExpiry(now, soon); got != 10*time.Second {
+ t.Fatalf("sooner expires_at: got %v, want 10s", got)
+ }
+
+ // Already expired (or exactly now) → 0, caller skips caching.
+ if got := TTLForExpiry(now, now); got != 0 {
+ t.Fatalf("expires_at == now: got %v, want 0", got)
+ }
+ if got := TTLForExpiry(now, now.Add(-time.Second)); got != 0 {
+ t.Fatalf("past expires_at: got %v, want 0", got)
+ }
+}
+
+// TestPATCache_Set_RespectsClampedTTL is the regression test for the
+// review finding: a PAT expiring in <AuthCacheTTL must NOT be cached for
+// the full AuthCacheTTL window, otherwise it would continue passing auth
+// on cache hit after expires_at.
+func TestPATCache_Set_RespectsClampedTTL(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ c := NewPATCache(rdb)
+ if c == nil {
+ t.Fatal("NewPATCache returned nil")
+ }
+ ctx := context.Background()
+
+ // Cache with a 5s TTL — what TTLForExpiry would return for a token
+ // expiring 5s from now.
+ c.Set(ctx, "hash-short", "user-short", 5*time.Second)
+ ttl, err := rdb.TTL(ctx, patCacheKey("hash-short")).Result()
+ if err != nil {
+ t.Fatalf("TTL: %v", err)
+ }
+ if ttl <= 0 || ttl > 5*time.Second+time.Second {
+ t.Fatalf("expected clamped TTL ~5s, got %v", ttl)
+ }
+
+ // Zero / negative TTL must skip caching entirely (already-expired
+ // token's TOCTOU-safe path).
+ c.Set(ctx, "hash-zero", "user-zero", 0)
+ if _, ok := c.Get(ctx, "hash-zero"); ok {
+ t.Fatal("zero-TTL Set must not cache")
+ }
+ c.Set(ctx, "hash-neg", "user-neg", -time.Second)
+ if _, ok := c.Get(ctx, "hash-neg"); ok {
+ t.Fatal("negative-TTL Set must not cache")
+ }
+}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 039e3cce26..a43b6cf854 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -66,6 +66,8 @@ type Handler struct {
Storage storage.Storage
CFSigner *auth.CloudFrontSigner
Analytics analytics.Client
+ PATCache *auth.PATCache
+ DaemonTokenCache *auth.DaemonTokenCache
cfg Config
}
diff --git a/server/internal/handler/personal_access_token.go b/server/internal/handler/personal_access_token.go
index f074aa442b..60af664349 100644
--- a/server/internal/handler/personal_access_token.go
+++ b/server/internal/handler/personal_access_token.go
@@ -2,10 +2,12 @@ package handler
import (
"encoding/json"
+ "errors"
"net/http"
"time"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/auth"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -124,10 +126,19 @@ func (h *Handler) RevokePersonalAccessToken(w http.ResponseWriter, r *http.Reque
if !ok {
return
}
- if err := h.Queries.RevokePersonalAccessToken(r.Context(), db.RevokePersonalAccessTokenParams{
+ hash, err := h.Queries.RevokePersonalAccessToken(r.Context(), db.RevokePersonalAccessTokenParams{
ID: idUUID,
UserID: parseUUID(userID),
- }); err != nil {
+ })
+ switch {
+ case err == nil:
+ // Drop the cache entry immediately so the revocation takes effect
+ // before the TTL would otherwise expire the cached lookup.
+ h.PATCache.Invalidate(r.Context(), hash)
+ case errors.Is(err, pgx.ErrNoRows):
+ // Token doesn't exist or doesn't belong to this user. Preserve the
+ // pre-existing idempotent 204 behavior — no cache entry to clear.
+ default:
writeError(w, http.StatusInternalServerError, "failed to revoke token")
return
}
diff --git a/server/internal/middleware/auth.go b/server/internal/middleware/auth.go
index 3227b83aac..8eeced0cbe 100644
--- a/server/internal/middleware/auth.go
+++ b/server/internal/middleware/auth.go
@@ -5,6 +5,7 @@ import (
"log/slog"
"net/http"
"strings"
+ "time"
"github.com/golang-jwt/jwt/v5"
"github.com/jackc/pgx/v5/pgtype"
@@ -21,7 +22,12 @@ func uuidToString(u pgtype.UUID) string { return util.UUIDToString(u) }
// 2. multica_auth HttpOnly cookie (JWT) — requires valid CSRF token for state-changing requests
//
// Sets X-User-ID and X-User-Email headers on the request for downstream handlers.
-func Auth(queries *db.Queries) func(http.Handler) http.Handler {
+//
+// patCache is optional; when non-nil, PAT lookups are cached with a short
+// TTL (auth.AuthCacheTTL). On cache hit the middleware skips both the DB
+// SELECT and the last_used_at UPDATE — last_used_at is therefore refreshed
+// at most once per TTL window per token, not per request.
+func Auth(queries *db.Queries, patCache *auth.PATCache) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenString, fromCookie := extractToken(r)
@@ -40,11 +46,22 @@ func Auth(queries *db.Queries) func(http.Handler) http.Handler {
// PAT: tokens starting with "mul_"
if strings.HasPrefix(tokenString, "mul_") {
+ hash := auth.HashToken(tokenString)
+
+ // Cache hit: TTL has not expired, the token was valid the
+ // last time we looked, and nothing has invalidated the
+ // entry since. Skip the DB SELECT and the last_used_at
+ // UPDATE — last_used_at is bumped once per TTL window.
+ if userID, ok := patCache.Get(r.Context(), hash); ok {
+ r.Header.Set("X-User-ID", userID)
+ next.ServeHTTP(w, r)
+ return
+ }
+
if queries == nil {
http.Error(w, `{"error":"invalid token"}`, http.StatusUnauthorized)
return
}
- hash := auth.HashToken(tokenString)
pat, err := queries.GetPersonalAccessTokenByHash(r.Context(), hash)
if err != nil {
slog.Warn("auth: invalid PAT", "path", r.URL.Path, "error", err)
@@ -52,9 +69,21 @@ func Auth(queries *db.Queries) func(http.Handler) http.Handler {
return
}
- r.Header.Set("X-User-ID", uuidToString(pat.UserID))
+ userID := uuidToString(pat.UserID)
+ r.Header.Set("X-User-ID", userID)
+
+ // Clamp cache TTL to the token's remaining lifetime so a
+ // PAT expiring in <AuthCacheTTL can't continue passing
+ // auth on a cache hit after expires_at.
+ var expiresAt time.Time
+ if pat.ExpiresAt.Valid {
+ expiresAt = pat.ExpiresAt.Time
+ }
+ patCache.Set(r.Context(), hash, userID, auth.TTLForExpiry(time.Now(), expiresAt))
- // Best-effort: update last_used_at
+ // Cache miss = TTL expired (or first use after revoke /
+ // process restart). Refresh last_used_at; subsequent hits
+ // within the TTL window skip this write entirely.
go queries.UpdatePersonalAccessTokenLastUsed(context.Background(), pat.ID)
next.ServeHTTP(w, r)
diff --git a/server/internal/middleware/auth_test.go b/server/internal/middleware/auth_test.go
index f7d65e8702..bc4abfc6fd 100644
--- a/server/internal/middleware/auth_test.go
+++ b/server/internal/middleware/auth_test.go
@@ -1,15 +1,46 @@
package middleware
import (
+ "context"
"net/http"
"net/http/httptest"
+ "os"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/multica-ai/multica/server/internal/auth"
+ "github.com/redis/go-redis/v9"
)
+// newRedisTestClient connects to REDIS_TEST_URL, flushes, and skips when
+// unset — same gating pattern the rest of the suite uses for Redis-backed
+// tests, so `go test ./...` works on a stock laptop without a Redis.
+func newRedisTestClient(t *testing.T) *redis.Client {
+ t.Helper()
+ url := os.Getenv("REDIS_TEST_URL")
+ if url == "" {
+ t.Skip("REDIS_TEST_URL not set")
+ }
+ opts, err := redis.ParseURL(url)
+ if err != nil {
+ t.Fatalf("parse REDIS_TEST_URL: %v", err)
+ }
+ rdb := redis.NewClient(opts)
+ ctx := context.Background()
+ if err := rdb.Ping(ctx).Err(); err != nil {
+ t.Skipf("REDIS_TEST_URL unreachable: %v", err)
+ }
+ if err := rdb.FlushDB(ctx).Err(); err != nil {
+ t.Fatalf("flushdb: %v", err)
+ }
+ t.Cleanup(func() {
+ rdb.FlushDB(context.Background())
+ rdb.Close()
+ })
+ return rdb
+}
+
func generateToken(claims jwt.MapClaims, secret []byte) string {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
s, _ := token.SignedString(secret)
@@ -26,7 +57,7 @@ func validClaims() jwt.MapClaims {
// authMiddleware returns the Auth middleware with nil queries (JWT-only tests).
func authMiddleware(next http.Handler) http.Handler {
- return Auth(nil)(next)
+ return Auth(nil, nil)(next)
}
func TestAuth_MissingHeader(t *testing.T) {
@@ -196,3 +227,41 @@ func TestAuth_InvalidPAT(t *testing.T) {
t.Fatalf("expected 401, got %d", w.Code)
}
}
+
+// TestAuth_PATCacheHit pins the optimization: when the PAT cache already
+// holds an entry for this token, the middleware MUST NOT call into queries
+// — it short-circuits before the DB lookup and the last_used_at update.
+//
+// We exploit that by passing nil queries: a cache miss would dereference
+// the nil and panic; a cache hit must not. Reaching the next handler with
+// the cached user_id therefore proves the short-circuit fired.
+func TestAuth_PATCacheHit(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ cache := auth.NewPATCache(rdb)
+ if cache == nil {
+ t.Fatal("expected non-nil cache")
+ }
+
+ const rawToken = "mul_cache_hit_test_token"
+ hash := auth.HashToken(rawToken)
+ cache.Set(context.Background(), hash, "cached-user-id", auth.AuthCacheTTL)
+
+ var gotUserID string
+ mw := Auth(nil, cache) // nil queries — only safe on cache hit
+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotUserID = r.Header.Get("X-User-ID")
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest("GET", "/api/me", nil)
+ req.Header.Set("Authorization", "Bearer "+rawToken)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200 on cache hit, got %d", w.Code)
+ }
+ if gotUserID != "cached-user-id" {
+ t.Fatalf("expected cached X-User-ID, got %q", gotUserID)
+ }
+}
diff --git a/server/internal/middleware/daemon_auth.go b/server/internal/middleware/daemon_auth.go
index b53c4acaca..de6bd79bc7 100644
--- a/server/internal/middleware/daemon_auth.go
+++ b/server/internal/middleware/daemon_auth.go
@@ -5,6 +5,7 @@ import (
"log/slog"
"net/http"
"strings"
+ "time"
"github.com/golang-jwt/jwt/v5"
"github.com/multica-ai/multica/server/internal/auth"
@@ -59,7 +60,16 @@ func WithDaemonContext(ctx context.Context, workspaceID, daemonID string) contex
// DaemonAuth validates daemon auth tokens (mdt_ prefix) or falls back to
// JWT/PAT validation for backward compatibility with daemons that
// authenticate via user tokens.
-func DaemonAuth(queries *db.Queries) func(http.Handler) http.Handler {
+//
+// Both caches are optional. When non-nil:
+// - daemonCache short-circuits the daemon_token DB lookup on the mdt_ path
+// - patCache short-circuits the PAT DB lookup AND the last_used_at update
+// on the mul_ fallback path. This is the same cache shared with the
+// regular Auth middleware, so a single hot PAT used by both human CLI
+// and a daemon converges on one DB round-trip per AuthCacheTTL window.
+//
+// Cache misses fall back to the original DB-backed behavior.
+func DaemonAuth(queries *db.Queries, patCache *auth.PATCache, daemonCache *auth.DaemonTokenCache) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
@@ -79,6 +89,19 @@ func DaemonAuth(queries *db.Queries) func(http.Handler) http.Handler {
// Daemon token: "mdt_" prefix.
if strings.HasPrefix(tokenString, "mdt_") {
hash := auth.HashToken(tokenString)
+
+ if id, ok := daemonCache.Get(r.Context(), hash); ok {
+ ctx := context.WithValue(r.Context(), ctxKeyDaemonWorkspaceID, id.WorkspaceID)
+ ctx = context.WithValue(ctx, ctxKeyDaemonID, id.DaemonID)
+ ctx = context.WithValue(ctx, ctxKeyDaemonAuthPath, DaemonAuthPathDaemonToken)
+ next.ServeHTTP(w, r.WithContext(ctx))
+ return
+ }
+
+ if queries == nil {
+ writeError(w, http.StatusUnauthorized, "invalid daemon token")
+ return
+ }
dt, err := queries.GetDaemonTokenByHash(r.Context(), hash)
if err != nil {
slog.Warn("daemon_auth: invalid daemon token", "path", r.URL.Path, "error", err)
@@ -86,8 +109,20 @@ func DaemonAuth(queries *db.Queries) func(http.Handler) http.Handler {
return
}
- ctx := context.WithValue(r.Context(), ctxKeyDaemonWorkspaceID, uuidToString(dt.WorkspaceID))
- ctx = context.WithValue(ctx, ctxKeyDaemonID, dt.DaemonID)
+ identity := auth.DaemonTokenIdentity{
+ WorkspaceID: uuidToString(dt.WorkspaceID),
+ DaemonID: dt.DaemonID,
+ }
+ // daemon_token.expires_at is NOT NULL; pgtype Valid is true
+ // in normal operation, but defend against zero just in case.
+ var expiresAt time.Time
+ if dt.ExpiresAt.Valid {
+ expiresAt = dt.ExpiresAt.Time
+ }
+ daemonCache.Set(r.Context(), hash, identity, auth.TTLForExpiry(time.Now(), expiresAt))
+
+ ctx := context.WithValue(r.Context(), ctxKeyDaemonWorkspaceID, identity.WorkspaceID)
+ ctx = context.WithValue(ctx, ctxKeyDaemonID, identity.DaemonID)
ctx = context.WithValue(ctx, ctxKeyDaemonAuthPath, DaemonAuthPathDaemonToken)
next.ServeHTTP(w, r.WithContext(ctx))
return
@@ -96,14 +131,38 @@ func DaemonAuth(queries *db.Queries) func(http.Handler) http.Handler {
// Fallback: PAT tokens ("mul_" prefix).
if strings.HasPrefix(tokenString, "mul_") {
hash := auth.HashToken(tokenString)
+
+ if userID, ok := patCache.Get(r.Context(), hash); ok {
+ r.Header.Set("X-User-ID", userID)
+ ctx := context.WithValue(r.Context(), ctxKeyDaemonAuthPath, DaemonAuthPathPAT)
+ next.ServeHTTP(w, r.WithContext(ctx))
+ return
+ }
+
+ if queries == nil {
+ writeError(w, http.StatusUnauthorized, "invalid token")
+ return
+ }
pat, err := queries.GetPersonalAccessTokenByHash(r.Context(), hash)
if err != nil {
slog.Warn("daemon_auth: invalid PAT", "path", r.URL.Path, "error", err)
writeError(w, http.StatusUnauthorized, "invalid token")
return
}
- r.Header.Set("X-User-ID", uuidToString(pat.UserID))
+
+ userID := uuidToString(pat.UserID)
+ r.Header.Set("X-User-ID", userID)
+
+ var expiresAt time.Time
+ if pat.ExpiresAt.Valid {
+ expiresAt = pat.ExpiresAt.Time
+ }
+ patCache.Set(r.Context(), hash, userID, auth.TTLForExpiry(time.Now(), expiresAt))
+
+ // Cache miss = first request in this TTL window. Refresh
+ // last_used_at; subsequent hits skip the write entirely.
go queries.UpdatePersonalAccessTokenLastUsed(context.Background(), pat.ID)
+
ctx := context.WithValue(r.Context(), ctxKeyDaemonAuthPath, DaemonAuthPathPAT)
next.ServeHTTP(w, r.WithContext(ctx))
return
diff --git a/server/internal/middleware/daemon_auth_test.go b/server/internal/middleware/daemon_auth_test.go
new file mode 100644
index 0000000000..8502d65e38
--- /dev/null
+++ b/server/internal/middleware/daemon_auth_test.go
@@ -0,0 +1,117 @@
+package middleware
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/auth"
+)
+
+// TestDaemonAuth_DaemonTokenCacheHit pins the daemon-token cache short-circuit:
+// when the cache holds an entry for an mdt_ token, DaemonAuth must skip the DB
+// lookup. nil queries would otherwise nil-deref on a miss.
+func TestDaemonAuth_DaemonTokenCacheHit(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ cache := auth.NewDaemonTokenCache(rdb)
+ if cache == nil {
+ t.Fatal("expected non-nil cache")
+ }
+
+ const rawToken = "mdt_cache_hit_test_token"
+ hash := auth.HashToken(rawToken)
+ cache.Set(context.Background(), hash, auth.DaemonTokenIdentity{
+ WorkspaceID: "ws-cached",
+ DaemonID: "daemon-cached",
+ }, auth.AuthCacheTTL)
+
+ var gotWS, gotDaemon, gotPath string
+ mw := DaemonAuth(nil, nil, cache) // nil queries — only safe on cache hit
+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotWS = DaemonWorkspaceIDFromContext(r.Context())
+ gotDaemon = DaemonIDFromContext(r.Context())
+ gotPath = DaemonAuthPathFromContext(r.Context())
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest("POST", "/api/daemon/heartbeat", nil)
+ req.Header.Set("Authorization", "Bearer "+rawToken)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200 on cache hit, got %d: %s", w.Code, w.Body.String())
+ }
+ if gotWS != "ws-cached" || gotDaemon != "daemon-cached" {
+ t.Fatalf("expected (ws-cached, daemon-cached), got (%q, %q)", gotWS, gotDaemon)
+ }
+ if gotPath != DaemonAuthPathDaemonToken {
+ t.Fatalf("expected auth path %q, got %q", DaemonAuthPathDaemonToken, gotPath)
+ }
+}
+
+// TestDaemonAuth_PATCacheHit pins the PAT-fallback short-circuit. Production
+// daemon traffic today uses mul_ PATs (mdt_ minting isn't wired up yet), so
+// this is the cache hit that actually matters for /api/daemon/* DB load.
+func TestDaemonAuth_PATCacheHit(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ cache := auth.NewPATCache(rdb)
+ if cache == nil {
+ t.Fatal("expected non-nil cache")
+ }
+
+ const rawToken = "mul_daemon_pat_cache_hit_test"
+ hash := auth.HashToken(rawToken)
+ cache.Set(context.Background(), hash, "cached-user-id", auth.AuthCacheTTL)
+
+ var gotUserID, gotPath string
+ mw := DaemonAuth(nil, cache, nil)
+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotUserID = r.Header.Get("X-User-ID")
+ gotPath = DaemonAuthPathFromContext(r.Context())
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ req := httptest.NewRequest("POST", "/api/daemon/heartbeat", nil)
+ req.Header.Set("Authorization", "Bearer "+rawToken)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if gotUserID != "cached-user-id" {
+ t.Fatalf("expected cached X-User-ID, got %q", gotUserID)
+ }
+ if gotPath != DaemonAuthPathPAT {
+ t.Fatalf("expected auth path %q, got %q", DaemonAuthPathPAT, gotPath)
+ }
+}
+
+func TestDaemonAuth_MissingAuth(t *testing.T) {
+ mw := DaemonAuth(nil, nil, nil)
+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ t.Fatal("next must not be called")
+ }))
+ req := httptest.NewRequest("POST", "/api/daemon/heartbeat", nil)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("expected 401, got %d", w.Code)
+ }
+}
+
+func TestDaemonAuth_InvalidMDT_NilQueries(t *testing.T) {
+ mw := DaemonAuth(nil, nil, nil) // no caches, no DB
+ handler := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ t.Fatal("next must not be called")
+ }))
+ req := httptest.NewRequest("POST", "/api/daemon/heartbeat", nil)
+ req.Header.Set("Authorization", "Bearer mdt_unknown")
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("expected 401, got %d", w.Code)
+ }
+}
diff --git a/server/pkg/db/generated/personal_access_token.sql.go b/server/pkg/db/generated/personal_access_token.sql.go
index 111286434a..7864285937 100644
--- a/server/pkg/db/generated/personal_access_token.sql.go
+++ b/server/pkg/db/generated/personal_access_token.sql.go
@@ -109,10 +109,11 @@ func (q *Queries) ListPersonalAccessTokensByUser(ctx context.Context, userID pgt
return items, nil
}
-const revokePersonalAccessToken = `-- name: RevokePersonalAccessToken :exec
+const revokePersonalAccessToken = `-- name: RevokePersonalAccessToken :one
UPDATE personal_access_token
SET revoked = TRUE
WHERE id = $1 AND user_id = $2
+RETURNING token_hash
`
type RevokePersonalAccessTokenParams struct {
@@ -120,9 +121,11 @@ type RevokePersonalAccessTokenParams struct {
UserID pgtype.UUID `json:"user_id"`
}
-func (q *Queries) RevokePersonalAccessToken(ctx context.Context, arg RevokePersonalAccessTokenParams) error {
- _, err := q.db.Exec(ctx, revokePersonalAccessToken, arg.ID, arg.UserID)
- return err
+func (q *Queries) RevokePersonalAccessToken(ctx context.Context, arg RevokePersonalAccessTokenParams) (string, error) {
+ row := q.db.QueryRow(ctx, revokePersonalAccessToken, arg.ID, arg.UserID)
+ var token_hash string
+ err := row.Scan(&token_hash)
+ return token_hash, err
}
const updatePersonalAccessTokenLastUsed = `-- name: UpdatePersonalAccessTokenLastUsed :exec
diff --git a/server/pkg/db/queries/daemon_token.sql b/server/pkg/db/queries/daemon_token.sql
index 252b17f22e..3544bfea9f 100644
--- a/server/pkg/db/queries/daemon_token.sql
+++ b/server/pkg/db/queries/daemon_token.sql
@@ -8,6 +8,11 @@ SELECT * FROM daemon_token
WHERE token_hash = $1 AND expires_at > now();
-- name: DeleteDaemonTokensByWorkspaceAndDaemon :exec
+-- Callers MUST also invalidate auth.DaemonTokenCache for each affected
+-- token_hash so the deletion takes effect before the cache TTL expires.
+-- Today this query has no caller; when a deregister / rotate flow lands,
+-- change this to :many RETURNING token_hash and call
+-- DaemonTokenCache.Invalidate(hash) for each row.
DELETE FROM daemon_token
WHERE workspace_id = $1 AND daemon_id = $2;
diff --git a/server/pkg/db/queries/personal_access_token.sql b/server/pkg/db/queries/personal_access_token.sql
index 2a6d2ffd14..ce0e5789d0 100644
--- a/server/pkg/db/queries/personal_access_token.sql
+++ b/server/pkg/db/queries/personal_access_token.sql
@@ -15,10 +15,11 @@ WHERE user_id = $1
AND revoked = FALSE
ORDER BY created_at DESC;
--- name: RevokePersonalAccessToken :exec
+-- name: RevokePersonalAccessToken :one
UPDATE personal_access_token
SET revoked = TRUE
-WHERE id = $1 AND user_id = $2;
+WHERE id = $1 AND user_id = $2
+RETURNING token_hash;
-- name: UpdatePersonalAccessTokenLastUsed :exec
UPDATE personal_access_token