Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(dao): allowlist orderby columns on the search, chat, file and dataset lists (#19601)

MarMar Labsa9a227f4c238
diff --git a/docs/references/http_api_reference.md b/docs/references/http_api_reference.md
index c7501ab98c..5f3957b72e 100644
--- a/docs/references/http_api_reference.md
+++ b/docs/references/http_api_reference.md
@@ -913,14 +913,14 @@ Failure:
### List datasets
-**GET** `/api/v1/datasets?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&name={dataset_name}&id={dataset_id}&include_parsing_status={include_parsing_status}`
+**GET** `/api/v1/datasets?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&sort={sort}&name={dataset_name}&id={dataset_id}&include_parsing_status={include_parsing_status}`
Lists datasets.
#### Request
- Method: GET
-- URL: `/api/v1/datasets?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&name={dataset_name}&id={dataset_id}&include_parsing_status={include_parsing_status}`
+- URL: `/api/v1/datasets?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&sort={sort}&name={dataset_name}&id={dataset_id}&include_parsing_status={include_parsing_status}`
- Headers:
- `'Authorization: Bearer <YOUR_API_KEY>'`
@@ -928,7 +928,7 @@ Lists datasets.
```bash
curl --request GET \
- --url http://{address}/api/v1/datasets?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&name={dataset_name}&id={dataset_id} \
+ --url http://{address}/api/v1/datasets?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&sort={sort}&name={dataset_name}&id={dataset_id} \
--header 'Authorization: Bearer <YOUR_API_KEY>'
```
@@ -951,6 +951,8 @@ curl --request GET \
- `update_time`
- `desc`: (*Filter parameter*)
Indicates whether the retrieved datasets should be sorted in descending order. Defaults to `true`.
+- `sort`: (*Filter parameter*)
+ Orders by several fields at once, written as `column:direction` terms separated by commas, such as `name:asc,create_time:desc`. A term with no direction is ascending. `sort` takes precedence over `orderby` and `desc`, which keep working on their own. A term naming a field this list does not sort by is skipped. When `sort` yields no terms at all, `orderby` and `desc` decide the order. When it yields terms whose fields are all skipped, the result is ordered by `create_time` in the direction of the first term, and the older pair is not read.
- `name`: (*Filter parameter*)
The name of the dataset to retrieve.
- `id`: (*Filter parameter*)
@@ -3168,14 +3170,14 @@ Failure:
### List chat assistants
-**GET** `/api/v1/chats?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&keywords={keywords}&owner_ids={owner_id}&name={chat_name}&id={chat_id}`
+**GET** `/api/v1/chats?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&sort={sort}&keywords={keywords}&owner_ids={owner_id}&name={chat_name}&id={chat_id}`
Lists chat assistants.
#### Request
- Method: GET
-- URL: `/api/v1/chats?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&keywords={keywords}&owner_ids={owner_id}&name={chat_name}&id={chat_id}`
+- URL: `/api/v1/chats?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&sort={sort}&keywords={keywords}&owner_ids={owner_id}&name={chat_name}&id={chat_id}`
- Headers:
- `'Authorization: Bearer <YOUR_API_KEY>'`
@@ -3183,7 +3185,7 @@ Lists chat assistants.
```bash
curl --request GET \
- --url http://{address}/api/v1/chats?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&keywords={keywords}&owner_ids={owner_id}&name={chat_name}&id={chat_id} \
+ --url http://{address}/api/v1/chats?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&sort={sort}&keywords={keywords}&owner_ids={owner_id}&name={chat_name}&id={chat_id} \
--header 'Authorization: Bearer <YOUR_API_KEY>'
```
@@ -3199,6 +3201,8 @@ curl --request GET \
- `update_time`
- `desc`: (*Filter parameter*), `boolean`
Indicates whether the retrieved chat assistants should be sorted in descending order. Defaults to `true`.
+- `sort`: (*Filter parameter*), `string`
+ Orders by several fields at once, written as `column:direction` terms separated by commas, such as `name:asc,create_time:desc`. A term with no direction is ascending. `sort` takes precedence over `orderby` and `desc`, which keep working on their own. A term naming a field this list does not sort by is skipped. When `sort` yields no terms at all, `orderby` and `desc` decide the order. When it yields terms whose fields are all skipped, the result is ordered by `create_time` in the direction of the first term, and the older pair is not read.
- `keywords`: (*Filter parameter*), `string`
Case-insensitive fuzzy match against chat assistant names.
- `owner_ids`: (*Filter parameter*), `string` (repeatable)
@@ -3435,14 +3439,14 @@ Failure:
### List chat assistant's sessions
-**GET** `/api/v1/chats/{chat_id}/sessions?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&name={session_name}&id={session_id}&user_id={user_id}`
+**GET** `/api/v1/chats/{chat_id}/sessions?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&sort={sort}&name={session_name}&id={session_id}&user_id={user_id}`
Lists sessions associated with a specified chat assistant.
#### Request
- Method: GET
-- URL: `/api/v1/chats/{chat_id}/sessions?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&name={session_name}&id={session_id}&user_id={user_id}`
+- URL: `/api/v1/chats/{chat_id}/sessions?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&sort={sort}&name={session_name}&id={session_id}&user_id={user_id}`
- Headers:
- `'Authorization: Bearer <YOUR_API_KEY>'`
@@ -3450,7 +3454,7 @@ Lists sessions associated with a specified chat assistant.
```bash
curl --request GET \
- --url http://{address}/api/v1/chats/{chat_id}/sessions?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&name={session_name}&id={session_id}&user_id={user_id} \
+ --url http://{address}/api/v1/chats/{chat_id}/sessions?page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&sort={sort}&name={session_name}&id={session_id}&user_id={user_id} \
--header 'Authorization: Bearer <YOUR_API_KEY>'
```
@@ -3468,6 +3472,8 @@ curl --request GET \
- `update_time`
- `desc`: (*Filter parameter*), `boolean`
Indicates whether the retrieved sessions should be sorted in descending order. Defaults to `true`.
+- `sort`: (*Filter parameter*), `string`
+ Orders by several fields at once, written as `column:direction` terms separated by commas, such as `name:asc,create_time:desc`. A term with no direction is ascending. `sort` takes precedence over `orderby` and `desc`, which keep working on their own. A term naming a field this list does not sort by is skipped. When `sort` yields no terms at all, `orderby` and `desc` decide the order. When it yields terms whose fields are all skipped, the result is ordered by `create_time` in the direction of the first term, and the older pair is not read.
- `name`: (*Filter parameter*) `string`
The name of the chat session to retrieve.
- `id`: (*Filter parameter*), `string`
@@ -5213,6 +5219,8 @@ curl --request GET \
- `update_time`
- `desc`: (*Filter parameter*), `boolean`
Indicates whether the retrieved agents should be sorted in descending order. Defaults to `true`.
+- `sort`: (*Filter parameter*), `string`
+ Orders by several fields at once, written as `column:direction` terms separated by commas, such as `name:asc,create_time:desc`. A term with no direction is ascending. `sort` takes precedence over `orderby` and `desc`, which keep working on their own. A term naming a field this list does not sort by is skipped. When `sort` yields no terms at all, `orderby` and `desc` decide the order. When it yields terms whose fields are all skipped, the result is ordered by `create_time` in the direction of the first term, and the older pair is not read.
- `keywords`: (*Filter parameter*), `string`
Fuzzy-searches agents by title.
- `canvas_category`: (*Filter parameter*), `string`
@@ -6872,7 +6880,7 @@ Failure:
### List files
-**GET** `/api/v1/files?parent_id={parent_id}&keywords={keywords}&page={page}&page_size={page_size}&orderby={orderby}&desc={desc}`
+**GET** `/api/v1/files?parent_id={parent_id}&keywords={keywords}&page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&sort={sort}`
Lists files and folders under a specific folder.
@@ -6883,7 +6891,7 @@ Lists files and folders under a specific folder.
#### Request
- Method: GET
-- URL: `/api/v1/files?parent_id={parent_id}&keywords={keywords}&page={page}&page_size={page_size}&orderby={orderby}&desc={desc}`
+- URL: `/api/v1/files?parent_id={parent_id}&keywords={keywords}&page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&sort={sort}`
- Headers:
- `'Authorization: Bearer <YOUR_API_KEY>'`
@@ -6910,6 +6918,8 @@ curl --request GET \
- `create_time` (default)
- `desc`: (*Filter parameter*), `boolean`
Indicates whether the retrieved files should be sorted in descending order. Defaults to `true`.
+- `sort`: (*Filter parameter*), `string`
+ Orders by several fields at once, written as `column:direction` terms separated by commas, such as `name:asc,create_time:desc`. A term with no direction is ascending. `sort` takes precedence over `orderby` and `desc`, which keep working on their own. A term naming a field this list does not sort by is skipped. When `sort` yields no terms at all, `orderby` and `desc` decide the order. When it yields terms whose fields are all skipped, the result is ordered by `create_time` in the direction of the first term, and the older pair is not read.
#### Response
@@ -7989,14 +7999,14 @@ Failure:
### List search apps
-**GET** `/api/v1/searches?keywords={keywords}&page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&owner_ids={owner_ids}`
+**GET** `/api/v1/searches?keywords={keywords}&page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&sort={sort}&owner_ids={owner_ids}`
Lists search apps for the current user.
#### Request
- Method: GET
-- URL: `/api/v1/searches?keywords={keywords}&page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&owner_ids={owner_ids}`
+- URL: `/api/v1/searches?keywords={keywords}&page={page}&page_size={page_size}&orderby={orderby}&desc={desc}&sort={sort}&owner_ids={owner_ids}`
- Headers:
- `'Authorization: Bearer <YOUR_API_KEY>'`
@@ -8020,6 +8030,8 @@ curl --request GET \
The field to sort by. Defaults to `create_time`.
- `desc`: (*Filter parameter*), `boolean`
Whether to sort in descending order. Defaults to `true`.
+- `sort`: (*Filter parameter*), `string`
+ Orders by several fields at once, written as `column:direction` terms separated by commas, such as `name:asc,create_time:desc`. A term with no direction is ascending. `sort` takes precedence over `orderby` and `desc`, which keep working on their own. A term naming a field this list does not sort by is skipped. When `sort` yields no terms at all, `orderby` and `desc` decide the order. When it yields terms whose fields are all skipped, the result is ordered by `create_time` in the direction of the first term, and the older pair is not read.
- `owner_ids`: (*Filter parameter*), `string` (repeatable)
Filter by owner tenant IDs. Can be specified multiple times: `?owner_ids=id1&owner_ids=id2`.
diff --git a/internal/dao/chat.go b/internal/dao/chat.go
index 14787663e8..d7503ddbe5 100644
--- a/internal/dao/chat.go
+++ b/internal/dao/chat.go
@@ -55,7 +55,7 @@ func (dao *ChatDAO) ListByTenantID(ctx context.Context, db *gorm.DB, tenantID st
}
// ListByTenantIDs list chats by tenant IDs with pagination and filtering
-func (dao *ChatDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, tenantIDs []string, userID string, page, pageSize int, orderby string, desc bool, keywords string) ([]*entity.ChatListItem, int64, error) {
+func (dao *ChatDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, tenantIDs []string, userID string, page, pageSize int, terms []OrderTerm, keywords string) ([]*entity.ChatListItem, int64, error) {
var chats []*entity.ChatListItem
var total int64
@@ -79,12 +79,12 @@ func (dao *ChatDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, tenantIDs
query = query.Where("LOWER(dialog.name) LIKE ?", "%"+strings.ToLower(keywords)+"%")
}
- // Apply ordering
- orderDirection := "ASC"
- if desc {
- orderDirection = "DESC"
- }
- query = query.Order(orderby + " " + orderDirection)
+ // Apply ordering. Route the requested terms through chatOrderClause so a user-supplied
+ // query param can never reach Order() verbatim: the helper validates
+ // against chatOrderableColumns (a closed allowlist) and falls back to
+ // "create_time" on a miss.
+ // codeql[go/sql-injection] False positive: chatOrderClause
+ query = query.Order(chatOrderClause(terms))
// Count total
if err := query.Count(&total).Error; err != nil {
@@ -107,7 +107,7 @@ func (dao *ChatDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, tenantIDs
}
// ListByOwnerIDs list chats by owner IDs with filtering (manual pagination)
-func (dao *ChatDAO) ListByOwnerIDs(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string, orderby string, desc bool, keywords string) ([]*entity.ChatListItem, int64, error) {
+func (dao *ChatDAO) ListByOwnerIDs(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string, terms []OrderTerm, keywords string) ([]*entity.ChatListItem, int64, error) {
var chats []*entity.ChatListItem
// Build query with join to user table
@@ -128,12 +128,12 @@ func (dao *ChatDAO) ListByOwnerIDs(ctx context.Context, db *gorm.DB, ownerIDs []
// Filter by owner IDs (additional filter to ensure tenant_id is in ownerIDs)
query = query.Where("dialog.tenant_id IN ?", ownerIDs)
- // Apply ordering
- orderDirection := "ASC"
- if desc {
- orderDirection = "DESC"
- }
- query = query.Order(orderby + " " + orderDirection)
+ // Apply ordering. Route the requested terms through chatOrderClause so a user-supplied
+ // query param can never reach Order() verbatim: the helper validates
+ // against chatOrderableColumns (a closed allowlist) and falls back to
+ // "create_time" on a miss.
+ // codeql[go/sql-injection] False positive: chatOrderClause
+ query = query.Order(chatOrderClause(terms))
// Get all matching records
if err := query.Scan(&chats).Error; err != nil {
diff --git a/internal/dao/chat_session.go b/internal/dao/chat_session.go
index cfe00425c7..351161f5cc 100644
--- a/internal/dao/chat_session.go
+++ b/internal/dao/chat_session.go
@@ -148,7 +148,7 @@ func (dao *ChatSessionDAO) DeleteByID(ctx context.Context, db *gorm.DB, id strin
}
// ListByChatID lists chat sessions by chat ID
-func (dao *ChatSessionDAO) ListByChatID(ctx context.Context, db *gorm.DB, chatID, sessionID, name, orderby string, desc bool, page, pageSize int, includeHistory ...bool) ([]*entity.ChatSession, error) {
+func (dao *ChatSessionDAO) ListByChatID(ctx context.Context, db *gorm.DB, chatID, sessionID, name string, terms []OrderTerm, page, pageSize int, includeHistory ...bool) ([]*entity.ChatSession, error) {
var chatSessions []*entity.ChatSession
query := db.WithContext(ctx).Session(&gorm.Session{QueryFields: true}).Where("dialog_id = ?", chatID)
if sessionID != "" {
@@ -157,14 +157,7 @@ func (dao *ChatSessionDAO) ListByChatID(ctx context.Context, db *gorm.DB, chatID
if name != "" {
query = query.Where("name = ?", name)
}
- if orderby == "" {
- orderby = "create_time"
- }
- if desc {
- query = query.Order(orderby + " DESC")
- } else {
- query = query.Order(orderby + " ASC")
- }
+ query = query.Order(chatSessionOrderClause(terms))
if pageSize > 0 {
if page < 1 {
page = 1
diff --git a/internal/dao/chat_test.go b/internal/dao/chat_test.go
new file mode 100644
index 0000000000..93fdddc123
--- /dev/null
+++ b/internal/dao/chat_test.go
@@ -0,0 +1,153 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package dao
+
+import (
+ "testing"
+
+ "github.com/glebarez/sqlite"
+ "gorm.io/gorm"
+
+ "ragflow/internal/entity"
+)
+
+func setupChatTestDB(t *testing.T) *gorm.DB {
+ t.Helper()
+
+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
+ TranslateError: true,
+ })
+ if err != nil {
+ t.Fatalf("failed to open sqlite: %v", err)
+ }
+
+ if err := db.AutoMigrate(&entity.User{}, &entity.Chat{}); err != nil {
+ t.Fatalf("failed to migrate: %v", err)
+ }
+
+ return db
+}
+
+// chatOrderExpressions are SQL expressions rather than column names, standing
+// in for an `orderby` query parameter that reaches ChatDAO (issue #14268).
+// The chat table is named dialog.
+var chatOrderExpressions = []string{
+ "(SELECT inner_dialog.name FROM dialog AS inner_dialog WHERE inner_dialog.id = dialog.id)",
+}
+
+// seedOrderableChats creates three chats whose create_time order is the reverse
+// of their name order, so a test can tell which column the ORDER BY clause
+// actually used.
+func seedOrderableChats(t *testing.T, db *gorm.DB) {
+ t.Helper()
+ chats := []entity.Chat{
+ {ID: "c-1", TenantID: "t1", Name: stringPtr("zulu"), BaseModel: entity.BaseModel{CreateTime: int64Ptr(100)}},
+ {ID: "c-2", TenantID: "t1", Name: stringPtr("mike"), BaseModel: entity.BaseModel{CreateTime: int64Ptr(200)}},
+ {ID: "c-3", TenantID: "t1", Name: stringPtr("alpha"), BaseModel: entity.BaseModel{CreateTime: int64Ptr(300)}},
+ }
+ for i := range chats {
+ chats[i].LLMID = "llm-1"
+ chats[i].LLMSetting = entity.JSONMap{}
+ chats[i].PromptType = "simple"
+ chats[i].PromptConfig = entity.JSONMap{}
+ chats[i].DoRefer = "1"
+ chats[i].KBIDs = entity.JSONSlice{}
+ chats[i].Status = stringPtr("1")
+ if err := db.Create(&chats[i]).Error; err != nil {
+ t.Fatalf("failed to create chat %s: %v", chats[i].ID, err)
+ }
+ }
+}
+
+func assertChatOrder(t *testing.T, rows []*entity.ChatListItem, want []string, orderby string) {
+ t.Helper()
+ if len(rows) != len(want) {
+ t.Fatalf("orderby %q returned %d rows, want %d", orderby, len(rows), len(want))
+ }
+ for i, row := range rows {
+ if row.ID != want[i] {
+ got := make([]string, 0, len(rows))
+ for _, r := range rows {
+ got = append(got, r.ID)
+ }
+ t.Fatalf("orderby %q produced order %v, want %v: the expression reached the ORDER BY clause", orderby, got, want)
+ }
+ }
+}
+
+// TestChatDAOListByTenantIDsOrderByExpressionFallsBack checks that an `orderby`
+// value that is an expression rather than an allowed column name leaves the
+// rows in the default create_time order.
+func TestChatDAOListByTenantIDsOrderByExpressionFallsBack(t *testing.T) {
+ db := setupChatTestDB(t)
+ pushDB(t, db)
+ seedOrderableChats(t, db)
+ ctx := t.Context()
+ d := NewChatDAO()
+
+ for _, orderby := range chatOrderExpressions {
+ t.Run(orderby, func(t *testing.T) {
+ rows, _, err := d.ListByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: orderby}}, "")
+ if err != nil {
+ t.Fatalf("ListByTenantIDs with orderby %q: %v", orderby, err)
+ }
+ assertChatOrder(t, rows, []string{"c-1", "c-2", "c-3"}, orderby)
+ })
+ }
+}
+
+// TestChatDAOListByOwnerIDsOrderByExpressionFallsBack is the ListByOwnerIDs
+// counterpart, the branch the endpoint takes when owner_ids is supplied.
+func TestChatDAOListByOwnerIDsOrderByExpressionFallsBack(t *testing.T) {
+ db := setupChatTestDB(t)
+ pushDB(t, db)
+ seedOrderableChats(t, db)
+ ctx := t.Context()
+ d := NewChatDAO()
+
+ for _, orderby := range chatOrderExpressions {
+ t.Run(orderby, func(t *testing.T) {
+ rows, _, err := d.ListByOwnerIDs(ctx, db, []string{"t1"}, "t1", []OrderTerm{{Column: orderby}}, "")
+ if err != nil {
+ t.Fatalf("ListByOwnerIDs with orderby %q: %v", orderby, err)
+ }
+ assertChatOrder(t, rows, []string{"c-1", "c-2", "c-3"}, orderby)
+ })
+ }
+}
+
+// TestChatDAOListOrderByAllowedColumn checks that the allowlist still honors a
+// real column in both directions.
+func TestChatDAOListOrderByAllowedColumn(t *testing.T) {
+ db := setupChatTestDB(t)
+ pushDB(t, db)
+ seedOrderableChats(t, db)
+ ctx := t.Context()
+ d := NewChatDAO()
+
+ rows, _, err := d.ListByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: "name"}}, "")
+ if err != nil {
+ t.Fatalf("ListByTenantIDs ascending by name: %v", err)
+ }
+ assertChatOrder(t, rows, []string{"c-3", "c-2", "c-1"}, "name")
+
+ rows, _, err = d.ListByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: "name", Desc: true}}, "")
+ if err != nil {
+ t.Fatalf("ListByTenantIDs descending by name: %v", err)
+ }
+ assertChatOrder(t, rows, []string{"c-1", "c-2", "c-3"}, "name")
+}
diff --git a/internal/dao/compilation_template_group.go b/internal/dao/compilation_template_group.go
index 2075a292b6..e1fbd79403 100644
--- a/internal/dao/compilation_template_group.go
+++ b/internal/dao/compilation_template_group.go
@@ -36,7 +36,7 @@ func NewCompilationTemplateGroupDAO() *CompilationTemplateGroupDAO {
// ListSaved returns the tenant's valid groups with optional keyword/scope
// filtering and ordering, mirroring Python list_saved(). Built-in groups
// (empty tenant) are included so every tenant sees the catalogue.
-func (dao *CompilationTemplateGroupDAO) ListSaved(ctx context.Context, db *gorm.DB, tenantID, keywords, scope, orderby string, desc bool) ([]*entity.CompilationTemplateGroup, error) {
+func (dao *CompilationTemplateGroupDAO) ListSaved(ctx context.Context, db *gorm.DB, tenantID, keywords, scope string, terms []OrderTerm) ([]*entity.CompilationTemplateGroup, error) {
q := db.WithContext(ctx).
Where("(tenant_id = ? OR tenant_id = '') AND status = ?", tenantID, string(entity.StatusValid))
if keywords != "" {
@@ -45,15 +45,8 @@ func (dao *CompilationTemplateGroupDAO) ListSaved(ctx context.Context, db *gorm.
if scope != "" {
q = q.Where("scope = ?", scope)
}
- if orderby != "name" && orderby != "scope" && orderby != "create_time" && orderby != "update_time" {
- orderby = "create_time"
- }
- dir := "asc"
- if desc {
- dir = "desc"
- }
var groups []*entity.CompilationTemplateGroup
- if err := q.Order(orderby + " " + dir).Find(&groups).Error; err != nil {
+ if err := q.Order(compilationTemplateGroupOrderClause(terms)).Find(&groups).Error; err != nil {
return nil, err
}
return groups, nil
@@ -63,7 +56,7 @@ func (dao *CompilationTemplateGroupDAO) ListSaved(ctx context.Context, db *gorm.
// with empty tenant_id are excluded), mirroring the Python list_saved() query
// (cls.model.tenant_id == tenant_id). The merged /agents list uses this so
// built-in catalogue groups do not leak into a tenant's canvas list.
-func (dao *CompilationTemplateGroupDAO) ListOwnedSaved(ctx context.Context, db *gorm.DB, tenantID, keywords, scope, orderby string, desc bool) ([]*entity.CompilationTemplateGroup, error) {
+func (dao *CompilationTemplateGroupDAO) ListOwnedSaved(ctx context.Context, db *gorm.DB, tenantID, keywords, scope string, terms []OrderTerm) ([]*entity.CompilationTemplateGroup, error) {
q := db.WithContext(ctx).
Where("tenant_id = ? AND status = ?", tenantID, string(entity.StatusValid))
if keywords != "" {
@@ -72,15 +65,8 @@ func (dao *CompilationTemplateGroupDAO) ListOwnedSaved(ctx context.Context, db *
if scope != "" {
q = q.Where("scope = ?", scope)
}
- if orderby != "name" && orderby != "scope" && orderby != "create_time" && orderby != "update_time" {
- orderby = "create_time"
- }
- dir := "asc"
- if desc {
- dir = "desc"
- }
var groups []*entity.CompilationTemplateGroup
- if err := q.Order(orderby + " " + dir).Find(&groups).Error; err != nil {
+ if err := q.Order(compilationTemplateGroupOrderClause(terms)).Find(&groups).Error; err != nil {
return nil, err
}
return groups, nil
diff --git a/internal/dao/file.go b/internal/dao/file.go
index 131644d887..ddbb75b1e7 100644
--- a/internal/dao/file.go
+++ b/internal/dao/file.go
@@ -67,7 +67,7 @@ func (dao *FileDAO) GetByIDAndTenant(ctx context.Context, db *gorm.DB, id, tenan
// When keywords is empty, only direct children of pfID are listed; when
// keywords is non-empty, the search covers the whole subtree under pfID so
// files and folders nested in sub-folders can be found too.
-func (dao *FileDAO) GetByPfID(ctx context.Context, db *gorm.DB, tenantID, pfID string, page, pageSize int, orderBy string, desc bool, keywords string, excludeSkills bool) ([]*entity.File, int64, error) {
+func (dao *FileDAO) GetByPfID(ctx context.Context, db *gorm.DB, tenantID, pfID string, page, pageSize int, terms []OrderTerm, keywords string, excludeSkills bool) ([]*entity.File, int64, error) {
var files []*entity.File
var total int64
@@ -93,12 +93,12 @@ func (dao *FileDAO) GetByPfID(ctx context.Context, db *gorm.DB, tenantID, pfID s
return nil, 0, err
}
- // Apply ordering
- orderDirection := "ASC"
- if desc {
- orderDirection = "DESC"
- }
- query = query.Order(orderBy + " " + orderDirection)
+ // Apply ordering. Route orderBy through fileOrderClause so a user-supplied
+ // query param can never reach Order() verbatim: the helper validates
+ // against fileOrderableColumns (a closed allowlist) and falls back to
+ // "create_time" on a miss.
+ // codeql[go/sql-injection] False positive: fileOrderClause
+ query = query.Order(fileOrderClause(terms))
// Apply pagination
if page > 0 && pageSize > 0 {
diff --git a/internal/dao/file_test.go b/internal/dao/file_test.go
index 1cd68dbacc..9bf67ffca7 100644
--- a/internal/dao/file_test.go
+++ b/internal/dao/file_test.go
@@ -76,7 +76,7 @@ func TestFileDAO_GetByPfID_KeywordsSearchesSubtree(t *testing.T) {
d := NewFileDAO()
ctx := t.Context()
- files, total, err := d.GetByPfID(ctx, db, "t1", "root", 1, 15, "create_time", true, "report", false)
+ files, total, err := d.GetByPfID(ctx, db, "t1", "root", 1, 15, []OrderTerm{{Column: "create_time", Desc: true}}, "report", false)
if err != nil {
t.Fatalf("GetByPfID failed: %v", err)
}
@@ -85,7 +85,7 @@ func TestFileDAO_GetByPfID_KeywordsSearchesSubtree(t *testing.T) {
}
// Nested file two levels down must be found from the root folder.
- files, total, err = d.GetByPfID(ctx, db, "t1", "root", 1, 15, "create_time", true, "notes", false)
+ files, total, err = d.GetByPfID(ctx, db, "t1", "root", 1, 15, []OrderTerm{{Column: "create_time", Desc: true}}, "notes", false)
if err != nil {
t.Fatalf("GetByPfID failed: %v", err)
}
@@ -94,7 +94,7 @@ func TestFileDAO_GetByPfID_KeywordsSearchesSubtree(t *testing.T) {
}
// Folders themselves are searchable by name.
- files, total, err = d.GetByPfID(ctx, db, "t1", "root", 1, 15, "create_time", true, "sub", false)
+ files, total, err = d.GetByPfID(ctx, db, "t1", "root", 1, 15, []OrderTerm{{Column: "create_time", Desc: true}}, "sub", false)
if err != nil {
t.Fatalf("GetByPfID failed: %v", err)
}
@@ -110,7 +110,7 @@ func TestFileDAO_GetByPfID_KeywordsScopedToSubtree(t *testing.T) {
ctx := t.Context()
// Searching inside dirA must not match files outside that subtree.
- files, total, err := d.GetByPfID(ctx, db, "t1", "dirA", 1, 15, "create_time", true, "report", false)
+ files, total, err := d.GetByPfID(ctx, db, "t1", "dirA", 1, 15, []OrderTerm{{Column: "create_time", Desc: true}}, "report", false)
if err != nil {
t.Fatalf("GetByPfID failed: %v", err)
}
@@ -119,7 +119,7 @@ func TestFileDAO_GetByPfID_KeywordsScopedToSubtree(t *testing.T) {
}
// Tenant isolation still applies.
- files, total, err = d.GetByPfID(ctx, db, "t2", "root", 1, 15, "create_time", true, "report", false)
+ files, total, err = d.GetByPfID(ctx, db, "t2", "root", 1, 15, []OrderTerm{{Column: "create_time", Desc: true}}, "report", false)
if err != nil {
t.Fatalf("GetByPfID failed: %v", err)
}
@@ -134,7 +134,7 @@ func TestFileDAO_GetByPfID_NoKeywordsListsDirectChildren(t *testing.T) {
d := NewFileDAO()
ctx := t.Context()
- files, total, err := d.GetByPfID(ctx, db, "t1", "root", 1, 15, "create_time", true, "", false)
+ files, total, err := d.GetByPfID(ctx, db, "t1", "root", 1, 15, []OrderTerm{{Column: "create_time", Desc: true}}, "", false)
if err != nil {
t.Fatalf("GetByPfID failed: %v", err)
}
@@ -148,6 +148,143 @@ func TestFileDAO_GetByPfID_NoKeywordsListsDirectChildren(t *testing.T) {
}
}
+// fileOrderExpressions are SQL expressions rather than column names. They stand
+// in for the `orderby` query parameter of GET /api/v1/files, which reaches
+// FileDAO straight from the request (issue #14268).
+var fileOrderExpressions = []string{
+ "(SELECT inner_file.name FROM file AS inner_file WHERE inner_file.id = file.id)",
+}
+
+// seedOrderableFiles creates a root folder and three children whose create_time
+// order is the reverse of their name order, so a test can tell which column the
+// ORDER BY clause actually used.
+func seedOrderableFiles(t *testing.T, db *gorm.DB) {
+ t.Helper()
+ testFile(t, db, "root", "root", "t1", "/", "folder")
+ files := []entity.File{
+ {ID: "f-1", ParentID: "root", TenantID: "t1", CreatedBy: "t1", Name: "zulu.txt", Type: "doc", BaseModel: entity.BaseModel{CreateTime: int64Ptr(100)}},
+ {ID: "f-2", ParentID: "root", TenantID: "t1", CreatedBy: "t1", Name: "mike.txt", Type: "doc", BaseModel: entity.BaseModel{CreateTime: int64Ptr(200)}},
+ {ID: "f-3", ParentID: "root", TenantID: "t1", CreatedBy: "t1", Name: "alpha.txt", Type: "doc", BaseModel: entity.BaseModel{CreateTime: int64Ptr(300)}},
+ }
+ for i := range files {
+ if err := db.Create(&files[i]).Error; err != nil {
+ t.Fatalf("failed to create file %s: %v", files[i].ID, err)
+ }
+ }
+}
+
+func assertFileOrder(t *testing.T, rows []*entity.File, want []string, orderBy string) {
+ t.Helper()
+ if len(rows) != len(want) {
+ t.Fatalf("orderby %q returned %d rows, want %d", orderBy, len(rows), len(want))
+ }
+ for i, row := range rows {
+ if row.ID != want[i] {
+ got := make([]string, 0, len(rows))
+ for _, r := range rows {
+ got = append(got, r.ID)
+ }
+ t.Fatalf("orderby %q produced order %v, want %v: the expression reached the ORDER BY clause", orderBy, got, want)
+ }
+ }
+}
+
+// TestFileDAO_GetByPfID_OrderByExpressionFallsBack checks that an `orderby`
+// value that is an expression rather than an allowed column name leaves the
+// rows in the default create_time order.
+func TestFileDAO_GetByPfID_OrderByExpressionFallsBack(t *testing.T) {
+ db := setupFileTestDB(t)
+ seedOrderableFiles(t, db)
+ ctx := t.Context()
+ d := NewFileDAO()
+
+ for _, orderBy := range fileOrderExpressions {
+ t.Run(orderBy, func(t *testing.T) {
+ rows, _, err := d.GetByPfID(ctx, db, "t1", "root", 1, 15, []OrderTerm{{Column: orderBy}}, "", false)
+ if err != nil {
+ t.Fatalf("GetByPfID with orderby %q: %v", orderBy, err)
+ }
+ assertFileOrder(t, rows, []string{"f-1", "f-2", "f-3"}, orderBy)
+ })
+ }
+}
+
+// TestFileDAO_GetByPfID_OrderByAllowedColumn checks that the allowlist still
+// honors a real column in both directions. The skill folder listing already
+// calls GetByPfID with "name".
+func TestFileDAO_GetByPfID_OrderByAllowedColumn(t *testing.T) {
+ db := setupFileTestDB(t)
+ seedOrderableFiles(t, db)
+ ctx := t.Context()
+ d := NewFileDAO()
+
+ rows, _, err := d.GetByPfID(ctx, db, "t1", "root", 1, 15, []OrderTerm{{Column: "name"}}, "", false)
+ if err != nil {
+ t.Fatalf("GetByPfID ascending by name: %v", err)
+ }
+ assertFileOrder(t, rows, []string{"f-3", "f-2", "f-1"}, "name")
+
+ rows, _, err = d.GetByPfID(ctx, db, "t1", "root", 1, 15, []OrderTerm{{Column: "name", Desc: true}}, "", false)
+ if err != nil {
+ t.Fatalf("GetByPfID descending by name: %v", err)
+ }
+ assertFileOrder(t, rows, []string{"f-1", "f-2", "f-3"}, "name")
+}
+
+// TestFileDAO_GetByPfID_OrderBySeveralTerms checks that a term list reaches the
+// ORDER BY clause in full, so a second term decides the rows the first one ties,
+// and that a term naming a column the file list does not expose costs only itself.
+func TestFileDAO_GetByPfID_OrderBySeveralTerms(t *testing.T) {
+ db := setupFileTestDB(t)
+ testFile(t, db, "root", "root", "t1", "/", "folder")
+ files := []entity.File{
+ {ID: "g-1", ParentID: "root", TenantID: "t1", CreatedBy: "t1", Name: "bravo.txt", Type: "doc", BaseModel: entity.BaseModel{CreateTime: int64Ptr(100)}},
+ {ID: "g-2", ParentID: "root", TenantID: "t1", CreatedBy: "t1", Name: "alpha.txt", Type: "doc", BaseModel: entity.BaseModel{CreateTime: int64Ptr(200)}},
+ {ID: "g-3", ParentID: "root", TenantID: "t1", CreatedBy: "t1", Name: "delta.txt", Type: "img", BaseModel: entity.BaseModel{CreateTime: int64Ptr(300)}},
+ {ID: "g-4", ParentID: "root", TenantID: "t1", CreatedBy: "t1", Name: "charlie.txt", Type: "img", BaseModel: entity.BaseModel{CreateTime: int64Ptr(400)}},
+ }
+ for i := range files {
+ if err := db.Create(&files[i]).Error; err != nil {
+ t.Fatalf("failed to create file %s: %v", files[i].ID, err)
+ }
+ }
+ ctx := t.Context()
+ d := NewFileDAO()
+
+ cases := []struct {
+ label string
+ terms []OrderTerm
+ want []string
+ }{
+ {
+ label: "type:asc,name:asc",
+ terms: []OrderTerm{{Column: "type"}, {Column: "name"}},
+ want: []string{"g-2", "g-1", "g-4", "g-3"},
+ },
+ {
+ // Same first term, so only the second one can account for the difference.
+ label: "type:asc,name:desc",
+ terms: []OrderTerm{{Column: "type"}, {Column: "name", Desc: true}},
+ want: []string{"g-1", "g-2", "g-3", "g-4"},
+ },
+ {
+ label: "password:asc,name:asc",
+ terms: []OrderTerm{{Column: "password"}, {Column: "name"}},
+ want: []string{"g-2", "g-1", "g-4", "g-3"},
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.label, func(t *testing.T) {
+ rows, _, err := d.GetByPfID(ctx, db, "t1", "root", 1, 15, tc.terms, "", false)
+ if err != nil {
+ t.Fatalf("GetByPfID %s: %v", tc.label, err)
+ }
+ assertFileOrder(t, rows, tc.want, tc.label)
+ })
+ }
+}
+
func TestFileDAO_GetByIDAndTenant(t *testing.T) {
db := setupFileTestDB(t)
seedFileTree(t, db) // f-t2 belongs to tenant t2
diff --git a/internal/dao/kb.go b/internal/dao/kb.go
index 314cdc4399..14961d9fce 100644
--- a/internal/dao/kb.go
+++ b/internal/dao/kb.go
@@ -218,7 +218,7 @@ func (dao *KnowledgebaseDAO) Count(ctx context.Context, db *gorm.DB, filters map
// GetByTenantIDs retrieves knowledge bases by tenant IDs with pagination
// This matches the Python get_by_tenant_ids method
-func (dao *KnowledgebaseDAO) GetByTenantIDs(ctx context.Context, db *gorm.DB, tenantIDs []string, userID string, pageNumber, itemsPerPage int, orderby string, desc bool, keywords, parserID, id, name string, ids []string) ([]*entity.KnowledgebaseListItem, int64, error) {
+func (dao *KnowledgebaseDAO) GetByTenantIDs(ctx context.Context, db *gorm.DB, tenantIDs []string, userID string, pageNumber, itemsPerPage int, terms []OrderTerm, keywords, parserID, id, name string, ids []string) ([]*entity.KnowledgebaseListItem, int64, error) {
var kbs []*entity.KnowledgebaseListItem
var total int64
@@ -254,11 +254,12 @@ func (dao *KnowledgebaseDAO) GetByTenantIDs(ctx context.Context, db *gorm.DB, te
query = query.Where("knowledgebase.parser_id = ?", parserID)
}
- if desc {
- query = query.Order("knowledgebase." + orderby + " DESC")
- } else {
- query = query.Order("knowledgebase." + orderby + " ASC")
- }
+ // Route the requested terms through knowledgebaseQualifiedOrderClause so a
+ // user-supplied query param can never reach Order() verbatim: the helper
+ // validates against knowledgebaseOrderableColumns (a closed allowlist) and
+ // falls back to "create_time" on a miss.
+ // codeql[go/sql-injection] False positive: knowledgebaseQualifiedOrderClause
+ query = query.Order(knowledgebaseQualifiedOrderClause(terms))
if err := query.Count(&total).Error; err != nil {
return nil, 0, err
@@ -566,7 +567,7 @@ func (dao *KnowledgebaseDAO) GetKBByNameAndUserID(ctx context.Context, db *gorm.
// GetList retrieves knowledge bases with filtering by ID and name
// This matches the Python get_list method
-func (dao *KnowledgebaseDAO) GetList(ctx context.Context, db *gorm.DB, tenantIDs []string, userID string, pageNumber, itemsPerPage int, orderby string, desc bool, id, name string) ([]*entity.Knowledgebase, int64, error) {
+func (dao *KnowledgebaseDAO) GetList(ctx context.Context, db *gorm.DB, tenantIDs []string, userID string, pageNumber, itemsPerPage int, terms []OrderTerm, id, name string) ([]*entity.Knowledgebase, int64, error) {
var kbs []*entity.Knowledgebase
var total int64
@@ -581,11 +582,12 @@ func (dao *KnowledgebaseDAO) GetList(ctx context.Context, db *gorm.DB, tenantIDs
query = query.Where("name = ?", name)
}
- if desc {
- query = query.Order(orderby + " DESC")
- } else {
- query = query.Order(orderby + " ASC")
- }
+ // Route the requested terms through knowledgebaseOrderClause so a user-supplied query
+ // param can never reach Order() verbatim: the helper validates against
+ // knowledgebaseOrderableColumns (a closed allowlist) and falls back to
+ // "create_time" on a miss.
+ // codeql[go/sql-injection] False positive: knowledgebaseOrderClause
+ query = query.Order(knowledgebaseOrderClause(terms))
if err := query.Count(&total).Error; err != nil {
return nil, 0, err
diff --git a/internal/dao/kb_test.go b/internal/dao/kb_test.go
index b2e0433dcf..f997b808e7 100644
--- a/internal/dao/kb_test.go
+++ b/internal/dao/kb_test.go
@@ -175,3 +175,131 @@ func TestKnowledgebaseDAO_DecreaseDocumentNum_ZeroDecrement(t *testing.T) {
t.Fatalf("chunk_num should be unchanged: expected 15, got %d", kb.ChunkNum)
}
}
+
+// knowledgebaseQualifiedOrderExpressions are clause fragments rather than
+// column names. GetByTenantIDs prefixes the value with "knowledgebase.", so
+// these stand in for the `orderby` query parameter that reaches it from the
+// dataset list request (issue #14268).
+var knowledgebaseQualifiedOrderExpressions = []string{
+ "name, (SELECT inner_kb.id FROM knowledgebase AS inner_kb WHERE inner_kb.id = knowledgebase.id)",
+}
+
+// knowledgebaseOrderExpressions are the unprefixed counterparts used by
+// GetList.
+var knowledgebaseOrderExpressions = []string{
+ "(SELECT inner_kb.name FROM knowledgebase AS inner_kb WHERE inner_kb.id = knowledgebase.id)",
+}
+
+// seedOrderableKnowledgebases creates three datasets whose create_time order is
+// the reverse of their name order, so a test can tell which column the ORDER BY
+// clause actually used.
+func seedOrderableKnowledgebases(t *testing.T, db *gorm.DB) {
+ t.Helper()
+ kbs := []entity.Knowledgebase{
+ {ID: "kb-1", TenantID: "t1", Name: "zulu", EmbdID: "embd-1", CreatedBy: "t1", Permission: "me", Status: stringPtr(string(entity.StatusValid)), BaseModel: entity.BaseModel{CreateTime: int64Ptr(100)}},
+ {ID: "kb-2", TenantID: "t1", Name: "mike", EmbdID: "embd-1", CreatedBy: "t1", Permission: "me", Status: stringPtr(string(entity.StatusValid)), BaseModel: entity.BaseModel{CreateTime: int64Ptr(200)}},
+ {ID: "kb-3", TenantID: "t1", Name: "alpha", EmbdID: "embd-1", CreatedBy: "t1", Permission: "me", Status: stringPtr(string(entity.StatusValid)), BaseModel: entity.BaseModel{CreateTime: int64Ptr(300)}},
+ }
+ for i := range kbs {
+ if err := db.Create(&kbs[i]).Error; err != nil {
+ t.Fatalf("failed to create knowledgebase %s: %v", kbs[i].ID, err)
+ }
+ }
+}
+
+func assertKnowledgebaseIDOrder(t *testing.T, got, want []string, orderby string) {
+ t.Helper()
+ if len(got) != len(want) {
+ t.Fatalf("orderby %q returned %d rows, want %d", orderby, len(got), len(want))
+ }
+ for i := range got {
+ if got[i] != want[i] {
+ t.Fatalf("orderby %q produced order %v, want %v: the expression reached the ORDER BY clause", orderby, got, want)
+ }
+ }
+}
+
+// TestKnowledgebaseDAOGetByTenantIDsOrderByExpressionFallsBack checks that an
+// `orderby` value that is not an allowed column name leaves the rows in the
+// default create_time order.
+func TestKnowledgebaseDAOGetByTenantIDsOrderByExpressionFallsBack(t *testing.T) {
+ db := setupKBTestDB(t)
+ if err := db.AutoMigrate(&entity.User{}); err != nil {
+ t.Fatalf("failed to migrate user: %v", err)
+ }
+ pushDB(t, db)
+ seedOrderableKnowledgebases(t, db)
+ ctx := t.Context()
+ d := NewKnowledgebaseDAO()
+
+ for _, orderby := range knowledgebaseQualifiedOrderExpressions {
+ t.Run(orderby, func(t *testing.T) {
+ rows, _, err := d.GetByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: orderby}}, "", "", "", "", nil)
+ if err != nil {
+ t.Fatalf("GetByTenantIDs with orderby %q: %v", orderby, err)
+ }
+ ids := make([]string, 0, len(rows))
+ for _, row := range rows {
+ ids = append(ids, row.ID)
+ }
+ assertKnowledgebaseIDOrder(t, ids, []string{"kb-1", "kb-2", "kb-3"}, orderby)
+ })
+ }
+}
+
+// TestKnowledgebaseDAOGetListOrderByExpressionFallsBack is the GetList
+// counterpart, which builds the clause without the table prefix.
+func TestKnowledgebaseDAOGetListOrderByExpressionFallsBack(t *testing.T) {
+ db := setupKBTestDB(t)
+ pushDB(t, db)
+ seedOrderableKnowledgebases(t, db)
+ ctx := t.Context()
+ d := NewKnowledgebaseDAO()
+
+ for _, orderby := range knowledgebaseOrderExpressions {
+ t.Run(orderby, func(t *testing.T) {
+ rows, _, err := d.GetList(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: orderby}}, "", "")
+ if err != nil {
+ t.Fatalf("GetList with orderby %q: %v", orderby, err)
+ }
+ ids := make([]string, 0, len(rows))
+ for _, row := range rows {
+ ids = append(ids, row.ID)
+ }
+ assertKnowledgebaseIDOrder(t, ids, []string{"kb-1", "kb-2", "kb-3"}, orderby)
+ })
+ }
+}
+
+// TestKnowledgebaseDAOOrderByAllowedColumn checks that the allowlist still
+// honors a real column in both directions on both list paths.
+func TestKnowledgebaseDAOOrderByAllowedColumn(t *testing.T) {
+ db := setupKBTestDB(t)
+ if err := db.AutoMigrate(&entity.User{}); err != nil {
+ t.Fatalf("failed to migrate user: %v", err)
+ }
+ pushDB(t, db)
+ seedOrderableKnowledgebases(t, db)
+ ctx := t.Context()
+ d := NewKnowledgebaseDAO()
+
+ rows, _, err := d.GetByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: "name"}}, "", "", "", "", nil)
+ if err != nil {
+ t.Fatalf("GetByTenantIDs ascending by name: %v", err)
+ }
+ ids := make([]string, 0, len(rows))
+ for _, row := range rows {
+ ids = append(ids, row.ID)
+ }
+ assertKnowledgebaseIDOrder(t, ids, []string{"kb-3", "kb-2", "kb-1"}, "name")
+
+ listed, _, err := d.GetList(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: "name", Desc: true}}, "", "")
+ if err != nil {
+ t.Fatalf("GetList descending by name: %v", err)
+ }
+ listedIDs := make([]string, 0, len(listed))
+ for _, row := range listed {
+ listedIDs = append(listedIDs, row.ID)
+ }
+ assertKnowledgebaseIDOrder(t, listedIDs, []string{"kb-1", "kb-2", "kb-3"}, "name")
+}
diff --git a/internal/dao/order_by.go b/internal/dao/order_by.go
new file mode 100644
index 0000000000..d1f7209ff9
--- /dev/null
+++ b/internal/dao/order_by.go
@@ -0,0 +1,262 @@
+package dao
+
+import "strings"
+
+// An ORDER BY body is built by string concatenation, so a column name that
+// reached it from a query parameter would be an injection point. Every entity
+// therefore names the columns its list rows expose, and only those names can be
+// rendered. The allowlists and the rendering live here so the rule has one
+// owner rather than a copy in each data access file.
+
+// OrderTerm is one column and direction in an ORDER BY list.
+type OrderTerm struct {
+ Column string
+ Desc bool
+}
+
+// ParseOrderTerms reads the `sort` query value, a comma separated list of
+// `column:direction` terms such as `name:asc,create_time:desc`. A term that
+// omits the direction is ascending. A term with an empty column or a direction
+// that is neither `asc` nor `desc` costs its own term rather than the list, and
+// an empty result leaves the caller on the older `orderby` and `desc` pair.
+// Whether a column is orderable at all stays the entity allowlist's decision.
+func ParseOrderTerms(sort string) []OrderTerm {
+ terms := make([]OrderTerm, 0, strings.Count(sort, ",")+1)
+ for _, part := range strings.Split(sort, ",") {
+ column, direction, hasDirection := strings.Cut(part, ":")
+ column = strings.TrimSpace(column)
+ if column == "" {
+ continue
+ }
+ term := OrderTerm{Column: column}
+ if hasDirection {
+ switch strings.ToLower(strings.TrimSpace(direction)) {
+ case "asc":
+ case "desc":
+ term.Desc = true
+ default:
+ continue
+ }
+ }
+ terms = append(terms, term)
+ }
+ if len(terms) == 0 {
+ return nil
+ }
+ return terms
+}
+
+func renderTerm(table string, term OrderTerm) string {
+ column := term.Column
+ if table != "" {
+ column = table + "." + column
+ }
+ if term.Desc {
+ return column + " DESC"
+ }
+ return column + " ASC"
+}
+
+// orderClause renders terms as an ORDER BY body, keeping only the terms whose
+// column the entity allows. When no term survives, the fallback column is
+// rendered in the direction the first requested term asked for, which is what
+// the single-value orderby parameter has always done with a name it does not
+// recognise.
+func orderClause(allowed map[string]struct{}, terms []OrderTerm, fallback string) string {
+ return qualifiedOrderClause("", allowed, terms, fallback)
+}
+
+// qualifiedOrderClause is orderClause with a table qualifier on every column,
+// for queries whose joins would otherwise leave a bare column name ambiguous.
+func qualifiedOrderClause(table string, allowed map[string]struct{}, terms []OrderTerm, fallback string) string {
+ kept := make([]string, 0, len(terms))
+ for _, term := range terms {
+ if _, ok := allowed[term.Column]; ok {
+ kept = append(kept, renderTerm(table, term))
+ }
+ }
+ if len(kept) == 0 {
+ desc := len(terms) > 0 && terms[0].Desc
+ return renderTerm(table, OrderTerm{Column: fallback, Desc: desc})
+ }
+ return strings.Join(kept, ", ")
+}
+
+// defaultOrderColumn is the column every entity falls back to.
+const defaultOrderColumn = "create_time"
+
+// chatOrderableColumns allows the scalar dialog columns the list rows expose plus the base timestamp columns.
+var chatOrderableColumns = map[string]struct{}{
+ "id": {},
+ "tenant_id": {},
+ "name": {},
+ "language": {},
+ "llm_id": {},
+ "tenant_llm_id": {},
+ "prompt_type": {},
+ "similarity_threshold": {},
+ "vector_similarity_weight": {},
+ "top_n": {},
+ "rerank_candidates_count": {},
+ "top_k": {},
+ "do_refer": {},
+ "rerank_id": {},
+ "tenant_rerank_id": {},
+ "status": {},
+ "create_time": {},
+ "create_date": {},
+ "update_time": {},
+ "update_date": {},
+}
+
+// chatSessionOrderableColumns allows the scalar conversation columns the list rows expose plus the base timestamp columns.
+var chatSessionOrderableColumns = map[string]struct{}{
+ "id": {},
+ "dialog_id": {},
+ "name": {},
+ "user_id": {},
+ "create_time": {},
+ "create_date": {},
+ "update_time": {},
+ "update_date": {},
+}
+
+// compilationTemplateGroupOrderableColumns keeps the four columns this list has
+// always accepted rather than every scalar column of the row, so moving the rule
+// here does not widen what callers can order by.
+var compilationTemplateGroupOrderableColumns = map[string]struct{}{
+ "name": {},
+ "scope": {},
+ "create_time": {},
+ "update_time": {},
+}
+
+// fileOrderableColumns allows the scalar file columns the list rows expose plus the base timestamp columns.
+var fileOrderableColumns = map[string]struct{}{
+ "id": {},
+ "parent_id": {},
+ "tenant_id": {},
+ "created_by": {},
+ "name": {},
+ "location": {},
+ "size": {},
+ "type": {},
+ "source_type": {},
+ "create_time": {},
+ "create_date": {},
+ "update_time": {},
+ "update_date": {},
+}
+
+// knowledgebaseOrderableColumns allows the scalar knowledge base columns the list rows expose plus the base timestamp columns.
+var knowledgebaseOrderableColumns = map[string]struct{}{
+ "id": {},
+ "tenant_id": {},
+ "name": {},
+ "language": {},
+ "permission": {},
+ "doc_num": {},
+ "token_num": {},
+ "chunk_num": {},
+ "parser_id": {},
+ "pagerank": {},
+ "embd_id": {},
+ "tenant_embd_id": {},
+ "create_time": {},
+ "create_date": {},
+ "update_time": {},
+ "update_date": {},
+}
+
+// pipelineLogOrderableColumns allows the scalar pipeline operation log columns the list rows expose plus the base timestamp columns.
+var pipelineLogOrderableColumns = map[string]struct{}{
+ "id": {},
+ "document_id": {},
+ "tenant_id": {},
+ "kb_id": {},
+ "pipeline_id": {},
+ "pipeline_title": {},
+ "parser_id": {},
+ "document_name": {},
+ "document_suffix": {},
+ "document_type": {},
+ "source_from": {},
+ "progress": {},
+ "process_begin_at": {},
+ "process_duration": {},
+ "task_type": {},
+ "operation_status": {},
+ "status": {},
+ "create_time": {},
+ "create_date": {},
+ "update_time": {},
+ "update_date": {},
+}
+
+// searchOrderableColumns allows the scalar search columns the list rows expose plus the base timestamp columns.
+var searchOrderableColumns = map[string]struct{}{
+ "id": {},
+ "tenant_id": {},
+ "name": {},
+ "created_by": {},
+ "status": {},
+ "create_time": {},
+ "create_date": {},
+ "update_time": {},
+ "update_date": {},
+}
+
+// userCanvasOrderableColumns allows the scalar user canvas columns the list rows expose plus the base timestamp columns.
+var userCanvasOrderableColumns = map[string]struct{}{
+ "id": {},
+ "user_id": {},
+ "title": {},
+ "permission": {},
+ "canvas_type": {},
+ "canvas_category": {},
+ "tags": {},
+ "create_time": {},
+ "create_date": {},
+ "update_time": {},
+ "update_date": {},
+}
+
+func chatOrderClause(terms []OrderTerm) string {
+ return orderClause(chatOrderableColumns, terms, defaultOrderColumn)
+}
+
+func chatSessionOrderClause(terms []OrderTerm) string {
+ return orderClause(chatSessionOrderableColumns, terms, defaultOrderColumn)
+}
+
+func compilationTemplateGroupOrderClause(terms []OrderTerm) string {
+ return orderClause(compilationTemplateGroupOrderableColumns, terms, defaultOrderColumn)
+}
+
+func fileOrderClause(terms []OrderTerm) string {
+ return orderClause(fileOrderableColumns, terms, defaultOrderColumn)
+}
+
+func knowledgebaseOrderClause(terms []OrderTerm) string {
+ return orderClause(knowledgebaseOrderableColumns, terms, defaultOrderColumn)
+}
+
+func knowledgebaseQualifiedOrderClause(terms []OrderTerm) string {
+ return qualifiedOrderClause("knowledgebase", knowledgebaseOrderableColumns, terms, defaultOrderColumn)
+}
+
+func pipelineLogOrderClause(terms []OrderTerm) string {
+ return orderClause(pipelineLogOrderableColumns, terms, defaultOrderColumn)
+}
+
+func searchOrderClause(terms []OrderTerm) string {
+ return orderClause(searchOrderableColumns, terms, defaultOrderColumn)
+}
+
+func userCanvasOrderClause(terms []OrderTerm) string {
+ return orderClause(userCanvasOrderableColumns, terms, defaultOrderColumn)
+}
+
+func userCanvasQualifiedOrderClause(terms []OrderTerm) string {
+ return qualifiedOrderClause("user_canvas", userCanvasOrderableColumns, terms, defaultOrderColumn)
+}
diff --git a/internal/dao/order_by_test.go b/internal/dao/order_by_test.go
new file mode 100644
index 0000000000..6716f753a9
--- /dev/null
+++ b/internal/dao/order_by_test.go
@@ -0,0 +1,204 @@
+package dao
+
+import "testing"
+
+func TestOrderClauseRendersAllowedTerms(t *testing.T) {
+ allowed := map[string]struct{}{"name": {}, "create_time": {}, "size": {}}
+
+ cases := []struct {
+ name string
+ terms []OrderTerm
+ want string
+ }{
+ {
+ name: "one allowed column ascending",
+ terms: []OrderTerm{{Column: "name"}},
+ want: "name ASC",
+ },
+ {
+ name: "one allowed column descending",
+ terms: []OrderTerm{{Column: "name", Desc: true}},
+ want: "name DESC",
+ },
+ {
+ name: "several terms keep their order and direction",
+ terms: []OrderTerm{{Column: "name"}, {Column: "size", Desc: true}, {Column: "create_time"}},
+ want: "name ASC, size DESC, create_time ASC",
+ },
+ {
+ name: "a term outside the allowlist is dropped and the rest survive",
+ terms: []OrderTerm{{Column: "name"}, {Column: "password", Desc: true}},
+ want: "name ASC",
+ },
+ {
+ name: "no surviving term falls back, keeping the first requested direction",
+ terms: []OrderTerm{{Column: "password", Desc: true}},
+ want: "create_time DESC",
+ },
+ {
+ name: "no terms at all falls back ascending",
+ terms: nil,
+ want: "create_time ASC",
+ },
+ {
+ name: "an injected expression is not a column name, so it is dropped",
+ terms: []OrderTerm{{Column: "name; DROP TABLE file"}},
+ want: "create_time ASC",
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := orderClause(allowed, tc.terms, defaultOrderColumn); got != tc.want {
+ t.Fatalf("orderClause = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestQualifiedOrderClauseNamesTheTableOnEveryColumn(t *testing.T) {
+ allowed := map[string]struct{}{"name": {}, "create_time": {}}
+
+ got := qualifiedOrderClause("knowledgebase", allowed,
+ []OrderTerm{{Column: "name", Desc: true}, {Column: "create_time"}}, defaultOrderColumn)
+ want := "knowledgebase.name DESC, knowledgebase.create_time ASC"
+ if got != want {
+ t.Fatalf("qualifiedOrderClause = %q, want %q", got, want)
+ }
+
+ // The fallback is a column too, so it has to carry the qualifier or a join
+ // would reject it as ambiguous.
+ got = qualifiedOrderClause("knowledgebase", allowed, []OrderTerm{{Column: "password"}}, defaultOrderColumn)
+ want = "knowledgebase.create_time ASC"
+ if got != want {
+ t.Fatalf("qualifiedOrderClause fallback = %q, want %q", got, want)
+ }
+}
+
+// Every entity binds its own allowlist, so a column one entity exposes must not
+// become orderable on another.
+func TestEntityAllowlistsDoNotLeakAcrossEntities(t *testing.T) {
+ if got := searchOrderClause([]OrderTerm{{Column: "size"}}); got != "create_time ASC" {
+ t.Fatalf("search accepted a file column: %q", got)
+ }
+ if got := fileOrderClause([]OrderTerm{{Column: "size"}}); got != "size ASC" {
+ t.Fatalf("file rejected its own column: %q", got)
+ }
+ if got := userCanvasOrderClause([]OrderTerm{{Column: "doc_num", Desc: true}}); got != "create_time DESC" {
+ t.Fatalf("user canvas accepted a knowledge base column: %q", got)
+ }
+}
+
+// The conversation list reached ORDER BY through string concatenation with no
+// allowlist at all, so these cases cover the column names it now refuses as well
+// as the empty value its callers still send.
+func TestChatSessionOrderClauseGuardsTheConversationList(t *testing.T) {
+ cases := []struct {
+ name string
+ orderby string
+ desc bool
+ want string
+ }{
+ {name: "a column the list rows expose", orderby: "name", desc: true, want: "name DESC"},
+ {name: "empty keeps the previous default", orderby: "", want: "create_time ASC"},
+ {name: "empty keeps the requested direction", orderby: "", desc: true, want: "create_time DESC"},
+ {name: "a column of another entity", orderby: "size", want: "create_time ASC"},
+ {name: "an injected expression", orderby: "name; DROP TABLE conversation", desc: true, want: "create_time DESC"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := chatSessionOrderClause([]OrderTerm{{Column: tc.orderby, Desc: tc.desc}}); got != tc.want {
+ t.Fatalf("chatSessionOrderClause(%q, %v) = %q, want %q", tc.orderby, tc.desc, got, tc.want)
+ }
+ })
+ }
+}
+
+// The template group list already refused unknown names before the rule moved
+// here, so these cases pin the set it accepted rather than the wider set its row
+// would allow.
+func TestCompilationTemplateGroupOrderClauseKeepsItsAcceptedColumns(t *testing.T) {
+ for _, column := range []string{"name", "scope", "create_time", "update_time"} {
+ if got := compilationTemplateGroupOrderClause([]OrderTerm{{Column: column}}); got != column+" ASC" {
+ t.Fatalf("template group rejected %q: %q", column, got)
+ }
+ }
+ for _, column := range []string{"id", "tenant_id", "description", "status", "create_date"} {
+ if got := compilationTemplateGroupOrderClause([]OrderTerm{{Column: column, Desc: true}}); got != "create_time DESC" {
+ t.Fatalf("template group accepted %q: %q", column, got)
+ }
+ }
+}
+
+func TestParseOrderTermsReadsTheSortParameter(t *testing.T) {
+ cases := []struct {
+ name string
+ sort string
+ want []OrderTerm
+ }{
+ {
+ name: "columns and directions",
+ sort: "name:asc,create_time:desc",
+ want: []OrderTerm{{Column: "name"}, {Column: "create_time", Desc: true}},
+ },
+ {
+ name: "a term without a direction is ascending",
+ sort: "name",
+ want: []OrderTerm{{Column: "name"}},
+ },
+ {
+ name: "spacing around terms and directions",
+ sort: " name : DESC , size ",
+ want: []OrderTerm{{Column: "name", Desc: true}, {Column: "size"}},
+ },
+ {
+ name: "a direction that is neither costs its own term",
+ sort: "name:sideways,size:asc",
+ want: []OrderTerm{{Column: "size"}},
+ },
+ {
+ name: "empty entries are skipped",
+ sort: "name,,:desc,",
+ want: []OrderTerm{{Column: "name"}},
+ },
+ {
+ name: "nothing usable leaves the caller on orderby",
+ sort: " , :asc ,",
+ want: nil,
+ },
+ {
+ name: "absent",
+ sort: "",
+ want: nil,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := ParseOrderTerms(tc.sort)
+ if len(got) != len(tc.want) {
+ t.Fatalf("ParseOrderTerms(%q) = %+v, want %+v", tc.sort, got, tc.want)
+ }
+ for i := range got {
+ if got[i] != tc.want[i] {
+ t.Fatalf("ParseOrderTerms(%q)[%d] = %+v, want %+v", tc.sort, i, got[i], tc.want[i])
+ }
+ }
+ })
+ }
+}
+
+// A parsed term still has to clear the entity allowlist, so a sort naming a
+// column of another entity renders no differently from the same name in orderby.
+func TestParsedTermsStillFaceTheEntityAllowlist(t *testing.T) {
+ if got := searchOrderClause(ParseOrderTerms("name:desc,size:asc")); got != "name DESC" {
+ t.Fatalf("search kept a file column: %q", got)
+ }
+ if got := fileOrderClause(ParseOrderTerms("size:asc,name:desc")); got != "size ASC, name DESC" {
+ t.Fatalf("file dropped its own columns: %q", got)
+ }
+ if got := searchOrderClause(ParseOrderTerms("size:desc")); got != "create_time DESC" {
+ t.Fatalf("a sort with nothing allowed did not fall back: %q", got)
+ }
+}
diff --git a/internal/dao/pipeline_operation_log.go b/internal/dao/pipeline_operation_log.go
index a33b42329f..b7cdd551ac 100644
--- a/internal/dao/pipeline_operation_log.go
+++ b/internal/dao/pipeline_operation_log.go
@@ -57,43 +57,6 @@ func normalizePipelineOperationStatuses(statuses []string) []string {
// api/db/services/task_service.py.
const graphRaptorFakeDocID = "graph_raptor_x"
-// pipelineLogOrderableColumns whitelists the columns that may appear in an
-// ORDER BY clause so an attacker cannot inject arbitrary SQL through the
-// `orderby` query parameter.
-var pipelineLogOrderableColumns = map[string]struct{}{
- "id": {},
- "document_id": {},
- "tenant_id": {},
- "kb_id": {},
- "pipeline_id": {},
- "pipeline_title": {},
- "parser_id": {},
- "document_name": {},
- "document_suffix": {},
- "document_type": {},
- "source_from": {},
- "progress": {},
- "process_begin_at": {},
- "process_duration": {},
- "task_type": {},
- "operation_status": {},
- "status": {},
- "create_time": {},
- "create_date": {},
- "update_time": {},
- "update_date": {},
-}
-
-func pipelineLogOrderClause(orderby string, desc bool) string {
- if _, ok := pipelineLogOrderableColumns[orderby]; !ok {
- orderby = "create_time"
- }
- if desc {
- return orderby + " DESC"
- }
- return orderby + " ASC"
-}
-
// PipelineOperationLogDAO data access object for pipeline_operation_log.
type PipelineOperationLogDAO struct{}
@@ -109,7 +72,7 @@ func NewPipelineOperationLogDAO() *PipelineOperationLogDAO {
// documentID is honoured for the same reason as in GetFileLogsByKBID. Dataset
// logs belong to no single document, so a caller that names one gets an empty
// list rather than the whole dataset history.
-func (dao *PipelineOperationLogDAO) GetDatasetLogsByKBID(ctx context.Context, db *gorm.DB, kbID string, page, pageSize int, orderby string, desc bool, operationStatus []string, createDateFrom, createDateTo, keywords, documentID string) ([]*entity.PipelineOperationLog, int64, error) {
+func (dao *PipelineOperationLogDAO) GetDatasetLogsByKBID(ctx context.Context, db *gorm.DB, kbID string, page, pageSize int, terms []OrderTerm, operationStatus []string, createDateFrom, createDateTo, keywords, documentID string) ([]*entity.PipelineOperationLog, int64, error) {
query := db.WithContext(ctx).Model(&entity.PipelineOperationLog{}).
Where("kb_id = ? AND document_id = ?", kbID, graphRaptorFakeDocID)
@@ -139,7 +102,7 @@ func (dao *PipelineOperationLogDAO) GetDatasetLogsByKBID(ctx context.Context, db
// if no match is found. The only string that flows into Order() is
// the whitelisted column name + " ASC"/" DESC" suffix.
// codeql[go/sql-injection] False positive: pipelineLogOrderClause
- query = query.Order(pipelineLogOrderClause(orderby, desc))
+ query = query.Order(pipelineLogOrderClause(terms))
if page > 0 && pageSize > 0 {
query = query.Offset((page - 1) * pageSize).Limit(pageSize)
}
@@ -157,7 +120,7 @@ func (dao *PipelineOperationLogDAO) GetDatasetLogsByKBID(ctx context.Context, db
// resolve a queued document's early row: matching by document_name is a fuzzy
// LIKE search that can push the row out of the first page when several
// documents share a name.
-func (dao *PipelineOperationLogDAO) GetFileLogsByKBID(ctx context.Context, db *gorm.DB, kbID string, page, pageSize int, orderby string, desc bool, keywords, documentID string, operationStatus []string, createDateFrom, createDateTo string) ([]*entity.PipelineOperationLog, int64, error) {
+func (dao *PipelineOperationLogDAO) GetFileLogsByKBID(ctx context.Context, db *gorm.DB, kbID string, page, pageSize int, terms []OrderTerm, keywords, documentID string, operationStatus []string, createDateFrom, createDateTo string) ([]*entity.PipelineOperationLog, int64, error) {
query := db.WithContext(ctx).Model(&entity.PipelineOperationLog{}).
Where("kb_id = ?", kbID)
@@ -189,7 +152,7 @@ func (dao *PipelineOperationLogDAO) GetFileLogsByKBID(ctx context.Context, db *g
// if no match is found. The only string that flows into Order() is
// the whitelisted column name + " ASC"/" DESC" suffix.
// codeql[go/sql-injection] False positive: pipelineLogOrderClause
- query = query.Order(pipelineLogOrderClause(orderby, desc))
+ query = query.Order(pipelineLogOrderClause(terms))
if page > 0 && pageSize > 0 {
query = query.Offset((page - 1) * pageSize).Limit(pageSize)
}
diff --git a/internal/dao/search.go b/internal/dao/search.go
index e12aa99707..cd9d99eb8c 100644
--- a/internal/dao/search.go
+++ b/internal/dao/search.go
@@ -48,7 +48,7 @@ type SearchDetailRow struct {
}
// ListByTenantIDs list searches by tenant IDs with pagination and filtering
-func (dao *SearchDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, tenantIDs []string, userID string, page, pageSize int, orderby string, desc bool, keywords string) ([]*entity.SearchListItem, int64, error) {
+func (dao *SearchDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, tenantIDs []string, userID string, page, pageSize int, terms []OrderTerm, keywords string) ([]*entity.SearchListItem, int64, error) {
var searches []*entity.SearchListItem
var total int64
@@ -72,12 +72,12 @@ func (dao *SearchDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, tenantID
query = query.Where("LOWER(search.name) LIKE ?", "%"+strings.ToLower(keywords)+"%")
}
- // Apply ordering
- orderDirection := "ASC"
- if desc {
- orderDirection = "DESC"
- }
- query = query.Order(orderby + " " + orderDirection)
+ // Apply ordering. Route the requested terms through searchOrderClause so a
+ // user-supplied query param can never reach Order() verbatim: the helper
+ // validates against searchOrderableColumns (a closed allowlist) and falls
+ // back to "create_time" on a miss.
+ // codeql[go/sql-injection] False positive: searchOrderClause
+ query = query.Order(searchOrderClause(terms))
// Count total
if err := query.Count(&total).Error; err != nil {
@@ -100,7 +100,7 @@ func (dao *SearchDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, tenantID
}
// ListByOwnerIDs list searches by owner IDs with filtering (manual pagination)
-func (dao *SearchDAO) ListByOwnerIDs(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string, orderby string, desc bool, keywords string) ([]*entity.SearchListItem, int64, error) {
+func (dao *SearchDAO) ListByOwnerIDs(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string, terms []OrderTerm, keywords string) ([]*entity.SearchListItem, int64, error) {
var searches []*entity.SearchListItem
// Build query with join to user table
@@ -121,12 +121,12 @@ func (dao *SearchDAO) ListByOwnerIDs(ctx context.Context, db *gorm.DB, ownerIDs
// Filter by owner IDs (additional filter to ensure tenant_id is in ownerIDs)
query = query.Where("search.tenant_id IN ?", ownerIDs)
- // Apply ordering
- orderDirection := "ASC"
- if desc {
- orderDirection = "DESC"
- }
- query = query.Order(orderby + " " + orderDirection)
+ // Apply ordering. Route the requested terms through searchOrderClause so a
+ // user-supplied query param can never reach Order() verbatim: the helper
+ // validates against searchOrderableColumns (a closed allowlist) and falls
+ // back to "create_time" on a miss.
+ // codeql[go/sql-injection] False positive: searchOrderClause
+ query = query.Order(searchOrderClause(terms))
// Get all matching records
if err := query.Scan(&searches).Error; err != nil {
diff --git a/internal/dao/search_test.go b/internal/dao/search_test.go
new file mode 100644
index 0000000000..c3ca9c99ab
--- /dev/null
+++ b/internal/dao/search_test.go
@@ -0,0 +1,132 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package dao
+
+import (
+ "testing"
+
+ "gorm.io/gorm"
+
+ "ragflow/internal/entity"
+)
+
+func int64Ptr(v int64) *int64 {
+ return &v
+}
+
+// searchOrderExpressions are SQL expressions rather than column names. They
+// stand in for the `orderby` query parameter of GET /api/v1/searches, which
+// reaches SearchDAO straight from the request (issue #14268).
+var searchOrderExpressions = []string{
+ "(SELECT inner_search.name FROM search AS inner_search WHERE inner_search.id = search.id)",
+}
+
+// seedOrderableSearches creates three searches whose create_time order is the
+// reverse of their name order, so a test can tell which column the ORDER BY
+// clause actually used.
+func seedOrderableSearches(t *testing.T, db *gorm.DB) {
+ t.Helper()
+ searches := []entity.Search{
+ {ID: "s-1", TenantID: "t1", Name: "zulu", CreatedBy: "t1", SearchConfig: entity.JSONMap{}, Status: stringPtr("1"), BaseModel: entity.BaseModel{CreateTime: int64Ptr(100)}},
+ {ID: "s-2", TenantID: "t1", Name: "mike", CreatedBy: "t1", SearchConfig: entity.JSONMap{}, Status: stringPtr("1"), BaseModel: entity.BaseModel{CreateTime: int64Ptr(200)}},
+ {ID: "s-3", TenantID: "t1", Name: "alpha", CreatedBy: "t1", SearchConfig: entity.JSONMap{}, Status: stringPtr("1"), BaseModel: entity.BaseModel{CreateTime: int64Ptr(300)}},
+ }
+ for i := range searches {
+ if err := db.Create(&searches[i]).Error; err != nil {
+ t.Fatalf("failed to create search %s: %v", searches[i].ID, err)
+ }
+ }
+}
+
+func assertSearchOrder(t *testing.T, rows []*entity.SearchListItem, want []string, orderby string) {
+ t.Helper()
+ if len(rows) != len(want) {
+ t.Fatalf("orderby %q returned %d rows, want %d", orderby, len(rows), len(want))
+ }
+ for i, row := range rows {
+ if row.ID != want[i] {
+ got := make([]string, 0, len(rows))
+ for _, r := range rows {
+ got = append(got, r.ID)
+ }
+ t.Fatalf("orderby %q produced order %v, want %v: the expression reached the ORDER BY clause", orderby, got, want)
+ }
+ }
+}
+
+// TestSearchDAOListByTenantIDsOrderByExpressionFallsBack checks that an
+// `orderby` value that is an expression rather than an allowed column name
+// leaves the rows in the default create_time order.
+func TestSearchDAOListByTenantIDsOrderByExpressionFallsBack(t *testing.T) {
+ db := setupSearchDetailDAOTestDB(t)
+ pushDB(t, db)
+ seedOrderableSearches(t, db)
+ ctx := t.Context()
+ d := NewSearchDAO()
+
+ for _, orderby := range searchOrderExpressions {
+ t.Run(orderby, func(t *testing.T) {
+ rows, _, err := d.ListByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: orderby}}, "")
+ if err != nil {
+ t.Fatalf("ListByTenantIDs with orderby %q: %v", orderby, err)
+ }
+ assertSearchOrder(t, rows, []string{"s-1", "s-2", "s-3"}, orderby)
+ })
+ }
+}
+
+// TestSearchDAOListByOwnerIDsOrderByExpressionFallsBack is the ListByOwnerIDs
+// counterpart, the branch the endpoint takes when owner_ids is supplied.
+func TestSearchDAOListByOwnerIDsOrderByExpressionFallsBack(t *testing.T) {
+ db := setupSearchDetailDAOTestDB(t)
+ pushDB(t, db)
+ seedOrderableSearches(t, db)
+ ctx := t.Context()
+ d := NewSearchDAO()
+
+ for _, orderby := range searchOrderExpressions {
+ t.Run(orderby, func(t *testing.T) {
+ rows, _, err := d.ListByOwnerIDs(ctx, db, []string{"t1"}, "t1", []OrderTerm{{Column: orderby}}, "")
+ if err != nil {
+ t.Fatalf("ListByOwnerIDs with orderby %q: %v", orderby, err)
+ }
+ assertSearchOrder(t, rows, []string{"s-1", "s-2", "s-3"}, orderby)
+ })
+ }
+}
+
+// TestSearchDAOListOrderByAllowedColumn checks that the allowlist still honors
+// a real column in both directions.
+func TestSearchDAOListOrderByAllowedColumn(t *testing.T) {
+ db := setupSearchDetailDAOTestDB(t)
+ pushDB(t, db)
+ seedOrderableSearches(t, db)
+ ctx := t.Context()
+ d := NewSearchDAO()
+
+ rows, _, err := d.ListByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: "name"}}, "")
+ if err != nil {
+ t.Fatalf("ListByTenantIDs ascending by name: %v", err)
+ }
+ assertSearchOrder(t, rows, []string{"s-3", "s-2", "s-1"}, "name")
+
+ rows, _, err = d.ListByTenantIDs(ctx, db, []string{"t1"}, "t1", 1, 10, []OrderTerm{{Column: "name", Desc: true}}, "")
+ if err != nil {
+ t.Fatalf("ListByTenantIDs descending by name: %v", err)
+ }
+ assertSearchOrder(t, rows, []string{"s-1", "s-2", "s-3"}, "name")
+}
diff --git a/internal/dao/user_canvas.go b/internal/dao/user_canvas.go
index 46dbc4fe80..3821638a02 100644
--- a/internal/dao/user_canvas.go
+++ b/internal/dao/user_canvas.go
@@ -32,44 +32,6 @@ import (
// distinguish "missing" from "forbidden" so the response cannot be used
// to enumerate other users' canvas ids — see plan §4.8 (IDOR mitigation).
-// userCanvasOrderableColumns whitelists the columns that may appear in an
-// ORDER BY clause. Keeps user-supplied `orderby` query params from being
-// spliced straight into SQL.
-var userCanvasOrderableColumns = map[string]struct{}{
- "id": {},
- "user_id": {},
- "title": {},
- "permission": {},
- "canvas_type": {},
- "canvas_category": {},
- "tags": {},
- "create_time": {},
- "create_date": {},
- "update_time": {},
- "update_date": {},
-}
-
-func userCanvasOrderClause(orderby string, desc bool) string {
- if _, ok := userCanvasOrderableColumns[orderby]; !ok {
- orderby = "create_time"
- }
- if desc {
- return orderby + " DESC"
- }
- return orderby + " ASC"
-}
-
-func userCanvasQualifiedOrderClause(orderby string, desc bool) string {
- if _, ok := userCanvasOrderableColumns[orderby]; !ok {
- orderby = "create_time"
- }
- order := "user_canvas." + orderby
- if desc {
- return order + " DESC"
- }
- return order + " ASC"
-}
-
func splitUserCanvasTags(raw string) []string {
parts := strings.Split(raw, ",")
tags := make([]string, 0, len(parts))
@@ -272,7 +234,7 @@ func (dao *UserCanvasDAO) GetByUserAndTitle(ctx context.Context, db *gorm.DB, us
// GetList get canvases list with pagination and filtering
// Similar to Python UserCanvasService.get_list
-func (dao *UserCanvasDAO) GetList(ctx context.Context, db *gorm.DB, tenantID string, pageNumber, itemsPerPage int, orderby string, desc bool, id, title string, canvasCategory, canvasType string) ([]*entity.UserCanvas, error) {
+func (dao *UserCanvasDAO) GetList(ctx context.Context, db *gorm.DB, tenantID string, pageNumber, itemsPerPage int, terms []OrderTerm, id, title string, canvasCategory, canvasType string) ([]*entity.UserCanvas, error) {
query := db.WithContext(ctx).Model(&entity.UserCanvas{}).
Where("user_id = ?", tenantID)
@@ -292,12 +254,12 @@ func (dao *UserCanvasDAO) GetList(ctx context.Context, db *gorm.DB, tenantID str
}
// Order by
- // Route orderby through userCanvasOrderClause above so user-supplied
+ // Route the requested terms through userCanvasOrderClause above so user-supplied
// query params can never reach Order() verbatim. The helper validates
// against userCanvasOrderableColumns (a closed allowlist) and falls
// back to "create_time" on any miss, so the string spliced into the
// SQL fragment is always one of a fixed set of column names.
- query = query.Order(userCanvasOrderClause(orderby, desc))
+ query = query.Order(userCanvasOrderClause(terms))
// Pagination
if pageNumber > 0 && itemsPerPage > 0 {
@@ -346,7 +308,7 @@ type UserCanvasListItem struct {
// ListByTenantIDs lists agent canvases accessible to the given owner IDs with optional
// keyword filter, tag filter, pagination, and ordering.
// Mirrors Python UserCanvasService.get_by_tenant_ids (list route only).
-func (dao *UserCanvasDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string, page, pageSize int, orderby string, desc bool, keywords string, canvasCategories []string, canvasType string, tags []string) ([]*UserCanvasListItem, int64, error) {
+func (dao *UserCanvasDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, ownerIDs []string, userID string, page, pageSize int, terms []OrderTerm, keywords string, canvasCategories []string, canvasType string, tags []string) ([]*UserCanvasListItem, int64, error) {
if len(ownerIDs) == 0 {
return nil, 0, nil
}
@@ -392,7 +354,7 @@ func (dao *UserCanvasDAO) ListByTenantIDs(ctx context.Context, db *gorm.DB, owne
return nil, 0, err
}
- order := userCanvasQualifiedOrderClause(orderby, desc)
+ order := userCanvasQualifiedOrderClause(terms)
// codeql[go/sql-injection] False positive: `order` was just derived
// from userCanvasQualifiedOrderClause above, which validates `orderby`
// against userCanvasOrderableColumns (a closed allowlist) and
diff --git a/internal/dao/user_canvas_test.go b/internal/dao/user_canvas_test.go
index 2e96c55b8f..9d12dbdb3b 100644
--- a/internal/dao/user_canvas_test.go
+++ b/internal/dao/user_canvas_test.go
@@ -290,7 +290,7 @@ func TestUserCanvasDAOKeywordSearchIncludesTags(t *testing.T) {
}
}
- results, _, err := d.ListByTenantIDs(ctx, db, []string{"u1"}, "u1", 1, 10, "create_time", false, "finance", nil, "", nil)
+ results, _, err := d.ListByTenantIDs(ctx, db, []string{"u1"}, "u1", 1, 10, []OrderTerm{{Column: "create_time"}}, "finance", nil, "", nil)
if err != nil {
t.Fatalf("ListByTenantIDs: %v", err)
}
@@ -327,7 +327,7 @@ func TestUserCanvasDAOListByTenantIDsCategoryUnion(t *testing.T) {
}
}
- rows, total, err := d.ListByTenantIDs(ctx, db, []string{"u1"}, "u1", 1, 10, "create_time", false, "", []string{"dataflow_canvas", "agent_canvas"}, "", nil)
+ rows, total, err := d.ListByTenantIDs(ctx, db, []string{"u1"}, "u1", 1, 10, []OrderTerm{{Column: "create_time"}}, "", []string{"dataflow_canvas", "agent_canvas"}, "", nil)
if err != nil {
t.Fatalf("ListByTenantIDs: %v", err)
}
@@ -335,7 +335,7 @@ func TestUserCanvasDAOListByTenantIDsCategoryUnion(t *testing.T) {
t.Fatalf("category union returned total=%d rows=%d, want 3/3", total, len(rows))
}
- rows, total, err = d.ListByTenantIDs(ctx, db, []string{"u1"}, "u1", 1, 10, "create_time", false, "", []string{"agent_canvas"}, "", nil)
+ rows, total, err = d.ListByTenantIDs(ctx, db, []string{"u1"}, "u1", 1, 10, []OrderTerm{{Column: "create_time"}}, "", []string{"agent_canvas"}, "", nil)
if err != nil {
t.Fatalf("ListByTenantIDs (single category): %v", err)
}
@@ -369,7 +369,7 @@ func TestUserCanvasDAOOrderByTags(t *testing.T) {
}
}
- results, _, err := d.ListByTenantIDs(ctx, db, []string{"u1"}, "u1", 1, 10, "tags", false, "", nil, "", nil)
+ results, _, err := d.ListByTenantIDs(ctx, db, []string{"u1"}, "u1", 1, 10, []OrderTerm{{Column: "tags"}}, "", nil, "", nil)
if err != nil {
t.Fatalf("ListByTenantIDs: %v", err)
}
diff --git a/internal/handler/agent.go b/internal/handler/agent.go
index 4e8398d9a2..450935568f 100644
--- a/internal/handler/agent.go
+++ b/internal/handler/agent.go
@@ -152,6 +152,7 @@ func (h *AgentHandler) WithNewExecutor(f func(taskCtx *task.TaskContext, canvasI
// @Param page query int false "Page number (0 = no pagination)"
// @Param page_size query int false "Items per page (0 = no pagination)"
// @Param orderby query string false "Order-by field (default: create_time)"
+// @Param sort query string false "Ordered terms, column:direction separated by commas, such as name:asc,create_time:desc. Takes precedence over orderby and desc"
// @Param desc query bool false "Descending order (default: true)"
// @Param owner_ids query string false "Comma-separated owner IDs to filter (default: all authorised tenants)"
// @Param canvas_category query string false "Canvas category (default: agent_canvas)"
@@ -201,6 +202,7 @@ func (h *AgentHandler) ListAgents(c *gin.Context) {
if v := c.Query("desc"); v != "" {
desc = strings.ToLower(v) != "false"
}
+ terms := orderTermsFromQuery(c, orderby, desc)
var ownerIDs []string
if raw := c.Query("owner_ids"); raw != "" {
@@ -228,8 +230,7 @@ func (h *AgentHandler) ListAgents(c *gin.Context) {
keywords,
page,
pageSize,
- orderby,
- desc,
+ terms,
ownerIDs,
canvasCategory,
canvasType,
diff --git a/internal/handler/chat.go b/internal/handler/chat.go
index c68b03dc1f..866f279f28 100644
--- a/internal/handler/chat.go
+++ b/internal/handler/chat.go
@@ -95,24 +95,30 @@ func (h *ChatHandler) ListChats(c *gin.Context) {
}
}
+ // `sort` supersedes the older pair, so a request it can order is not rejected
+ // for the spelling of an `orderby` that will not be read.
+ sortTerms := sortTermsFromQuery(c)
orderby := c.DefaultQuery("orderby", "create_time")
- switch orderby {
- case "create_time", "update_time", "name":
- default:
- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("invalid orderby field: %s", orderby))
- return
+ if len(sortTerms) == 0 {
+ switch orderby {
+ case "create_time", "update_time", "name":
+ default:
+ common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("invalid orderby field: %s", orderby))
+ return
+ }
}
desc := true
if descStr := c.Query("desc"); descStr != "" {
desc = !strings.EqualFold(descStr, "false")
}
+ terms := orderTerms(sortTerms, orderby, desc)
ownerIDs := getOwnerIDs(c)
ctx := c.Request.Context()
// List chats - default to valid status "1" (same as Python StatusEnum.VALID.value)
- result, err := h.chatService.ListChats(ctx, userID, "1", keywords, page, pageSize, orderby, desc, ownerIDs)
+ result, err := h.chatService.ListChats(ctx, userID, "1", keywords, page, pageSize, terms, ownerIDs)
if err != nil {
common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, 500, nil, err.Error())
return
diff --git a/internal/handler/chat_session.go b/internal/handler/chat_session.go
index 9e8da5602e..7af16f44e5 100644
--- a/internal/handler/chat_session.go
+++ b/internal/handler/chat_session.go
@@ -85,14 +85,19 @@ func (h *ChatSessionHandler) ListChatSessions(c *gin.Context) {
}
}
+ // `sort` supersedes the older pair, so a request it can order is not rejected
+ // for the spelling of an `orderby` that will not be read.
+ sortTerms := sortTermsFromQuery(c)
orderby := "create_time"
if queryOrderby := c.Query("orderby"); queryOrderby != "" {
switch queryOrderby {
case "create_time", "update_time", "name":
orderby = queryOrderby
default:
- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("invalid orderby field: %s", queryOrderby))
- return
+ if len(sortTerms) == 0 {
+ common.ResponseWithCodeData(c, common.CodeArgumentError, nil, fmt.Sprintf("invalid orderby field: %s", queryOrderby))
+ return
+ }
}
}
@@ -100,11 +105,12 @@ func (h *ChatSessionHandler) ListChatSessions(c *gin.Context) {
if descStr := c.Query("desc"); descStr != "" {
desc = !strings.EqualFold(descStr, "false")
}
+ terms := orderTerms(sortTerms, orderby, desc)
// Call service to list chat sessions
ctx := c.Request.Context()
includeHistory := c.DefaultQuery("include_history", "true")
- result, err := h.chatSessionService.ListChatSessions(ctx, userID, chatID, c.Query("id"), c.Query("name"), orderby, desc, page, pageSize, includeHistory != "false" && includeHistory != "False")
+ result, err := h.chatSessionService.ListChatSessions(ctx, userID, chatID, c.Query("id"), c.Query("name"), terms, page, pageSize, includeHistory != "false" && includeHistory != "False")
if err != nil {
// Mirror Python: ownership failures return code 109 "no authorization"
if strings.Contains(err.Error(), "no authorization") {
diff --git a/internal/handler/common.go b/internal/handler/common.go
index 44f34c8d8b..7ddf3c5c5c 100644
--- a/internal/handler/common.go
+++ b/internal/handler/common.go
@@ -18,11 +18,36 @@ package handler
import (
"ragflow/internal/common"
+ "ragflow/internal/dao"
"ragflow/internal/entity"
"github.com/gin-gonic/gin"
)
+// sortTermsFromQuery reads the `sort` parameter, a comma separated list of
+// `column:direction` terms such as `name:asc,create_time:desc`. A handler that
+// rejects an unrecognised `orderby` or `desc` reads this first and skips that
+// check when terms came back, because a request whose `sort` decides the order
+// is not held to the spelling of a field it does not use.
+func sortTermsFromQuery(c *gin.Context) []dao.OrderTerm {
+ return dao.ParseOrderTerms(c.Query("sort"))
+}
+
+// orderTerms prefers the parsed `sort` terms and falls back to the older
+// `orderby` and `desc` pair, which still works on its own. A term naming a
+// column the entity does not order by is dropped rather than rejected, so a
+// caller that already sends an unknown name keeps the result it has today.
+func orderTerms(sortTerms []dao.OrderTerm, orderby string, desc bool) []dao.OrderTerm {
+ if len(sortTerms) > 0 {
+ return sortTerms
+ }
+ return []dao.OrderTerm{{Column: orderby, Desc: desc}}
+}
+
+func orderTermsFromQuery(c *gin.Context, orderby string, desc bool) []dao.OrderTerm {
+ return orderTerms(sortTermsFromQuery(c), orderby, desc)
+}
+
func GetUser(c *gin.Context) (*entity.User, common.ErrorCode, string) {
userAny, exist := c.Get("user")
if !exist {
diff --git a/internal/handler/compilation_template_group.go b/internal/handler/compilation_template_group.go
index fed392925a..629bfef4c7 100644
--- a/internal/handler/compilation_template_group.go
+++ b/internal/handler/compilation_template_group.go
@@ -47,6 +47,7 @@ func NewCompilationTemplateGroupHandler(svc *service.CompilationTemplateGroupSer
// @Param page query int false "page number" default(1)
// @Param page_size query int false "items per page" default(30)
// @Param orderby query string false "order field" default(create_time)
+// @Param sort query string false "ordered terms, column:direction separated by commas, such as name:asc,create_time:desc. Takes precedence over orderby and desc"
// @Param desc query bool false "descending" default(true)
// @Success 200 {object} map[string]interface{}
// @Router /v1/compilation-template-groups [get]
@@ -68,8 +69,9 @@ func (h *CompilationTemplateGroupHandler) List(c *gin.Context) {
scope := c.Query("scope")
orderby := c.DefaultQuery("orderby", "create_time")
desc := c.DefaultQuery("desc", "true") != "false"
+ terms := orderTermsFromQuery(c, orderby, desc)
- groups, err := h.compilationTemplateGroupService.ListSaved(c.Request.Context(), user.ID, keywords, scope, orderby, desc)
+ groups, err := h.compilationTemplateGroupService.ListSaved(c.Request.Context(), user.ID, keywords, scope, terms)
if err != nil {
common.ResponseWithCodeData(c, common.CodeExceptionError, nil, err.Error())
return
diff --git a/internal/handler/dataset.go b/internal/handler/dataset.go
index 9e766f563e..7c5a2d9b29 100644
--- a/internal/handler/dataset.go
+++ b/internal/handler/dataset.go
@@ -119,24 +119,34 @@ func (h *DatasetsHandler) ListDatasets(c *gin.Context) {
pageSize = ps
}
+ // `sort` supersedes the older pair, so a request it can order is not rejected
+ // for the spelling of an `orderby` or `desc` that will not be read.
+ sortTerms := sortTermsFromQuery(c)
orderby := "create_time"
if queryOrderby, exists := c.GetQuery("orderby"); exists {
if queryOrderby != "create_time" && queryOrderby != "update_time" {
- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "Input should be 'create_time' or 'update_time'")
- return
+ if len(sortTerms) == 0 {
+ common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "Input should be 'create_time' or 'update_time'")
+ return
+ }
+ } else {
+ orderby = queryOrderby
}
- orderby = queryOrderby
}
desc := true
if descStr := c.Query("desc"); descStr != "" {
parsed, ok := parsePythonBool(descStr)
if !ok {
- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "Input should be a valid boolean, unable to interpret input")
- return
+ if len(sortTerms) == 0 {
+ common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "Input should be a valid boolean, unable to interpret input")
+ return
+ }
+ } else {
+ desc = parsed
}
- desc = parsed
}
+ terms := orderTerms(sortTerms, orderby, desc)
keywords := c.Query("keywords")
parserID := c.Query("parser_id")
@@ -197,8 +207,7 @@ func (h *DatasetsHandler) ListDatasets(c *gin.Context) {
c.Query("name"),
page,
pageSize,
- orderby,
- desc,
+ terms,
keywords,
ownerIDs,
parserID,
@@ -354,7 +363,7 @@ func pythonJSONTypeName(v interface{}) string {
// before validation in the Python endpoint).
var listDatasetsAllowedParams = map[string]bool{
"id": true, "ids": true, "name": true, "page": true, "page_size": true,
- "orderby": true, "desc": true, "include_parsing_status": true,
+ "orderby": true, "desc": true, "sort": true, "include_parsing_status": true,
"keywords": true, "owner_ids": true, "parser_id": true, "type": true,
}
@@ -543,6 +552,7 @@ func (h *DatasetsHandler) ListIngestionLogs(c *gin.Context) {
orderby := c.DefaultQuery("orderby", "create_time")
// desc defaults to true and is only disabled by the literal value "false".
desc := strings.ToLower(c.DefaultQuery("desc", "true")) != "false"
+ terms := orderTermsFromQuery(c, orderby, desc)
operationStatus := c.QueryArray("operation_status")
createDateFrom := c.Query("create_date_from")
createDateTo := c.Query("create_date_to")
@@ -554,7 +564,7 @@ func (h *DatasetsHandler) ListIngestionLogs(c *gin.Context) {
ctx := c.Request.Context()
- result, code, err := h.datasetsService.ListIngestionLogs(ctx, datasetID, user.ID, page, pageSize, orderby, desc, operationStatus, createDateFrom, createDateTo, logType, keywords, documentID)
+ result, code, err := h.datasetsService.ListIngestionLogs(ctx, datasetID, user.ID, page, pageSize, terms, operationStatus, createDateFrom, createDateTo, logType, keywords, documentID)
if err != nil {
common.ErrorWithCode(c, code, err.Error())
return
diff --git a/internal/handler/dataset_list_test.go b/internal/handler/dataset_list_test.go
index 6792300946..a627e8cfd1 100644
--- a/internal/handler/dataset_list_test.go
+++ b/internal/handler/dataset_list_test.go
@@ -145,3 +145,69 @@ func TestDatasetsHandlerListDatasetsRejectsDuplicateIDs(t *testing.T) {
t.Fatalf("message=%q want=%q", body.Message, expected)
}
}
+
+// `sort` is a query key like any other on this endpoint, and the key gate runs
+// before the ordering is read, so the gate has to know the name.
+func TestDatasetsHandlerListDatasetsAcceptsSort(t *testing.T) {
+ setupListDatasetsTestDB(t)
+ insertListDatasetsTestKB(t, listDatasetsTestKBID, "user-1", "Alpha")
+
+ body := getListDatasets(t, newListDatasetsTestRouter(), "sort=update_time:asc")
+
+ if body.Code != int(common.CodeSuccess) {
+ t.Fatalf("code=%d message=%q", body.Code, body.Message)
+ }
+ if body.TotalDatasets != 1 {
+ t.Fatalf("expected the dataset to be listed, got total=%d", body.TotalDatasets)
+ }
+}
+
+// A request `sort` can order is not rejected for the spelling of an `orderby` or
+// `desc` that will not be read, while the same values without `sort` still are.
+func TestDatasetsHandlerListDatasetsLegacyOrderingValidation(t *testing.T) {
+ cases := []struct {
+ name string
+ rawQuery string
+ wantCode common.ErrorCode
+ wantMsg string
+ }{
+ {
+ name: "an unrecognised orderby alone is rejected",
+ rawQuery: "orderby=nonsense",
+ wantCode: common.CodeArgumentError,
+ wantMsg: "Input should be 'create_time' or 'update_time'",
+ },
+ {
+ name: "an unparseable desc alone is rejected",
+ rawQuery: "desc=maybe",
+ wantCode: common.CodeArgumentError,
+ wantMsg: "Input should be a valid boolean, unable to interpret input",
+ },
+ {
+ name: "sort carries an unrecognised orderby",
+ rawQuery: "sort=update_time:asc&orderby=nonsense",
+ wantCode: common.CodeSuccess,
+ },
+ {
+ name: "sort carries an unparseable desc",
+ rawQuery: "sort=update_time:asc&desc=maybe",
+ wantCode: common.CodeSuccess,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ setupListDatasetsTestDB(t)
+ insertListDatasetsTestKB(t, listDatasetsTestKBID, "user-1", "Alpha")
+
+ body := getListDatasets(t, newListDatasetsTestRouter(), tc.rawQuery)
+
+ if body.Code != int(tc.wantCode) {
+ t.Fatalf("code=%d want=%d message=%q", body.Code, tc.wantCode, body.Message)
+ }
+ if tc.wantMsg != "" && body.Message != tc.wantMsg {
+ t.Fatalf("message=%q want=%q", body.Message, tc.wantMsg)
+ }
+ })
+ }
+}
diff --git a/internal/handler/file.go b/internal/handler/file.go
index dc571eb967..5451a6dd81 100644
--- a/internal/handler/file.go
+++ b/internal/handler/file.go
@@ -68,6 +68,7 @@ func NewFileHandler(fileService *file.FileService, userService *service.UserServ
// @Param page query int false "page number (default: 1, min: 1)"
// @Param page_size query int false "items per page (default: 15, min: 1, max: 100)"
// @Param orderby query string false "order by field (default: create_time)"
+// @Param sort query string false "ordered terms, column:direction separated by commas, such as name:asc,create_time:desc. Takes precedence over orderby and desc"
// @Param desc query bool false "descending order (default: true)"
// @Success 200 {object} file.ListFilesResponse
// @Router /api/v1/files [get]
@@ -114,9 +115,10 @@ func (h *FileHandler) ListFiles(c *gin.Context) {
if descStr := c.Query("desc"); descStr != "" {
desc = descStr != "false"
}
+ terms := orderTermsFromQuery(c, orderby, desc)
ctx := c.Request.Context()
- result, err := h.fileService.ListFiles(ctx, userID, parentID, page, pageSize, orderby, desc, keywords)
+ result, err := h.fileService.ListFiles(ctx, userID, parentID, page, pageSize, terms, keywords)
if err != nil {
jsonInternalError(c, err)
return
diff --git a/internal/handler/mcp_server.go b/internal/handler/mcp_server.go
index 0b1fc943b8..fc7275f496 100644
--- a/internal/handler/mcp_server.go
+++ b/internal/handler/mcp_server.go
@@ -26,6 +26,7 @@ import (
"github.com/gin-gonic/gin"
"ragflow/internal/common"
+ "ragflow/internal/dao"
"ragflow/internal/mcp"
"ragflow/internal/service"
dataset "ragflow/internal/service/dataset"
@@ -117,7 +118,7 @@ func (h *MCPServerHandler) HandleMCP(c *gin.Context) {
// filling in default values for parameters that the MCP tool does not expose.
func MCPListDatasets(ctx context.Context, ds *dataset.DatasetService, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {
data, total, _, err := ds.ListDatasets(ctx,
- "", "", page, pageSize, orderby, desc,
+ "", "", page, pageSize, []dao.OrderTerm{{Column: orderby, Desc: desc}},
"", nil, "", userID, nil,
)
return data, total, err
@@ -126,7 +127,7 @@ func MCPListDatasets(ctx context.Context, ds *dataset.DatasetService, userID str
// MCPListChats wraps ChatService.ListChats for the MCP tool handler,
// converting the typed response into a generic []map[string]interface{}.
func MCPListChats(ctx context.Context, chatService *service.ChatService, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {
- resp, err := chatService.ListChats(ctx, userID, "1", "", page, pageSize, orderby, desc, nil)
+ resp, err := chatService.ListChats(ctx, userID, "1", "", page, pageSize, []dao.OrderTerm{{Column: orderby, Desc: desc}}, nil)
if err != nil {
return nil, 0, err
}
@@ -178,7 +179,7 @@ func MCPRetrieval(ctx context.Context, ds *dataset.DatasetService, userID string
const maxPageSize = 100
ids, err := fetchAllDatasetIDs(func(page, pageSize int) ([]map[string]interface{}, int64, error) {
data, total, _, err := ds.ListDatasets(ctx,
- "", "", page, pageSize, "create_time", true,
+ "", "", page, pageSize, []dao.OrderTerm{{Column: "create_time", Desc: true}},
"", nil, "", userID, nil,
)
return data, total, err
diff --git a/internal/handler/order_terms_test.go b/internal/handler/order_terms_test.go
new file mode 100644
index 0000000000..15daf1b9ff
--- /dev/null
+++ b/internal/handler/order_terms_test.go
@@ -0,0 +1,110 @@
+package handler
+
+import (
+ "net/http/httptest"
+ "testing"
+
+ "ragflow/internal/dao"
+
+ "github.com/gin-gonic/gin"
+)
+
+func termsForQuery(t *testing.T, rawQuery, orderby string, desc bool) []dao.OrderTerm {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest("GET", "/v1/list?"+rawQuery, nil)
+ return orderTermsFromQuery(c, orderby, desc)
+}
+
+func TestOrderTermsFromQuery(t *testing.T) {
+ cases := []struct {
+ name string
+ rawQuery string
+ orderby string
+ desc bool
+ want []dao.OrderTerm
+ }{
+ {
+ name: "sort carries several columns with their own directions",
+ rawQuery: "sort=name:asc,create_time:desc",
+ orderby: "create_time",
+ desc: true,
+ want: []dao.OrderTerm{{Column: "name"}, {Column: "create_time", Desc: true}},
+ },
+ {
+ name: "sort wins over the older pair",
+ rawQuery: "sort=name:asc&orderby=update_time&desc=true",
+ orderby: "update_time",
+ desc: true,
+ want: []dao.OrderTerm{{Column: "name"}},
+ },
+ {
+ name: "the older pair still orders on its own",
+ rawQuery: "orderby=update_time&desc=false",
+ orderby: "update_time",
+ want: []dao.OrderTerm{{Column: "update_time"}},
+ },
+ {
+ // The column is kept here and dropped by the entity allowlist, which is
+ // where a name the list does not order by has always been answered.
+ name: "an unknown column is carried rather than rejected",
+ rawQuery: "sort=nonsense:asc",
+ orderby: "create_time",
+ desc: true,
+ want: []dao.OrderTerm{{Column: "nonsense"}},
+ },
+ {
+ name: "a sort with nothing usable falls back to the older pair",
+ rawQuery: "sort=:asc,&orderby=name&desc=true",
+ orderby: "name",
+ desc: true,
+ want: []dao.OrderTerm{{Column: "name", Desc: true}},
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := termsForQuery(t, tc.rawQuery, tc.orderby, tc.desc)
+ if len(got) != len(tc.want) {
+ t.Fatalf("orderTermsFromQuery(%q) = %+v, want %+v", tc.rawQuery, got, tc.want)
+ }
+ for i := range got {
+ if got[i] != tc.want[i] {
+ t.Fatalf("orderTermsFromQuery(%q)[%d] = %+v, want %+v", tc.rawQuery, i, got[i], tc.want[i])
+ }
+ }
+ })
+ }
+}
+
+// A handler that rejects an unrecognised `orderby` reads the sort terms first, so
+// this is the signal it gates that check on.
+func TestSortTermsFromQuerySignalsWhoDecides(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ newContext := func(rawQuery string) *gin.Context {
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest("GET", "/v1/list?"+rawQuery, nil)
+ return c
+ }
+
+ if terms := sortTermsFromQuery(newContext("orderby=nonsense&desc=maybe")); len(terms) != 0 {
+ t.Fatalf("a request without sort reported terms: %+v", terms)
+ }
+ if terms := sortTermsFromQuery(newContext("sort=:asc,")); len(terms) != 0 {
+ t.Fatalf("an unusable sort reported terms: %+v", terms)
+ }
+ terms := sortTermsFromQuery(newContext("sort=name:desc&orderby=nonsense"))
+ if len(terms) != 1 || terms[0] != (dao.OrderTerm{Column: "name", Desc: true}) {
+ t.Fatalf("sort terms = %+v, want one name DESC term", terms)
+ }
+
+ // The same terms decide the order, and the older pair is only read without them.
+ if got := orderTerms(terms, "create_time", false); len(got) != 1 || got[0] != terms[0] {
+ t.Fatalf("orderTerms dropped the sort terms: %+v", got)
+ }
+ got := orderTerms(nil, "create_time", true)
+ if len(got) != 1 || got[0] != (dao.OrderTerm{Column: "create_time", Desc: true}) {
+ t.Fatalf("orderTerms = %+v, want the older pair", got)
+ }
+}
diff --git a/internal/handler/search.go b/internal/handler/search.go
index df4c371cbb..12b6cebfb9 100644
--- a/internal/handler/search.go
+++ b/internal/handler/search.go
@@ -78,6 +78,7 @@ func getOwnerIDs(c *gin.Context) []string {
// @Param page query int false "page number"
// @Param page_size query int false "items per page"
// @Param orderby query string false "order by field (default: create_time)"
+// @Param sort query string false "ordered terms, column:direction separated by commas, such as name:asc,create_time:desc. Takes precedence over orderby and desc"
// @Param desc query bool false "descending order (default: true)"
// @Param owner_ids query []string false "owner IDs"
// @Success 200 {object} service.ListSearchAppsResponse
@@ -113,6 +114,7 @@ func (h *SearchHandler) ListSearches(c *gin.Context) {
if descStr := c.Query("desc"); descStr != "" {
desc = descStr != "false"
}
+ terms := orderTermsFromQuery(c, orderby, desc)
ownerIDs := getOwnerIDs(c)
@@ -129,7 +131,7 @@ func (h *SearchHandler) ListSearches(c *gin.Context) {
// List search apps with filtering
ctx := c.Request.Context()
- result, err := h.searchService.ListSearches(ctx, userID, keywords, page, pageSize, orderby, desc, ownerIDs)
+ result, err := h.searchService.ListSearches(ctx, userID, keywords, page, pageSize, terms, ownerIDs)
if err != nil {
common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, 500, nil, err.Error())
return
diff --git a/internal/service/agent.go b/internal/service/agent.go
index 21dc2300bf..a4874c953a 100644
--- a/internal/service/agent.go
+++ b/internal/service/agent.go
@@ -613,7 +613,7 @@ func toAgentItem(c *dao.UserCanvasListItem) *AgentItem {
// ListAgents returns agent canvases visible to userID.
// Mirrors Python agent_api.list_agents — validates owner_ids against joined tenants,
// then delegates to the DAO.
-func (s *AgentService) ListAgents(ctx context.Context, userID string, keywords string, page, pageSize int, orderBy string, desc bool, ownerIDs []string, canvasCategory, canvasType string, tags []string) (*ListAgentsResponse, common.ErrorCode, error) {
+func (s *AgentService) ListAgents(ctx context.Context, userID string, keywords string, page, pageSize int, terms []dao.OrderTerm, ownerIDs []string, canvasCategory, canvasType string, tags []string) (*ListAgentsResponse, common.ErrorCode, error) {
// Build the set of tenant IDs the user is authorized to query.
tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
@@ -658,7 +658,7 @@ func (s *AgentService) ListAgents(ctx context.Context, userID string, keywords s
if !sliceContains(effectiveOwnerIDs, userID) {
return &ListAgentsResponse{Canvas: []json.RawMessage{}, Total: 0}, common.CodeSuccess, nil
}
- return s.listAgentsGroupsOnly(ctx, userID, keywords, orderBy, desc, page, pageSize)
+ return s.listAgentsGroupsOnly(ctx, userID, keywords, terms, page, pageSize)
}
// Fetch agents. In merge/mixed modes we disable SQL pagination (page=0) and
@@ -674,8 +674,7 @@ func (s *AgentService) ListAgents(ctx context.Context, userID string, keywords s
userID,
listPage,
listSize,
- orderBy,
- desc,
+ terms,
keywords,
agentCategories,
canvasType,
@@ -696,7 +695,7 @@ func (s *AgentService) ListAgents(ctx context.Context, userID string, keywords s
// (Python include_template_groups).
includeGroups := sliceContains(effectiveOwnerIDs, userID)
if includeGroups && (mergeMode || wantsGroups) {
- return s.mergeAgentsAndGroups(ctx, userID, agentItems, keywords, orderBy, desc, page, pageSize)
+ return s.mergeAgentsAndGroups(ctx, userID, agentItems, keywords, terms, page, pageSize)
}
raw := make([]json.RawMessage, len(agentItems))
@@ -709,8 +708,8 @@ func (s *AgentService) ListAgents(ctx context.Context, userID string, keywords s
// listAgentsGroupsOnly returns only the caller's compilation template groups
// (Python canvas_category == ["compilation_template_group"] branch).
-func (s *AgentService) listAgentsGroupsOnly(ctx context.Context, userID, keywords, orderBy string, desc bool, page, pageSize int) (*ListAgentsResponse, common.ErrorCode, error) {
- groups, err := s.compilationTemplateGroupDAO.ListOwnedSaved(ctx, dao.DB, userID, keywords, "", orderBy, desc)
+func (s *AgentService) listAgentsGroupsOnly(ctx context.Context, userID, keywords string, terms []dao.OrderTerm, page, pageSize int) (*ListAgentsResponse, common.ErrorCode, error) {
+ groups, err := s.compilationTemplateGroupDAO.ListOwnedSaved(ctx, dao.DB, userID, keywords, "", terms)
if err != nil {
return nil, common.CodeServerError, fmt.Errorf("failed to list compilation template groups: %w", err)
}
@@ -731,8 +730,8 @@ func (s *AgentService) listAgentsGroupsOnly(ctx context.Context, userID, keyword
// groups into a single list ordered by update_time, then pages in Go. This
// mirrors Python's merged /agents response. A stable sort retains the original
// agent-before-group order when timestamps are equal.
-func (s *AgentService) mergeAgentsAndGroups(ctx context.Context, userID string, agentItems []*AgentItem, keywords, orderBy string, desc bool, page, pageSize int) (*ListAgentsResponse, common.ErrorCode, error) {
- groups, err := s.compilationTemplateGroupDAO.ListOwnedSaved(ctx, dao.DB, userID, keywords, "", orderBy, desc)
+func (s *AgentService) mergeAgentsAndGroups(ctx context.Context, userID string, agentItems []*AgentItem, keywords string, terms []dao.OrderTerm, page, pageSize int) (*ListAgentsResponse, common.ErrorCode, error) {
+ groups, err := s.compilationTemplateGroupDAO.ListOwnedSaved(ctx, dao.DB, userID, keywords, "", terms)
if err != nil {
return nil, common.CodeServerError, fmt.Errorf("failed to list compilation template groups: %w", err)
}
@@ -754,8 +753,11 @@ func (s *AgentService) mergeAgentsAndGroups(ctx context.Context, userID string,
time: intValuePtr(g.UpdateTime),
})
}
+ // The merge orders by update time whatever column was asked for, so it takes
+ // the direction from the first term the way the fallback clause does.
+ descending := len(terms) > 0 && terms[0].Desc
sort.SliceStable(merged, func(i, j int) bool {
- if desc {
+ if descending {
return merged[i].time > merged[j].time
}
return merged[i].time < merged[j].time
diff --git a/internal/service/agent_test.go b/internal/service/agent_test.go
index 3d13a3004a..005dca3211 100644
--- a/internal/service/agent_test.go
+++ b/internal/service/agent_test.go
@@ -1902,7 +1902,7 @@ func TestListAgentsIncludesReleaseTime(t *testing.T) {
t.Fatalf("failed to seed released version: %v", err)
}
ctx := t.Context()
- resp, code, err := NewAgentService().ListAgents(ctx, "user-1", "", 1, 30, "create_time", true, nil, "", "", nil)
+ resp, code, err := NewAgentService().ListAgents(ctx, "user-1", "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil, "", "", nil)
if err != nil || code != common.CodeSuccess {
t.Fatalf("ListAgents failed: code=%v err=%v", code, err)
}
@@ -1952,7 +1952,7 @@ func TestListAgents_MultiCategoryFilter(t *testing.T) {
}
ctx := t.Context()
- resp, code, err := NewAgentService().ListAgents(ctx, "user-1", "", 1, 30, "create_time", true, nil, "dataflow_canvas,agent_canvas", "", nil)
+ resp, code, err := NewAgentService().ListAgents(ctx, "user-1", "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil, "dataflow_canvas,agent_canvas", "", nil)
if err != nil || code != common.CodeSuccess {
t.Fatalf("ListAgents failed: code=%v err=%v", code, err)
}
@@ -1960,7 +1960,7 @@ func TestListAgents_MultiCategoryFilter(t *testing.T) {
t.Fatalf("multi-category filter returned total=%d rows=%d, want 3/3", resp.Total, len(resp.Canvas))
}
- single, code, err := NewAgentService().ListAgents(ctx, "user-1", "", 1, 30, "create_time", true, nil, "agent_canvas", "", nil)
+ single, code, err := NewAgentService().ListAgents(ctx, "user-1", "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil, "agent_canvas", "", nil)
if err != nil || code != common.CodeSuccess {
t.Fatalf("ListAgents (single category) failed: code=%v err=%v", code, err)
}
@@ -2001,7 +2001,7 @@ func TestListAgents_MergesCompilationTemplateGroups(t *testing.T) {
t.Fatalf("failed to seed builtin group: %v", err)
}
- resp, code, err := NewAgentService().ListAgents(t.Context(), "user-1", "", 1, 30, "create_time", true, nil, "", "", nil)
+ resp, code, err := NewAgentService().ListAgents(t.Context(), "user-1", "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil, "", "", nil)
if err != nil || code != common.CodeSuccess {
t.Fatalf("ListAgents failed: code=%v err=%v", code, err)
}
diff --git a/internal/service/chat.go b/internal/service/chat.go
index 449314a6bf..ee804e2e85 100644
--- a/internal/service/chat.go
+++ b/internal/service/chat.go
@@ -79,7 +79,7 @@ type ListChatsResponse struct {
}
// ListChats list chats for a user
-func (s *ChatService) ListChats(ctx context.Context, userID, status, keywords string, page, pageSize int, orderBy string, desc bool, ownerIDs []string) (*ListChatsResponse, error) {
+func (s *ChatService) ListChats(ctx context.Context, userID, status, keywords string, page, pageSize int, terms []dao.OrderTerm, ownerIDs []string) (*ListChatsResponse, error) {
var chats []*entity.ChatListItem
var total int64
var err error
@@ -92,8 +92,7 @@ func (s *ChatService) ListChats(ctx context.Context, userID, status, keywords st
userID,
page,
pageSize,
- orderBy,
- desc,
+ terms,
keywords,
)
if err != nil {
@@ -112,7 +111,7 @@ func (s *ChatService) ListChats(ctx context.Context, userID, status, keywords st
}, nil
}
- chats, total, err = s.chatDAO.ListByOwnerIDs(ctx, dao.DB, filterOwnerIDs, userID, orderBy, desc, keywords)
+ chats, total, err = s.chatDAO.ListByOwnerIDs(ctx, dao.DB, filterOwnerIDs, userID, terms, keywords)
if err != nil {
return nil, err
}
diff --git a/internal/service/chat_list_test.go b/internal/service/chat_list_test.go
index fc9ab5e356..bffd266a0a 100644
--- a/internal/service/chat_list_test.go
+++ b/internal/service/chat_list_test.go
@@ -83,7 +83,7 @@ func TestChatServiceListChatsDefaultReturnsAllWithCorrectTotal(t *testing.T) {
svc := NewChatService()
ctx := t.Context()
- result, err := svc.ListChats(ctx, "user-1", "1", "", 0, 0, "create_time", true, nil)
+ result, err := svc.ListChats(ctx, "user-1", "1", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats failed: %v", err)
}
@@ -125,7 +125,7 @@ func TestChatServiceListChatsFiltersByOwnerIDs(t *testing.T) {
svc := NewChatService()
ctx := t.Context()
- result, err := svc.ListChats(ctx, "user-1", "1", "", 0, 0, "create_time", true, []string{"tenant-2"})
+ result, err := svc.ListChats(ctx, "user-1", "1", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, []string{"tenant-2"})
if err != nil {
t.Fatalf("ListChats failed: %v", err)
}
@@ -149,7 +149,7 @@ func TestChatServiceListChatsKeywordFiltersCorrectly(t *testing.T) {
svc := NewChatService()
ctx := t.Context()
- exactResult, err := svc.ListChats(ctx, "user-1", "1", "list_keyword_1", 0, 0, "create_time", true, nil)
+ exactResult, err := svc.ListChats(ctx, "user-1", "1", "list_keyword_1", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats keyword exact failed: %v", err)
}
@@ -160,7 +160,7 @@ func TestChatServiceListChatsKeywordFiltersCorrectly(t *testing.T) {
t.Fatalf("expected chat name 'list_keyword_1', got %+v", exactResult.Chats[0].Name)
}
- unknownResult, err := svc.ListChats(ctx, "user-1", "1", "unknown_keyword", 0, 0, "create_time", true, nil)
+ unknownResult, err := svc.ListChats(ctx, "user-1", "1", "unknown_keyword", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats unknown keyword failed: %v", err)
}
@@ -168,7 +168,7 @@ func TestChatServiceListChatsKeywordFiltersCorrectly(t *testing.T) {
t.Fatalf("expected 0 chats for unknown keyword, got %d", len(unknownResult.Chats))
}
- partialResult, err := svc.ListChats(ctx, "user-1", "1", "list_keyword", 0, 0, "create_time", true, nil)
+ partialResult, err := svc.ListChats(ctx, "user-1", "1", "list_keyword", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats partial keyword failed: %v", err)
}
@@ -186,7 +186,7 @@ func TestChatServiceListChatsPagination(t *testing.T) {
svc := NewChatService()
ctx := t.Context()
- page1, err := svc.ListChats(ctx, "user-1", "1", "", 1, 2, "create_time", true, nil)
+ page1, err := svc.ListChats(ctx, "user-1", "1", "", 1, 2, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats page 1 failed: %v", err)
}
@@ -197,7 +197,7 @@ func TestChatServiceListChatsPagination(t *testing.T) {
t.Fatalf("expected total=5, got %d", page1.Total)
}
- page3, err := svc.ListChats(ctx, "user-1", "1", "", 3, 2, "create_time", true, nil)
+ page3, err := svc.ListChats(ctx, "user-1", "1", "", 3, 2, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats page 3 failed: %v", err)
}
@@ -216,7 +216,7 @@ func TestChatServiceListChatsExcludesDeletedChats(t *testing.T) {
svc := NewChatService()
ctx := t.Context()
- result, err := svc.ListChats(ctx, "user-1", "1", "", 0, 0, "create_time", true, nil)
+ result, err := svc.ListChats(ctx, "user-1", "1", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats failed: %v", err)
}
diff --git a/internal/service/chat_session.go b/internal/service/chat_session.go
index 67a54d3b93..386dc8966b 100644
--- a/internal/service/chat_session.go
+++ b/internal/service/chat_session.go
@@ -47,7 +47,7 @@ type chatSessionStore interface {
Create(ctx context.Context, db *gorm.DB, conv *entity.ChatSession) error
UpdateByID(ctx context.Context, db *gorm.DB, id string, updates map[string]interface{}) error
DeleteByID(ctx context.Context, db *gorm.DB, id string) error
- ListByChatID(ctx context.Context, db *gorm.DB, chatID, sessionID, name, orderby string, desc bool, page, pageSize int, includeHistory ...bool) ([]*entity.ChatSession, error)
+ ListByChatID(ctx context.Context, db *gorm.DB, chatID, sessionID, name string, terms []dao.OrderTerm, page, pageSize int, includeHistory ...bool) ([]*entity.ChatSession, error)
GetDialogByID(ctx context.Context, db *gorm.DB, chatID string) (*entity.Chat, error)
CheckDialogExists(ctx context.Context, db *gorm.DB, tenantID, chatID string) (bool, error)
}
@@ -244,7 +244,7 @@ type ChatSessionPayload struct {
}
// ListChatSessions lists chat sessions for a dialog
-func (s *ChatSessionService) ListChatSessions(ctx context.Context, userID, chatID, sessionID, name, orderby string, desc bool, page, pageSize int, includeHistory ...bool) (*ListChatSessionsResponse, error) {
+func (s *ChatSessionService) ListChatSessions(ctx context.Context, userID, chatID, sessionID, name string, terms []dao.OrderTerm, page, pageSize int, includeHistory ...bool) (*ListChatSessionsResponse, error) {
// Get user's tenants
tenantIDs, err := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID)
if err != nil {
@@ -285,7 +285,7 @@ func (s *ChatSessionService) ListChatSessions(ctx context.Context, userID, chatI
}
// List chat sessions
- sessions, err := s.chatSessionDAO.ListByChatID(ctx, dao.DB, chatID, sessionID, name, orderby, desc, page, pageSize, includeHistory...)
+ sessions, err := s.chatSessionDAO.ListByChatID(ctx, dao.DB, chatID, sessionID, name, terms, page, pageSize, includeHistory...)
if err != nil {
return nil, err
}
@@ -407,7 +407,7 @@ func (s *ChatSessionService) DeleteSessions(ctx context.Context, userID, chatID
if !hasIDs || len(sessionIDs) == 0 {
deleteAll, _ := req["delete_all"].(bool)
if deleteAll {
- sessions, err := s.chatSessionDAO.ListByChatID(ctx, dao.DB, chatID, "", "", "create_time", true, 0, -1, false)
+ sessions, err := s.chatSessionDAO.ListByChatID(ctx, dao.DB, chatID, "", "", []dao.OrderTerm{{Column: "create_time", Desc: true}}, 0, -1, false)
if err != nil {
return nil, "", common.CodeServerError, err
}
diff --git a/internal/service/chat_session_test.go b/internal/service/chat_session_test.go
index 5ec3620a6a..a18ebe3ce8 100644
--- a/internal/service/chat_session_test.go
+++ b/internal/service/chat_session_test.go
@@ -163,7 +163,7 @@ func (f *fakeSessionStore) DeleteByID(ctx context.Context, db *gorm.DB, id strin
return nil
}
-func (f *fakeSessionStore) ListByChatID(ctx context.Context, db *gorm.DB, chatID, sessionID, name, orderby string, desc bool, page, pageSize int, includeHistory ...bool) ([]*entity.ChatSession, error) {
+func (f *fakeSessionStore) ListByChatID(ctx context.Context, db *gorm.DB, chatID, sessionID, name string, terms []dao.OrderTerm, page, pageSize int, includeHistory ...bool) ([]*entity.ChatSession, error) {
var result []*entity.ChatSession
for _, s := range f.sessions {
if s.DialogID != chatID {
@@ -351,7 +351,7 @@ func TestListChatSessions_Success(t *testing.T) {
}
ctx := t.Context()
- resp, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", "create_time", true, 1, 30)
+ resp, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", []dao.OrderTerm{{Column: "create_time", Desc: true}}, 1, 30)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -370,7 +370,7 @@ func TestListChatSessions_NotOwner(t *testing.T) {
}
ctx := t.Context()
- _, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", "create_time", true, 1, 30)
+ _, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", []dao.OrderTerm{{Column: "create_time", Desc: true}}, 1, 30)
if err == nil || !strings.Contains(err.Error(), "no authorization") {
t.Fatalf("got %v", err)
}
diff --git a/internal/service/compilation_template_group_service.go b/internal/service/compilation_template_group_service.go
index 2d6bc4bdd6..50714c5a4e 100644
--- a/internal/service/compilation_template_group_service.go
+++ b/internal/service/compilation_template_group_service.go
@@ -91,8 +91,8 @@ type GroupListItem struct {
// ListSaved returns the tenant's groups with nested templates. Mirrors Python
// list_saved(). total is derived from the full (unpaginated) result set.
-func (s *CompilationTemplateGroupService) ListSaved(ctx context.Context, tenantID, keywords, scope, orderby string, desc bool) ([]*GroupListItem, error) {
- groups, err := s.groupDAO.ListSaved(ctx, dao.DB, tenantID, keywords, scope, orderby, desc)
+func (s *CompilationTemplateGroupService) ListSaved(ctx context.Context, tenantID, keywords, scope string, terms []dao.OrderTerm) ([]*GroupListItem, error) {
+ groups, err := s.groupDAO.ListSaved(ctx, dao.DB, tenantID, keywords, scope, terms)
if err != nil {
return nil, err
}
diff --git a/internal/service/dataset/crud.go b/internal/service/dataset/crud.go
index 263e9ee339..5dde0eeddb 100644
--- a/internal/service/dataset/crud.go
+++ b/internal/service/dataset/crud.go
@@ -346,7 +346,7 @@ func (d *DatasetService) deleteDataset(ctx context.Context, tenantID string, kb
})
}
-func (d *DatasetService) ListDatasets(ctx context.Context, id, name string, page, pageSize int, orderby string, desc bool, keywords string, ownerIDs []string, parserID, userID string, ids []string) ([]map[string]interface{}, int64, common.ErrorCode, error) {
+func (d *DatasetService) ListDatasets(ctx context.Context, id, name string, page, pageSize int, terms []dao.OrderTerm, keywords string, ownerIDs []string, parserID, userID string, ids []string) ([]map[string]interface{}, int64, common.ErrorCode, error) {
id = strings.TrimSpace(id)
if id != "" && len(ids) > 0 {
return nil, 0, common.CodeDataError, fmt.Errorf("should not provide both 'id':%s and 'ids':%s", id, pythonStringListRepr(ids))
@@ -385,10 +385,7 @@ func (d *DatasetService) ListDatasets(ctx context.Context, id, name string, page
pageSize = 30
}
- orderby = strings.TrimSpace(orderby)
- if _, ok := datasetAllowedOrderByFields[orderby]; !ok {
- orderby = "create_time"
- }
+ terms = keepDatasetOrderTerms(terms)
keywords = strings.TrimSpace(keywords)
parserID = strings.TrimSpace(parserID)
@@ -463,7 +460,7 @@ func (d *DatasetService) ListDatasets(ctx context.Context, id, name string, page
}
}
- kbs, total, err := d.kbDAO.GetByTenantIDs(ctx, dao.DB, tenantIDs, queryUserID, page, pageSize, orderby, desc, keywords, parserID, id, name, ids)
+ kbs, total, err := d.kbDAO.GetByTenantIDs(ctx, dao.DB, tenantIDs, queryUserID, page, pageSize, terms, keywords, parserID, id, name, ids)
if err != nil {
return nil, 0, common.CodeServerError, errors.New("database operation failed")
}
diff --git a/internal/service/dataset/helpers.go b/internal/service/dataset/helpers.go
index 340692fee1..8dadf4edda 100644
--- a/internal/service/dataset/helpers.go
+++ b/internal/service/dataset/helpers.go
@@ -16,6 +16,24 @@ import (
"github.com/google/uuid"
)
+// keepDatasetOrderTerms narrows the requested terms to the columns the dataset
+// list has always accepted, which is a smaller set than the knowledge base row
+// exposes. A list with nothing left falls back to create_time in the first
+// requested direction, which is what an unrecognised single name did.
+func keepDatasetOrderTerms(terms []dao.OrderTerm) []dao.OrderTerm {
+ kept := make([]dao.OrderTerm, 0, len(terms))
+ for _, term := range terms {
+ column := strings.TrimSpace(term.Column)
+ if _, ok := datasetAllowedOrderByFields[column]; ok {
+ kept = append(kept, dao.OrderTerm{Column: column, Desc: term.Desc})
+ }
+ }
+ if len(kept) == 0 {
+ return []dao.OrderTerm{{Column: "create_time", Desc: len(terms) > 0 && terms[0].Desc}}
+ }
+ return kept
+}
+
// Package-level vars and constants used by the dataset service.
var (
datasetSupportedAvatarMIMETypes = map[string]struct{}{
diff --git a/internal/service/dataset/ingestion.go b/internal/service/dataset/ingestion.go
index e7a68eac9c..d64e170686 100644
--- a/internal/service/dataset/ingestion.go
+++ b/internal/service/dataset/ingestion.go
@@ -39,7 +39,7 @@ func (d *DatasetService) GetIngestionSummary(ctx context.Context, datasetID, use
}, common.CodeSuccess, nil
}
-func (d *DatasetService) ListIngestionLogs(ctx context.Context, datasetID, userID string, page, pageSize int, orderby string, desc bool, operationStatus []string, createDateFrom, createDateTo, logType, keywords, documentID string) (map[string]interface{}, common.ErrorCode, error) {
+func (d *DatasetService) ListIngestionLogs(ctx context.Context, datasetID, userID string, page, pageSize int, terms []dao.OrderTerm, operationStatus []string, createDateFrom, createDateTo, logType, keywords, documentID string) (map[string]interface{}, common.ErrorCode, error) {
if datasetID == "" {
return nil, common.CodeDataError, errors.New(`lack of "Dataset ID"`)
}
@@ -53,9 +53,6 @@ func (d *DatasetService) ListIngestionLogs(ctx context.Context, datasetID, userI
if pageSize <= 0 {
pageSize = 30
}
- if orderby == "" {
- orderby = "create_time"
- }
var (
logs []*entity.PipelineOperationLog
@@ -63,9 +60,9 @@ func (d *DatasetService) ListIngestionLogs(ctx context.Context, datasetID, userI
err error
)
if logType == "file" {
- logs, total, err = d.pipelineLogDAO.GetFileLogsByKBID(ctx, dao.DB, datasetID, page, pageSize, orderby, desc, keywords, documentID, operationStatus, createDateFrom, createDateTo)
+ logs, total, err = d.pipelineLogDAO.GetFileLogsByKBID(ctx, dao.DB, datasetID, page, pageSize, terms, keywords, documentID, operationStatus, createDateFrom, createDateTo)
} else {
- logs, total, err = d.pipelineLogDAO.GetDatasetLogsByKBID(ctx, dao.DB, datasetID, page, pageSize, orderby, desc, operationStatus, createDateFrom, createDateTo, keywords, documentID)
+ logs, total, err = d.pipelineLogDAO.GetDatasetLogsByKBID(ctx, dao.DB, datasetID, page, pageSize, terms, operationStatus, createDateFrom, createDateTo, keywords, documentID)
}
if err != nil {
return nil, common.CodeServerError, fmt.Errorf("list ingestion logs: %w", err)
diff --git a/internal/service/dataset/list_test.go b/internal/service/dataset/list_test.go
index c43e1b7d90..46ce3265d1 100644
--- a/internal/service/dataset/list_test.go
+++ b/internal/service/dataset/list_test.go
@@ -27,7 +27,7 @@ func TestDatasetServiceListDatasetsFiltersByIDs(t *testing.T) {
ctx := t.Context()
data, total, code, err := testDatasetListService(t).ListDatasets(ctx,
- "", "", 1, 30, "create_time", true,
+ "", "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}},
"", nil, "", "tenant-1", []string{"kb-1"},
)
if err != nil {
@@ -60,7 +60,7 @@ func TestDatasetServiceListDatasetsIDsAccessibleViaTeamTenant(t *testing.T) {
ctx := t.Context()
data, total, code, err := testDatasetListService(t).ListDatasets(ctx,
- "", "", 1, 30, "create_time", true,
+ "", "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}},
"", nil, "", "user-1", []string{"kb-team"},
)
if err != nil {
@@ -81,7 +81,7 @@ func TestDatasetServiceListDatasetsRejectsIDAndIDsTogether(t *testing.T) {
ctx := t.Context()
_, _, code, err := testDatasetListService(t).ListDatasets(ctx,
- "kb-1", "", 1, 30, "create_time", true,
+ "kb-1", "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}},
"", nil, "", "tenant-1", []string{"kb-1"},
)
if err == nil {
@@ -103,7 +103,7 @@ func TestDatasetServiceListDatasetsRejectsDeniedIDs(t *testing.T) {
ctx := t.Context()
_, _, code, err := testDatasetListService(t).ListDatasets(ctx,
- "", "", 1, 30, "create_time", true,
+ "", "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}},
"", nil, "", "user-1", []string{"kb-private"},
)
if err == nil {
diff --git a/internal/service/file/file_folder.go b/internal/service/file/file_folder.go
index 918079cf0f..edae130eff 100644
--- a/internal/service/file/file_folder.go
+++ b/internal/service/file/file_folder.go
@@ -24,7 +24,7 @@ func (s *FileService) GetRootFolder(ctx context.Context, tenantID string) (map[s
// ListFiles lists files by parent folder ID (matching Python /files endpoint)
// This method includes init_dataset_docs initialization when parent_id is empty
-func (s *FileService) ListFiles(ctx context.Context, tenantID, pfID string, page, pageSize int, orderby string, desc bool, keywords string) (*ListFilesResponse, error) {
+func (s *FileService) ListFiles(ctx context.Context, tenantID, pfID string, page, pageSize int, terms []dao.OrderTerm, keywords string) (*ListFilesResponse, error) {
// If pfID is empty, get root folder and initialize dataset docs
if pfID == "" {
rootFolder, err := s.fileDAO.GetRootFolder(ctx, dao.DB, tenantID)
@@ -52,7 +52,7 @@ func (s *FileService) ListFiles(ctx context.Context, tenantID, pfID string, page
// Get files by parent folder ID
excludeSkills := folder.ID == folder.ParentID
- files, total, err := s.fileDAO.GetByPfID(ctx, dao.DB, tenantID, pfID, page, pageSize, orderby, desc, keywords, excludeSkills)
+ files, total, err := s.fileDAO.GetByPfID(ctx, dao.DB, tenantID, pfID, page, pageSize, terms, keywords, excludeSkills)
if err != nil {
return nil, err
}
diff --git a/internal/service/search.go b/internal/service/search.go
index 0e965c505d..eaaebf67cc 100644
--- a/internal/service/search.go
+++ b/internal/service/search.go
@@ -80,13 +80,13 @@ type SearchShareDetail struct {
}
// ListSearches list search apps with advanced filtering (equivalent to list_search_app)
-func (s *SearchService) ListSearches(ctx context.Context, userID string, keywords string, page, pageSize int, orderby string, desc bool, ownerIDs []string) (*ListSearchAppsResponse, error) {
+func (s *SearchService) ListSearches(ctx context.Context, userID string, keywords string, page, pageSize int, terms []dao.OrderTerm, ownerIDs []string) (*ListSearchAppsResponse, error) {
var searches []*entity.SearchListItem
var total int64
var err error
if len(ownerIDs) == 0 {
- searches, total, err = s.searchDAO.ListByTenantIDs(ctx, dao.DB, nil, userID, page, pageSize, orderby, desc, keywords)
+ searches, total, err = s.searchDAO.ListByTenantIDs(ctx, dao.DB, nil, userID, page, pageSize, terms, keywords)
if err != nil {
return nil, err
}
@@ -102,7 +102,7 @@ func (s *SearchService) ListSearches(ctx context.Context, userID string, keyword
}, nil
}
- searches, total, err = s.searchDAO.ListByOwnerIDs(ctx, dao.DB, ownerIDs, userID, orderby, desc, keywords)
+ searches, total, err = s.searchDAO.ListByOwnerIDs(ctx, dao.DB, ownerIDs, userID, terms, keywords)
if err != nil {
return nil, err
}
diff --git a/internal/service/search_test.go b/internal/service/search_test.go
index 31b7608a29..4a474dd613 100644
--- a/internal/service/search_test.go
+++ b/internal/service/search_test.go
@@ -138,7 +138,7 @@ func TestSearchServiceListSearchesReturnsOwnerDisplayFields(t *testing.T) {
createSearchServiceTestSearch(t, "search-1", "user-1", "Search One")
ctx := t.Context()
- result, err := NewSearchService().ListSearches(ctx, "user-1", "", 0, 0, "create_time", true, nil)
+ result, err := NewSearchService().ListSearches(ctx, "user-1", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListSearches failed: %v", err)
}
@@ -156,7 +156,7 @@ func TestSearchServiceListSearchesNicknameFallsBackToTenantID(t *testing.T) {
createSearchServiceTestSearch(t, "search-1", "user-1", "Search One")
ctx := t.Context()
- result, err := NewSearchService().ListSearches(ctx, "user-1", "", 0, 0, "create_time", true, nil)
+ result, err := NewSearchService().ListSearches(ctx, "user-1", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListSearches failed: %v", err)
}
diff --git a/internal/service/skill_indexer.go b/internal/service/skill_indexer.go
index c7ce6d3620..0937785d37 100644
--- a/internal/service/skill_indexer.go
+++ b/internal/service/skill_indexer.go
@@ -681,7 +681,7 @@ func (s *SkillIndexerService) getSpaceFolderIDByName(ctx context.Context, tenant
}
// Find skills folder under root
- files, _, err := s.fileDAO.GetByPfID(ctx, dao.DB, tenantID, rootFolder.ID, 0, 0, "name", false, "", false)
+ files, _, err := s.fileDAO.GetByPfID(ctx, dao.DB, tenantID, rootFolder.ID, 0, 0, []dao.OrderTerm{{Column: "name"}}, "", false)
if err != nil {
return "", fmt.Errorf("failed to list root folder contents: %w", err)
}
@@ -699,7 +699,7 @@ func (s *SkillIndexerService) getSpaceFolderIDByName(ctx context.Context, tenant
}
// Find space folder by name under skills folder
- spaceFolders, _, err := s.fileDAO.GetByPfID(ctx, dao.DB, tenantID, skillsFolderID, 0, 0, "name", false, "", false)
+ spaceFolders, _, err := s.fileDAO.GetByPfID(ctx, dao.DB, tenantID, skillsFolderID, 0, 0, []dao.OrderTerm{{Column: "name"}}, "", false)
if err != nil {
return "", fmt.Errorf("failed to list skills folder contents: %w", err)
}
diff --git a/internal/service/skill_space.go b/internal/service/skill_space.go
index 0405cbc6f5..c69ed0133a 100644
--- a/internal/service/skill_space.go
+++ b/internal/service/skill_space.go
@@ -106,7 +106,7 @@ func (s *SkillSpaceService) getSkillsFolderID(ctx context.Context, tenantID stri
}
// Look for skills folder under root
- files, _, err := s.fileDAO.GetByPfID(ctx, dao.DB, tenantID, rootFolder.ID, 0, 0, "name", false, "", false)
+ files, _, err := s.fileDAO.GetByPfID(ctx, dao.DB, tenantID, rootFolder.ID, 0, 0, []dao.OrderTerm{{Column: "name"}}, "", false)
if err != nil {
return "", fmt.Errorf("failed to list root folder contents: %w", err)
}