4
0

middleware.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. package webapi
  2. import (
  3. "context"
  4. "fmt"
  5. "log/slog"
  6. "net/http"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/patrickmn/go-cache"
  11. "golang.org/x/time/rate"
  12. "github.com/mk6i/open-oscar-server/state"
  13. "github.com/mk6i/open-oscar-server/wire"
  14. )
  15. // contextKey is a custom type for context keys to avoid collisions.
  16. type contextKey string
  17. const (
  18. // ContextKeyAPIKey is the context key for storing the validated API key.
  19. ContextKeyAPIKey contextKey = "api_key"
  20. // contextKeyResolvedAPIKey caches an API key lookup across middlewares
  21. // handling the same request. Unexported: it is an internal memo, not
  22. // something handlers should read.
  23. contextKeyResolvedAPIKey contextKey = "resolved_api_key"
  24. )
  25. // RateLimitInfo contains rate limit metadata for a request.
  26. type RateLimitInfo struct {
  27. Limit int // Total requests allowed per window
  28. Remaining int // Requests remaining in current window
  29. Reset int64 // Unix timestamp when the window resets
  30. Allowed bool // Whether the request is allowed
  31. }
  32. // rateLimiterEntry tracks rate limiting data for a single devID.
  33. type rateLimiterEntry struct {
  34. limiter *rate.Limiter
  35. limit int
  36. windowSize time.Duration
  37. lastReset time.Time
  38. }
  39. // RateLimiter manages per-devID rate limiting for the Web API.
  40. type RateLimiter struct {
  41. limiters *cache.Cache
  42. mu sync.RWMutex
  43. windowSize time.Duration // Rate limit window size (default: 1 minute)
  44. }
  45. // NewRateLimiter creates a new rate limiter with automatic cleanup.
  46. func NewRateLimiter() *RateLimiter {
  47. // Create cache with 5 minute expiration and 10 minute cleanup interval
  48. c := cache.New(5*time.Minute, 10*time.Minute)
  49. return &RateLimiter{
  50. limiters: c,
  51. windowSize: time.Minute, // Default 1 minute window
  52. }
  53. }
  54. // CheckRateLimit checks if a request from the given devID is allowed and returns rate limit info.
  55. func (r *RateLimiter) CheckRateLimit(devID string, limit int) RateLimitInfo {
  56. if limit <= 0 {
  57. return RateLimitInfo{
  58. Reset: time.Now().Add(r.windowSize).Unix(),
  59. Allowed: true,
  60. }
  61. }
  62. r.mu.Lock()
  63. defer r.mu.Unlock()
  64. now := time.Now()
  65. // Get or create limiter entry for this devID
  66. var entry *rateLimiterEntry
  67. if val, found := r.limiters.Get(devID); found {
  68. entry = val.(*rateLimiterEntry)
  69. // Check if limit has changed
  70. if entry.limit != limit {
  71. // Recreate limiter with new limit
  72. entry.limiter = rate.NewLimiter(rate.Every(r.windowSize/time.Duration(limit)), limit)
  73. entry.limit = limit
  74. }
  75. } else {
  76. // Create new limiter with burst equal to limit (allows initial burst)
  77. entry = &rateLimiterEntry{
  78. limiter: rate.NewLimiter(rate.Every(r.windowSize/time.Duration(limit)), limit),
  79. limit: limit,
  80. windowSize: r.windowSize,
  81. lastReset: now,
  82. }
  83. r.limiters.Set(devID, entry, cache.DefaultExpiration)
  84. }
  85. // Check if request is allowed
  86. allowed := entry.limiter.Allow()
  87. // Calculate remaining requests (approximate based on tokens available)
  88. tokens := entry.limiter.Tokens()
  89. remaining := int(tokens)
  90. if remaining < 0 {
  91. remaining = 0
  92. }
  93. // Calculate reset time (next window start)
  94. resetTime := now.Add(r.windowSize).Unix()
  95. return RateLimitInfo{
  96. Limit: limit,
  97. Remaining: remaining,
  98. Reset: resetTime,
  99. Allowed: allowed,
  100. }
  101. }
  102. // AuthMiddleware provides authentication and rate limiting for Web API endpoints.
  103. type AuthMiddleware struct {
  104. Validator APIKeyValidator
  105. RateLimiter *RateLimiter
  106. Logger *slog.Logger
  107. }
  108. // NewAuthMiddleware creates a new authentication middleware instance.
  109. func NewAuthMiddleware(validator APIKeyValidator, logger *slog.Logger) *AuthMiddleware {
  110. return &AuthMiddleware{
  111. Validator: validator,
  112. RateLimiter: NewRateLimiter(),
  113. Logger: logger,
  114. }
  115. }
  116. // RequireSession resolves the aimsid session and passes it to next. It rejects
  117. // requests whose session is missing or expired with an auth error. On success it
  118. // touches the session, sliding its expiry forward; this is the keepalive that
  119. // holds a long-polling client's session open (see the session lifecycle timeline
  120. // on state's Session manager).
  121. //
  122. // A session with a nil OSCARSession is rejected as a 500: startSession no longer
  123. // creates such sessions (anonymous guests are unsupported), so a nil is a broken
  124. // server invariant, not a client error. This lets downstream handlers treat
  125. // session.OSCARSession as non-nil.
  126. func (m *AuthMiddleware) RequireSession(sm SessionResolver, next func(http.ResponseWriter, *http.Request, *Session)) http.Handler {
  127. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  128. aimsid := param(r, "aimsid")
  129. if aimsid == "" {
  130. SendError(w, r, http.StatusBadRequest, "missing aimsid parameter")
  131. return
  132. }
  133. session, err := sm.GetSession(r.Context(), aimsid)
  134. if err != nil {
  135. SendError(w, r, http.StatusUnauthorized, "invalid or expired session")
  136. return
  137. }
  138. _ = sm.TouchSession(r.Context(), aimsid)
  139. next(w, r, session)
  140. })
  141. }
  142. // Authenticate is an HTTP middleware that validates API keys and enforces rate limits.
  143. func (m *AuthMiddleware) Authenticate(next http.Handler) http.Handler {
  144. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  145. // Extract API key from 'k' parameter (query or form)
  146. apiKey := param(r, "k")
  147. if apiKey == "" {
  148. SendEnvelopeStatus(w, r, http.StatusBadRequest, "required parameter 'k' is missing", m.Logger)
  149. return
  150. }
  151. // Validate API key
  152. key, r := m.resolveAPIKeyCached(r, apiKey)
  153. ctx := r.Context()
  154. if key == nil {
  155. m.Logger.DebugContext(ctx, "invalid API key attempted", "key", apiKey[:min(8, len(apiKey))]+"...")
  156. SendEnvelopeStatus(w, r, http.StatusForbidden, "invalid API key", m.Logger)
  157. return
  158. }
  159. // Check rate limit
  160. rateLimitInfo := m.RateLimiter.CheckRateLimit(key.DevID, key.RateLimit)
  161. // Always add rate limit headers
  162. w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", rateLimitInfo.Limit))
  163. w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", rateLimitInfo.Remaining))
  164. w.Header().Set("X-RateLimit-Reset", fmt.Sprintf("%d", rateLimitInfo.Reset))
  165. if !rateLimitInfo.Allowed {
  166. m.Logger.WarnContext(ctx, "rate limit exceeded", "dev_id", key.DevID, "limit", key.RateLimit)
  167. // Add Retry-After header
  168. retryAfter := rateLimitInfo.Reset - time.Now().Unix()
  169. if retryAfter < 1 {
  170. retryAfter = 1
  171. }
  172. w.Header().Set("Retry-After", fmt.Sprintf("%d", retryAfter))
  173. SendEnvelopeStatus(w, r, http.StatusTooManyRequests, "rate limit exceeded", m.Logger)
  174. return
  175. }
  176. // Add API key info to context for use in handlers
  177. ctx = context.WithValue(ctx, ContextKeyAPIKey, key)
  178. // Log the API request
  179. m.Logger.InfoContext(ctx, "API request authenticated",
  180. "dev_id", key.DevID,
  181. "app_name", key.AppName,
  182. "method", r.Method,
  183. "path", r.URL.Path,
  184. )
  185. // Pass to next handler with enriched context
  186. next.ServeHTTP(w, r.WithContext(ctx))
  187. })
  188. }
  189. // CORSMiddleware emits CORS headers and answers preflight requests.
  190. //
  191. // It must be the OUTERMOST middleware on every route. A response that the auth
  192. // layer rejects still needs an Access-Control-Allow-Origin header: without one
  193. // the browser blocks the response, and the Web AIM client reads a status-0 empty
  194. // response as "CORS blocked" and permanently downgrades its whole request
  195. // pipeline to JSONP (aim.client.js onXhrFailed_ clears its useXhr flag and never
  196. // sets it again). A single 400/403/429 from the auth layer is enough to latch it.
  197. //
  198. // Running ahead of authentication means the key is not in the request context
  199. // yet, so this resolves it itself to find the key's origin allowlist. The lookup
  200. // is memoized on the request context, so the auth middleware downstream reuses it
  201. // rather than hitting the store a second time.
  202. func (m *AuthMiddleware) CORSMiddleware(next http.Handler) http.Handler {
  203. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  204. // Only the query parameter is consulted here: reading the form would
  205. // consume a POST body before the handler sees it.
  206. key, r := m.resolveAPIKeyCached(r, r.URL.Query().Get("k"))
  207. // If there is no API key (e.g. using aimsid auth), allow all origins.
  208. // This is safe because the actual authentication is handled by the session.
  209. var allowedOrigins []string
  210. if key != nil {
  211. allowedOrigins = key.AllowedOrigins
  212. } else {
  213. // For session-based auth without API key, allow all origins
  214. // The session itself provides the security boundary
  215. m.Logger.DebugContext(r.Context(), "CORS handling for non-API-key auth (aimsid/token)")
  216. allowedOrigins = []string{"*"}
  217. }
  218. origin := r.Header.Get("Origin")
  219. // The response body varies with the request Origin, so it must not be
  220. // cached under a single key across origins.
  221. w.Header().Add("Vary", "Origin")
  222. // Check if origin is allowed
  223. if m.isOriginAllowed(origin, allowedOrigins) {
  224. if len(allowedOrigins) == 1 && allowedOrigins[0] == "*" {
  225. // For wildcard, set the actual origin to allow credentials
  226. if origin != "" {
  227. w.Header().Set("Access-Control-Allow-Origin", origin)
  228. } else {
  229. w.Header().Set("Access-Control-Allow-Origin", "*")
  230. }
  231. } else {
  232. w.Header().Set("Access-Control-Allow-Origin", origin)
  233. }
  234. w.Header().Set("Access-Control-Allow-Credentials", "true")
  235. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
  236. w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
  237. w.Header().Set("Access-Control-Max-Age", "3600")
  238. }
  239. // Handle preflight requests
  240. if r.Method == "OPTIONS" {
  241. w.WriteHeader(http.StatusNoContent)
  242. return
  243. }
  244. next.ServeHTTP(w, r)
  245. })
  246. }
  247. // isOriginAllowed checks if an origin is in the allowed list.
  248. func (m *AuthMiddleware) isOriginAllowed(origin string, allowedOrigins []string) bool {
  249. // If no origins specified, allow all (for backward compatibility/development)
  250. if len(allowedOrigins) == 0 {
  251. return true
  252. }
  253. origin = strings.ToLower(origin)
  254. for _, allowed := range allowedOrigins {
  255. allowed = strings.ToLower(allowed)
  256. // Exact match
  257. if origin == allowed {
  258. return true
  259. }
  260. // Wildcard support (e.g., "*.example.com")
  261. if strings.HasPrefix(allowed, "*.") {
  262. domain := allowed[2:]
  263. if strings.HasSuffix(origin, domain) {
  264. return true
  265. }
  266. }
  267. // Allow all origins (development only)
  268. if allowed == "*" {
  269. m.Logger.Warn("wildcard origin (*) used - should not be used in production")
  270. return true
  271. }
  272. }
  273. return false
  274. }
  275. // AuthenticateFlexible is an HTTP middleware that supports multiple authentication methods:
  276. // 1. aimsid (session ID) - no k required
  277. // 2. a (AOL token) - no k required
  278. // 3. ts + sig_sha256 (signed request) - no k required
  279. // 4. k (API key) - fallback if no other auth provided
  280. // This follows the Web AIM API specification where k is not required when aimsid is present.
  281. func (m *AuthMiddleware) AuthenticateFlexible(next http.Handler) http.Handler {
  282. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  283. ctx := r.Context()
  284. // Priority 1: Check for session-based auth (aimsid)
  285. // According to the spec, when aimsid is provided, k is not required
  286. if aimsid := param(r, "aimsid"); aimsid != "" {
  287. // The handler itself will validate the aimsid
  288. // We just need to pass the request through without requiring k
  289. m.Logger.DebugContext(ctx, "using aimsid authentication", "aimsid", aimsid[:min(16, len(aimsid))]+"...")
  290. next.ServeHTTP(w, r)
  291. return
  292. }
  293. // Priority 2: AOL token auth — user identity is in the token; k is optional.
  294. if token := param(r, "a"); token != "" {
  295. key, r := m.resolveAPIKeyCached(r, param(r, "k"))
  296. ctx := r.Context()
  297. if key == nil {
  298. devKey := param(r, "k")
  299. key = &state.WebAPIKey{
  300. DevID: "aim_web",
  301. DevKey: devKey,
  302. AppName: "AIM Web Client",
  303. IsActive: true,
  304. RateLimit: 600,
  305. }
  306. }
  307. ctx = context.WithValue(ctx, ContextKeyAPIKey, key)
  308. m.Logger.DebugContext(ctx, "using token authentication", "dev_id", key.DevID)
  309. next.ServeHTTP(w, r.WithContext(ctx))
  310. return
  311. }
  312. // Priority 3: Check for signed request auth
  313. if ts := param(r, "ts"); ts != "" {
  314. if sig := param(r, "sig_sha256"); sig != "" {
  315. // For now, signed requests still require 'k' parameter for API key validation
  316. // The signature provides additional security on top of the API key
  317. // When full signature validation is implemented, this can be made optional
  318. m.Logger.DebugContext(ctx, "signed request detected, falling through to API key validation")
  319. // Don't return here - continue to API key validation below
  320. }
  321. }
  322. // Priority 4: Fall back to API key requirement
  323. apiKey := param(r, "k")
  324. if apiKey == "" {
  325. SendEnvelopeStatus(w, r, http.StatusBadRequest, "authentication required: provide aimsid or k parameter", m.Logger)
  326. return
  327. }
  328. key, r := m.resolveAPIKeyCached(r, apiKey)
  329. ctx = r.Context()
  330. if key == nil {
  331. m.Logger.DebugContext(ctx, "invalid API key attempted", "key", apiKey[:min(8, len(apiKey))]+"...")
  332. SendEnvelopeStatus(w, r, http.StatusForbidden, "invalid API key", m.Logger)
  333. return
  334. }
  335. // Check rate limit
  336. rateLimitInfo := m.RateLimiter.CheckRateLimit(key.DevID, key.RateLimit)
  337. // Always add rate limit headers
  338. w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", rateLimitInfo.Limit))
  339. w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", rateLimitInfo.Remaining))
  340. w.Header().Set("X-RateLimit-Reset", fmt.Sprintf("%d", rateLimitInfo.Reset))
  341. if !rateLimitInfo.Allowed {
  342. m.Logger.WarnContext(ctx, "rate limit exceeded", "dev_id", key.DevID, "limit", key.RateLimit)
  343. // Add Retry-After header
  344. retryAfter := rateLimitInfo.Reset - time.Now().Unix()
  345. if retryAfter < 1 {
  346. retryAfter = 1
  347. }
  348. w.Header().Set("Retry-After", fmt.Sprintf("%d", retryAfter))
  349. SendEnvelopeStatus(w, r, http.StatusTooManyRequests, "rate limit exceeded", m.Logger)
  350. return
  351. }
  352. // Add API key info to context for use in handlers
  353. ctx = context.WithValue(ctx, ContextKeyAPIKey, key)
  354. // Log the API request
  355. m.Logger.InfoContext(ctx, "API request authenticated via key",
  356. "dev_id", key.DevID,
  357. "app_name", key.AppName,
  358. "method", r.Method,
  359. "path", r.URL.Path,
  360. )
  361. // Pass to next handler with enriched context
  362. next.ServeHTTP(w, r.WithContext(ctx))
  363. })
  364. }
  365. // resolvedAPIKey memoizes one API key lookup for the lifetime of a request.
  366. // A nil key is a cached result too: it records that devKey is unknown or
  367. // inactive, which is what lets the auth layer skip a repeat lookup.
  368. type resolvedAPIKey struct {
  369. devKey string
  370. key *state.WebAPIKey
  371. }
  372. // resolveAPIKeyCached resolves devKey, reusing the result of an earlier lookup on
  373. // the same request. It returns the key (nil when devKey is empty, unknown, or
  374. // inactive) along with a request carrying the memoized result, which callers must
  375. // pass down the chain for the caching to take effect.
  376. func (m *AuthMiddleware) resolveAPIKeyCached(r *http.Request, devKey string) (*state.WebAPIKey, *http.Request) {
  377. if devKey == "" {
  378. return nil, r
  379. }
  380. if cached, ok := r.Context().Value(contextKeyResolvedAPIKey).(*resolvedAPIKey); ok && cached.devKey == devKey {
  381. return cached.key, r
  382. }
  383. key := m.resolveAPIKey(r.Context(), devKey)
  384. ctx := context.WithValue(r.Context(), contextKeyResolvedAPIKey, &resolvedAPIKey{devKey: devKey, key: key})
  385. return key, r.WithContext(ctx)
  386. }
  387. func (m *AuthMiddleware) resolveAPIKey(ctx context.Context, devKey string) *state.WebAPIKey {
  388. if devKey == "" {
  389. return nil
  390. }
  391. key, err := m.Validator.GetAPIKeyByDevKey(ctx, devKey)
  392. if err != nil || key == nil || !key.IsActive {
  393. return nil
  394. }
  395. return key
  396. }
  397. // minRetryAfter floors the Retry-After hint sent with a rate-limited response.
  398. // The computed wait can round down to nothing when a class is barely over its
  399. // limit, and a hint of zero invites an immediate retry.
  400. const minRetryAfter = 1 * time.Second
  401. // SessionHandlerFunc is the session-aware handler shape that
  402. // AuthMiddleware.RequireSession invokes once it has resolved an aimsid.
  403. type SessionHandlerFunc = func(http.ResponseWriter, *http.Request, *Session)
  404. // RateLimitMiddleware enforces OSCAR rate limits on Web API routes that reach a
  405. // food group.
  406. //
  407. // Such routes are limited by OSCAR itself: OSCAR charges the session's shared
  408. // per-rate-class budget, the same budget a native OSCAR or TOC client spends, so
  409. // a user cannot dodge a limit by switching transports. Routes that reach no food
  410. // group are not limited here; edge rate limiting (a reverse proxy keyed by client
  411. // IP) is expected to cover the unauthenticated login/asset endpoints and the
  412. // authenticated bookkeeping ones.
  413. //
  414. // It lives in package webapi (rather than in server/oscar/middleware) so that its
  415. // rejection can be encoded through the same SendResponse path the handlers use,
  416. // honoring the request's JSON/JSONP/XML/AMF format.
  417. //
  418. // It only enforces the limit (the 430 rejection). Telling the client its status
  419. // changed is the job of OServiceService.MonitorRateLimits.
  420. type RateLimitMiddleware struct {
  421. snacRateLimits wire.SNACRateLimits
  422. logger *slog.Logger
  423. }
  424. // NewRateLimitMiddleware creates a RateLimitMiddleware. snacRateLimits is the
  425. // same SNAC-to-rate-class mapping the OSCAR and TOC servers use.
  426. func NewRateLimitMiddleware(snacRateLimits wire.SNACRateLimits, logger *slog.Logger) *RateLimitMiddleware {
  427. return &RateLimitMiddleware{
  428. snacRateLimits: snacRateLimits,
  429. logger: logger,
  430. }
  431. }
  432. // OSCAR returns middleware that charges one unit against the OSCAR rate class
  433. // mapped to (foodGroup, subGroup) before invoking the wrapped handler. It is the
  434. // HTTP counterpart of the TOC server's per-command rate check.
  435. //
  436. // A SNAC with no rate class mapping is allowed through, since refusing traffic
  437. // because the server's own table is incomplete would be worse than not limiting
  438. // it.
  439. func (l *RateLimitMiddleware) OSCAR(foodGroup uint16, subGroup uint16) func(SessionHandlerFunc) SessionHandlerFunc {
  440. return func(next SessionHandlerFunc) SessionHandlerFunc {
  441. return func(w http.ResponseWriter, r *http.Request, session *Session) {
  442. ctx := r.Context()
  443. rateClassID, ok := l.snacRateLimits.RateClassLookup(foodGroup, subGroup)
  444. if !ok {
  445. l.logger.ErrorContext(ctx, "rate limit not found, allowing request through",
  446. "foodgroup", wire.FoodGroupName(foodGroup),
  447. "subgroup", wire.SubGroupName(foodGroup, subGroup))
  448. next(w, r, session)
  449. return
  450. }
  451. sess := session.OSCARSession.Session()
  452. status := sess.EvaluateRateLimit(time.Now(), rateClassID)
  453. // Disconnect is rejected alongside Limited: EvaluateRateLimit has
  454. // already closed the account's OSCAR session by the time it returns,
  455. // so there is nothing left for the handler to act on. That close also
  456. // invalidates the aimsid (GetSession stops resolving a session whose
  457. // OSCAR instance is closed), so every subsequent request is turned
  458. // away at RequireSession rather than reaching here again.
  459. if status == wire.RateLimitStatusLimited || status == wire.RateLimitStatusDisconnect {
  460. l.logger.DebugContext(ctx, "(webapi) rate limit exceeded, dropping request",
  461. "foodgroup", wire.FoodGroupName(foodGroup),
  462. "subgroup", wire.SubGroupName(foodGroup, subGroup),
  463. "status", rateLimitStatusName(status))
  464. // A disconnected session has no aimsid left to retry with, so
  465. // there is no wait to advertise.
  466. var retryAfter time.Duration
  467. if status == wire.RateLimitStatusLimited {
  468. retryAfter = retryAfterFor(sess.RateLimitStates()[rateClassID-1])
  469. }
  470. l.sendRateLimited(w, r, retryAfter)
  471. return
  472. }
  473. next(w, r, session)
  474. }
  475. }
  476. }
  477. // retryAfterFor returns how long the client must wait for its next request on
  478. // this class to clear the limit.
  479. //
  480. // OSCAR's limiter has no fixed window: it tracks a moving average of the gap
  481. // between requests, and a request lifts the limit only once that average climbs
  482. // back to ClearLevel. Inverting CheckRateLimit's update for the elapsed time that
  483. // lands the new average exactly on ClearLevel gives
  484. //
  485. // elapsed = ClearLevel*WindowSize - CurrentLevel*(WindowSize-1)
  486. //
  487. // A flat hint cannot work here, because a rejected request is still charged: a
  488. // client retrying on a fixed interval drives the average toward that interval, so
  489. // any hint below the class's ClearLevel holds the average just under the bar and
  490. // the client stays limited forever. The production ICBM class clears at 5100ms,
  491. // which a 5s hint would do exactly.
  492. func retryAfterFor(rcs state.RateClassState) time.Duration {
  493. neededMs := int64(rcs.ClearLevel)*int64(rcs.WindowSize) - int64(rcs.CurrentLevel)*int64(rcs.WindowSize-1)
  494. // Retry-After carries whole seconds, so round up: a hint that is short by a
  495. // fraction of a second reproduces the same never-clears loop. A class barely
  496. // over its limit can compute to no wait at all, hence the floor.
  497. return max(time.Duration((neededMs+999)/1000)*time.Second, minRetryAfter)
  498. }
  499. // rateLimitStatusName maps an OSCAR rate limit status onto the status string the
  500. // web client switches on. It returns "" for a status the client does not know.
  501. func rateLimitStatusName(status wire.RateLimitStatus) string {
  502. switch status {
  503. case wire.RateLimitStatusClear:
  504. return "clear"
  505. case wire.RateLimitStatusAlert:
  506. return "warn"
  507. case wire.RateLimitStatusLimited:
  508. return "limit"
  509. case wire.RateLimitStatusDisconnect:
  510. return "disconnect"
  511. default:
  512. return ""
  513. }
  514. }
  515. // sendRateLimited writes a rate limit rejection. The transport status is 200 and
  516. // the rejection lives entirely in the Web AIM API envelope's own rate limit code.
  517. //
  518. // The transport status is deliberately not 429: the AIM client's WIM request layer
  519. // (XhrManager) and its Fetcher only parse the response body on a 2xx. A non-2xx is
  520. // routed to their error handlers, which synthesize a generic "request failed"
  521. // result and never look at the body, so the envelope's 430 — which the client
  522. // swallows on the IM path in favor of the rateLimit event — would go unread and the
  523. // user would see a generic send failure instead.
  524. //
  525. // The body is encoded via SendResponse, so it honors the request's format
  526. // (JSON/JSONP/XML/AMF) and echoes the request id into response.requestId — which
  527. // the JSONP fallback needs to correlate the reply, or its UI hangs — exactly as a
  528. // normal handler response would.
  529. //
  530. // A retryAfter of zero sends no Retry-After header, for the rejections that have
  531. // nothing to retry.
  532. func (l *RateLimitMiddleware) sendRateLimited(w http.ResponseWriter, r *http.Request, retryAfter time.Duration) {
  533. if retryAfter > 0 {
  534. w.Header().Set("Retry-After", fmt.Sprintf("%d", int(retryAfter.Seconds())))
  535. }
  536. resp := BaseResponse{}
  537. resp.Response.StatusCode = statusRateLimited
  538. resp.Response.StatusText = "rate limit exceeded"
  539. SendResponse(w, r, resp, l.logger)
  540. }
  541. // RequestLogger logs each request with method, path, and raw query string.
  542. func RequestLogger(logger *slog.Logger, next http.Handler) http.Handler {
  543. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  544. logger.Info("request",
  545. "method", r.Method,
  546. "path", r.URL.Path,
  547. "query", r.URL.RawQuery,
  548. )
  549. next.ServeHTTP(w, r)
  550. })
  551. }