Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 53 additions & 1 deletion controller/token.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package controller

import (
"github.com/gin-gonic/gin"
"net/http"
"one-api/common"
"one-api/model"
"strconv"
"strings"

"github.com/gin-gonic/gin"
)

func GetAllTokens(c *gin.Context) {
Expand Down Expand Up @@ -106,6 +108,56 @@ func GetTokenStatus(c *gin.Context) {
})
}

func GetTokenUsage(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"message": "No Authorization header",
})
return
}

parts := strings.Split(authHeader, " ")
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"message": "Invalid Bearer token",
})
return
}
tokenKey := parts[1]

token, err := model.GetTokenByKey(tokenKey, true)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Authorization bypass across users — validate ownership and use cache path

Any authenticated user can currently supply any known token key and retrieve its usage. Enforce that the token belongs to the current user. While here, prefer the cache path for lookups.

Apply:

-    token, err := model.GetTokenByKey(tokenKey, true)
+    // Try cache first to reduce DB load
+    token, err := model.GetTokenByKey(tokenKey, false)
     if err != nil {
         c.JSON(http.StatusOK, gin.H{
             "success": false,
             "message": err.Error(),
         })
         return
     }
+    // Ensure the token belongs to the current user
+    userId := c.GetInt("id")
+    if token.UserId != userId {
+        c.JSON(http.StatusForbidden, gin.H{
+            "success": false,
+            "message": "forbidden",
+        })
+        return
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
token, err := model.GetTokenByKey(tokenKey, true)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
// Try cache first to reduce DB load
token, err := model.GetTokenByKey(tokenKey, false)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"message": err.Error(),
})
return
}
// Ensure the token belongs to the current user
userId := c.GetInt("id")
if token.UserId != userId {
c.JSON(http.StatusForbidden, gin.H{
"success": false,
"message": "forbidden",
})
return
}
🤖 Prompt for AI Agents
In controller/token.go around lines 106 to 113, the code currently returns token
info for any supplied token key; change the lookup to use the cache path (call
model.GetTokenByKey with the cache flag instead of the DB flag) and then verify
token ownership by comparing token.UserID to the authenticated user ID from the
request context (fetch current user ID from the Gin context/middleware). If the
lookup fails return the existing error response, and if the token exists but
token.UserID does not match the current user return a 403 JSON response
(success: false, message: "forbidden" or similar) and stop processing.


expiredAt := token.ExpiredTime
if expiredAt == -1 {
expiredAt = 0
}

c.JSON(http.StatusOK, gin.H{
"code": true,
"message": "ok",
"data": gin.H{
"object": "token_usage",
"id": token.Id,
"name": token.Name,
"total_granted": token.RemainQuota + token.UsedQuota,
"total_used": token.UsedQuota,
"total_available": token.RemainQuota,
"unlimited_quota": token.UnlimitedQuota,
"expires_at": expiredAt,
},
})
Comment on lines +120 to +134

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Align response envelope and expires_at units with existing endpoints

Other token endpoints use "success" and return expires_at in milliseconds (see GetTokenStatus). Keep this consistent to avoid client breakage.

Apply:

-    c.JSON(http.StatusOK, gin.H{
-        "code": true,
-        "message": "ok",
-        "data": gin.H{
+    c.JSON(http.StatusOK, gin.H{
+        "success": true,
+        "message": "",
+        "data": gin.H{
             "object":          "token_usage",
             "id":              token.Id,
             "name":            token.Name,
             "total_granted":   token.RemainQuota + token.UsedQuota,
             "total_used":      token.UsedQuota,
             "total_available": token.RemainQuota,
             "unlimited_quota": token.UnlimitedQuota,
-            "expires_at":      expiredAt,
+            "expires_at":      expiredAt * 1000,
         },
     })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
c.JSON(http.StatusOK, gin.H{
"code": true,
"message": "ok",
"data": gin.H{
"object": "token_usage",
"id": token.Id,
"name": token.Name,
"total_granted": token.RemainQuota + token.UsedQuota,
"total_used": token.UsedQuota,
"total_available": token.RemainQuota,
"unlimited_quota": token.UnlimitedQuota,
"expires_at": expiredAt,
},
})
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "",
"data": gin.H{
"object": "token_usage",
"id": token.Id,
"name": token.Name,
"total_granted": token.RemainQuota + token.UsedQuota,
"total_used": token.UsedQuota,
"total_available": token.RemainQuota,
"unlimited_quota": token.UnlimitedQuota,
"expires_at": expiredAt * 1000,
},
})
🤖 Prompt for AI Agents
In controller/token.go around lines 120-133, the response envelope and
expires_at units must match other token endpoints: replace the "code" field with
"success" (boolean) and return "expires_at" as milliseconds since epoch instead
of the current unit; compute expires_at via expiredAt.UnixMilli() (or
equivalent) and ensure the JSON value is an integer, leaving other fields
unchanged.

}
Comment on lines +86 to +135

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Add endpoint tests for contract and auth behavior

Cover: 401 no header (if header-parsing kept), 401 invalid scheme, happy path shape (envelope + ms for expires_at), and ownership enforcement (403) if you continue accepting arbitrary token keys.

Proposed verification script to ensure routing and consistency:


🏁 Script executed:

#!/bin/bash
# Confirm the route is protected by TokenAuth
rg -nC3 'GetTokenUsage' -- router | cat
rg -n 'TokenAuth\(' router | cat

# Confirm GetTokenStatus returns expires_at in ms for consistency reference
rg -nC2 'GetTokenStatus|expires_at.*\* *1000' controller | cat

Length of output: 1989


Add tests for GetTokenUsage and normalize expires_at units

Please address the following before merging:

  • Ensure expires_at in GetTokenUsage is returned in milliseconds, to match GetTokenStatus (which does expiredAt * 1000 in controller/token.go:82)
  • Add endpoint tests covering:
    • 401 when the Authorization header is missing
    • 401 when the scheme is not Bearer
    • 403 when a valid token key is used by a non-owner (ownership enforcement)
    • 200 “happy path” response shape, including the JSON envelope and expires_at in ms

Files/locations to update:

  • controller/token.go (normalize expires_at unit)
  • tests for token endpoints (e.g. in controller/token_test.go or equivalent)


func AddToken(c *gin.Context) {
token := model.Token{}
err := c.ShouldBindJSON(&token)
Expand Down
2 changes: 1 addition & 1 deletion router/api-router.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ func SetApiRouter(router *gin.Engine) {
{
tokenRoute.GET("/", controller.GetAllTokens)
tokenRoute.GET("/search", controller.SearchTokens)
tokenRoute.GET("/usage", controller.GetTokenUsage)
tokenRoute.GET("/:id", controller.GetToken)
tokenRoute.POST("/", controller.AddToken)
tokenRoute.PUT("/", controller.UpdateToken)
Expand Down Expand Up @@ -142,7 +143,6 @@ func SetApiRouter(router *gin.Engine) {
logRoute.Use(middleware.CORS())
{
logRoute.GET("/token", controller.GetLogByKey)

}
groupRoute := apiRouter.Group("/group")
groupRoute.Use(middleware.AdminAuth())
Expand Down