Something went wrong. Try again.
Stateless auth proxy that converts AT Protocol native apps from public to confidential OAuth clients. Deploy once, get 180-day refresh token
Something went wrong. Try again.
atproto-auth-proxy cache.go
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168package main
import ( "context" "crypto/sha256" "encoding/hex" "sync" "time")
const ( refreshCacheTTL = 10 * time.Minute refreshCacheMaxSize = 10_000)
// cachedTokenResponse is the portion of a successful /oauth/token proxy// response we replay to clients whose original response was lost in transit// (TCP reset, app backgrounded before reading the body, network blip between// proxy and client, etc.). Because AT Protocol refresh tokens rotate on use,// the client only has one shot — if the original response never lands, the// token is consumed on the authorization server but the client is stuck with// the old value and every retry gets "invalid_grant: Refresh token replayed".type cachedTokenResponse struct { response *upstreamResponse usedKeyID string}
type refreshCacheEntry struct { ready chan struct{} result *cachedTokenResponse expires time.Time}
// refreshCache combines a short-TTL idempotency cache with a single-flight// gate. Concurrent requests for the same refresh token coalesce onto one// upstream call; retries after a lost response pick up the cached result.// Negative outcomes (4xx/5xx from upstream, or upstream transport failures)// are not cached — the authorization server is authoritative on whether a// given token is still alive.//// The gate holds for the whole life of a token: at no time are two upstream// refreshes of one token in flight (see claim).type refreshCache struct { mu sync.Mutex entries map[string]*refreshCacheEntry}
func newRefreshCache() *refreshCache { return &refreshCache{entries: make(map[string]*refreshCacheEntry)}}
func refreshCacheKey(refreshToken string) string { sum := sha256.Sum256([]byte(refreshToken)) return hex.EncodeToString(sum[:])}
// acquire returns the cache entry for the given refresh token and reports// whether the caller is the leader (must perform the upstream call and then// call finalize or release) or a follower (should wait on the entry).func (c *refreshCache) acquire(refreshToken string) (entry *refreshCacheEntry, isLeader bool) { key := refreshCacheKey(refreshToken) c.mu.Lock() defer c.mu.Unlock() c.sweepLocked()
if existing, ok := c.entries[key]; ok { return existing, false }
entry = &refreshCacheEntry{ ready: make(chan struct{}), expires: time.Now().Add(refreshCacheTTL), } c.entries[key] = entry return entry, true}
// finalize records a successful upstream response and wakes any followers.// The entry remains in the cache for its TTL so later retries whose original// response was lost can pick up the same rotated token.func (c *refreshCache) finalize(entry *refreshCacheEntry, result *cachedTokenResponse) { c.mu.Lock() entry.result = result c.mu.Unlock() close(entry.ready)}
// release removes a non-cacheable entry and wakes any followers with no// cached result so they can fall through to a fresh upstream attempt.func (c *refreshCache) release(refreshToken string, entry *refreshCacheEntry) { key := refreshCacheKey(refreshToken) c.mu.Lock() if current, ok := c.entries[key]; ok && current == entry { delete(c.entries, key) } c.mu.Unlock() close(entry.ready)}
// claim waits until refreshToken is the caller's to refresh, or until// someone else's refresh of it has succeeded.//// It returns the slot the caller now leads (to be settled with finalize or// release), or the result to replay. Both are nil when ctx ended first.//// A caller whose leader settled nothing takes the next turn instead of going// upstream alongside whoever leads next: two refreshes of one token in flight// at once is the replay the authorization server revokes sessions for.func (c *refreshCache) claim(ctx context.Context, refreshToken string) (*refreshCacheEntry, *cachedTokenResponse) { for { entry, isLeader := c.acquire(refreshToken) if isLeader { return entry, nil } if cached := c.wait(ctx, entry); cached != nil { return nil, cached } if ctx.Err() != nil { return nil, nil } }}
// wait blocks until the entry is finalized or released, honoring context// cancellation. Returns nil if the entry was released or the context ended.func (c *refreshCache) wait(ctx context.Context, entry *refreshCacheEntry) *cachedTokenResponse { select { case <-entry.ready: case <-ctx.Done(): return nil } c.mu.Lock() defer c.mu.Unlock() return entry.result}
// sweepLocked drops expired entries that have already settled. In-flight// entries are left alone regardless of TTL — the leader is responsible for// calling finalize or release, after which the next sweep will reap them.// Called under c.mu.func (c *refreshCache) sweepLocked() { now := time.Now() for key, entry := range c.entries { select { case <-entry.ready: if now.After(entry.expires) { delete(c.entries, key) } default: } } if len(c.entries) < refreshCacheMaxSize { return } // Bound memory under pathological load: drop settled entries until we // are back under the cap. In-flight entries are never evicted. for key, entry := range c.entries { if len(c.entries) < refreshCacheMaxSize { break } select { case <-entry.ready: delete(c.entries, key) default: } }}