Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 5 additions & 1 deletion .github/workflows/e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ concurrency:
jobs:
e2e-test:
name: E2E (KinD)
runs-on: ubuntu-latest
# ubuntu-latest currently resolves to 26.04, which Playwright 1.55 does not
# support ("Playwright does not support chromium on ubuntu26.04-x64").
# Keep the browser install on a supported LTS until the pinned Playwright
# version is upgraded.
runs-on: ubuntu-24.04
timeout-minutes: 25
steps:
- uses: actions/checkout@v4
Expand Down
59 changes: 59 additions & 0 deletions controller/token_self.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
Copyright (C) 2023-2026 QuantumNous
Copyright (C) 2026 CubeRouter

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact [email protected]
*/

package controller

import (
"strconv"

"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/service"

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

// GetSelfTokens returns the caller's personal keys and the organization keys
// they may use, in one paginated list for the personal API Keys page.
func GetSelfTokens(c *gin.Context) {
userId := c.GetInt("id")
if userId <= 0 {
common.ApiErrorMsg(c, "无效的身份信息")
return
}
pageInfo := common.GetPageQuery(c)
status, _ := strconv.Atoi(c.Query("status"))
organizationId, _ := strconv.Atoi(c.Query("organization_id"))
tokens, total, err := service.ListSelfTokens(userId, service.SelfTokenListRequest{
Offset: pageInfo.GetStartIdx(),
Limit: pageInfo.GetPageSize(),
Keyword: c.Query("keyword"),
Token: c.Query("token"),
Status: status,
Visibility: c.Query("visibility"),
OrganizationID: organizationId,
})
if err != nil {
common.ApiError(c, err)
return
}
pageInfo.SetTotal(int(total))
pageInfo.SetItems(tokens)
common.ApiSuccess(c, pageInfo)
}
102 changes: 102 additions & 0 deletions controller/token_self_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*
Copyright (C) 2023-2026 QuantumNous
Copyright (C) 2026 CubeRouter

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact [email protected]
*/

package controller

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/model"
"github.com/gin-gonic/gin"
"github.com/glebarez/sqlite"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/gorm"
)

func newSelfTokenControllerTestDB(t *testing.T) *gorm.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
origDB, origLog := model.DB, model.LOG_DB
origOptions := common.OptionMap
origRedis := common.RedisEnabled
model.DB, model.LOG_DB = db, db
common.OptionMap = map[string]string{}
common.RedisEnabled = false
require.NoError(t, db.AutoMigrate(
&model.User{},
&model.Token{},
&model.Organization{},
&model.OrganizationMember{},
&model.OrganizationTokenSystemBlocker{},
))
t.Cleanup(func() {
model.DB, model.LOG_DB = origDB, origLog
common.OptionMap = origOptions
common.RedisEnabled = origRedis
})
return db
}

func seedSelfTokenController(t *testing.T) {
t.Helper()
db := model.DB
require.NoError(t, db.Create(&[]model.User{
{Id: 101, Username: "alice", DisplayName: "Alice", AffCode: "alice", Status: common.UserStatusEnabled, Role: common.RoleCommonUser},
}).Error)
require.NoError(t, db.Create(&model.Organization{
Id: 9, Name: "Acme", Slug: "acme", Status: model.OrganizationStatusActive, OwnerUserId: 101,
}).Error)
require.NoError(t, db.Create(&model.OrganizationMember{
OrganizationId: 9, UserId: 101, Role: model.OrganizationRoleMember, Status: model.OrganizationMemberStatusActive,
}).Error)
require.NoError(t, db.Create(&[]model.Token{
{Id: 1, UserId: 101, Name: "personal", Key: "personal", ScopeType: model.TokenScopePersonal, Status: common.TokenStatusEnabled},
{Id: 2, UserId: 101, Name: "acme-public", Key: "acme-public", ScopeType: model.TokenScopeOrganization, OrganizationId: 9, Visibility: model.TokenVisibilityPublic, Status: common.TokenStatusEnabled},
}).Error)
}

func TestGetSelfTokensControllerReturnsPersonalAndUsableOrganizationKeys(t *testing.T) {
newSelfTokenControllerTestDB(t)
seedSelfTokenController(t)

gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodGet, "/api/token/self/all?p=1&size=20", nil)
c.Set("id", 101)

GetSelfTokens(c)

require.Equal(t, http.StatusOK, rec.Code)
body := rec.Body.String()
assert.Contains(t, body, `"total":2`)
assert.Contains(t, body, `"name":"personal"`)
assert.Contains(t, body, `"name":"acme-public"`)
assert.Contains(t, body, `"organization_name":"Acme"`)
assert.Contains(t, body, `"key":"acme-public"`)
assert.Contains(t, body, `"key_preview":"`)
// The personal row keeps the masked-key behavior of the personal list.
assert.Contains(t, body, `"key":"pe****al"`)
}
14 changes: 14 additions & 0 deletions middleware/rate-limit.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,3 +252,17 @@ func SearchRateLimit() func(c *gin.Context) {
}
return userRateLimitFactory(common.SearchRateLimitNum, common.SearchRateLimitDuration, "SR")
}

// SearchRateLimitWhenQuery applies the search limiter only when the request
// actually searches. A list endpoint that also serves its page's search box
// must not spend the search budget on ordinary pagination.
func SearchRateLimitWhenQuery() func(c *gin.Context) {
limit := SearchRateLimit()
return func(c *gin.Context) {
if c.Query("keyword") == "" && c.Query("token") == "" {
c.Next()
return
}
limit(c)
}
}
74 changes: 74 additions & 0 deletions middleware/search_rate_limit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
Copyright (C) 2023-2026 QuantumNous
Copyright (C) 2026 CubeRouter

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

