api_key_auth.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. package middleware
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. "github.com/Wei-Shaw/sub2api/internal/config"
  9. "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
  10. "github.com/Wei-Shaw/sub2api/internal/pkg/ip"
  11. "github.com/Wei-Shaw/sub2api/internal/service"
  12. "github.com/gin-gonic/gin"
  13. )
  14. const maxAPIKeyAuthorizationHeaderBytes = service.MaxAPIKeyCredentialBytes + 128
  15. // NewAPIKeyAuthMiddleware 创建 API Key 认证中间件
  16. // 可选传入分级路由服务(第 4 参):鉴权成功后按用户等级把目标账号池写入 ctx,
  17. // 调度器据此优先选择同池账号;不传则保持原行为。
  18. func NewAPIKeyAuthMiddleware(apiKeyService *service.APIKeyService, subscriptionService *service.SubscriptionService, cfg *config.Config, tierRouting ...*service.TieredRoutingService) APIKeyAuthMiddleware {
  19. return APIKeyAuthMiddleware(apiKeyAuthWithSubscription(apiKeyService, subscriptionService, cfg, tierRouting...))
  20. }
  21. // apiKeyAuthWithSubscription API Key认证中间件(支持订阅验证)
  22. //
  23. // 中间件职责分为两层:
  24. // - 鉴权(Authentication):验证 Key 有效性、用户状态、IP 限制 —— 始终执行
  25. // - 计费执行(Billing Enforcement):过期/配额/订阅/余额检查 —— skipBilling 时整块跳过
  26. //
  27. // /v1/usage、/v1/sub2api/billing 端点与异步生图任务查询只需鉴权,不需要计费执行。
  28. // usage 允许过期/配额耗尽的 Key 查询自身用量,billing 用于读取当前 Key 的倍率配置,
  29. // 异步生图查询允许已耗尽额度的 Key 拉取自身任务结果。
  30. func apiKeyAuthWithSubscription(apiKeyService *service.APIKeyService, subscriptionService *service.SubscriptionService, cfg *config.Config, tierServices ...*service.TieredRoutingService) gin.HandlerFunc {
  31. var tierRouting *service.TieredRoutingService
  32. if len(tierServices) > 0 {
  33. tierRouting = tierServices[0]
  34. }
  35. return func(c *gin.Context) {
  36. // ── 1. 提取 API Key ──────────────────────────────────────────
  37. if rejectInvalidAuthAbuse(c, apiKeyService) {
  38. AbortWithError(c, http.StatusTooManyRequests, "INVALID_AUTH_RATE_LIMITED", "Too many invalid authentication attempts; retry later")
  39. return
  40. }
  41. if apiKeyHeadersTooLarge(c) {
  42. recordInvalidAuthFailure(c, apiKeyService)
  43. MarkIngressRejected(c, IngressRejectInvalidAPIKey)
  44. AbortWithError(c, http.StatusUnauthorized, "INVALID_API_KEY", "Invalid API key")
  45. return
  46. }
  47. queryKey := strings.TrimSpace(c.Query("key"))
  48. queryApiKey := strings.TrimSpace(c.Query("api_key"))
  49. if queryKey != "" || queryApiKey != "" {
  50. recordInvalidAuthFailure(c, apiKeyService)
  51. MarkIngressRejected(c, IngressRejectQueryAPIKeyDeprecated)
  52. AbortWithError(c, 400, "api_key_in_query_deprecated", "API key in query parameter is deprecated. Please use Authorization header instead.")
  53. return
  54. }
  55. // 尝试从Authorization header中提取API key (Bearer scheme)
  56. authHeader := c.GetHeader("Authorization")
  57. var apiKeyString string
  58. if authHeader != "" {
  59. // 验证Bearer scheme
  60. parts := strings.SplitN(authHeader, " ", 2)
  61. if len(parts) == 2 && strings.EqualFold(parts[0], "Bearer") {
  62. apiKeyString = strings.TrimSpace(parts[1])
  63. }
  64. }
  65. // 如果Authorization header中没有,尝试从x-api-key header中提取
  66. if apiKeyString == "" {
  67. apiKeyString = c.GetHeader("x-api-key")
  68. }
  69. if len(apiKeyString) > service.MaxAPIKeyCredentialBytes {
  70. recordInvalidAuthFailure(c, apiKeyService)
  71. MarkIngressRejected(c, IngressRejectInvalidAPIKey)
  72. AbortWithError(c, http.StatusUnauthorized, "INVALID_API_KEY", "Invalid API key")
  73. return
  74. }
  75. // 如果x-api-key header中没有,尝试从x-goog-api-key header中提取(Gemini CLI兼容)
  76. if apiKeyString == "" {
  77. apiKeyString = c.GetHeader("x-goog-api-key")
  78. }
  79. // 如果所有header都没有API key
  80. if apiKeyString == "" {
  81. recordInvalidAuthFailure(c, apiKeyService)
  82. if hasAPIKeyCredentialInput(c) {
  83. MarkIngressRejected(c, IngressRejectInvalidAPIKey)
  84. } else {
  85. MarkIngressRejected(c, IngressRejectAPIKeyRequired)
  86. }
  87. AbortWithError(c, 401, "API_KEY_REQUIRED", "API key is required in Authorization header (Bearer scheme), x-api-key header, or x-goog-api-key header")
  88. return
  89. }
  90. // ── 2. 验证 Key 存在 ─────────────────────────────────────────
  91. apiKey, err := apiKeyService.GetByKey(c.Request.Context(), apiKeyString)
  92. if err != nil {
  93. if errors.Is(err, service.ErrAPIKeyNotFound) {
  94. recordInvalidAuthFailure(c, apiKeyService)
  95. MarkIngressRejected(c, IngressRejectInvalidAPIKey)
  96. AbortWithError(c, 401, "INVALID_API_KEY", "Invalid API key")
  97. return
  98. }
  99. if errors.Is(err, service.ErrAPIKeyAuthOverloaded) {
  100. MarkIngressRejected(c, IngressRejectAPIKeyAuthOverloaded)
  101. AbortWithError(c, http.StatusServiceUnavailable, "API_KEY_AUTH_OVERLOADED", "API key authentication is temporarily unavailable")
  102. return
  103. }
  104. AbortWithError(c, 500, "INTERNAL_ERROR", "Failed to validate API key")
  105. return
  106. }
  107. // apiKey 已加载(含 User/Group)。即便后续因分组停用/Key 停用/用户停用/
  108. // IP 限制等早退中断,也让 Ops 错误日志能回退取到 user/group/platform。
  109. SetOpsFallbackAPIKey(c, apiKey)
  110. // ── 3. 基础鉴权(始终执行) ─────────────────────────────────
  111. // disabled / 未知状态 → 无条件拦截(expired 和 quota_exhausted 留给计费阶段)
  112. if !apiKey.IsActive() &&
  113. apiKey.Status != service.StatusAPIKeyExpired &&
  114. apiKey.Status != service.StatusAPIKeyQuotaExhausted {
  115. MarkIngressRejected(c, IngressRejectAPIKeyDisabled)
  116. AbortWithError(c, 401, "API_KEY_DISABLED", "API key is disabled")
  117. return
  118. }
  119. // 检查 IP 限制(白名单/黑名单)
  120. // 注意:错误信息故意模糊,避免暴露具体的 IP 限制机制
  121. if len(apiKey.IPWhitelist) > 0 || len(apiKey.IPBlacklist) > 0 {
  122. clientIP := ip.GetSecurityClientIP(c, cfg.TrustForwardedIPForAPIKeyACL())
  123. allowed, _ := ip.CheckIPRestrictionWithCompiledRules(clientIP, apiKey.CompiledIPWhitelist, apiKey.CompiledIPBlacklist)
  124. if !allowed {
  125. if clientIP == "" {
  126. clientIP = "unknown"
  127. }
  128. service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonIPRestriction)
  129. MarkIngressRejected(c, IngressRejectIPRestricted)
  130. AbortWithError(c, 403, "ACCESS_DENIED", fmt.Sprintf("Access denied. Your IP is %s", clientIP))
  131. return
  132. }
  133. }
  134. // 检查关联的用户
  135. if apiKey.User == nil {
  136. AbortWithError(c, 401, "USER_NOT_FOUND", "User associated with API key not found")
  137. return
  138. }
  139. // 检查用户状态
  140. if !apiKey.User.IsActive() {
  141. MarkIngressRejected(c, IngressRejectUserInactive)
  142. AbortWithError(c, 401, "USER_INACTIVE", "User account is not active")
  143. return
  144. }
  145. if abortIfAPIKeyGroupUnavailable(c, apiKey) {
  146. return
  147. }
  148. if abortIfAPIKeyGroupNotAllowed(c, apiKey) {
  149. return
  150. }
  151. ctx := context.WithValue(c.Request.Context(), ctxkey.UserID, apiKey.User.ID)
  152. c.Request = c.Request.WithContext(ctx)
  153. // 分级路由:按用户等级写入目标账号池(standard 不过滤,无行为变化)。
  154. if tierRouting != nil && apiKey.User != nil {
  155. c.Request = c.Request.WithContext(service.WithTierPool(ctx, tierRouting.ResolvePool(apiKey.User)))
  156. }
  157. billingInfoRequest := c.Request.URL.Path == "/v1/sub2api/billing"
  158. // Async image task polling only reads data that already belongs to the
  159. // authenticated key and must remain available after the completed
  160. // generation consumes the key's remaining balance.
  161. skipBilling := c.Request.URL.Path == "/v1/usage" || billingInfoRequest || isAsyncImageTaskRead(c.Request.Method, c.Request.URL.Path)
  162. // ── 4. SimpleMode → early return ─────────────────────────────
  163. if cfg.RunMode == config.RunModeSimple {
  164. c.Set(string(ContextKeyAPIKey), apiKey)
  165. c.Set(string(ContextKeyUser), AuthSubject{
  166. UserID: apiKey.User.ID,
  167. Concurrency: apiKey.User.Concurrency,
  168. })
  169. c.Set(string(ContextKeyUserRole), apiKey.User.Role)
  170. setGroupContext(c, apiKey.Group)
  171. if !billingInfoRequest {
  172. _ = apiKeyService.TouchLastUsed(c.Request.Context(), apiKey.ID)
  173. }
  174. c.Next()
  175. return
  176. }
  177. // ── 5. 按端点需要加载订阅 ───────────────────────────────────
  178. var subscription *service.UserSubscription
  179. isSubscriptionType := apiKey.Group != nil && apiKey.Group.IsSubscriptionType()
  180. // 倍率自省不需要订阅数据;/v1/usage 仍保留原有订阅读取行为。
  181. if isSubscriptionType && subscriptionService != nil && !billingInfoRequest {
  182. sub, subErr := subscriptionService.GetActiveSubscription(
  183. c.Request.Context(),
  184. apiKey.User.ID,
  185. apiKey.Group.ID,
  186. )
  187. if subErr != nil {
  188. if !skipBilling {
  189. AbortWithError(c, 403, "SUBSCRIPTION_NOT_FOUND", "No active subscription found for this group")
  190. return
  191. }
  192. // skipBilling: 订阅不存在也放行,handler 会返回可用的数据
  193. } else {
  194. subscription = sub
  195. }
  196. }
  197. // ── 6. 计费执行(skipBilling 时整块跳过) ────────────────────
  198. if !skipBilling {
  199. // Key 状态检查
  200. switch apiKey.Status {
  201. case service.StatusAPIKeyQuotaExhausted:
  202. abortWithAPIKeyQuotaError(c)
  203. return
  204. case service.StatusAPIKeyExpired:
  205. AbortWithError(c, 403, "API_KEY_EXPIRED", "API key 已过期")
  206. return
  207. }
  208. // 运行时过期/配额检查(即使状态是 active,也要检查时间和用量)
  209. if apiKey.IsExpired() {
  210. AbortWithError(c, 403, "API_KEY_EXPIRED", "API key 已过期")
  211. return
  212. }
  213. if apiKey.IsQuotaExhausted() {
  214. abortWithAPIKeyQuotaError(c)
  215. return
  216. }
  217. // 订阅模式:验证订阅限额
  218. if subscription != nil {
  219. needsMaintenance, validateErr := subscriptionService.ValidateAndCheckLimits(subscription, apiKey.Group)
  220. if needsMaintenance {
  221. refreshed, maintenanceErr := subscriptionService.EnsureWindowMaintenance(c.Request.Context(), subscription)
  222. if maintenanceErr != nil {
  223. AbortWithError(c, 500, "SUBSCRIPTION_MAINTENANCE_FAILED", "Failed to maintain subscription usage windows")
  224. return
  225. }
  226. subscription = refreshed
  227. _, validateErr = subscriptionService.ValidateAndCheckLimits(subscription, apiKey.Group)
  228. }
  229. if validateErr != nil {
  230. code := "SUBSCRIPTION_INVALID"
  231. status := 403
  232. if errors.Is(validateErr, service.ErrDailyLimitExceeded) ||
  233. errors.Is(validateErr, service.ErrWeeklyLimitExceeded) ||
  234. errors.Is(validateErr, service.ErrMonthlyLimitExceeded) {
  235. code = "USAGE_LIMIT_EXCEEDED"
  236. status = 429
  237. }
  238. AbortWithError(c, status, code, validateErr.Error())
  239. return
  240. }
  241. } else {
  242. // 非订阅模式 或 订阅模式但 subscriptionService 未注入:回退到余额检查
  243. if apiKeyBalanceBelowAuthThreshold(apiKey.User.Balance, cfg) {
  244. AbortWithError(c, 403, "INSUFFICIENT_BALANCE", "Insufficient account balance")
  245. return
  246. }
  247. }
  248. }
  249. // ── 7. 设置上下文 → Next ─────────────────────────────────────
  250. if subscription != nil {
  251. c.Set(string(ContextKeySubscription), subscription)
  252. }
  253. c.Set(string(ContextKeyAPIKey), apiKey)
  254. c.Set(string(ContextKeyUser), AuthSubject{
  255. UserID: apiKey.User.ID,
  256. Concurrency: apiKey.User.Concurrency,
  257. })
  258. c.Set(string(ContextKeyUserRole), apiKey.User.Role)
  259. setGroupContext(c, apiKey.Group)
  260. if !billingInfoRequest {
  261. _ = apiKeyService.TouchLastUsed(c.Request.Context(), apiKey.ID)
  262. }
  263. c.Next()
  264. }
  265. }
  266. func apiKeyHeadersTooLarge(c *gin.Context) bool {
  267. if c == nil {
  268. return false
  269. }
  270. return len(c.GetHeader("Authorization")) > maxAPIKeyAuthorizationHeaderBytes ||
  271. len(c.GetHeader("x-api-key")) > service.MaxAPIKeyCredentialBytes ||
  272. len(c.GetHeader("x-goog-api-key")) > service.MaxAPIKeyCredentialBytes
  273. }
  274. func hasAPIKeyCredentialInput(c *gin.Context) bool {
  275. if c == nil {
  276. return false
  277. }
  278. return c.GetHeader("Authorization") != "" ||
  279. c.GetHeader("x-api-key") != "" ||
  280. c.GetHeader("x-goog-api-key") != ""
  281. }
  282. func abortWithAPIKeyQuotaError(c *gin.Context) {
  283. const message = "API key 额度已用完"
  284. if isOpenAICompatibleAPIKeyRequest(c) {
  285. abortWithOpenAIQuotaError(c, http.StatusTooManyRequests, message)
  286. return
  287. }
  288. AbortWithError(c, http.StatusTooManyRequests, "API_KEY_QUOTA_EXHAUSTED", message)
  289. }
  290. func isOpenAICompatibleAPIKeyRequest(c *gin.Context) bool {
  291. if c == nil || c.Request == nil || c.Request.URL == nil {
  292. return false
  293. }
  294. path := strings.TrimRight(c.Request.URL.Path, "/")
  295. for _, root := range []string{
  296. "/v1/responses",
  297. "/openai/v1/responses",
  298. "/responses",
  299. "/backend-api/codex/responses",
  300. } {
  301. if path == root || strings.HasPrefix(path, root+"/") {
  302. return true
  303. }
  304. }
  305. return false
  306. }
  307. func isAsyncImageTaskRead(method, path string) bool {
  308. if method != http.MethodGet {
  309. return false
  310. }
  311. return strings.HasPrefix(path, "/v1/images/tasks/") || strings.HasPrefix(path, "/images/tasks/")
  312. }
  313. // GetAPIKeyFromContext 从上下文中获取API key
  314. func GetAPIKeyFromContext(c *gin.Context) (*service.APIKey, bool) {
  315. value, exists := c.Get(string(ContextKeyAPIKey))
  316. if !exists {
  317. return nil, false
  318. }
  319. apiKey, ok := value.(*service.APIKey)
  320. return apiKey, ok
  321. }
  322. // SetOpsFallbackAPIKey 记录已加载的 API Key,供 Ops 错误日志在鉴权早退时回退使用。
  323. // 与 ContextKeyAPIKey 区分:写入它不代表请求已通过鉴权,因此不影响 handler、
  324. // 审计日志等对“已鉴权”的判断。
  325. func SetOpsFallbackAPIKey(c *gin.Context, apiKey *service.APIKey) {
  326. if c == nil || apiKey == nil {
  327. return
  328. }
  329. c.Set(string(ContextKeyOpsFallbackAPIKey), apiKey)
  330. }
  331. // GetOpsFallbackAPIKey 读取 Ops 错误日志专用的回退 API Key。
  332. func GetOpsFallbackAPIKey(c *gin.Context) (*service.APIKey, bool) {
  333. value, exists := c.Get(string(ContextKeyOpsFallbackAPIKey))
  334. if !exists {
  335. return nil, false
  336. }
  337. apiKey, ok := value.(*service.APIKey)
  338. return apiKey, ok
  339. }
  340. // GetSubscriptionFromContext 从上下文中获取订阅信息
  341. func GetSubscriptionFromContext(c *gin.Context) (*service.UserSubscription, bool) {
  342. value, exists := c.Get(string(ContextKeySubscription))
  343. if !exists {
  344. return nil, false
  345. }
  346. subscription, ok := value.(*service.UserSubscription)
  347. return subscription, ok
  348. }
  349. func setGroupContext(c *gin.Context, group *service.Group) {
  350. if !service.IsGroupContextValid(group) {
  351. return
  352. }
  353. if existing, ok := c.Request.Context().Value(ctxkey.Group).(*service.Group); ok && existing != nil && existing.ID == group.ID && service.IsGroupContextValid(existing) {
  354. return
  355. }
  356. ctx := context.WithValue(c.Request.Context(), ctxkey.Group, group)
  357. c.Request = c.Request.WithContext(ctx)
  358. }
  359. // apiKeyBalanceBelowAuthThreshold 保持鉴权层的历史语义:仅在余额耗尽(<=0)时拒绝。
  360. // MinimumBalanceReserve 只作为 billing-cache 预检的保守下限,不得复用为鉴权硬门槛,
  361. // 否则已配置该值的存量部署升级后,0 < balance < reserve 的用户会在所有端点被静默 403。
  362. func apiKeyBalanceBelowAuthThreshold(balance float64, _ *config.Config) bool {
  363. return balance <= 0
  364. }
  365. func abortIfAPIKeyGroupUnavailable(c *gin.Context, apiKey *service.APIKey) bool {
  366. code, message, ok := validateAPIKeyGroupAvailable(apiKey)
  367. if ok {
  368. return false
  369. }
  370. service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonAPIKeyGroupUnavailable)
  371. if code == "GROUP_DELETED" {
  372. MarkIngressRejected(c, IngressRejectGroupDeleted)
  373. } else {
  374. MarkIngressRejected(c, IngressRejectGroupDisabled)
  375. }
  376. AbortWithError(c, 403, code, message)
  377. return true
  378. }
  379. func abortIfAPIKeyGroupNotAllowed(c *gin.Context, apiKey *service.APIKey) bool {
  380. if validateAPIKeyGroupAllowed(apiKey) {
  381. return false
  382. }
  383. service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonAPIKeyGroupUnavailable)
  384. MarkIngressRejected(c, IngressRejectGroupNotAllowed)
  385. AbortWithError(c, 403, "GROUP_NOT_ALLOWED", "API Key 所属专属分组不再允许当前用户使用")
  386. return true
  387. }
  388. func validateAPIKeyGroupAllowed(apiKey *service.APIKey) bool {
  389. if apiKey == nil || apiKey.GroupID == nil || apiKey.User == nil || apiKey.Group == nil {
  390. return true
  391. }
  392. group := apiKey.Group
  393. if group.IsSubscriptionType() {
  394. return true
  395. }
  396. return apiKey.User.CanBindGroup(group.ID, group.IsExclusive)
  397. }
  398. func validateAPIKeyGroupAvailable(apiKey *service.APIKey) (string, string, bool) {
  399. if apiKey == nil || apiKey.GroupID == nil {
  400. return "", "", true
  401. }
  402. group := apiKey.Group
  403. if group == nil || strings.EqualFold(group.Status, "deleted") {
  404. return "GROUP_DELETED", "API Key 所属分组已删除", false
  405. }
  406. if !group.IsActive() {
  407. return "GROUP_DISABLED", "API Key 所属分组已停用", false
  408. }
  409. return "", "", true
  410. }