Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions internal/api/middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ type AuthMiddleware struct {
sessionValidator SessionValidator
apiKeyValidator APIKeyValidator // nil if API keys not configured
apiKeyUserLoader APIKeyUserLoader // nil if API keys not configured

apiKeyLastUsed *auth.APIKeyLastUsedTracker
}

// NewAuthMiddleware creates a new AuthMiddleware with the given token validator
Expand All @@ -57,6 +59,7 @@ func NewAuthMiddleware(tv TokenValidator, sv SessionValidator, akv APIKeyValidat
sessionValidator: sv,
apiKeyValidator: akv,
apiKeyUserLoader: akul,
apiKeyLastUsed: auth.NewAPIKeyLastUsedTracker(akv, nil),
}
}

Expand Down Expand Up @@ -98,10 +101,7 @@ func (am *AuthMiddleware) RequireAuth(next http.Handler) http.Handler {
return
}

// Update last_used_at asynchronously.
go func(id int64) {
_ = am.apiKeyValidator.UpdateLastUsed(context.Background(), id)
}(apiKey.ID)
am.apiKeyLastUsed.Touch(apiKey.ID)

claims = &auth.Claims{
UserID: user.ID,
Expand Down
80 changes: 80 additions & 0 deletions internal/auth/api_key_last_used.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package auth

import (
"context"
"log/slog"
"sync"
"time"
)

const (
apiKeyLastUsedInterval = time.Minute
apiKeyLastUsedTimeout = 5 * time.Second
)

// APIKeyLastUsedUpdater persists an API key's last-used timestamp.
type APIKeyLastUsedUpdater interface {
UpdateLastUsed(ctx context.Context, id int64) error
}

// APIKeyLastUsedTracker coalesces last-used writes per key without blocking
// authentication requests. Stale entries are pruned inline once per interval,
// avoiding both unbounded historical-key retention and another goroutine.
type APIKeyLastUsedTracker struct {
updater APIKeyLastUsedUpdater
now func() time.Time

mu sync.Mutex
lastUsedAt map[int64]time.Time
nextPrune time.Time
}

// NewAPIKeyLastUsedTracker creates a tracker. A nil clock uses time.Now.
func NewAPIKeyLastUsedTracker(updater APIKeyLastUsedUpdater, now func() time.Time) *APIKeyLastUsedTracker {
if now == nil {
now = time.Now
}
return &APIKeyLastUsedTracker{
updater: updater,
now: now,
lastUsedAt: make(map[int64]time.Time),
}
}

// Touch records key usage asynchronously, at most once per interval per key.
func (t *APIKeyLastUsedTracker) Touch(id int64) {
if t == nil || t.updater == nil || !t.shouldUpdate(id) {
return
}

go func() {
ctx, cancel := context.WithTimeout(context.Background(), apiKeyLastUsedTimeout)
defer cancel()
if err := t.updater.UpdateLastUsed(ctx, id); err != nil {
slog.DebugContext(ctx, "api key last-used update failed", "component", "auth", "id", id, "error", err)
}
}()
}

func (t *APIKeyLastUsedTracker) shouldUpdate(id int64) bool {
now := t.now()

t.mu.Lock()
defer t.mu.Unlock()

if t.nextPrune.IsZero() || !now.Before(t.nextPrune) {
cutoff := now.Add(-apiKeyLastUsedInterval)
for keyID, lastUsed := range t.lastUsedAt {
if !lastUsed.After(cutoff) {
delete(t.lastUsedAt, keyID)
}
}
t.nextPrune = now.Add(apiKeyLastUsedInterval)
}

if lastUsed, ok := t.lastUsedAt[id]; ok && now.Sub(lastUsed) < apiKeyLastUsedInterval {
return false
}
t.lastUsedAt[id] = now
return true
}
82 changes: 82 additions & 0 deletions internal/auth/api_key_last_used_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package auth

import (
"context"
"testing"
"time"
)

type recordingLastUsedUpdater struct {
calls chan lastUsedCall
}

type lastUsedCall struct {
id int64
deadline time.Time
}

func (u *recordingLastUsedUpdater) UpdateLastUsed(ctx context.Context, id int64) error {
deadline, _ := ctx.Deadline()
u.calls <- lastUsedCall{id: id, deadline: deadline}
return nil
}

func TestAPIKeyLastUsedTrackerThrottlesPerKey(t *testing.T) {
now := time.Date(2026, time.July, 20, 12, 0, 0, 0, time.UTC)
tracker := NewAPIKeyLastUsedTracker(nil, func() time.Time { return now })

if !tracker.shouldUpdate(1) {
t.Fatal("first use should update")
}
if tracker.shouldUpdate(1) {
t.Fatal("repeat use inside the interval should be throttled")
}
if !tracker.shouldUpdate(2) {
t.Fatal("a different key should update independently")
}

now = now.Add(apiKeyLastUsedInterval)
if !tracker.shouldUpdate(1) {
t.Fatal("use at the next interval should update")
}
}

func TestAPIKeyLastUsedTrackerPrunesExpiredKeys(t *testing.T) {
now := time.Date(2026, time.July, 20, 12, 0, 0, 0, time.UTC)
tracker := NewAPIKeyLastUsedTracker(nil, func() time.Time { return now })

tracker.shouldUpdate(1)
tracker.shouldUpdate(2)

now = now.Add(apiKeyLastUsedInterval)
tracker.shouldUpdate(3)

if len(tracker.lastUsedAt) != 1 {
t.Fatalf("retained entries = %d, want 1", len(tracker.lastUsedAt))
}
if _, ok := tracker.lastUsedAt[3]; !ok {
t.Fatal("current key was not retained")
}
}

func TestAPIKeyLastUsedTrackerAddsWriteDeadline(t *testing.T) {
updater := &recordingLastUsedUpdater{calls: make(chan lastUsedCall, 1)}
tracker := NewAPIKeyLastUsedTracker(updater, nil)
tracker.Touch(42)

select {
case call := <-updater.calls:
if call.id != 42 {
t.Fatalf("key id = %d, want 42", call.id)
}
if call.deadline.IsZero() {
t.Fatal("last-used update context has no deadline")
}
remaining := time.Until(call.deadline)
if remaining <= 0 || remaining > apiKeyLastUsedTimeout {
t.Fatalf("deadline after %s, want within (0, %s]", remaining, apiKeyLastUsedTimeout)
}
case <-time.After(time.Second):
t.Fatal("timed out waiting for last-used update")
}
}
45 changes: 10 additions & 35 deletions internal/jellycompat/auth_api_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"sync"
"time"

"github.com/Silo-Server/silo-server/internal/auth"
"github.com/Silo-Server/silo-server/internal/models"
"github.com/Silo-Server/silo-server/internal/userstore"
)
Expand Down Expand Up @@ -36,8 +37,7 @@ type AdminAPIKeyAuthenticator struct {
// authorization decision, which is re-checked on every request.
profiles *apiKeyProfileCache

lastUsedMu sync.Mutex
lastUsedAt map[int64]time.Time
apiKeyLastUsed *auth.APIKeyLastUsedTracker
}

