auth.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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/open-oscar-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. // AuthMiddleware provides authentication and rate limiting for Web API endpoints.
  102. type AuthMiddleware struct {
  103. Validator APIKeyValidator
  104. RateLimiter *RateLimiter
  105. Logger *slog.Logger
  106. }
  107. // NewAuthMiddleware creates a new authentication middleware instance.
  108. func NewAuthMiddleware(validator APIKeyValidator, logger *slog.Logger) *AuthMiddleware {
  109. return &AuthMiddleware{
  110. Validator: validator,
  111. RateLimiter: NewRateLimiter(),
  112. Logger: logger,
  113. }
  114. }
  115. // Authenticate is an HTTP middleware that validates API keys and enforces rate limits.
  116. func (m *AuthMiddleware) Authenticate(next http.Handler) http.Handler {
  117. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  118. // Extract API key from 'k' parameter (query or form)
  119. apiKey := r.URL.Query().Get("k")
  120. if apiKey == "" {
  121. // Try form value for POST requests
  122. apiKey = r.FormValue("k")
  123. }
  124. if apiKey == "" {
  125. m.sendErrorResponse(w, r, http.StatusBadRequest, "required parameter 'k' is missing")
  126. return
  127. }
  128. // Validate API key
  129. ctx := r.Context()
  130. key := m.resolveAPIKey(ctx, apiKey)
  131. if key == nil {
  132. m.Logger.DebugContext(ctx, "invalid API key attempted", "key", apiKey[:min(8, len(apiKey))]+"...")
  133. m.sendErrorResponse(w, r, http.StatusForbidden, "invalid API key")
  134. return
  135. }
  136. // Check rate limit
  137. rateLimitInfo := m.RateLimiter.CheckRateLimit(key.DevID, key.RateLimit)
  138. // Always add rate limit headers
  139. w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", rateLimitInfo.Limit))
  140. w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", rateLimitInfo.Remaining))
  141. w.Header().Set("X-RateLimit-Reset", fmt.Sprintf("%d", rateLimitInfo.Reset))
  142. if !rateLimitInfo.Allowed {
  143. m.Logger.WarnContext(ctx, "rate limit exceeded", "dev_id", key.DevID, "limit", key.RateLimit)
  144. // Add Retry-After header
  145. retryAfter := rateLimitInfo.Reset - time.Now().Unix()
  146. if retryAfter < 1 {
  147. retryAfter = 1
  148. }
  149. w.Header().Set("Retry-After", fmt.Sprintf("%d", retryAfter))
  150. m.sendErrorResponse(w, r, http.StatusTooManyRequests, "rate limit exceeded")
  151. return
  152. }
  153. // Update last used timestamp asynchronously
  154. go func() {
  155. if err := m.Validator.UpdateLastUsed(context.Background(), apiKey); err != nil {
  156. m.Logger.Error("failed to update last_used timestamp", "err", err.Error())
  157. }
  158. }()
  159. // Add API key info to context for use in handlers
  160. ctx = context.WithValue(ctx, ContextKeyAPIKey, key)
  161. ctx = context.WithValue(ctx, ContextKeyDevID, key.DevID)
  162. // Log the API request
  163. m.Logger.InfoContext(ctx, "API request authenticated",
  164. "dev_id", key.DevID,
  165. "app_name", key.AppName,
  166. "method", r.Method,
  167. "path", r.URL.Path,
  168. )
  169. // Pass to next handler with enriched context
  170. next.ServeHTTP(w, r.WithContext(ctx))
  171. })
  172. }
  173. // CORSMiddleware handles CORS headers based on allowed origins for the API key.
  174. func (m *AuthMiddleware) CORSMiddleware(next http.Handler) http.Handler {
  175. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  176. // Get API key from context (set by Authenticate middleware)
  177. key, ok := r.Context().Value(ContextKeyAPIKey).(*state.WebAPIKey)
  178. // If no API key in context (e.g., using aimsid auth), allow all origins
  179. // This is safe because the actual authentication is handled by the session
  180. var allowedOrigins []string
  181. if ok && key != nil {
  182. allowedOrigins = key.AllowedOrigins
  183. } else {
  184. // For session-based auth without API key, allow all origins
  185. // The session itself provides the security boundary
  186. m.Logger.DebugContext(r.Context(), "CORS handling for non-API-key auth (aimsid/token)")
  187. allowedOrigins = []string{"*"}
  188. }
  189. origin := r.Header.Get("Origin")
  190. // Check if origin is allowed
  191. if m.isOriginAllowed(origin, allowedOrigins) {
  192. if len(allowedOrigins) == 1 && allowedOrigins[0] == "*" {
  193. // For wildcard, set the actual origin to allow credentials
  194. if origin != "" {
  195. w.Header().Set("Access-Control-Allow-Origin", origin)
  196. } else {
  197. w.Header().Set("Access-Control-Allow-Origin", "*")
  198. }
  199. } else {
  200. w.Header().Set("Access-Control-Allow-Origin", origin)
  201. }
  202. w.Header().Set("Access-Control-Allow-Credentials", "true")
  203. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
  204. w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
  205. w.Header().Set("Access-Control-Max-Age", "3600")
  206. }
  207. // Handle preflight requests
  208. if r.Method == "OPTIONS" {
  209. w.WriteHeader(http.StatusNoContent)
  210. return
  211. }
  212. next.ServeHTTP(w, r)
  213. })
  214. }
  215. // isOriginAllowed checks if an origin is in the allowed list.
  216. func (m *AuthMiddleware) isOriginAllowed(origin string, allowedOrigins []string) bool {
  217. // If no origins specified, allow all (for backward compatibility/development)
  218. if len(allowedOrigins) == 0 {
  219. return true
  220. }
  221. origin = strings.ToLower(origin)
  222. for _, allowed := range allowedOrigins {
  223. allowed = strings.ToLower(allowed)
  224. // Exact match
  225. if origin == allowed {
  226. return true
  227. }
  228. // Wildcard support (e.g., "*.example.com")
  229. if strings.HasPrefix(allowed, "*.") {
  230. domain := allowed[2:]
  231. if strings.HasSuffix(origin, domain) {
  232. return true
  233. }
  234. }
  235. // Allow all origins (development only)
  236. if allowed == "*" {
  237. m.Logger.Warn("wildcard origin (*) used - should not be used in production")
  238. return true
  239. }
  240. }
  241. return false
  242. }
  243. // sendErrorResponse sends a Web AIM API error envelope, with JSONP support when requested.
  244. func (m *AuthMiddleware) sendErrorResponse(w http.ResponseWriter, r *http.Request, statusCode int, message string) {
  245. response := map[string]interface{}{
  246. "response": map[string]interface{}{
  247. "statusCode": statusCode,
  248. "statusText": message,
  249. },
  250. }
  251. body, err := json.Marshal(response)
  252. if err != nil {
  253. m.Logger.Error("failed to encode error response", "err", err.Error())
  254. http.Error(w, "internal server error", http.StatusInternalServerError)
  255. return
  256. }
  257. callback := jsonpCallback(r)
  258. if callback != "" && isValidJSONPCallback(callback) {
  259. w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
  260. _, _ = w.Write([]byte(callback))
  261. _, _ = w.Write([]byte("("))
  262. _, _ = w.Write(body)
  263. _, _ = w.Write([]byte(");"))
  264. return
  265. }
  266. w.Header().Set("Content-Type", "application/json")
  267. _, _ = w.Write(body)
  268. }
  269. func jsonpCallback(r *http.Request) string {
  270. if callback := r.URL.Query().Get("c"); callback != "" {
  271. return callback
  272. }
  273. return r.URL.Query().Get("callback")
  274. }
  275. func isValidJSONPCallback(callback string) bool {
  276. if len(callback) == 0 || len(callback) > 100 {
  277. return false
  278. }
  279. for _, r := range callback {
  280. if (r < 'a' || r > 'z') &&
  281. (r < 'A' || r > 'Z') &&
  282. (r < '0' || r > '9') &&
  283. r != '_' && r != '$' && r != '.' {
  284. return false
  285. }
  286. }
  287. return true
  288. }
  289. // min returns the minimum of two integers.
  290. func min(a, b int) int {
  291. if a < b {
  292. return a
  293. }
  294. return b
  295. }
  296. // AuthenticateFlexible is an HTTP middleware that supports multiple authentication methods:
  297. // 1. aimsid (session ID) - no k required
  298. // 2. a (AOL token) - no k required
  299. // 3. ts + sig_sha256 (signed request) - no k required
  300. // 4. k (API key) - fallback if no other auth provided
  301. // This follows the Web AIM API specification where k is not required when aimsid is present.
  302. func (m *AuthMiddleware) AuthenticateFlexible(next http.Handler) http.Handler {
  303. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  304. ctx := r.Context()
  305. // Priority 1: Check for session-based auth (aimsid)
  306. // According to the spec, when aimsid is provided, k is not required
  307. if aimsid := r.URL.Query().Get("aimsid"); aimsid != "" {
  308. // The handler itself will validate the aimsid
  309. // We just need to pass the request through without requiring k
  310. m.Logger.DebugContext(ctx, "using aimsid authentication", "aimsid", aimsid[:min(16, len(aimsid))]+"...")
  311. next.ServeHTTP(w, r)
  312. return
  313. }
  314. // Priority 2: AOL token auth — user identity is in the token; k is optional.
  315. if token := r.URL.Query().Get("a"); token != "" {
  316. key := m.resolveAPIKey(ctx, r.URL.Query().Get("k"))
  317. if key == nil {
  318. devKey := r.URL.Query().Get("k")
  319. key = &state.WebAPIKey{
  320. DevID: "aim_web",
  321. DevKey: devKey,
  322. AppName: "AIM Web Client",
  323. IsActive: true,
  324. RateLimit: 600,
  325. }
  326. }
  327. ctx = context.WithValue(ctx, ContextKeyAPIKey, key)
  328. ctx = context.WithValue(ctx, ContextKeyDevID, key.DevID)
  329. m.Logger.DebugContext(ctx, "using token authentication", "dev_id", key.DevID)
  330. next.ServeHTTP(w, r.WithContext(ctx))
  331. return
  332. }
  333. // Priority 3: Check for signed request auth
  334. if ts := r.URL.Query().Get("ts"); ts != "" {
  335. if sig := r.URL.Query().Get("sig_sha256"); sig != "" {
  336. // For now, signed requests still require 'k' parameter for API key validation
  337. // The signature provides additional security on top of the API key
  338. // When full signature validation is implemented, this can be made optional
  339. m.Logger.DebugContext(ctx, "signed request detected, falling through to API key validation")
  340. // Don't return here - continue to API key validation below
  341. }
  342. }
  343. // Priority 4: Fall back to API key requirement
  344. apiKey := r.URL.Query().Get("k")
  345. if apiKey == "" {
  346. // Try form value for POST requests
  347. apiKey = r.FormValue("k")
  348. }
  349. if apiKey == "" {
  350. m.sendErrorResponse(w, r, http.StatusBadRequest, "authentication required: provide aimsid or k parameter")
  351. return
  352. }
  353. key := m.resolveAPIKey(ctx, apiKey)
  354. if key == nil {
  355. m.Logger.DebugContext(ctx, "invalid API key attempted", "key", apiKey[:min(8, len(apiKey))]+"...")
  356. m.sendErrorResponse(w, r, http.StatusForbidden, "invalid API key")
  357. return
  358. }
  359. // Check rate limit
  360. rateLimitInfo := m.RateLimiter.CheckRateLimit(key.DevID, key.RateLimit)
  361. // Always add rate limit headers
  362. w.Header().Set("X-RateLimit-Limit", fmt.Sprintf("%d", rateLimitInfo.Limit))
  363. w.Header().Set("X-RateLimit-Remaining", fmt.Sprintf("%d", rateLimitInfo.Remaining))
  364. w.Header().Set("X-RateLimit-Reset", fmt.Sprintf("%d", rateLimitInfo.Reset))
  365. if !rateLimitInfo.Allowed {
  366. m.Logger.WarnContext(ctx, "rate limit exceeded", "dev_id", key.DevID, "limit", key.RateLimit)
  367. // Add Retry-After header
  368. retryAfter := rateLimitInfo.Reset - time.Now().Unix()
  369. if retryAfter < 1 {
  370. retryAfter = 1
  371. }
  372. w.Header().Set("Retry-After", fmt.Sprintf("%d", retryAfter))
  373. m.sendErrorResponse(w, r, http.StatusTooManyRequests, "rate limit exceeded")
  374. return
  375. }
  376. // Update last used timestamp asynchronously
  377. go func() {
  378. if err := m.Validator.UpdateLastUsed(context.Background(), apiKey); err != nil {
  379. m.Logger.Error("failed to update last_used timestamp", "err", err.Error())
  380. }
  381. }()
  382. // Add API key info to context for use in handlers
  383. ctx = context.WithValue(ctx, ContextKeyAPIKey, key)
  384. ctx = context.WithValue(ctx, ContextKeyDevID, key.DevID)
  385. // Log the API request
  386. m.Logger.InfoContext(ctx, "API request authenticated via key",
  387. "dev_id", key.DevID,
  388. "app_name", key.AppName,
  389. "method", r.Method,
  390. "path", r.URL.Path,
  391. )
  392. // Pass to next handler with enriched context
  393. next.ServeHTTP(w, r.WithContext(ctx))
  394. })
  395. }
  396. func (m *AuthMiddleware) resolveAPIKey(ctx context.Context, devKey string) *state.WebAPIKey {
  397. if devKey == "" {
  398. return nil
  399. }
  400. key, err := m.Validator.GetAPIKeyByDevKey(ctx, devKey)
  401. if err != nil || key == nil || !key.IsActive {
  402. return nil
  403. }
  404. return key
  405. }