auth.go 16 KB

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