auth.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. package middleware
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "log/slog"
  7. "net/http"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/patrickmn/go-cache"
  12. "golang.org/x/time/rate"
  13. "github.com/mk6i/retro-aim-server/state"
  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. // ContextKeyDevID is the context key for storing the developer ID.
  21. ContextKeyDevID contextKey = "dev_id"
  22. )
  23. // APIKeyValidator defines methods for validating Web API keys.
  24. type APIKeyValidator interface {
  25. // GetAPIKeyByDevKey retrieves and validates an API key by its dev_key value.
  26. GetAPIKeyByDevKey(ctx context.Context, devKey string) (*state.WebAPIKey, error)
  27. // UpdateLastUsed updates the last_used timestamp for an API key.
  28. UpdateLastUsed(ctx context.Context, devKey string) error
  29. }
  30. // RateLimitInfo contains rate limit metadata for a request.
  31. type RateLimitInfo struct {
  32. Limit int // Total requests allowed per window
  33. Remaining int // Requests remaining in current window
  34. Reset int64 // Unix timestamp when the window resets
  35. Allowed bool // Whether the request is allowed
  36. }
  37. // rateLimiterEntry tracks rate limiting data for a single devID.
  38. type rateLimiterEntry struct {
  39. limiter *rate.Limiter
  40. limit int
  41. windowSize time.Duration
  42. lastReset time.Time
  43. }
  44. // RateLimiter manages per-devID rate limiting for the Web API.
  45. type RateLimiter struct {
  46. limiters *cache.Cache
  47. mu sync.RWMutex
  48. windowSize time.Duration // Rate limit window size (default: 1 minute)
  49. }
  50. // NewRateLimiter creates a new rate limiter with automatic cleanup.
  51. func NewRateLimiter() *RateLimiter {
  52. // Create cache with 5 minute expiration and 10 minute cleanup interval
  53. c := cache.New(5*time.Minute, 10*time.Minute)
  54. return &RateLimiter{
  55. limiters: c,
  56. windowSize: time.Minute, // Default 1 minute window
  57. }
  58. }
  59. // CheckRateLimit checks if a request from the given devID is allowed and returns rate limit info.
  60. func (r *RateLimiter) CheckRateLimit(devID string, limit int) RateLimitInfo {
  61. r.mu.Lock()
  62. defer r.mu.Unlock()
  63. now := time.Now()
  64. // Get or create limiter entry for this devID
  65. var entry *rateLimiterEntry
  66. if val, found := r.limiters.Get(devID); found {
  67. entry = val.(*rateLimiterEntry)
  68. // Check if limit has changed
  69. if entry.limit != limit {
  70. // Recreate limiter with new limit
  71. entry.limiter = rate.NewLimiter(rate.Every(r.windowSize/time.Duration(limit)), limit)
  72. entry.limit = limit
  73. }
  74. } else {
  75. // Create new limiter with burst equal to limit (allows initial burst)
  76. entry = &rateLimiterEntry{
  77. limiter: rate.NewLimiter(rate.Every(r.windowSize/time.Duration(limit)), limit),
  78. limit: limit,
  79. windowSize: r.windowSize,
  80. lastReset: now,
  81. }
  82. r.limiters.Set(devID, entry, cache.DefaultExpiration)
  83. }
  84. // Check if request is allowed
  85. allowed := entry.limiter.Allow()
  86. // Calculate remaining requests (approximate based on tokens available)
  87. tokens := entry.limiter.Tokens()
  88. remaining := int(tokens)
  89. if remaining < 0 {
  90. remaining = 0
  91. }
  92. // Calculate reset time (next window start)
  93. resetTime := now.Add(r.windowSize).Unix()
  94. return RateLimitInfo{
  95. Limit: limit,
  96. Remaining: remaining,
  97. Reset: resetTime,
  98. Allowed: allowed,
  99. }
  100. }
  101. // Allow checks if a request from the given devID is allowed based on rate limits.
  102. func (r *RateLimiter) Allow(devID string, limit int) bool {
  103. info := r.CheckRateLimit(devID, limit)
  104. return info.Allowed
  105. }
  106. // AuthMiddleware provides authentication and rate limiting for Web API endpoints.
  107. type AuthMiddleware struct {
  108. Validator APIKeyValidator
  109. RateLimiter *RateLimiter
  110. Logger *slog.Logger
  111. }
  112. // NewAuthMiddleware creates a new authentication middleware instance.
  113. func NewAuthMiddleware(validator APIKeyValidator, logger *slog.Logger) *AuthMiddleware {
  114. return &AuthMiddleware{
  115. Validator: validator,
  116. RateLimiter: NewRateLimiter(),
  117. Logger: logger,
  118. }
  119. }
  120. // Authenticate is an HTTP middleware that validates API keys and enforces rate limits.
  121. func (m *AuthMiddleware) Authenticate(next http.Handler) http.Handler {
  122. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  123. // Extract API key from 'k' parameter (query or form)
  124. apiKey := r.URL.Query().Get("k")
  125. if apiKey == "" {
  126. // Try form value for POST requests
  127. apiKey = r.FormValue("k")
  128. }
  129. if apiKey == "" {
  130. m.sendErrorResponse(w, http.StatusBadRequest, "required parameter 'k' is missing")
  131. return
  132. }
  133. // Validate API key
  134. ctx := r.Context()
  135. key, err := m.Validator.GetAPIKeyByDevKey(ctx, apiKey)
  136. if err != nil {
  137. if err == state.ErrNoAPIKey {
  138. m.Logger.DebugContext(ctx, "invalid API key attempted", "key", apiKey[:min(8, len(apiKey))]+"...")
  139. m.sendErrorResponse(w, http.StatusForbidden, "invalid API key")
  140. return
  141. }
  142. m.Logger.ErrorContext(ctx, "error validating API key", "err", err.Error())
  143. m.sendErrorResponse(w, http.StatusInternalServerError, "internal server error")
  144. return
  145. }
  146. // Check if key is active
  147. if !key.IsActive {
  148. m.Logger.DebugContext(ctx, "inactive API key used", "dev_id", key.DevID)
  149. m.sendErrorResponse(w, http.StatusForbidden, "API key is inactive")
  150. return
  151. }
  152. // Check rate limit
  153. rateLimitInfo := m.RateLimiter.CheckRateLimit(key.DevID, key.RateLimit)
  154. // Always add rate limit headers
  155. w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", rateLimitInfo.Limit))
  156. w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", rateLimitInfo.Remaining))
  157. w.Header().Set("X-RateLimit-Reset", fmt.Sprintf("%d", rateLimitInfo.Reset))
  158. if !rateLimitInfo.Allowed {
  159. m.Logger.WarnContext(ctx, "rate limit exceeded", "dev_id", key.DevID, "limit", key.RateLimit)
  160. // Add Retry-After header
  161. retryAfter := rateLimitInfo.Reset - time.Now().Unix()
  162. if retryAfter < 1 {
  163. retryAfter = 1
  164. }
  165. w.Header().Set("Retry-After", fmt.Sprintf("%d", retryAfter))
  166. m.sendErrorResponse(w, http.StatusTooManyRequests, "rate limit exceeded")
  167. return
  168. }
  169. // Update last used timestamp asynchronously
  170. go func() {
  171. if err := m.Validator.UpdateLastUsed(context.Background(), apiKey); err != nil {
  172. m.Logger.Error("failed to update last_used timestamp", "err", err.Error())
  173. }
  174. }()
  175. // Add API key info to context for use in handlers
  176. ctx = context.WithValue(ctx, ContextKeyAPIKey, key)
  177. ctx = context.WithValue(ctx, ContextKeyDevID, key.DevID)
  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 handles CORS headers based on allowed origins for the API key.
  190. func (m *AuthMiddleware) CORSMiddleware(next http.Handler) http.Handler {
  191. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  192. // Get API key from context (set by Authenticate middleware)
  193. key, ok := r.Context().Value(ContextKeyAPIKey).(*state.WebAPIKey)
  194. // If no API key in context (e.g., using aimsid auth), allow all origins
  195. // This is safe because the actual authentication is handled by the session
  196. var allowedOrigins []string
  197. if ok && key != nil {
  198. allowedOrigins = key.AllowedOrigins
  199. } else {
  200. // For session-based auth without API key, allow all origins
  201. // The session itself provides the security boundary
  202. m.Logger.DebugContext(r.Context(), "CORS handling for non-API-key auth (aimsid/token)")
  203. allowedOrigins = []string{"*"}
  204. }
  205. origin := r.Header.Get("Origin")
  206. // Check if origin is allowed
  207. if m.isOriginAllowed(origin, allowedOrigins) {
  208. if len(allowedOrigins) == 1 && allowedOrigins[0] == "*" {
  209. // For wildcard, set the actual origin to allow credentials
  210. if origin != "" {
  211. w.Header().Set("Access-Control-Allow-Origin", origin)
  212. } else {
  213. w.Header().Set("Access-Control-Allow-Origin", "*")
  214. }
  215. } else {
  216. w.Header().Set("Access-Control-Allow-Origin", origin)
  217. }
  218. w.Header().Set("Access-Control-Allow-Credentials", "true")
  219. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
  220. w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
  221. w.Header().Set("Access-Control-Max-Age", "3600")
  222. }
  223. // Handle preflight requests
  224. if r.Method == "OPTIONS" {
  225. w.WriteHeader(http.StatusNoContent)
  226. return
  227. }
  228. next.ServeHTTP(w, r)
  229. })
  230. }
  231. // CapabilitiesMiddleware checks if the API key has the required capability for an endpoint.
  232. func (m *AuthMiddleware) CapabilitiesMiddleware(requiredCapability string) func(http.Handler) http.Handler {
  233. return func(next http.Handler) http.Handler {
  234. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  235. // Get API key from context
  236. key, ok := r.Context().Value(ContextKeyAPIKey).(*state.WebAPIKey)
  237. if !ok {
  238. m.Logger.Error("CapabilitiesMiddleware called without authentication context")
  239. http.Error(w, "internal server error", http.StatusInternalServerError)
  240. return
  241. }
  242. // If no capabilities are defined, allow all (backward compatibility)
  243. if len(key.Capabilities) == 0 {
  244. next.ServeHTTP(w, r)
  245. return
  246. }
  247. // Check if required capability is present
  248. hasCapability := false
  249. for _, cap := range key.Capabilities {
  250. if cap == requiredCapability || cap == "*" {
  251. hasCapability = true
  252. break
  253. }
  254. }
  255. if !hasCapability {
  256. m.Logger.WarnContext(r.Context(), "capability check failed",
  257. "dev_id", key.DevID,
  258. "required", requiredCapability,
  259. "available", key.Capabilities,
  260. )
  261. m.sendErrorResponse(w, http.StatusForbidden, fmt.Sprintf("missing required capability: %s", requiredCapability))
  262. return
  263. }
  264. next.ServeHTTP(w, r)
  265. })
  266. }
  267. }
  268. // isOriginAllowed checks if an origin is in the allowed list.
  269. func (m *AuthMiddleware) isOriginAllowed(origin string, allowedOrigins []string) bool {
  270. // If no origins specified, allow all (for backward compatibility/development)
  271. if len(allowedOrigins) == 0 {
  272. return true
  273. }
  274. origin = strings.ToLower(origin)
  275. for _, allowed := range allowedOrigins {
  276. allowed = strings.ToLower(allowed)
  277. // Exact match
  278. if origin == allowed {
  279. return true
  280. }
  281. // Wildcard support (e.g., "*.example.com")
  282. if strings.HasPrefix(allowed, "*.") {
  283. domain := allowed[2:]
  284. if strings.HasSuffix(origin, domain) {
  285. return true
  286. }
  287. }
  288. // Allow all origins (development only)
  289. if allowed == "*" {
  290. m.Logger.Warn("wildcard origin (*) used - should not be used in production")
  291. return true
  292. }
  293. }
  294. return false
  295. }
  296. // sendErrorResponse sends a JSON error response.
  297. func (m *AuthMiddleware) sendErrorResponse(w http.ResponseWriter, statusCode int, message string) {
  298. w.Header().Set("Content-Type", "application/json")
  299. w.WriteHeader(statusCode)
  300. response := map[string]interface{}{
  301. "error": message,
  302. "code": statusCode,
  303. }
  304. if err := json.NewEncoder(w).Encode(response); err != nil {
  305. m.Logger.Error("failed to encode error response", "err", err.Error())
  306. }
  307. }
  308. // GetAPIKeyFromContext retrieves the API key from the request context.
  309. func GetAPIKeyFromContext(ctx context.Context) (*state.WebAPIKey, bool) {
  310. key, ok := ctx.Value(ContextKeyAPIKey).(*state.WebAPIKey)
  311. return key, ok
  312. }
  313. // GetDevIDFromContext retrieves the developer ID from the request context.
  314. func GetDevIDFromContext(ctx context.Context) (string, bool) {
  315. devID, ok := ctx.Value(ContextKeyDevID).(string)
  316. return devID, ok
  317. }
  318. // min returns the minimum of two integers.
  319. func min(a, b int) int {
  320. if a < b {
  321. return a
  322. }
  323. return b
  324. }
  325. // AuthenticateFlexible is an HTTP middleware that supports multiple authentication methods:
  326. // 1. aimsid (session ID) - no k required
  327. // 2. a (AOL token) - no k required
  328. // 3. ts + sig_sha256 (signed request) - no k required
  329. // 4. k (API key) - fallback if no other auth provided
  330. // This follows the Web AIM API specification where k is not required when aimsid is present.
  331. func (m *AuthMiddleware) AuthenticateFlexible(next http.Handler) http.Handler {
  332. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  333. ctx := r.Context()
  334. // Priority 1: Check for session-based auth (aimsid)
  335. // According to the spec, when aimsid is provided, k is not required
  336. if aimsid := r.URL.Query().Get("aimsid"); aimsid != "" {
  337. // The handler itself will validate the aimsid
  338. // We just need to pass the request through without requiring k
  339. m.Logger.DebugContext(ctx, "using aimsid authentication", "aimsid", aimsid[:min(16, len(aimsid))]+"...")
  340. next.ServeHTTP(w, r)
  341. return
  342. }
  343. // Priority 2: Check for AOL token auth
  344. if token := r.URL.Query().Get("a"); token != "" {
  345. // Token auth is present, but we still need to validate the API key
  346. // The token provides user authentication while the API key identifies the app
  347. m.Logger.DebugContext(ctx, "token authentication detected, will validate API key as well")
  348. // Don't return here - continue to API key validation below
  349. }
  350. // Priority 3: Check for signed request auth
  351. if ts := r.URL.Query().Get("ts"); ts != "" {
  352. if sig := r.URL.Query().Get("sig_sha256"); sig != "" {
  353. // For now, signed requests still require 'k' parameter for API key validation
  354. // The signature provides additional security on top of the API key
  355. // When full signature validation is implemented, this can be made optional
  356. m.Logger.DebugContext(ctx, "signed request detected, falling through to API key validation")
  357. // Don't return here - continue to API key validation below
  358. }
  359. }
  360. // Priority 4: Fall back to API key requirement
  361. apiKey := r.URL.Query().Get("k")
  362. if apiKey == "" {
  363. // Try form value for POST requests
  364. apiKey = r.FormValue("k")
  365. }
  366. if apiKey == "" {
  367. m.sendErrorResponse(w, http.StatusBadRequest, "authentication required: provide aimsid or k parameter")
  368. return
  369. }
  370. // Validate API key as before
  371. key, err := m.Validator.GetAPIKeyByDevKey(ctx, apiKey)
  372. if err != nil {
  373. if err == state.ErrNoAPIKey {
  374. m.Logger.DebugContext(ctx, "invalid API key attempted", "key", apiKey[:min(8, len(apiKey))]+"...")
  375. m.sendErrorResponse(w, http.StatusForbidden, "invalid API key")
  376. return
  377. }
  378. m.Logger.ErrorContext(ctx, "error validating API key", "err", err.Error())
  379. m.sendErrorResponse(w, http.StatusInternalServerError, "internal server error")
  380. return
  381. }
  382. // Check if key is active
  383. if !key.IsActive {
  384. m.Logger.DebugContext(ctx, "inactive API key used", "dev_id", key.DevID)
  385. m.sendErrorResponse(w, http.StatusForbidden, "API key is inactive")
  386. return
  387. }
  388. // Check rate limit
  389. rateLimitInfo := m.RateLimiter.CheckRateLimit(key.DevID, key.RateLimit)
  390. // Always add rate limit headers
  391. w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", rateLimitInfo.Limit))
  392. w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", rateLimitInfo.Remaining))
  393. w.Header().Set("X-RateLimit-Reset", fmt.Sprintf("%d", rateLimitInfo.Reset))
  394. if !rateLimitInfo.Allowed {
  395. m.Logger.WarnContext(ctx, "rate limit exceeded", "dev_id", key.DevID, "limit", key.RateLimit)
  396. // Add Retry-After header
  397. retryAfter := rateLimitInfo.Reset - time.Now().Unix()
  398. if retryAfter < 1 {
  399. retryAfter = 1
  400. }
  401. w.Header().Set("Retry-After", fmt.Sprintf("%d", retryAfter))
  402. m.sendErrorResponse(w, http.StatusTooManyRequests, "rate limit exceeded")
  403. return
  404. }
  405. // Update last used timestamp asynchronously
  406. go func() {
  407. if err := m.Validator.UpdateLastUsed(context.Background(), apiKey); err != nil {
  408. m.Logger.Error("failed to update last_used timestamp", "err", err.Error())
  409. }
  410. }()
  411. // Add API key info to context for use in handlers
  412. ctx = context.WithValue(ctx, ContextKeyAPIKey, key)
  413. ctx = context.WithValue(ctx, ContextKeyDevID, key.DevID)
  414. // Log the API request
  415. m.Logger.InfoContext(ctx, "API request authenticated via key",
  416. "dev_id", key.DevID,
  417. "app_name", key.AppName,
  418. "method", r.Method,
  419. "path", r.URL.Path,
  420. )
  421. // Pass to next handler with enriched context
  422. next.ServeHTTP(w, r.WithContext(ctx))
  423. })
  424. }