type adminAPIKeyAuthResult struct {
Expand All @@ -61,12 +61,12 @@ func NewAdminAPIKeyAuthenticator(keys apiKeyValidator, users apiKeyUserLoader, p
now = time.Now
}
return &AdminAPIKeyAuthenticator{
keys: keys,
users: users,
provider: provider,
now: now,
profiles: newAPIKeyProfileCache(),
lastUsedAt: make(map[int64]time.Time),
keys: keys,
users: users,
provider: provider,
now: now,
profiles: newAPIKeyProfileCache(),
apiKeyLastUsed: auth.NewAPIKeyLastUsedTracker(keys, now),
}
}

Expand Down Expand Up @@ -138,7 +138,7 @@ func (a *AdminAPIKeyAuthenticator) authenticate(r *http.Request) adminAPIKeyAuth
if !res.ok {
return res
}
a.touchLastUsed(apiKey.ID)
a.apiKeyLastUsed.Touch(apiKey.ID)
return adminAPIKeyAuthResult{
ctx: context.WithValue(r.Context(), adminAPIKeyKey, true),
status: http.StatusOK,
Expand Down Expand Up @@ -182,28 +182,6 @@ func (a *AdminAPIKeyAuthenticator) validate(ctx context.Context, token string) (
return apiKey, user, adminAPIKeyAuthResult{ok: true}
}

// touchLastUsed records key usage without blocking the request, throttled to at
// most once per apiKeyLastUsedInterval per key so per-request validation on the
// hot path (e.g. HLS segments) does not issue a DB write each time.
func (a *AdminAPIKeyAuthenticator) touchLastUsed(id int64) {
now := a.now()
a.lastUsedMu.Lock()
if last, ok := a.lastUsedAt[id]; ok && now.Sub(last) < apiKeyLastUsedInterval {
a.lastUsedMu.Unlock()
return
}
a.lastUsedAt[id] = now
a.lastUsedMu.Unlock()

go func(id int64) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := a.keys.UpdateLastUsed(ctx, id); err != nil {
slog.Debug("jellycompat api key last-used update failed", "id", id, "error", err)
}
}(id)
}

// resolveSession authenticates an sa_ API key and returns a compat session
// synthesized for the key user's primary profile, so ordinary browse/stream
// handlers (which read SessionFromContext) work unchanged for an API key.
Expand All @@ -224,7 +202,7 @@ func (a *AdminAPIKeyAuthenticator) resolveSession(ctx context.Context, token str
if !res.ok {
return nil, res, true
}
a.touchLastUsed(apiKey.ID)
a.apiKeyLastUsed.Touch(apiKey.ID)

profile, err := a.primaryProfile(ctx, user.ID)
if err != nil {
Expand Down Expand Up @@ -298,9 +276,6 @@ const (
// reassigned/renamed primary profile is picked up, never authorization
// (the key and user are re-validated on every request).
apiKeyProfileCacheTTL = 5 * time.Minute
// apiKeyLastUsedInterval throttles api_keys.last_used_at writes so that
// per-request validation on the hot path does not write each time.
apiKeyLastUsedInterval = time.Minute
)

type apiKeyProfileCacheEntry struct {
Expand Down