For commercial licensing, please contact [email protected]
*/

package middleware

import (
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/QuantumNous/new-api/common"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)

func TestSearchRateLimitWhenQueryOnlyThrottlesSearchRequests(t *testing.T) {
gin.SetMode(gin.TestMode)
previousEnable := common.SearchRateLimitEnable
previousNum := common.SearchRateLimitNum
previousDuration := common.SearchRateLimitDuration
previousRedis := common.RedisEnabled
common.RedisEnabled = false
common.SearchRateLimitEnable = true
common.SearchRateLimitNum = 1
common.SearchRateLimitDuration = 60
t.Cleanup(func() {
common.SearchRateLimitEnable = previousEnable
common.SearchRateLimitNum = previousNum
common.SearchRateLimitDuration = previousDuration
common.RedisEnabled = previousRedis
})

router := gin.New()
// The in-memory limiter keeps the key for RateLimitKeyExpirationDuration,
// so a per-run user ID keeps repeated `go test -count=N` runs independent.
userID := int(time.Now().UnixNano())
router.Use(func(c *gin.Context) {
c.Set("id", userID)
})
Comment thread
skeeey marked this conversation as resolved.
Resolved
router.GET("/keys", SearchRateLimitWhenQuery(), func(c *gin.Context) {
c.Status(http.StatusNoContent)
})

request := func(target string) int {
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, target, nil))
return recorder.Code
}

// Pagination is not a search and must not consume the search budget.
assert.Equal(t, http.StatusNoContent, request("/keys?p=1&size=20"))
assert.Equal(t, http.StatusNoContent, request("/keys?p=2&size=20"))

assert.Equal(t, http.StatusNoContent, request("/keys?keyword=acme"))
assert.Equal(t, http.StatusTooManyRequests, request("/keys?token=sk-acme"))
}
34 changes: 34 additions & 0 deletions model/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ type Token struct {
ResponsibleUsername string `json:"responsible_username,omitempty" gorm:"-"`
ResponsibleDisplayName string `json:"responsible_display_name,omitempty" gorm:"-"`
ResponsibleEmail string `json:"-" gorm:"-"`
OrganizationName string `json:"organization_name,omitempty" gorm:"-"`
UnavailableReasons []string `json:"unavailable_reasons,omitempty" gorm:"-"`
// CacheScopeVersion 只存在于 Redis 哈希里,不入库。作用域字段加入缓存之前写入的旧哈希
// 读出来是零值,会让组织令牌看上去像个人令牌,因此带版本号的哈希才被接受,见 token_cache.go。
Expand Down Expand Up @@ -206,6 +207,39 @@ func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error) {
return tokens, err
}

// SelfTokensQuery is the personal API Keys page's combined source: the caller's
// personal keys plus every organization key they may use. Both sets live in the
// same table, so a single query keeps pagination and counts correct.
func SelfTokensQuery(userId int) *gorm.DB {
personalIds := personalTokenScopeQuery(DB.Model(&Token{}).Where("user_id = ?", userId)).Select("id")
organizationIds := SelfOrganizationTokensQuery(userId).Select("id")
return DB.Model(&Token{}).Where("id IN (?) OR id IN (?)", personalIds, organizationIds)
}

// TokenKeyColumn is the dialect-quoted `key` column, which is a reserved word
// in MySQL. Callers that build a raw keyword search on the column need it.
func TokenKeyColumn() string {
return commonKeyCol
}

// SelfOrganizationTokensQuery returns the organization keys the user may use:
// public keys, keys they are responsible for, and keys they created, across
// the active organizations they belong to. This is the personal API Keys view;
// an organization owner/administrator is treated like any other member here and
// keeps the full organization key list in the organization detail page.
func SelfOrganizationTokensQuery(userId int) *gorm.DB {
memberOrganizationIds := DB.Table("organization_members").
Select("organization_members.organization_id").
Joins("JOIN organizations ON organizations.id = organization_members.organization_id").
Where("organization_members.user_id = ? AND organization_members.status = ? AND organizations.status <> ?",
userId, OrganizationMemberStatusActive, OrganizationStatusDissolved)
return DB.Model(&Token{}).
Where("scope_type = ? AND organization_id IN (?)", TokenScopeOrganization, memberOrganizationIds).
Where(DB.Where("visibility = ?", TokenVisibilityPublic).
Or("responsible_user_id = ?", userId).
Or("creator_user_id = ?", userId))
}

// sanitizeLikePattern 校验并清洗用户输入的 LIKE 搜索模式。
// 规则:
// 1. 转义 ! 和 _(使用 ! 作为 ESCAPE 字符,兼容 MySQL/PostgreSQL/SQLite)
Expand Down
1 change: 1 addition & 0 deletions router/api-router.go
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ func registerApiRoutes(apiRouter *gin.RouterGroup) {
tokenRoute.Use(middleware.UserAuth())
{
tokenRoute.GET("/", controller.GetAllTokens)
tokenRoute.GET("/self/all", middleware.SearchRateLimitWhenQuery(), controller.GetSelfTokens)
tokenRoute.GET("/search", middleware.SearchRateLimit(), controller.SearchTokens)
tokenRoute.GET("/auto-groups", controller.GetTokenAutoGroups)
tokenRoute.GET("/:id", controller.GetToken)
Expand Down
Loading
Loading