auth.go 16 KB

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