refactor(api-keys): use role field and route-level API key guards
Replace scopes JSON with a viewer/contributor/admin role column, move unsafe-method authorization from path-prefix middleware to declarative APIKey* guards on routes, and close remaining KB-scope gaps in handlers.
This commit is contained in:
+16
-16
@@ -62,35 +62,35 @@ type TenantListResponse struct {
|
|||||||
} `json:"data"`
|
} `json:"data"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// TenantAPIKeyScope is an operation scope for revocable tenant API keys.
|
// TenantAPIKeyRole is the tenant RBAC role bound to a revocable API key.
|
||||||
type TenantAPIKeyScope string
|
type TenantAPIKeyRole string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
TenantAPIKeyScopeRead TenantAPIKeyScope = "read"
|
TenantAPIKeyRoleViewer TenantAPIKeyRole = "viewer"
|
||||||
TenantAPIKeyScopeWrite TenantAPIKeyScope = "write"
|
TenantAPIKeyRoleContributor TenantAPIKeyRole = "contributor"
|
||||||
TenantAPIKeyScopeAdmin TenantAPIKeyScope = "admin"
|
TenantAPIKeyRoleAdmin TenantAPIKeyRole = "admin"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TenantAPIKey is the API key metadata returned by list/create APIs.
|
// TenantAPIKey is the API key metadata returned by list/create APIs.
|
||||||
type TenantAPIKey struct {
|
type TenantAPIKey struct {
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
TenantID uint64 `json:"tenant_id"`
|
TenantID uint64 `json:"tenant_id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
APIKey string `json:"api_key"`
|
APIKey string `json:"api_key"`
|
||||||
Scopes []TenantAPIKeyScope `json:"scopes"`
|
Role TenantAPIKeyRole `json:"role"`
|
||||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
|
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
|
||||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateTenantAPIKeyRequest creates a scoped, revocable tenant API key.
|
// CreateTenantAPIKeyRequest creates a revocable tenant API key.
|
||||||
type CreateTenantAPIKeyRequest struct {
|
type CreateTenantAPIKeyRequest struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Scopes []TenantAPIKeyScope `json:"scopes,omitempty"`
|
Role TenantAPIKeyRole `json:"role,omitempty"`
|
||||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
|
KnowledgeBaseIDs []string `json:"knowledge_base_ids,omitempty"`
|
||||||
ExpiresAtUnix *int64 `json:"expires_at_unix,omitempty"`
|
ExpiresAtUnix *int64 `json:"expires_at_unix,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreatedTenantAPIKey includes the created API key. Token is kept for
|
// CreatedTenantAPIKey includes the created API key. Token is kept for
|
||||||
|
|||||||
+4
-4
@@ -17,7 +17,7 @@
|
|||||||
| DELETE | `/tenants/:id` | 删除租户 |
|
| DELETE | `/tenants/:id` | 删除租户 |
|
||||||
| POST | `/tenants/:id/api-key` | 重置租户 API Key(吊销该租户全部旧 Key 后创建一把新的全权限 Key) |
|
| POST | `/tenants/:id/api-key` | 重置租户 API Key(吊销该租户全部旧 Key 后创建一把新的全权限 Key) |
|
||||||
| GET | `/tenants/:id/api-keys` | 列出租户 API Key(Owner) |
|
| GET | `/tenants/:id/api-keys` | 列出租户 API Key(Owner) |
|
||||||
| POST | `/tenants/:id/api-keys` | 创建带 scope 的 API Key(Owner) |
|
| POST | `/tenants/:id/api-keys` | 创建带角色的 API Key(Owner) |
|
||||||
| DELETE | `/tenants/:id/api-keys/:key_id` | 吊销指定 API Key(Owner) |
|
| DELETE | `/tenants/:id/api-keys/:key_id` | 吊销指定 API Key(Owner) |
|
||||||
| GET | `/tenants/:id/api-principal-config` | 获取 API Key 用户身份配置(Owner) |
|
| GET | `/tenants/:id/api-principal-config` | 获取 API Key 用户身份配置(Owner) |
|
||||||
| PUT | `/tenants/:id/api-principal-config` | 更新 API Key 用户身份配置(Owner) |
|
| PUT | `/tenants/:id/api-principal-config` | 更新 API Key 用户身份配置(Owner) |
|
||||||
@@ -363,12 +363,12 @@ curl --location --request POST 'http://localhost:8080/api/v1/tenants/10000/api-k
|
|||||||
|
|
||||||
自 scoped API Key 改造后,密钥以独立记录存储,支持:
|
自 scoped API Key 改造后,密钥以独立记录存储,支持:
|
||||||
|
|
||||||
- **scopes**:`read`(只读 + 语义检索 POST)、`write`(知识库写入)、`admin`(租户级管理,不含 `/api-keys` 管理面)
|
- **role**:`viewer`(只读 + 语义检索 POST)、`contributor`(知识库写入)、`admin`(租户级管理,不含 `/api-keys` 管理面)
|
||||||
- **knowledge_base_ids**:可选,将 Key 限制在指定知识库
|
- **knowledge_base_ids**:可选,将 Key 限制在指定知识库
|
||||||
- **吊销**:`DELETE /tenants/:id/api-keys/:key_id`
|
- **吊销**:`DELETE /tenants/:id/api-keys/:key_id`
|
||||||
- **过期**:创建时可选 `expires_at_unix`
|
- **过期**:创建时可选 `expires_at_unix`
|
||||||
|
|
||||||
认证上下文中的租户角色由 scope 映射:`read` → Viewer,`write` → Contributor,`admin` → Admin。路由级 scope 校验与 KB 访问守卫在 `X-API-Key` 认证后强制执行。
|
认证上下文中的租户角色与 Key 的 `role` 一致(`viewer` / `contributor` / `admin`)。路由级 API Key 鉴权与 KB 访问守卫在 `X-API-Key` 认证后强制执行。
|
||||||
|
|
||||||
## API Key Principal:隔离边界与安全说明
|
## API Key Principal:隔离边界与安全说明
|
||||||
|
|
||||||
@@ -382,7 +382,7 @@ Principal **仅**用于按终端用户隔离以下能力:
|
|||||||
- **MCP OAuth** 访问令牌(同一租户下不同外部用户各自授权,token 互不共用)
|
- **MCP OAuth** 访问令牌(同一租户下不同外部用户各自授权,token 互不共用)
|
||||||
- 对话内 MCP OAuth 提示、MCP 工具审批等与终端用户绑定的流程
|
- 对话内 MCP OAuth 提示、MCP 工具审批等与终端用户绑定的流程
|
||||||
|
|
||||||
Principal **不会**缩小 API Key 的 HTTP 路由权限:路由访问由 Key 的 `scopes` 控制;租户内 RBAC 角色由 scope 映射为 Viewer / Contributor / Admin。知识库、Agent 等资源的细粒度访问另受 scope 与 KB 守卫约束。
|
Principal **不会**缩小 API Key 的 HTTP 路由权限:路由访问由 Key 的 `role` 控制;租户内 RBAC 角色与 `role` 一致。知识库、Agent 等资源的细粒度访问另受 KB 守卫约束。
|
||||||
|
|
||||||
### 模式与安全假设
|
### 模式与安全假设
|
||||||
|
|
||||||
|
|||||||
@@ -48,13 +48,13 @@ export interface APIPrincipalTestToken {
|
|||||||
external_user_id: string
|
external_user_id: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export type TenantAPIKeyScope = 'read' | 'write' | 'admin'
|
export type TenantAPIKeyRole = 'viewer' | 'contributor' | 'admin'
|
||||||
|
|
||||||
export interface TenantAPIKey {
|
export interface TenantAPIKey {
|
||||||
id: number
|
id: number
|
||||||
name: string
|
name: string
|
||||||
api_key: string
|
api_key: string
|
||||||
scopes: TenantAPIKeyScope[]
|
role: TenantAPIKeyRole
|
||||||
knowledge_base_ids: string[]
|
knowledge_base_ids: string[]
|
||||||
last_used_at?: string
|
last_used_at?: string
|
||||||
expires_at?: string
|
expires_at?: string
|
||||||
@@ -67,7 +67,7 @@ export interface CreatedTenantAPIKey extends TenantAPIKey {
|
|||||||
|
|
||||||
export interface CreateTenantAPIKeyPayload {
|
export interface CreateTenantAPIKeyPayload {
|
||||||
name: string
|
name: string
|
||||||
scopes: TenantAPIKeyScope[]
|
role: TenantAPIKeyRole
|
||||||
knowledge_base_ids?: string[]
|
knowledge_base_ids?: string[]
|
||||||
expires_at_unix?: number
|
expires_at_unix?: number
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -130,7 +130,7 @@
|
|||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<t-tag size="small" variant="light">
|
<t-tag size="small" variant="light">
|
||||||
{{ formatApiKeyAccessRoleLabel(key.scopes) }}
|
{{ formatApiKeyAccessRoleLabel(key.role) }}
|
||||||
</t-tag>
|
</t-tag>
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
@@ -469,7 +469,7 @@
|
|||||||
</t-radio-group>
|
</t-radio-group>
|
||||||
<p class="scope-role-hint">{{ $t('integrations.api.apiKeyAccessRoleHint') }}</p>
|
<p class="scope-role-hint">{{ $t('integrations.api.apiKeyAccessRoleHint') }}</p>
|
||||||
<div class="scope-help scope-help--role">
|
<div class="scope-help scope-help--role">
|
||||||
<p class="scope-help__role">{{ formatApiKeyAccessRoleLabel(accessRoleToScopes(apiKeyForm.role)) }}</p>
|
<p class="scope-help__role">{{ formatApiKeyAccessRoleLabel(apiKeyForm.role) }}</p>
|
||||||
<p class="scope-help__desc">{{ apiKeyFormRoleDesc }}</p>
|
<p class="scope-help__desc">{{ apiKeyFormRoleDesc }}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -522,7 +522,7 @@ import {
|
|||||||
type APIPrincipalConfig,
|
type APIPrincipalConfig,
|
||||||
type APIPrincipalMode,
|
type APIPrincipalMode,
|
||||||
type TenantAPIKey,
|
type TenantAPIKey,
|
||||||
type TenantAPIKeyScope,
|
type TenantAPIKeyRole,
|
||||||
} from '@/api/tenant'
|
} from '@/api/tenant'
|
||||||
import { listKnowledgeBases } from '@/api/knowledge-base'
|
import { listKnowledgeBases } from '@/api/knowledge-base'
|
||||||
import { getApiBaseUrl } from '@/utils/api-base'
|
import { getApiBaseUrl } from '@/utils/api-base'
|
||||||
@@ -576,32 +576,14 @@ const apiKeyForm = reactive({
|
|||||||
knowledge_base_ids: [] as string[],
|
knowledge_base_ids: [] as string[],
|
||||||
})
|
})
|
||||||
|
|
||||||
function scopesToAccessRole(scopes: TenantAPIKeyScope[] | undefined): ApiKeyAccessRole {
|
function formatApiKeyAccessRoleLabel(role: ApiKeyAccessRole | TenantAPIKeyRole | undefined): string {
|
||||||
const normalized = (scopes ?? []).map((scope) => scope.toLowerCase())
|
const normalized = (role ?? 'viewer') as ApiKeyAccessRole
|
||||||
if (normalized.includes('admin')) return 'admin'
|
|
||||||
if (normalized.includes('write')) return 'contributor'
|
|
||||||
return 'viewer'
|
|
||||||
}
|
|
||||||
|
|
||||||
function accessRoleToScopes(role: ApiKeyAccessRole): TenantAPIKeyScope[] {
|
|
||||||
switch (role) {
|
|
||||||
case 'admin':
|
|
||||||
return ['admin']
|
|
||||||
case 'contributor':
|
|
||||||
return ['write']
|
|
||||||
default:
|
|
||||||
return ['read']
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatApiKeyAccessRoleLabel(scopes: TenantAPIKeyScope[] | undefined): string {
|
|
||||||
const role = scopesToAccessRole(scopes)
|
|
||||||
const labels: Record<ApiKeyAccessRole, string> = {
|
const labels: Record<ApiKeyAccessRole, string> = {
|
||||||
viewer: t('integrations.api.accessRoleViewer'),
|
viewer: t('integrations.api.accessRoleViewer'),
|
||||||
contributor: t('integrations.api.accessRoleContributor'),
|
contributor: t('integrations.api.accessRoleContributor'),
|
||||||
admin: t('integrations.api.accessRoleAdmin'),
|
admin: t('integrations.api.accessRoleAdmin'),
|
||||||
}
|
}
|
||||||
return labels[role]
|
return labels[normalized] ?? labels.viewer
|
||||||
}
|
}
|
||||||
|
|
||||||
const apiKeyFormRoleDesc = computed(() => {
|
const apiKeyFormRoleDesc = computed(() => {
|
||||||
@@ -1152,7 +1134,7 @@ async function createScopedAPIKey() {
|
|||||||
try {
|
try {
|
||||||
const resp = await createTenantAPIKey(tenantId.value, {
|
const resp = await createTenantAPIKey(tenantId.value, {
|
||||||
name: apiKeyForm.name.trim(),
|
name: apiKeyForm.name.trim(),
|
||||||
scopes: accessRoleToScopes(apiKeyForm.role),
|
role: apiKeyForm.role,
|
||||||
knowledge_base_ids: apiKeyForm.knowledge_base_ids,
|
knowledge_base_ids: apiKeyForm.knowledge_base_ids,
|
||||||
})
|
})
|
||||||
if (!resp.success || !resp.data?.api_key) {
|
if (!resp.success || !resp.data?.api_key) {
|
||||||
|
|||||||
@@ -462,6 +462,13 @@ func (s *customAgentService) GetSuggestedQuestions(
|
|||||||
limit = 6
|
limit = 6
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := types.AuthorizeTenantAPIKeyKnowledgeTargets(ctx, kbIDs, knowledgeIDs); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := types.AuthorizeTenantAPIKeyOptionalTagIDs(ctx, tagIDs); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
// Get tenant ID from context
|
// Get tenant ID from context
|
||||||
tenantID, ok := types.TenantIDFromContext(ctx)
|
tenantID, ok := types.TenantIDFromContext(ctx)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -541,6 +548,12 @@ func (s *customAgentService) GetSuggestedQuestions(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
filteredKBIDs, err := types.FilterKnowledgeBasesForTenantAPIKeyScope(ctx, kbIDs, effectiveKBIDs)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
effectiveKBIDs = filteredKBIDs
|
||||||
|
|
||||||
if len(effectiveKBIDs) == 0 && len(knowledgeIDs) == 0 {
|
if len(effectiveKBIDs) == 0 && len(knowledgeIDs) == 0 {
|
||||||
return s.truncateQuestions(result, limit), nil
|
return s.truncateQuestions(result, limit), nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Tencent/WeKnora/internal/types"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetSuggestedQuestionsRejectsOutOfScopeKnowledgeBaseIDs(t *testing.T) {
|
||||||
|
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
|
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||||
|
})
|
||||||
|
ctx = context.WithValue(ctx, types.TenantIDContextKey, uint64(1))
|
||||||
|
|
||||||
|
svc := &customAgentService{}
|
||||||
|
_, err := svc.GetSuggestedQuestions(ctx, "agent-1", []string{"kb-2"}, nil, nil, 6)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected forbidden for out-of-scope knowledge_base_ids")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetSuggestedQuestionsRejectsKnowledgeIDsForRestrictedKey(t *testing.T) {
|
||||||
|
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
|
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||||
|
})
|
||||||
|
ctx = context.WithValue(ctx, types.TenantIDContextKey, uint64(1))
|
||||||
|
|
||||||
|
svc := &customAgentService{}
|
||||||
|
_, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, []string{"doc-1"}, nil, 6)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected forbidden for knowledge_ids under KB-restricted key")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetSuggestedQuestionsRejectsTagIDsForRestrictedKey(t *testing.T) {
|
||||||
|
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
|
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||||
|
})
|
||||||
|
ctx = context.WithValue(ctx, types.TenantIDContextKey, uint64(1))
|
||||||
|
|
||||||
|
svc := &customAgentService{}
|
||||||
|
_, err := svc.GetSuggestedQuestions(ctx, "agent-1", nil, nil, []string{"tag-1"}, 6)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected forbidden for tag_ids under KB-restricted key")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -43,12 +43,12 @@ func (s *tenantAPIKeyService) CreateAPIKey(
|
|||||||
Name: name,
|
Name: name,
|
||||||
KeyHash: hashTenantAPIKey(token),
|
KeyHash: hashTenantAPIKey(token),
|
||||||
APIKey: token,
|
APIKey: token,
|
||||||
Scopes: normalizeAPIKeyScopes(req.Scopes),
|
Role: types.NormalizeTenantAPIKeyRole(req.Role),
|
||||||
KnowledgeBaseIDs: normalizeAPIKeyIDs(req.KnowledgeBaseIDs),
|
KnowledgeBaseIDs: normalizeAPIKeyIDs(req.KnowledgeBaseIDs),
|
||||||
ExpiresAt: req.ExpiresAt,
|
ExpiresAt: req.ExpiresAt,
|
||||||
}
|
}
|
||||||
if len(key.Scopes) == 0 {
|
if key.Role == "" {
|
||||||
key.Scopes = types.StringArray{types.TenantAPIKeyScopeRead}
|
key.Role = types.TenantRoleViewer
|
||||||
}
|
}
|
||||||
if err := s.repo.CreateAPIKey(ctx, key); err != nil {
|
if err := s.repo.CreateAPIKey(ctx, key); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -162,25 +162,6 @@ func (s *tenantAPIKeyService) ensureAPIKeyHash(ctx context.Context, key *types.T
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func normalizeAPIKeyScopes(in []string) types.StringArray {
|
|
||||||
out := types.StringArray{}
|
|
||||||
seen := map[string]struct{}{}
|
|
||||||
for _, scope := range in {
|
|
||||||
scope = strings.ToLower(strings.TrimSpace(scope))
|
|
||||||
switch scope {
|
|
||||||
case types.TenantAPIKeyScopeRead, types.TenantAPIKeyScopeWrite, types.TenantAPIKeyScopeAdmin:
|
|
||||||
default:
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if _, ok := seen[scope]; ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
seen[scope] = struct{}{}
|
|
||||||
out = append(out, scope)
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
func normalizeAPIKeyIDs(in []string) types.StringArray {
|
func normalizeAPIKeyIDs(in []string) types.StringArray {
|
||||||
out := types.StringArray{}
|
out := types.StringArray{}
|
||||||
seen := map[string]struct{}{}
|
seen := map[string]struct{}{}
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ func TestTenantAPIKeyServiceCreateAPIKeyUsesSKPrefix(t *testing.T) {
|
|||||||
result, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
result, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||||
TenantID: 42,
|
TenantID: 42,
|
||||||
Name: "integration",
|
Name: "integration",
|
||||||
Scopes: []string{types.TenantAPIKeyScopeRead},
|
Role: types.TenantRoleViewer,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("CreateAPIKey returned error: %v", err)
|
t.Fatalf("CreateAPIKey returned error: %v", err)
|
||||||
@@ -126,7 +126,7 @@ func TestTenantAPIKeyServiceAuthenticateTenantAPIKeyRepairsMigratedHash(t *testi
|
|||||||
Name: "Tenant API key",
|
Name: "Tenant API key",
|
||||||
KeyHash: "migrated-tenant-42",
|
KeyHash: "migrated-tenant-42",
|
||||||
APIKey: token,
|
APIKey: token,
|
||||||
Scopes: types.StringArray{types.TenantAPIKeyScopeAdmin},
|
Role: types.TenantRoleAdmin,
|
||||||
}
|
}
|
||||||
if err := repo.CreateAPIKey(ctx, key); err != nil {
|
if err := repo.CreateAPIKey(ctx, key); err != nil {
|
||||||
t.Fatalf("CreateAPIKey returned error: %v", err)
|
t.Fatalf("CreateAPIKey returned error: %v", err)
|
||||||
@@ -151,7 +151,7 @@ func TestTenantAPIKeyServiceRevokeAllAPIKeys(t *testing.T) {
|
|||||||
first, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
first, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||||
TenantID: 42,
|
TenantID: 42,
|
||||||
Name: "first",
|
Name: "first",
|
||||||
Scopes: []string{types.TenantAPIKeyScopeRead},
|
Role: types.TenantRoleViewer,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("CreateAPIKey first returned error: %v", err)
|
t.Fatalf("CreateAPIKey first returned error: %v", err)
|
||||||
@@ -159,7 +159,7 @@ func TestTenantAPIKeyServiceRevokeAllAPIKeys(t *testing.T) {
|
|||||||
second, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
second, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||||
TenantID: 42,
|
TenantID: 42,
|
||||||
Name: "second",
|
Name: "second",
|
||||||
Scopes: []string{types.TenantAPIKeyScopeRead},
|
Role: types.TenantRoleViewer,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("CreateAPIKey second returned error: %v", err)
|
t.Fatalf("CreateAPIKey second returned error: %v", err)
|
||||||
|
|||||||
@@ -170,6 +170,10 @@ func (h *DataSourceHandler) ListDataSources(c *gin.Context) {
|
|||||||
c.JSON(status, gin.H{"error": msg})
|
c.JSON(status, gin.H{"error": msg})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID); err != nil {
|
||||||
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
dataSources, err := h.service.ListDataSources(ctx, kbID)
|
dataSources, err := h.service.ListDataSources(ctx, kbID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -2439,14 +2439,7 @@ func requireTenantAPIKeyKnowledgeBase(ctx context.Context, kbID string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func requireTenantAPIKeyKnowledgeBases(ctx context.Context, kbIDs ...string) error {
|
func requireTenantAPIKeyKnowledgeBases(ctx context.Context, kbIDs ...string) error {
|
||||||
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
|
return types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbIDs...)
|
||||||
if !ok || !scope.IsKnowledgeBaseRestricted() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if !scope.AllowsKnowledgeBases(kbIDs) {
|
|
||||||
return errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func tenantAPIKeyAllowedKBSet(ctx context.Context) map[string]bool {
|
func tenantAPIKeyAllowedKBSet(ctx context.Context) map[string]bool {
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
|
|||||||
|
|
||||||
// Merge @mentioned items into knowledge_base_ids and knowledge_ids
|
// Merge @mentioned items into knowledge_base_ids and knowledge_ids
|
||||||
kbIDs, knowledgeIDs := mergeKnowledgeTargets(request.KnowledgeBaseIDs, request.KnowledgeIds, request.MentionedItems)
|
kbIDs, knowledgeIDs := mergeKnowledgeTargets(request.KnowledgeBaseIDs, request.KnowledgeIds, request.MentionedItems)
|
||||||
if err := authorizeTenantAPIKeyKnowledgeTargets(ctx, kbIDs, knowledgeIDs); err != nil {
|
if err := types.AuthorizeTenantAPIKeyKnowledgeTargets(ctx, kbIDs, knowledgeIDs); err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -533,7 +533,7 @@ func (h *Handler) SearchKnowledge(c *gin.Context) {
|
|||||||
c.Error(errors.NewBadRequestError("At least one knowledge_base_id, knowledge_base_ids, knowledge_ids, or scoped tag must be provided"))
|
c.Error(errors.NewBadRequestError("At least one knowledge_base_id, knowledge_base_ids, knowledge_ids, or scoped tag must be provided"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err := authorizeTenantAPIKeyKnowledgeTargets(ctx, knowledgeBaseIDs, request.KnowledgeIDs); err != nil {
|
if err := types.AuthorizeTenantAPIKeyKnowledgeTargets(ctx, knowledgeBaseIDs, request.KnowledgeIDs); err != nil {
|
||||||
c.Error(err)
|
c.Error(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -562,20 +562,6 @@ func (h *Handler) SearchKnowledge(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func authorizeTenantAPIKeyKnowledgeTargets(ctx context.Context, kbIDs []string, knowledgeIDs []string) error {
|
|
||||||
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
|
|
||||||
if !ok || !scope.IsKnowledgeBaseRestricted() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if len(knowledgeIDs) > 0 {
|
|
||||||
return errors.NewForbiddenError("API key scope does not allow knowledge_ids without a verified knowledge base")
|
|
||||||
}
|
|
||||||
if !scope.AllowsKnowledgeBases(kbIDs) {
|
|
||||||
return errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// KnowledgeQA godoc
|
// KnowledgeQA godoc
|
||||||
// @Summary 知识问答
|
// @Summary 知识问答
|
||||||
// @Description 基于知识库的问答(使用LLM总结),支持SSE流式响应
|
// @Description 基于知识库的问答(使用LLM总结),支持SSE流式响应
|
||||||
|
|||||||
+11
-15
@@ -135,7 +135,7 @@ type apiPrincipalTestTokenResponse struct {
|
|||||||
|
|
||||||
type tenantAPIKeyCreateRequest struct {
|
type tenantAPIKeyCreateRequest struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Scopes []string `json:"scopes"`
|
Role string `json:"role"`
|
||||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
|
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
|
||||||
ExpiresAt *int64 `json:"expires_at_unix"`
|
ExpiresAt *int64 `json:"expires_at_unix"`
|
||||||
}
|
}
|
||||||
@@ -144,7 +144,7 @@ type tenantAPIKeyResponse struct {
|
|||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
APIKey string `json:"api_key"`
|
APIKey string `json:"api_key"`
|
||||||
Scopes types.StringArray `json:"scopes"`
|
Role types.TenantRole `json:"role"`
|
||||||
KnowledgeBaseIDs types.StringArray `json:"knowledge_base_ids"`
|
KnowledgeBaseIDs types.StringArray `json:"knowledge_base_ids"`
|
||||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||||
@@ -570,11 +570,7 @@ func (h *TenantHandler) ResetAPIKey(c *gin.Context) {
|
|||||||
result, err := h.apiKeyService.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
result, err := h.apiKeyService.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||||
TenantID: id,
|
TenantID: id,
|
||||||
Name: "Tenant API key",
|
Name: "Tenant API key",
|
||||||
Scopes: []string{
|
Role: types.TenantRoleAdmin,
|
||||||
types.TenantAPIKeyScopeRead,
|
|
||||||
types.TenantAPIKeyScopeWrite,
|
|
||||||
types.TenantAPIKeyScopeAdmin,
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if appErr, ok := errors.IsAppError(err); ok {
|
if appErr, ok := errors.IsAppError(err); ok {
|
||||||
@@ -631,6 +627,10 @@ func (h *TenantHandler) CreateAPIKey(c *gin.Context) {
|
|||||||
c.Error(err)
|
c.Error(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
role := types.NormalizeTenantAPIKeyRole(types.TenantRole(strings.TrimSpace(req.Role)))
|
||||||
|
if role == "" {
|
||||||
|
role = types.TenantRoleViewer
|
||||||
|
}
|
||||||
var expiresAt *time.Time
|
var expiresAt *time.Time
|
||||||
if req.ExpiresAt != nil {
|
if req.ExpiresAt != nil {
|
||||||
t := time.Unix(*req.ExpiresAt, 0)
|
t := time.Unix(*req.ExpiresAt, 0)
|
||||||
@@ -643,7 +643,7 @@ func (h *TenantHandler) CreateAPIKey(c *gin.Context) {
|
|||||||
result, err := h.apiKeyService.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
result, err := h.apiKeyService.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||||
TenantID: id,
|
TenantID: id,
|
||||||
Name: req.Name,
|
Name: req.Name,
|
||||||
Scopes: req.Scopes,
|
Role: role,
|
||||||
KnowledgeBaseIDs: req.KnowledgeBaseIDs,
|
KnowledgeBaseIDs: req.KnowledgeBaseIDs,
|
||||||
ExpiresAt: expiresAt,
|
ExpiresAt: expiresAt,
|
||||||
})
|
})
|
||||||
@@ -687,7 +687,7 @@ func tenantAPIKeyForResponse(key *types.TenantAPIKey) tenantAPIKeyResponse {
|
|||||||
ID: key.ID,
|
ID: key.ID,
|
||||||
Name: key.Name,
|
Name: key.Name,
|
||||||
APIKey: key.APIKey,
|
APIKey: key.APIKey,
|
||||||
Scopes: key.Scopes,
|
Role: types.NormalizeTenantAPIKeyRole(key.Role),
|
||||||
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
|
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
|
||||||
LastUsedAt: key.LastUsedAt,
|
LastUsedAt: key.LastUsedAt,
|
||||||
ExpiresAt: key.ExpiresAt,
|
ExpiresAt: key.ExpiresAt,
|
||||||
@@ -704,12 +704,8 @@ func validateTenantAPIKeyRequest(
|
|||||||
if strings.TrimSpace(req.Name) == "" {
|
if strings.TrimSpace(req.Name) == "" {
|
||||||
return errors.NewValidationError("name is required")
|
return errors.NewValidationError("name is required")
|
||||||
}
|
}
|
||||||
for _, scope := range req.Scopes {
|
if role := types.NormalizeTenantAPIKeyRole(types.TenantRole(strings.TrimSpace(req.Role))); req.Role != "" && role == "" {
|
||||||
switch strings.ToLower(strings.TrimSpace(scope)) {
|
return errors.NewValidationError("role must be viewer, contributor, or admin")
|
||||||
case types.TenantAPIKeyScopeRead, types.TenantAPIKeyScopeWrite, types.TenantAPIKeyScopeAdmin:
|
|
||||||
default:
|
|
||||||
return errors.NewValidationError("scopes must contain only read, write, or admin")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
for _, kbID := range req.KnowledgeBaseIDs {
|
for _, kbID := range req.KnowledgeBaseIDs {
|
||||||
kbID = strings.TrimSpace(kbID)
|
kbID = strings.TrimSpace(kbID)
|
||||||
|
|||||||
@@ -183,7 +183,7 @@ func TestCloneContextPreservesTenantAPIKeyScope(t *testing.T) {
|
|||||||
|
|
||||||
want := types.TenantAPIKeyScope{
|
want := types.TenantAPIKeyScope{
|
||||||
KeyID: 7,
|
KeyID: 7,
|
||||||
Scopes: types.StringArray{types.TenantAPIKeyScopeRead},
|
Role: types.TenantRoleViewer,
|
||||||
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||||
}
|
}
|
||||||
ctx := types.WithTenantAPIKeyScope(context.Background(), want)
|
ctx := types.WithTenantAPIKeyScope(context.Background(), want)
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/Tencent/WeKnora/internal/types"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
// isTenantAPIKeyManagementPath reports tenant API-key lifecycle endpoints that
|
||||||
|
// no scoped key may call, regardless of role.
|
||||||
|
func isTenantAPIKeyManagementPath(path string) bool {
|
||||||
|
for _, marker := range []string{"/api-keys", "/api-principal"} {
|
||||||
|
if strings.Contains(path, marker) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Legacy reset endpoint: POST /tenants/:id/api-key (singular).
|
||||||
|
return strings.HasSuffix(path, "/api-key")
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequireAPIKeyDeny rejects all X-API-Key callers. JWT sessions pass through.
|
||||||
|
func RequireAPIKeyDeny() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
if _, ok := types.TenantAPIKeyScopeFromContext(c.Request.Context()); ok {
|
||||||
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||||
|
"error": "Forbidden: API key scope does not allow this operation",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequireAPIKeyMinRole enforces minRole for X-API-Key callers on every HTTP
|
||||||
|
// method. JWT sessions pass through.
|
||||||
|
func RequireAPIKeyMinRole(minRole types.TenantRole) gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
if err := requireTenantAPIKeyMinRole(c.Request.Context(), minRole); err != nil {
|
||||||
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||||
|
"error": "Forbidden: API key scope does not allow this operation",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequireAPIKeyMinRoleForUnsafe enforces minRole for X-API-Key callers on
|
||||||
|
// POST/PUT/PATCH/DELETE only. Safe reads (GET/HEAD/OPTIONS) pass through so
|
||||||
|
// group-level guards can cover mixed read/write route trees.
|
||||||
|
func RequireAPIKeyMinRoleForUnsafe(minRole types.TenantRole) gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
if isSafeHTTPMethod(c.Request.Method) {
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := requireTenantAPIKeyMinRole(c.Request.Context(), minRole); err != nil {
|
||||||
|
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
|
||||||
|
"error": "Forbidden: API key scope does not allow this operation",
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func requireTenantAPIKeyMinRole(ctx context.Context, minRole types.TenantRole) error {
|
||||||
|
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
role := scope.Role
|
||||||
|
if role == "" {
|
||||||
|
role = types.TenantRoleViewer
|
||||||
|
}
|
||||||
|
if !role.HasPermission(minRole) {
|
||||||
|
return errTenantAPIKeyScopeForbidden
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
stderrors "errors"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Tencent/WeKnora/internal/types"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRequireAPIKeyDenyBlocksAPIKey(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
|
Role: types.TenantRoleAdmin,
|
||||||
|
})
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/knowledge-bases", nil)
|
||||||
|
c.Request = c.Request.WithContext(ctx)
|
||||||
|
|
||||||
|
RequireAPIKeyDeny()(c)
|
||||||
|
if !c.IsAborted() {
|
||||||
|
t.Fatal("expected API key request to be aborted")
|
||||||
|
}
|
||||||
|
if w.Code != http.StatusForbidden {
|
||||||
|
t.Fatalf("status = %d, want %d", w.Code, http.StatusForbidden)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequireAPIKeyDenyAllowsJWT(t *testing.T) {
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/knowledge-bases", nil)
|
||||||
|
|
||||||
|
RequireAPIKeyDeny()(c)
|
||||||
|
if c.IsAborted() {
|
||||||
|
t.Fatal("expected JWT request to pass RequireAPIKeyDeny")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequireAPIKeyMinRoleForUnsafeSkipsSafeMethods(t *testing.T) {
|
||||||
|
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
|
Role: types.TenantRoleViewer,
|
||||||
|
})
|
||||||
|
if err := requireTenantAPIKeyMinRole(ctx, types.TenantRoleAdmin); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
||||||
|
t.Fatalf("viewer should not satisfy admin min role: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/models", nil)
|
||||||
|
c.Request = c.Request.WithContext(ctx)
|
||||||
|
|
||||||
|
RequireAPIKeyMinRoleForUnsafe(types.TenantRoleAdmin)(c)
|
||||||
|
if c.IsAborted() {
|
||||||
|
t.Fatal("safe GET should skip unsafe min-role guard")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequireAPIKeyMinRoleEnforcesOnPost(t *testing.T) {
|
||||||
|
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
|
Role: types.TenantRoleViewer,
|
||||||
|
})
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/knowledge-search", nil)
|
||||||
|
c.Request = c.Request.WithContext(ctx)
|
||||||
|
|
||||||
|
RequireAPIKeyMinRole(types.TenantRoleViewer)(c)
|
||||||
|
if c.IsAborted() {
|
||||||
|
t.Fatal("viewer key should pass viewer min role on POST")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/Tencent/WeKnora/internal/types"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestTenantAPIKeyRouteScopeManifest(t *testing.T) {
|
||||||
|
readCtx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
|
Role: types.TenantRoleViewer,
|
||||||
|
})
|
||||||
|
writeCtx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
|
Role: types.TenantRoleContributor,
|
||||||
|
})
|
||||||
|
adminCtx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
|
Role: types.TenantRoleAdmin,
|
||||||
|
})
|
||||||
|
|
||||||
|
baselineCases := []struct {
|
||||||
|
name string
|
||||||
|
ctx context.Context
|
||||||
|
method string
|
||||||
|
path string
|
||||||
|
allowed bool
|
||||||
|
}{
|
||||||
|
{name: "read get kb list", ctx: readCtx, method: http.MethodGet, path: "/api/v1/knowledge-bases", allowed: true},
|
||||||
|
{name: "read get wiki page", ctx: readCtx, method: http.MethodGet, path: "/api/v1/knowledgebase/kb-1/wiki/pages", allowed: true},
|
||||||
|
{name: "admin reset api key blocked", ctx: adminCtx, method: http.MethodPost, path: "/api/v1/tenants/1/api-key", allowed: false},
|
||||||
|
{name: "admin api principal blocked", ctx: adminCtx, method: http.MethodGet, path: "/api/v1/tenants/1/api-principal-config", allowed: false},
|
||||||
|
}
|
||||||
|
for _, tc := range baselineCases {
|
||||||
|
t.Run("baseline/"+tc.name, func(t *testing.T) {
|
||||||
|
err := authorizeTenantAPIKeyAccess(tc.ctx, tc.method, tc.path)
|
||||||
|
got := err == nil
|
||||||
|
if got != tc.allowed {
|
||||||
|
t.Fatalf("authorizeTenantAPIKeyAccess(%s %s) allowed=%v, want %v (err=%v)",
|
||||||
|
tc.method, tc.path, got, tc.allowed, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
guardCases := []struct {
|
||||||
|
name string
|
||||||
|
ctx context.Context
|
||||||
|
method string
|
||||||
|
guard gin.HandlerFunc
|
||||||
|
allowed bool
|
||||||
|
}{
|
||||||
|
{name: "read delete kb", ctx: readCtx, method: http.MethodDelete, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleContributor), allowed: false},
|
||||||
|
{name: "write put kb", ctx: writeCtx, method: http.MethodPut, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleContributor), allowed: true},
|
||||||
|
{name: "write create kb", ctx: writeCtx, method: http.MethodPost, guard: RequireAPIKeyDeny(), allowed: false},
|
||||||
|
{name: "write batch delete", ctx: writeCtx, method: http.MethodPost, guard: RequireAPIKeyDeny(), allowed: false},
|
||||||
|
{name: "write faq upsert", ctx: writeCtx, method: http.MethodPost, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleContributor), allowed: true},
|
||||||
|
{name: "write semantic search post", ctx: writeCtx, method: http.MethodPost, guard: RequireAPIKeyMinRole(types.TenantRoleViewer), allowed: true},
|
||||||
|
{name: "read semantic search post", ctx: readCtx, method: http.MethodPost, guard: RequireAPIKeyMinRole(types.TenantRoleViewer), allowed: true},
|
||||||
|
{name: "read knowledge chat post", ctx: readCtx, method: http.MethodPost, guard: RequireAPIKeyMinRole(types.TenantRoleViewer), allowed: true},
|
||||||
|
{name: "admin tenant kv", ctx: adminCtx, method: http.MethodPut, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleAdmin), allowed: true},
|
||||||
|
{name: "contributor tenant kv", ctx: writeCtx, method: http.MethodPut, guard: RequireAPIKeyMinRoleForUnsafe(types.TenantRoleAdmin), allowed: false},
|
||||||
|
}
|
||||||
|
for _, tc := range guardCases {
|
||||||
|
t.Run("guard/"+tc.name, func(t *testing.T) {
|
||||||
|
got := runAPIKeyGuard(t, tc.ctx, tc.method, tc.guard)
|
||||||
|
if got != tc.allowed {
|
||||||
|
t.Fatalf("guard allowed=%v, want %v", got, tc.allowed)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runAPIKeyGuard(t *testing.T, ctx context.Context, method string, guard gin.HandlerFunc) bool {
|
||||||
|
t.Helper()
|
||||||
|
gin.SetMode(gin.TestMode)
|
||||||
|
w := httptest.NewRecorder()
|
||||||
|
c, _ := gin.CreateTestContext(w)
|
||||||
|
c.Request = httptest.NewRequest(method, "/api/v1/test", nil)
|
||||||
|
c.Request = c.Request.WithContext(ctx)
|
||||||
|
guard(c)
|
||||||
|
return !c.IsAborted() && w.Code != http.StatusForbidden
|
||||||
|
}
|
||||||
@@ -4,39 +4,34 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
stderrors "errors"
|
stderrors "errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/Tencent/WeKnora/internal/types"
|
"github.com/Tencent/WeKnora/internal/types"
|
||||||
)
|
)
|
||||||
|
|
||||||
var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidden")
|
var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidden")
|
||||||
|
|
||||||
// authorizeTenantAPIKeyAccess enforces per-key operation and route scopes for
|
// authorizeTenantAPIKeyAccess enforces baseline rules for X-API-Key callers
|
||||||
// X-API-Key callers. Non-API-key principals are not restricted.
|
// before route-level guards run: block key-management paths and require
|
||||||
|
// Viewer+ for safe reads. Unsafe methods defer to per-route APIKey* guards.
|
||||||
func authorizeTenantAPIKeyAccess(ctx context.Context, method, path string) error {
|
func authorizeTenantAPIKeyAccess(ctx context.Context, method, path string) error {
|
||||||
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
|
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if strings.Contains(path, "/api-keys") {
|
role := scope.Role
|
||||||
|
if role == "" {
|
||||||
|
role = types.TenantRoleViewer
|
||||||
|
}
|
||||||
|
if isTenantAPIKeyManagementPath(path) {
|
||||||
return errTenantAPIKeyScopeForbidden
|
return errTenantAPIKeyScopeForbidden
|
||||||
}
|
}
|
||||||
if isSafeHTTPMethod(method) {
|
if isSafeHTTPMethod(method) {
|
||||||
if allowsTenantAPIKeyRead(scope) {
|
if role.HasPermission(types.TenantRoleViewer) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return errTenantAPIKeyScopeForbidden
|
return errTenantAPIKeyScopeForbidden
|
||||||
}
|
}
|
||||||
if isTenantAPIKeyReadUnsafePath(method, path) && allowsTenantAPIKeyRead(scope) {
|
return nil
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if isKnowledgeScopedUnsafePath(path) && allowsTenantAPIKeyWrite(scope) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if allowsTenantAPIKeyAdmin(scope) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return errTenantAPIKeyScopeForbidden
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func authorizeTenantAPIKeyKnowledgeBase(ctx context.Context, kbID string) error {
|
func authorizeTenantAPIKeyKnowledgeBase(ctx context.Context, kbID string) error {
|
||||||
@@ -58,85 +53,3 @@ func isSafeHTTPMethod(method string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func isKnowledgeScopedUnsafePath(path string) bool {
|
|
||||||
denyPrefixes := []string{
|
|
||||||
"/api/v1/knowledge-bases/copy",
|
|
||||||
"/api/v1/knowledge/tags",
|
|
||||||
"/api/v1/knowledge/batch-reparse",
|
|
||||||
"/api/v1/knowledge/batch-delete",
|
|
||||||
"/api/v1/knowledge/move",
|
|
||||||
}
|
|
||||||
for _, prefix := range denyPrefixes {
|
|
||||||
if path == prefix || strings.HasPrefix(path, prefix+"/") {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if path == "/api/v1/sessions" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
allowPrefixes := []string{
|
|
||||||
"/api/v1/knowledge-bases/",
|
|
||||||
"/api/v1/knowledge/",
|
|
||||||
"/api/v1/chunks/",
|
|
||||||
"/api/v1/knowledgebase/",
|
|
||||||
"/api/v1/knowledge-search",
|
|
||||||
"/api/v1/knowledge-chat/",
|
|
||||||
}
|
|
||||||
for _, prefix := range allowPrefixes {
|
|
||||||
if path == prefix || strings.HasPrefix(path, prefix) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func allowsTenantAPIKeyRead(scope types.TenantAPIKeyScope) bool {
|
|
||||||
scope = scope.Normalize()
|
|
||||||
return scope.HasScope(types.TenantAPIKeyScopeRead) ||
|
|
||||||
scope.HasScope(types.TenantAPIKeyScopeWrite) ||
|
|
||||||
scope.HasScope(types.TenantAPIKeyScopeAdmin)
|
|
||||||
}
|
|
||||||
|
|
||||||
func allowsTenantAPIKeyWrite(scope types.TenantAPIKeyScope) bool {
|
|
||||||
scope = scope.Normalize()
|
|
||||||
return scope.HasScope(types.TenantAPIKeyScopeWrite) ||
|
|
||||||
scope.HasScope(types.TenantAPIKeyScopeAdmin)
|
|
||||||
}
|
|
||||||
|
|
||||||
func allowsTenantAPIKeyAdmin(scope types.TenantAPIKeyScope) bool {
|
|
||||||
scope = scope.Normalize()
|
|
||||||
return scope.HasScope(types.TenantAPIKeyScopeAdmin)
|
|
||||||
}
|
|
||||||
|
|
||||||
func isTenantAPIKeyReadUnsafePath(method, path string) bool {
|
|
||||||
if method != http.MethodPost {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if path == "/api/v1/sessions" ||
|
|
||||||
path == "/api/v1/knowledge-search" ||
|
|
||||||
path == "/api/v1/messages/search" ||
|
|
||||||
path == "/api/v1/chunker/preview" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
readPrefixes := []string{
|
|
||||||
"/api/v1/knowledge-chat/",
|
|
||||||
"/api/v1/agent-chat/",
|
|
||||||
}
|
|
||||||
for _, prefix := range readPrefixes {
|
|
||||||
if strings.HasPrefix(path, prefix) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
readSuffixes := []string{
|
|
||||||
"/hybrid-search",
|
|
||||||
"/faq/search",
|
|
||||||
}
|
|
||||||
for _, suffix := range readSuffixes {
|
|
||||||
if strings.HasSuffix(path, suffix) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -11,37 +11,27 @@ import (
|
|||||||
|
|
||||||
func TestTenantAPIKeyScopeReadOnlyAllowsSafeMethods(t *testing.T) {
|
func TestTenantAPIKeyScopeReadOnlyAllowsSafeMethods(t *testing.T) {
|
||||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
Scopes: types.StringArray{types.TenantAPIKeyScopeRead},
|
Role: types.TenantRoleViewer,
|
||||||
})
|
})
|
||||||
|
|
||||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodGet, "/api/v1/knowledge-bases"); err != nil {
|
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodGet, "/api/v1/knowledge-bases"); err != nil {
|
||||||
t.Fatalf("read scoped key should allow GET: %v", err)
|
t.Fatalf("viewer key should allow GET: %v", err)
|
||||||
}
|
}
|
||||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodHead, "/api/v1/knowledge-bases"); err != nil {
|
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodHead, "/api/v1/knowledge-bases"); err != nil {
|
||||||
t.Fatalf("read scoped key should allow HEAD: %v", err)
|
t.Fatalf("viewer key should allow HEAD: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTenantAPIKeyScopeReadOnlyRejectsUnsafeMethods(t *testing.T) {
|
func TestTenantAPIKeyScopeBaselineAllowsUnsafeThrough(t *testing.T) {
|
||||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
Scopes: types.StringArray{types.TenantAPIKeyScopeRead},
|
Role: types.TenantRoleViewer,
|
||||||
})
|
})
|
||||||
|
|
||||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/knowledge-bases/kb-1/knowledge/file"); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/knowledge-bases/kb-1/knowledge/file"); err != nil {
|
||||||
t.Fatalf("read scoped key POST error = %v, want errTenantAPIKeyScopeForbidden", err)
|
t.Fatalf("baseline should defer unsafe checks to route guards: %v", err)
|
||||||
}
|
}
|
||||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodDelete, "/api/v1/knowledge-bases/kb-1"); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodDelete, "/api/v1/knowledge-bases/kb-1"); err != nil {
|
||||||
t.Fatalf("read scoped key DELETE error = %v, want errTenantAPIKeyScopeForbidden", err)
|
t.Fatalf("baseline should defer unsafe checks to route guards: %v", err)
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTenantAPIKeyScopeReadOnlyAllowsSemanticReadPost(t *testing.T) {
|
|
||||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
|
||||||
Scopes: types.StringArray{types.TenantAPIKeyScopeRead},
|
|
||||||
})
|
|
||||||
|
|
||||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/knowledge-search"); err != nil {
|
|
||||||
t.Fatalf("read scoped key should allow semantic read POST: %v", err)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,80 +50,52 @@ func TestTenantAPIKeyScopeAllowsScopedKnowledgeBase(t *testing.T) {
|
|||||||
|
|
||||||
func TestTenantAPIKeyRouteRejectsAPIKeyManagement(t *testing.T) {
|
func TestTenantAPIKeyRouteRejectsAPIKeyManagement(t *testing.T) {
|
||||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
Scopes: types.StringArray{types.TenantAPIKeyScopeAdmin},
|
Role: types.TenantRoleAdmin,
|
||||||
})
|
})
|
||||||
|
|
||||||
err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/tenants/1/api-keys")
|
for _, path := range []string{
|
||||||
if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
"/api/v1/tenants/1/api-keys",
|
||||||
t.Fatalf("api key management error = %v, want errTenantAPIKeyScopeForbidden", err)
|
"/api/v1/tenants/1/api-key",
|
||||||
|
"/api/v1/tenants/1/api-principal-config",
|
||||||
|
"/api/v1/tenants/1/api-principal-test-token",
|
||||||
|
} {
|
||||||
|
err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, path)
|
||||||
|
if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
||||||
|
t.Fatalf("api key management path %s error = %v, want errTenantAPIKeyScopeForbidden", path, err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTenantAPIKeyRouteRejectsTenantWriteForKnowledgeRestrictedKey(t *testing.T) {
|
func TestTenantAPIKeyScopeEmptyRoleDefaultsToViewer(t *testing.T) {
|
||||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
Scopes: types.StringArray{types.TenantAPIKeyScopeWrite},
|
Role: "",
|
||||||
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
|
||||||
})
|
})
|
||||||
|
|
||||||
err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/kv/theme")
|
|
||||||
if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
|
||||||
t.Fatalf("tenant write error = %v, want errTenantAPIKeyScopeForbidden", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTenantAPIKeyRouteRejectsTenantWriteForWriteScope(t *testing.T) {
|
|
||||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
|
||||||
Scopes: types.StringArray{types.TenantAPIKeyScopeWrite},
|
|
||||||
})
|
|
||||||
|
|
||||||
err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/1")
|
|
||||||
if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
|
||||||
t.Fatalf("tenant write error = %v, want errTenantAPIKeyScopeForbidden", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTenantAPIKeyRouteAllowsTenantWriteForAdminScope(t *testing.T) {
|
|
||||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
|
||||||
Scopes: types.StringArray{types.TenantAPIKeyScopeAdmin},
|
|
||||||
})
|
|
||||||
|
|
||||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/kv/theme"); err != nil {
|
|
||||||
t.Fatalf("admin scoped key should allow tenant management route: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTenantAPIKeyRouteAllowsKnowledgeWriteForKnowledgeRestrictedKey(t *testing.T) {
|
|
||||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
|
||||||
Scopes: types.StringArray{types.TenantAPIKeyScopeWrite},
|
|
||||||
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
|
||||||
})
|
|
||||||
|
|
||||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/knowledge-bases/kb-1"); err != nil {
|
|
||||||
t.Fatalf("scoped knowledge write should pass route layer: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTenantAPIKeyRouteRejectsCrossKnowledgeBatchWriteForKnowledgeRestrictedKey(t *testing.T) {
|
|
||||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
|
||||||
Scopes: types.StringArray{types.TenantAPIKeyScopeWrite},
|
|
||||||
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
|
||||||
})
|
|
||||||
|
|
||||||
err := authorizeTenantAPIKeyAccess(ctx, http.MethodPost, "/api/v1/knowledge/batch-delete")
|
|
||||||
if !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
|
||||||
t.Fatalf("batch write error = %v, want errTenantAPIKeyScopeForbidden", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTenantAPIKeyScopeEmptyScopesDefaultToReadOnly(t *testing.T) {
|
|
||||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
|
||||||
Scopes: types.StringArray{},
|
|
||||||
})
|
|
||||||
|
|
||||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodPut, "/api/v1/tenants/kv/theme"); !stderrors.Is(err, errTenantAPIKeyScopeForbidden) {
|
|
||||||
t.Fatalf("empty scopes should default to read-only, got %v", err)
|
|
||||||
}
|
|
||||||
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodGet, "/api/v1/knowledge-bases"); err != nil {
|
if err := authorizeTenantAPIKeyAccess(ctx, http.MethodGet, "/api/v1/knowledge-bases"); err != nil {
|
||||||
t.Fatalf("empty scopes should allow GET: %v", err)
|
t.Fatalf("empty role should allow GET: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequireAPIKeyMinRoleForUnsafeAllowsContributorKnowledgeWrite(t *testing.T) {
|
||||||
|
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
|
Role: types.TenantRoleContributor,
|
||||||
|
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||||
|
})
|
||||||
|
if err := requireTenantAPIKeyMinRole(ctx, types.TenantRoleContributor); err != nil {
|
||||||
|
t.Fatalf("scoped knowledge write should pass route guard: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRequireAPIKeyDenyBlocksBatchWrite(t *testing.T) {
|
||||||
|
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||||
|
Role: types.TenantRoleContributor,
|
||||||
|
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||||
|
})
|
||||||
|
if err := requireTenantAPIKeyMinRole(ctx, types.TenantRoleContributor); err != nil {
|
||||||
|
t.Fatalf("unexpected contributor role check failure: %v", err)
|
||||||
|
}
|
||||||
|
// Deny is enforced by RequireAPIKeyDeny middleware on the route; verify scope exists.
|
||||||
|
if _, ok := types.TenantAPIKeyScopeFromContext(ctx); !ok {
|
||||||
|
t.Fatal("expected api key scope in context")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -313,10 +313,10 @@ func attachAPIKeyAuthContext(
|
|||||||
c.Set(types.PrincipalContextKey.String(), principal)
|
c.Set(types.PrincipalContextKey.String(), principal)
|
||||||
apiKeyRole := types.TenantRoleViewer
|
apiKeyRole := types.TenantRoleViewer
|
||||||
if key != nil {
|
if key != nil {
|
||||||
apiKeyRole = types.TenantAPIKeyScope{
|
apiKeyRole = types.NormalizeTenantAPIKeyRole(key.Role)
|
||||||
Scopes: key.Scopes,
|
if apiKeyRole == "" {
|
||||||
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
|
apiKeyRole = types.TenantRoleViewer
|
||||||
}.TenantRole()
|
}
|
||||||
}
|
}
|
||||||
c.Set(types.TenantRoleContextKey.String(), apiKeyRole)
|
c.Set(types.TenantRoleContextKey.String(), apiKeyRole)
|
||||||
c.Set(types.SystemAdminContextKey.String(), false)
|
c.Set(types.SystemAdminContextKey.String(), false)
|
||||||
@@ -328,7 +328,7 @@ func attachAPIKeyAuthContext(
|
|||||||
if key != nil {
|
if key != nil {
|
||||||
ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{
|
ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{
|
||||||
KeyID: key.ID,
|
KeyID: key.ID,
|
||||||
Scopes: key.Scopes,
|
Role: apiKeyRole,
|
||||||
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
|
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,13 +21,16 @@ func TestAuthenticateAPIKeyScopeUsesRequestContextAfterAttach(t *testing.T) {
|
|||||||
preAttach := c.Request.Context()
|
preAttach := c.Request.Context()
|
||||||
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(preAttach, types.TenantAPIKeyScope{
|
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(preAttach, types.TenantAPIKeyScope{
|
||||||
KeyID: 1,
|
KeyID: 1,
|
||||||
Scopes: types.StringArray{types.TenantAPIKeyScopeRead},
|
Role: types.TenantRoleViewer,
|
||||||
}))
|
}))
|
||||||
|
|
||||||
if err := authorizeTenantAPIKeyAccess(preAttach, c.Request.Method, c.Request.URL.Path); err != nil {
|
if err := authorizeTenantAPIKeyAccess(preAttach, c.Request.Method, c.Request.URL.Path); err != nil {
|
||||||
t.Fatalf("pre-attach ctx should not carry scope and must not block: %v", err)
|
t.Fatalf("pre-attach ctx should not carry scope and must not block: %v", err)
|
||||||
}
|
}
|
||||||
if err := authorizeTenantAPIKeyAccess(c.Request.Context(), c.Request.Method, c.Request.URL.Path); err == nil {
|
if err := authorizeTenantAPIKeyAccess(c.Request.Context(), c.Request.Method, c.Request.URL.Path); err != nil {
|
||||||
t.Fatal("post-attach request context must enforce read scope on DELETE")
|
t.Fatalf("baseline defers unsafe DELETE to route guards: %v", err)
|
||||||
|
}
|
||||||
|
if err := requireTenantAPIKeyMinRole(c.Request.Context(), types.TenantRoleContributor); err == nil {
|
||||||
|
t.Fatal("viewer key must not satisfy contributor route guard on DELETE")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -198,6 +198,25 @@ func (g *rbacGuards) Owner() gin.HandlerFunc {
|
|||||||
return middleware.RequireRole(types.TenantRoleOwner, g.cfg)
|
return middleware.RequireRole(types.TenantRoleOwner, g.cfg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// API-key guards — orthogonal to JWT role guards. They only constrain
|
||||||
|
// X-API-Key principals; bearer sessions pass through unchanged.
|
||||||
|
|
||||||
|
func (g *rbacGuards) APIKeyDeny() gin.HandlerFunc {
|
||||||
|
return middleware.RequireAPIKeyDeny()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *rbacGuards) APIKeyViewer() gin.HandlerFunc {
|
||||||
|
return middleware.RequireAPIKeyMinRole(types.TenantRoleViewer)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *rbacGuards) APIKeyContributor() gin.HandlerFunc {
|
||||||
|
return middleware.RequireAPIKeyMinRoleForUnsafe(types.TenantRoleContributor)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *rbacGuards) APIKeyAdmin() gin.HandlerFunc {
|
||||||
|
return middleware.RequireAPIKeyMinRoleForUnsafe(types.TenantRoleAdmin)
|
||||||
|
}
|
||||||
|
|
||||||
func (g *rbacGuards) SystemAdmin() gin.HandlerFunc {
|
func (g *rbacGuards) SystemAdmin() gin.HandlerFunc {
|
||||||
return middleware.RequireSystemAdmin(g.cfg)
|
return middleware.RequireSystemAdmin(g.cfg)
|
||||||
}
|
}
|
||||||
|
|||||||
+67
-67
@@ -245,7 +245,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
|||||||
// has not yet expired are kept out by the role check, matching the
|
// has not yet expired are kept out by the role check, matching the
|
||||||
// rest of the RBAC matrix in this file.
|
// rest of the RBAC matrix in this file.
|
||||||
func RegisterChunkerDebugRoutes(r *gin.RouterGroup, g *rbacGuards) {
|
func RegisterChunkerDebugRoutes(r *gin.RouterGroup, g *rbacGuards) {
|
||||||
r.POST("/chunker/preview", g.Viewer(), handler.PreviewChunking)
|
r.POST("/chunker/preview", g.Viewer(), g.APIKeyViewer(), handler.PreviewChunking)
|
||||||
}
|
}
|
||||||
|
|
||||||
// RegisterChunkRoutes 注册分块相关的路由
|
// RegisterChunkRoutes 注册分块相关的路由
|
||||||
@@ -256,7 +256,7 @@ func RegisterChunkerDebugRoutes(r *gin.RouterGroup, g *rbacGuards) {
|
|||||||
// same "creator-of-the-KB OR Admin+" rule applies to chunk edits.
|
// same "creator-of-the-KB OR Admin+" rule applies to chunk edits.
|
||||||
func RegisterChunkRoutes(r *gin.RouterGroup, handler *handler.ChunkHandler, g *rbacGuards) {
|
func RegisterChunkRoutes(r *gin.RouterGroup, handler *handler.ChunkHandler, g *rbacGuards) {
|
||||||
// 分块路由组
|
// 分块路由组
|
||||||
chunks := r.Group("/chunks")
|
chunks := r.Group("/chunks", g.APIKeyContributor())
|
||||||
{
|
{
|
||||||
// 获取分块列表 — Viewer+ 且对父 KB 有 read 权限(own / shared / via shared agent)
|
// 获取分块列表 — Viewer+ 且对父 KB 有 read 权限(own / shared / via shared agent)
|
||||||
chunks.GET("/:knowledge_id", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("knowledge_id"), handler.ListKnowledgeChunks)
|
chunks.GET("/:knowledge_id", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("knowledge_id"), handler.ListKnowledgeChunks)
|
||||||
@@ -289,7 +289,7 @@ func RegisterChunkRoutes(r *gin.RouterGroup, handler *handler.ChunkHandler, g *r
|
|||||||
// a single owning KB to check against.
|
// a single owning KB to check against.
|
||||||
func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandler, g *rbacGuards) {
|
func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandler, g *rbacGuards) {
|
||||||
// 知识库下的知识路由组(URL :id is the KB id)
|
// 知识库下的知识路由组(URL :id is the KB id)
|
||||||
kb := r.Group("/knowledge-bases/:id/knowledge")
|
kb := r.Group("/knowledge-bases/:id/knowledge", g.APIKeyContributor())
|
||||||
{
|
{
|
||||||
kb.POST("/file", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateKnowledgeFromFile)
|
kb.POST("/file", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateKnowledgeFromFile)
|
||||||
kb.POST("/url", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateKnowledgeFromURL)
|
kb.POST("/url", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateKnowledgeFromURL)
|
||||||
@@ -297,11 +297,11 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl
|
|||||||
kb.GET("", g.Viewer(), g.KBAccessRead("id"), handler.ListKnowledge)
|
kb.GET("", g.Viewer(), g.KBAccessRead("id"), handler.ListKnowledge)
|
||||||
// Clearing all contents under a KB is a destructive op; gate
|
// Clearing all contents under a KB is a destructive op; gate
|
||||||
// behind Admin instead of Contributor.
|
// behind Admin instead of Contributor.
|
||||||
kb.DELETE("", g.Admin(), g.KBAccessWrite("id"), handler.ClearKnowledgeBaseContents)
|
kb.DELETE("", g.Admin(), g.KBAccessWrite("id"), g.APIKeyAdmin(), handler.ClearKnowledgeBaseContents)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 知识路由组(URL :id is a knowledge id; the guard walks it to the parent KB)
|
// 知识路由组(URL :id is a knowledge id; the guard walks it to the parent KB)
|
||||||
k := r.Group("/knowledge")
|
k := r.Group("/knowledge", g.APIKeyContributor())
|
||||||
{
|
{
|
||||||
// Cross-knowledge endpoints (no :id) can't be gated on a single
|
// Cross-knowledge endpoints (no :id) can't be gated on a single
|
||||||
// KB — they accept arbitrary knowledge IDs and the handler must
|
// KB — they accept arbitrary knowledge IDs and the handler must
|
||||||
@@ -323,11 +323,11 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl
|
|||||||
// single owning KB to walk back to. A future PR could add a
|
// single owning KB to walk back to. A future PR could add a
|
||||||
// "must own every targeted KB" guard if the requirement
|
// "must own every targeted KB" guard if the requirement
|
||||||
// surfaces.
|
// surfaces.
|
||||||
k.PUT("/tags", g.Contributor(), handler.UpdateKnowledgeTagBatch)
|
k.PUT("/tags", g.Contributor(), g.APIKeyDeny(), handler.UpdateKnowledgeTagBatch)
|
||||||
k.POST("/batch-reparse", g.Contributor(), handler.BatchReparseKnowledge)
|
k.POST("/batch-reparse", g.Contributor(), g.APIKeyDeny(), handler.BatchReparseKnowledge)
|
||||||
k.GET("/search", g.Viewer(), handler.SearchKnowledge)
|
k.GET("/search", g.Viewer(), handler.SearchKnowledge)
|
||||||
k.POST("/batch-delete", g.Contributor(), handler.BatchDeleteKnowledge)
|
k.POST("/batch-delete", g.Contributor(), g.APIKeyDeny(), handler.BatchDeleteKnowledge)
|
||||||
k.POST("/move", g.Contributor(), handler.MoveKnowledge)
|
k.POST("/move", g.Contributor(), g.APIKeyDeny(), handler.MoveKnowledge)
|
||||||
k.GET("/move/progress/:task_id", g.Viewer(), handler.GetKnowledgeMoveProgress)
|
k.GET("/move/progress/:task_id", g.Viewer(), handler.GetKnowledgeMoveProgress)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -345,7 +345,7 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler, g *rbacG
|
|||||||
// 等价于修改 KB 内容,必须遵循 KB 的"creator OR Admin+"矩阵 ——
|
// 等价于修改 KB 内容,必须遵循 KB 的"creator OR Admin+"矩阵 ——
|
||||||
// 跟 chunks / wiki pages 保持一致。Viewer+ 可以读,Contributor 不能
|
// 跟 chunks / wiki pages 保持一致。Viewer+ 可以读,Contributor 不能
|
||||||
// 改不属于自己的 KB 的 FAQ。
|
// 改不属于自己的 KB 的 FAQ。
|
||||||
faq := r.Group("/knowledge-bases/:id/faq")
|
faq := r.Group("/knowledge-bases/:id/faq", g.APIKeyContributor())
|
||||||
{
|
{
|
||||||
// KBAccessRead/Write resolve own/shared/agent-visible access and
|
// KBAccessRead/Write resolve own/shared/agent-visible access and
|
||||||
// rewrite the request's tenant context — handler no longer
|
// rewrite the request's tenant context — handler no longer
|
||||||
@@ -361,7 +361,7 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler, g *rbacG
|
|||||||
faq.PUT("/entries/fields", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateEntryFieldsBatch)
|
faq.PUT("/entries/fields", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateEntryFieldsBatch)
|
||||||
faq.PUT("/entries/tags", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateEntryTagBatch)
|
faq.PUT("/entries/tags", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateEntryTagBatch)
|
||||||
faq.DELETE("/entries", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.DeleteEntries)
|
faq.DELETE("/entries", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.DeleteEntries)
|
||||||
faq.POST("/search", g.Viewer(), g.KBAccessRead("id"), handler.SearchFAQ)
|
faq.POST("/search", g.Viewer(), g.KBAccessRead("id"), g.APIKeyViewer(), handler.SearchFAQ)
|
||||||
// FAQ import result display status
|
// FAQ import result display status
|
||||||
faq.PUT("/import/last-result/display", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateLastImportResultDisplayStatus)
|
faq.PUT("/import/last-result/display", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateLastImportResultDisplayStatus)
|
||||||
}
|
}
|
||||||
@@ -377,16 +377,16 @@ func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeB
|
|||||||
// 知识库路由组
|
// 知识库路由组
|
||||||
kb := r.Group("/knowledge-bases")
|
kb := r.Group("/knowledge-bases")
|
||||||
{
|
{
|
||||||
// 创建知识库 — Contributor+ (no :id, role-only floor)
|
// 创建知识库 — Contributor+ (no :id, role-only floor); API keys may not create KBs.
|
||||||
kb.POST("", g.Contributor(), handler.CreateKnowledgeBase)
|
kb.POST("", g.Contributor(), g.APIKeyDeny(), handler.CreateKnowledgeBase)
|
||||||
// 获取知识库列表 — Viewer+ (no :id, role-only floor)
|
// 获取知识库列表 — Viewer+ (no :id, role-only floor)
|
||||||
kb.GET("", g.Viewer(), handler.ListKnowledgeBases)
|
kb.GET("", g.Viewer(), handler.ListKnowledgeBases)
|
||||||
// 获取知识库详情 — Viewer+ 且对 KB 有 read 权限
|
// 获取知识库详情 — Viewer+ 且对 KB 有 read 权限
|
||||||
kb.GET("/:id", g.Viewer(), g.KBAccessRead("id"), handler.GetKnowledgeBase)
|
kb.GET("/:id", g.Viewer(), g.KBAccessRead("id"), handler.GetKnowledgeBase)
|
||||||
// 更新知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
// 更新知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
||||||
kb.PUT("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateKnowledgeBase)
|
kb.PUT("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), g.APIKeyContributor(), handler.UpdateKnowledgeBase)
|
||||||
// 删除知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
// 删除知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
||||||
kb.DELETE("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.DeleteKnowledgeBase)
|
kb.DELETE("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), g.APIKeyContributor(), handler.DeleteKnowledgeBase)
|
||||||
// 置顶/取消置顶知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
// 置顶/取消置顶知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
||||||
// Pin state is now per-(user, kb) (migration 000050). Anyone with
|
// Pin state is now per-(user, kb) (migration 000050). Anyone with
|
||||||
// at least Viewer-level read access to the KB — including users
|
// at least Viewer-level read access to the KB — including users
|
||||||
@@ -394,13 +394,13 @@ func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeB
|
|||||||
// no edit permission is required. The OwnedKBOrAdmin guard was
|
// no edit permission is required. The OwnedKBOrAdmin guard was
|
||||||
// removed accordingly. The route still requires KB read access
|
// removed accordingly. The route still requires KB read access
|
||||||
// so callers can't poke at KBs they can't see.
|
// so callers can't poke at KBs they can't see.
|
||||||
kb.PUT("/:id/pin", g.Viewer(), g.KBAccessRead("id"), handler.TogglePinKnowledgeBase)
|
kb.PUT("/:id/pin", g.Viewer(), g.KBAccessRead("id"), g.APIKeyContributor(), handler.TogglePinKnowledgeBase)
|
||||||
// 混合搜索 — Viewer+ 且对 KB 有 read 权限 (read-only)
|
// 混合搜索 — Viewer+ 且对 KB 有 read 权限 (read-only)
|
||||||
// POST is preferred; GET with JSON body is kept for backward compatibility (#1727).
|
// POST is preferred; GET with JSON body is kept for backward compatibility (#1727).
|
||||||
kb.POST("/:id/hybrid-search", g.Viewer(), g.KBAccessRead("id"), handler.HybridSearch)
|
kb.POST("/:id/hybrid-search", g.Viewer(), g.KBAccessRead("id"), g.APIKeyViewer(), handler.HybridSearch)
|
||||||
kb.GET("/:id/hybrid-search", g.Viewer(), g.KBAccessRead("id"), handler.HybridSearch)
|
kb.GET("/:id/hybrid-search", g.Viewer(), g.KBAccessRead("id"), handler.HybridSearch)
|
||||||
// 拷贝知识库 — Contributor+ (副本归调用者所有;不需要原 KB 的所有权)
|
// 拷贝知识库 — Contributor+ (副本归调用者所有;不需要原 KB 的所有权)
|
||||||
kb.POST("/copy", g.Contributor(), handler.CopyKnowledgeBase)
|
kb.POST("/copy", g.Contributor(), g.APIKeyDeny(), handler.CopyKnowledgeBase)
|
||||||
// 获取知识库复制进度 — Viewer+
|
// 获取知识库复制进度 — Viewer+
|
||||||
kb.GET("/copy/progress/:task_id", g.Viewer(), handler.GetKBCloneProgress)
|
kb.GET("/copy/progress/:task_id", g.Viewer(), handler.GetKBCloneProgress)
|
||||||
// 获取可移动目标知识库列表 — Viewer+ 且对 KB 有 read 权限
|
// 获取可移动目标知识库列表 — Viewer+ 且对 KB 有 read 权限
|
||||||
@@ -420,7 +420,7 @@ func RegisterKnowledgeTagRoutes(r *gin.RouterGroup, tagHandler *handler.TagHandl
|
|||||||
// Tags 是 KB 的子资源 — 创建/编辑/删除标签会改变 KB 内容的检索分类
|
// Tags 是 KB 的子资源 — 创建/编辑/删除标签会改变 KB 内容的检索分类
|
||||||
// 行为,应该与 KB 主体的"creator OR Admin+"矩阵一致,避免一个无
|
// 行为,应该与 KB 主体的"creator OR Admin+"矩阵一致,避免一个无
|
||||||
// 关 Contributor 在他人 KB 里乱建/删标签影响 KB owner 的内容组织。
|
// 关 Contributor 在他人 KB 里乱建/删标签影响 KB owner 的内容组织。
|
||||||
kbTags := r.Group("/knowledge-bases/:id/tags")
|
kbTags := r.Group("/knowledge-bases/:id/tags", g.APIKeyContributor())
|
||||||
{
|
{
|
||||||
// KBAccessRead/Write resolve own/shared/agent-visible access and
|
// KBAccessRead/Write resolve own/shared/agent-visible access and
|
||||||
// rewrite the request's tenant context to the effective tenant
|
// rewrite the request's tenant context to the effective tenant
|
||||||
@@ -442,10 +442,10 @@ func RegisterKnowledgeTagRoutes(r *gin.RouterGroup, tagHandler *handler.TagHandl
|
|||||||
func RegisterMessageRoutes(r *gin.RouterGroup, handler *handler.MessageHandler, g *rbacGuards) {
|
func RegisterMessageRoutes(r *gin.RouterGroup, handler *handler.MessageHandler, g *rbacGuards) {
|
||||||
messages := r.Group("/messages")
|
messages := r.Group("/messages")
|
||||||
{
|
{
|
||||||
messages.POST("/search", g.Viewer(), handler.SearchMessages)
|
messages.POST("/search", g.Viewer(), g.APIKeyViewer(), handler.SearchMessages)
|
||||||
messages.GET("/chat-history-stats", g.Viewer(), handler.GetChatHistoryKBStats)
|
messages.GET("/chat-history-stats", g.Viewer(), handler.GetChatHistoryKBStats)
|
||||||
messages.GET("/:session_id/load", g.Viewer(), handler.LoadMessages)
|
messages.GET("/:session_id/load", g.Viewer(), handler.LoadMessages)
|
||||||
messages.DELETE("/:session_id/:id", g.Viewer(), handler.DeleteMessage)
|
messages.DELETE("/:session_id/:id", g.Viewer(), g.APIKeyAdmin(), handler.DeleteMessage)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -457,7 +457,7 @@ func RegisterMessageRoutes(r *gin.RouterGroup, handler *handler.MessageHandler,
|
|||||||
// per-session ownership in the middleware layer the same way KB/agent
|
// per-session ownership in the middleware layer the same way KB/agent
|
||||||
// routes do today.
|
// routes do today.
|
||||||
func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGuards) {
|
func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGuards) {
|
||||||
sessions := r.Group("/sessions", g.Viewer())
|
sessions := r.Group("/sessions", g.Viewer(), g.APIKeyContributor())
|
||||||
{
|
{
|
||||||
sessions.POST("", handler.CreateSession)
|
sessions.POST("", handler.CreateSession)
|
||||||
sessions.DELETE("/batch", handler.BatchDeleteSessions)
|
sessions.DELETE("/batch", handler.BatchDeleteSessions)
|
||||||
@@ -483,19 +483,19 @@ func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbac
|
|||||||
// surfaces; Viewer+ is sufficient because per-session/per-agent
|
// surfaces; Viewer+ is sufficient because per-session/per-agent
|
||||||
// authorisation is enforced inside the handlers.
|
// authorisation is enforced inside the handlers.
|
||||||
func RegisterChatRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGuards) {
|
func RegisterChatRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGuards) {
|
||||||
knowledgeChat := r.Group("/knowledge-chat", g.Viewer())
|
knowledgeChat := r.Group("/knowledge-chat", g.Viewer(), g.APIKeyViewer())
|
||||||
{
|
{
|
||||||
knowledgeChat.POST("/:session_id", handler.KnowledgeQA)
|
knowledgeChat.POST("/:session_id", handler.KnowledgeQA)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Agent-based chat
|
// Agent-based chat
|
||||||
agentChat := r.Group("/agent-chat", g.Viewer())
|
agentChat := r.Group("/agent-chat", g.Viewer(), g.APIKeyViewer())
|
||||||
{
|
{
|
||||||
agentChat.POST("/:session_id", handler.AgentQA)
|
agentChat.POST("/:session_id", handler.AgentQA)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 新增知识检索接口,不需要session_id
|
// 新增知识检索接口,不需要session_id
|
||||||
knowledgeSearch := r.Group("/knowledge-search", g.Viewer())
|
knowledgeSearch := r.Group("/knowledge-search", g.Viewer(), g.APIKeyViewer())
|
||||||
{
|
{
|
||||||
knowledgeSearch.POST("", handler.SearchKnowledge)
|
knowledgeSearch.POST("", handler.SearchKnowledge)
|
||||||
}
|
}
|
||||||
@@ -555,7 +555,7 @@ func RegisterTenantRoutes(
|
|||||||
// 安全说明:这里不挂 g.CrossTenant(),因为 self-service 创建
|
// 安全说明:这里不挂 g.CrossTenant(),因为 self-service 创建
|
||||||
// 不需要跨租户特权;handler 也不读写 X-Tenant-ID 指向的现有
|
// 不需要跨租户特权;handler 也不读写 X-Tenant-ID 指向的现有
|
||||||
// 租户,所以越过 PathTenantMatch 守卫不会扩大攻击面。
|
// 租户,所以越过 PathTenantMatch 守卫不会扩大攻击面。
|
||||||
tenantRoutes.POST("", handler.CreateTenant)
|
tenantRoutes.POST("", g.APIKeyDeny(), handler.CreateTenant)
|
||||||
tenantRoutes.GET("", handler.ListTenants)
|
tenantRoutes.GET("", handler.ListTenants)
|
||||||
|
|
||||||
// Generic KV configuration management (tenant-level). Tenant ID
|
// Generic KV configuration management (tenant-level). Tenant ID
|
||||||
@@ -563,7 +563,7 @@ func RegisterTenantRoutes(
|
|||||||
// config key, not a tenant ID, so these stay outside the
|
// config key, not a tenant ID, so these stay outside the
|
||||||
// PathTenantMatch group.
|
// PathTenantMatch group.
|
||||||
tenantRoutes.GET("/kv/:key", g.Viewer(), handler.GetTenantKV)
|
tenantRoutes.GET("/kv/:key", g.Viewer(), handler.GetTenantKV)
|
||||||
tenantRoutes.PUT("/kv/:key", g.Admin(), handler.UpdateTenantKV)
|
tenantRoutes.PUT("/kv/:key", g.Admin(), g.APIKeyAdmin(), handler.UpdateTenantKV)
|
||||||
|
|
||||||
// Per-tenant endpoints share PathTenantMatch at the group level.
|
// Per-tenant endpoints share PathTenantMatch at the group level.
|
||||||
tenantByID := tenantRoutes.Group("/:id", g.PathTenantMatch())
|
tenantByID := tenantRoutes.Group("/:id", g.PathTenantMatch())
|
||||||
@@ -571,13 +571,13 @@ func RegisterTenantRoutes(
|
|||||||
tenantByID.GET("", g.Viewer(), handler.GetTenant)
|
tenantByID.GET("", g.Viewer(), handler.GetTenant)
|
||||||
tenantByID.PUT("", g.Owner(), handler.UpdateTenant)
|
tenantByID.PUT("", g.Owner(), handler.UpdateTenant)
|
||||||
tenantByID.DELETE("", g.Owner(), handler.DeleteTenant)
|
tenantByID.DELETE("", g.Owner(), handler.DeleteTenant)
|
||||||
tenantByID.POST("/api-key", g.Owner(), handler.ResetAPIKey)
|
tenantByID.POST("/api-key", g.Owner(), g.APIKeyDeny(), handler.ResetAPIKey)
|
||||||
tenantByID.GET("/api-keys", g.Owner(), handler.ListAPIKeys)
|
tenantByID.GET("/api-keys", g.Owner(), g.APIKeyDeny(), handler.ListAPIKeys)
|
||||||
tenantByID.POST("/api-keys", g.Owner(), handler.CreateAPIKey)
|
tenantByID.POST("/api-keys", g.Owner(), g.APIKeyDeny(), handler.CreateAPIKey)
|
||||||
tenantByID.DELETE("/api-keys/:key_id", g.Owner(), handler.DeleteAPIKey)
|
tenantByID.DELETE("/api-keys/:key_id", g.Owner(), g.APIKeyDeny(), handler.DeleteAPIKey)
|
||||||
tenantByID.GET("/api-principal-config", g.Owner(), handler.GetAPIPrincipalConfig)
|
tenantByID.GET("/api-principal-config", g.Owner(), g.APIKeyDeny(), handler.GetAPIPrincipalConfig)
|
||||||
tenantByID.PUT("/api-principal-config", g.Owner(), handler.UpdateAPIPrincipalConfig)
|
tenantByID.PUT("/api-principal-config", g.Owner(), g.APIKeyDeny(), handler.UpdateAPIPrincipalConfig)
|
||||||
tenantByID.POST("/api-principal-test-token", g.Owner(), handler.CreateAPIPrincipalTestToken)
|
tenantByID.POST("/api-principal-test-token", g.Owner(), g.APIKeyDeny(), handler.CreateAPIPrincipalTestToken)
|
||||||
|
|
||||||
// Tenant member management (PR 3 of #1303). Listing is
|
// Tenant member management (PR 3 of #1303). Listing is
|
||||||
// Viewer+ so any active member can see the roster; mutation
|
// Viewer+ so any active member can see the roster; mutation
|
||||||
@@ -635,7 +635,7 @@ func RegisterModelRoutes(
|
|||||||
g *rbacGuards,
|
g *rbacGuards,
|
||||||
) {
|
) {
|
||||||
// 模型路由组
|
// 模型路由组
|
||||||
models := r.Group("/models")
|
models := r.Group("/models", g.APIKeyAdmin())
|
||||||
{
|
{
|
||||||
// 获取模型厂商列表 — Viewer+
|
// 获取模型厂商列表 — Viewer+
|
||||||
models.GET("/providers", g.Viewer(), handler.ListModelProviders)
|
models.GET("/providers", g.Viewer(), handler.ListModelProviders)
|
||||||
@@ -664,7 +664,7 @@ func RegisterModelRoutes(
|
|||||||
func RegisterEvaluationRoutes(r *gin.RouterGroup, handler *handler.EvaluationHandler, g *rbacGuards) {
|
func RegisterEvaluationRoutes(r *gin.RouterGroup, handler *handler.EvaluationHandler, g *rbacGuards) {
|
||||||
evaluationRoutes := r.Group("/evaluation")
|
evaluationRoutes := r.Group("/evaluation")
|
||||||
{
|
{
|
||||||
evaluationRoutes.POST("/", g.Admin(), handler.Evaluation)
|
evaluationRoutes.POST("/", g.Admin(), g.APIKeyAdmin(), handler.Evaluation)
|
||||||
evaluationRoutes.GET("/", g.Viewer(), handler.GetEvaluationResult)
|
evaluationRoutes.GET("/", g.Viewer(), handler.GetEvaluationResult)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -727,29 +727,29 @@ func RegisterInitializationRoutes(r *gin.RouterGroup, handler *handler.Initializ
|
|||||||
r.GET("/initialization/config/:kbId", g.Viewer(), g.KBAccessRead("kbId"), handler.GetCurrentConfigByKB)
|
r.GET("/initialization/config/:kbId", g.Viewer(), g.KBAccessRead("kbId"), handler.GetCurrentConfigByKB)
|
||||||
// InitializeByKB / UpdateKBConfig 都是改 KB 的核心模型/storage 配置 —
|
// InitializeByKB / UpdateKBConfig 都是改 KB 的核心模型/storage 配置 —
|
||||||
// 跟 PUT /knowledge-bases/:id 同等敏感,挂同款 OwnedKB 矩阵。
|
// 跟 PUT /knowledge-bases/:id 同等敏感,挂同款 OwnedKB 矩阵。
|
||||||
r.POST("/initialization/initialize/:kbId", g.OwnedKBOrAdminFromKbIDParam(), handler.InitializeByKB)
|
r.POST("/initialization/initialize/:kbId", g.OwnedKBOrAdminFromKbIDParam(), g.APIKeyContributor(), handler.InitializeByKB)
|
||||||
r.PUT("/initialization/config/:kbId", g.OwnedKBOrAdminFromKbIDParam(), handler.UpdateKBConfig)
|
r.PUT("/initialization/config/:kbId", g.OwnedKBOrAdminFromKbIDParam(), g.APIKeyContributor(), handler.UpdateKBConfig)
|
||||||
|
|
||||||
// Ollama / 远程 API / 抽取等系统级检测/下载操作。这些不绑某个 KB,
|
// Ollama / 远程 API / 抽取等系统级检测/下载操作。这些不绑某个 KB,
|
||||||
// 但会改租户级模型配置或拉远端模型 — 一律 Admin+。Viewer+ 的检测
|
// 但会改租户级模型配置或拉远端模型 — 一律 Admin+。Viewer+ 的检测
|
||||||
// 入口已经在 settings 页面隐藏,但服务端仍要兜底。
|
// 入口已经在 settings 页面隐藏,但服务端仍要兜底。
|
||||||
r.GET("/initialization/ollama/status", g.Viewer(), handler.CheckOllamaStatus)
|
r.GET("/initialization/ollama/status", g.Viewer(), handler.CheckOllamaStatus)
|
||||||
r.GET("/initialization/ollama/models", g.Viewer(), handler.ListOllamaModels)
|
r.GET("/initialization/ollama/models", g.Viewer(), handler.ListOllamaModels)
|
||||||
r.POST("/initialization/ollama/models/check", g.Admin(), handler.CheckOllamaModels)
|
r.POST("/initialization/ollama/models/check", g.Admin(), g.APIKeyAdmin(), handler.CheckOllamaModels)
|
||||||
r.POST("/initialization/ollama/models/download", g.Admin(), handler.DownloadOllamaModel)
|
r.POST("/initialization/ollama/models/download", g.Admin(), g.APIKeyAdmin(), handler.DownloadOllamaModel)
|
||||||
r.GET("/initialization/ollama/download/progress/:taskId", g.Viewer(), handler.GetDownloadProgress)
|
r.GET("/initialization/ollama/download/progress/:taskId", g.Viewer(), handler.GetDownloadProgress)
|
||||||
r.GET("/initialization/ollama/download/tasks", g.Viewer(), handler.ListDownloadTasks)
|
r.GET("/initialization/ollama/download/tasks", g.Viewer(), handler.ListDownloadTasks)
|
||||||
|
|
||||||
// 远程API相关接口
|
// 远程API相关接口
|
||||||
r.POST("/initialization/remote/check", g.Admin(), handler.CheckRemoteModel)
|
r.POST("/initialization/remote/check", g.Admin(), g.APIKeyAdmin(), handler.CheckRemoteModel)
|
||||||
r.POST("/initialization/embedding/test", g.Admin(), handler.TestEmbeddingModel)
|
r.POST("/initialization/embedding/test", g.Admin(), g.APIKeyAdmin(), handler.TestEmbeddingModel)
|
||||||
r.POST("/initialization/rerank/check", g.Admin(), handler.CheckRerankModel)
|
r.POST("/initialization/rerank/check", g.Admin(), g.APIKeyAdmin(), handler.CheckRerankModel)
|
||||||
r.POST("/initialization/asr/check", g.Admin(), handler.CheckASRModel)
|
r.POST("/initialization/asr/check", g.Admin(), g.APIKeyAdmin(), handler.CheckASRModel)
|
||||||
r.POST("/initialization/multimodal/test", g.Admin(), handler.TestMultimodalFunction)
|
r.POST("/initialization/multimodal/test", g.Admin(), g.APIKeyAdmin(), handler.TestMultimodalFunction)
|
||||||
|
|
||||||
r.POST("/initialization/extract/text-relation", g.Admin(), handler.ExtractTextRelations)
|
r.POST("/initialization/extract/text-relation", g.Admin(), g.APIKeyAdmin(), handler.ExtractTextRelations)
|
||||||
r.POST("/initialization/extract/fabri-tag", g.Admin(), handler.FabriTag)
|
r.POST("/initialization/extract/fabri-tag", g.Admin(), g.APIKeyAdmin(), handler.FabriTag)
|
||||||
r.POST("/initialization/extract/fabri-text", g.Admin(), handler.FabriText)
|
r.POST("/initialization/extract/fabri-text", g.Admin(), g.APIKeyAdmin(), handler.FabriText)
|
||||||
}
|
}
|
||||||
|
|
||||||
// RegisterSystemRoutes registers system information routes
|
// RegisterSystemRoutes registers system information routes
|
||||||
@@ -760,7 +760,7 @@ func RegisterInitializationRoutes(r *gin.RouterGroup, handler *handler.Initializ
|
|||||||
// remote services with tenant credentials and could trigger network
|
// remote services with tenant credentials and could trigger network
|
||||||
// fanout, so they're Admin+.
|
// fanout, so they're Admin+.
|
||||||
func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler, g *rbacGuards) {
|
func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler, g *rbacGuards) {
|
||||||
systemRoutes := r.Group("/system")
|
systemRoutes := r.Group("/system", g.APIKeyAdmin())
|
||||||
{
|
{
|
||||||
systemRoutes.GET("/info", g.Viewer(), handler.GetSystemInfo)
|
systemRoutes.GET("/info", g.Viewer(), handler.GetSystemInfo)
|
||||||
systemRoutes.GET("/parser-engines", g.Viewer(), handler.ListParserEngines)
|
systemRoutes.GET("/parser-engines", g.Viewer(), handler.ListParserEngines)
|
||||||
@@ -853,7 +853,7 @@ func RegisterMCPServiceRoutes(
|
|||||||
// redirect carries no WeKnora bearer — the single-use state authenticates.
|
// redirect carries no WeKnora bearer — the single-use state authenticates.
|
||||||
r.GET("/mcp-oauth/callback", oauthHandler.Callback)
|
r.GET("/mcp-oauth/callback", oauthHandler.Callback)
|
||||||
|
|
||||||
mcpServices := r.Group("/mcp-services")
|
mcpServices := r.Group("/mcp-services", g.APIKeyAdmin())
|
||||||
{
|
{
|
||||||
// Create MCP service — Admin+
|
// Create MCP service — Admin+
|
||||||
mcpServices.POST("", g.Admin(), handler.CreateMCPService)
|
mcpServices.POST("", g.Admin(), handler.CreateMCPService)
|
||||||
@@ -886,7 +886,7 @@ func RegisterMCPServiceRoutes(
|
|||||||
mcpServices.DELETE("/:id/oauth/token", g.Viewer(), oauthHandler.Revoke)
|
mcpServices.DELETE("/:id/oauth/token", g.Viewer(), oauthHandler.Revoke)
|
||||||
}
|
}
|
||||||
|
|
||||||
agentTool := r.Group("/agent")
|
agentTool := r.Group("/agent", g.APIKeyDeny())
|
||||||
{
|
{
|
||||||
// Resolving a pending tool-approval is gated to tenant members
|
// Resolving a pending tool-approval is gated to tenant members
|
||||||
// (Viewer+). The approval card surfaces inside an agent chat the
|
// (Viewer+). The approval card surfaces inside an agent chat the
|
||||||
@@ -923,7 +923,7 @@ func RegisterWebSearchProviderRoutes(
|
|||||||
credHandler *handler.WebSearchProviderCredentialsHandler,
|
credHandler *handler.WebSearchProviderCredentialsHandler,
|
||||||
g *rbacGuards,
|
g *rbacGuards,
|
||||||
) {
|
) {
|
||||||
providers := r.Group("/web-search-providers")
|
providers := r.Group("/web-search-providers", g.APIKeyAdmin())
|
||||||
{
|
{
|
||||||
// List available provider types (metadata for UI forms) — Viewer+
|
// List available provider types (metadata for UI forms) — Viewer+
|
||||||
providers.GET("/types", g.Viewer(), h.ListProviderTypes)
|
providers.GET("/types", g.Viewer(), h.ListProviderTypes)
|
||||||
@@ -949,7 +949,7 @@ func RegisterWebSearchProviderRoutes(
|
|||||||
// writes (and connection tests, which probe external systems with stored
|
// writes (and connection tests, which probe external systems with stored
|
||||||
// credentials) are Admin+.
|
// credentials) are Admin+.
|
||||||
func RegisterVectorStoreRoutes(r *gin.RouterGroup, h *handler.VectorStoreHandler, g *rbacGuards) {
|
func RegisterVectorStoreRoutes(r *gin.RouterGroup, h *handler.VectorStoreHandler, g *rbacGuards) {
|
||||||
stores := r.Group("/vector-stores")
|
stores := r.Group("/vector-stores", g.APIKeyAdmin())
|
||||||
{
|
{
|
||||||
// List available engine types (metadata for UI forms) — Viewer+
|
// List available engine types (metadata for UI forms) — Viewer+
|
||||||
stores.GET("/types", g.Viewer(), h.ListStoreTypes)
|
stores.GET("/types", g.Viewer(), h.ListStoreTypes)
|
||||||
@@ -973,7 +973,7 @@ func RegisterVectorStoreRoutes(r *gin.RouterGroup, h *handler.VectorStoreHandler
|
|||||||
// (IsBuiltin=true) have an empty creator and are always Admin+. Reads
|
// (IsBuiltin=true) have an empty creator and are always Admin+. Reads
|
||||||
// are Viewer+, copy is Contributor+ (the copy is owned by the caller).
|
// are Viewer+, copy is Contributor+ (the copy is owned by the caller).
|
||||||
func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomAgentHandler, g *rbacGuards) {
|
func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomAgentHandler, g *rbacGuards) {
|
||||||
agents := r.Group("/agents")
|
agents := r.Group("/agents", g.APIKeyAdmin())
|
||||||
{
|
{
|
||||||
// Get placeholder definitions (must be before /:id to avoid conflict) — Viewer+
|
// Get placeholder definitions (must be before /:id to avoid conflict) — Viewer+
|
||||||
agents.GET("/placeholders", g.Viewer(), agentHandler.GetPlaceholders)
|
agents.GET("/placeholders", g.Viewer(), agentHandler.GetPlaceholders)
|
||||||
@@ -1004,7 +1004,7 @@ func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomA
|
|||||||
// don't follow the OwnedXOrAdmin pattern: favorites aren't owned by the
|
// don't follow the OwnedXOrAdmin pattern: favorites aren't owned by the
|
||||||
// resource's creator, they're owned by the user *doing* the starring.
|
// resource's creator, they're owned by the user *doing* the starring.
|
||||||
func RegisterUserFavoriteRoutes(r *gin.RouterGroup, h *handler.UserResourceFavoriteHandler, g *rbacGuards) {
|
func RegisterUserFavoriteRoutes(r *gin.RouterGroup, h *handler.UserResourceFavoriteHandler, g *rbacGuards) {
|
||||||
favs := r.Group("/user/favorites")
|
favs := r.Group("/user/favorites", g.APIKeyDeny())
|
||||||
{
|
{
|
||||||
favs.GET("", g.Viewer(), h.ListFavorites)
|
favs.GET("", g.Viewer(), h.ListFavorites)
|
||||||
favs.POST("", g.Viewer(), h.AddFavorite)
|
favs.POST("", g.Viewer(), h.AddFavorite)
|
||||||
@@ -1028,7 +1028,7 @@ func RegisterSkillRoutes(r *gin.RouterGroup, skillHandler *handler.SkillHandler,
|
|||||||
// RegisterOrganizationRoutes registers organization and sharing routes
|
// RegisterOrganizationRoutes registers organization and sharing routes
|
||||||
func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.OrganizationHandler, g *rbacGuards) {
|
func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.OrganizationHandler, g *rbacGuards) {
|
||||||
// Organization routes
|
// Organization routes
|
||||||
orgs := r.Group("/organizations")
|
orgs := r.Group("/organizations", g.APIKeyAdmin())
|
||||||
{
|
{
|
||||||
// Create organization (Admin+ in caller's tenant only)
|
// Create organization (Admin+ in caller's tenant only)
|
||||||
orgs.POST("", g.Admin(), orgHandler.CreateOrganization)
|
orgs.POST("", g.Admin(), orgHandler.CreateOrganization)
|
||||||
@@ -1109,7 +1109,7 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
|
|||||||
// 分享 KB 到组织 = 让组织里所有人能读这个 KB;这跟"修改 KB 元信息"
|
// 分享 KB 到组织 = 让组织里所有人能读这个 KB;这跟"修改 KB 元信息"
|
||||||
// 同等敏感,所以挂同款 OwnedKBOrAdmin 矩阵。Viewer 在自己租户里
|
// 同等敏感,所以挂同款 OwnedKBOrAdmin 矩阵。Viewer 在自己租户里
|
||||||
// 也不能私自把 KB 暴露出去。
|
// 也不能私自把 KB 暴露出去。
|
||||||
kbShares := r.Group("/knowledge-bases/:id/shares")
|
kbShares := r.Group("/knowledge-bases/:id/shares", g.APIKeyDeny())
|
||||||
{
|
{
|
||||||
// Share knowledge base
|
// Share knowledge base
|
||||||
kbShares.POST("", g.OwnedKBOrAdmin(), orgHandler.ShareKnowledgeBase)
|
kbShares.POST("", g.OwnedKBOrAdmin(), orgHandler.ShareKnowledgeBase)
|
||||||
@@ -1128,7 +1128,7 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
|
|||||||
// 校验(与 ListSharesByKnowledgeBase 不对称),如果路由层只挂 Viewer
|
// 校验(与 ListSharesByKnowledgeBase 不对称),如果路由层只挂 Viewer
|
||||||
// 任何同租户成员都能枚举他人 agent 的分享去向——这里把 owner 校验
|
// 任何同租户成员都能枚举他人 agent 的分享去向——这里把 owner 校验
|
||||||
// 兜底到路由层,匹配 POST/DELETE 的矩阵。
|
// 兜底到路由层,匹配 POST/DELETE 的矩阵。
|
||||||
agentShares := r.Group("/agents/:id/shares")
|
agentShares := r.Group("/agents/:id/shares", g.APIKeyDeny())
|
||||||
{
|
{
|
||||||
agentShares.POST("", g.OwnedAgentOrAdmin(), orgHandler.ShareAgent)
|
agentShares.POST("", g.OwnedAgentOrAdmin(), orgHandler.ShareAgent)
|
||||||
agentShares.GET("", g.OwnedAgentOrAdmin(), orgHandler.ListAgentShares)
|
agentShares.GET("", g.OwnedAgentOrAdmin(), orgHandler.ListAgentShares)
|
||||||
@@ -1142,7 +1142,7 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
|
|||||||
// "Disable by me" 是租户级偏好(写到 tenant_disabled_shared_agents),
|
// "Disable by me" 是租户级偏好(写到 tenant_disabled_shared_agents),
|
||||||
// 影响整个租户在会话下拉里看到的 agent 列表。任何 Viewer 改这个表就
|
// 影响整个租户在会话下拉里看到的 agent 列表。任何 Viewer 改这个表就
|
||||||
// 等于替整个租户做决定 — 必须 Admin+ 才允许调整。
|
// 等于替整个租户做决定 — 必须 Admin+ 才允许调整。
|
||||||
r.POST("/shared-agents/disabled", g.Admin(), orgHandler.SetSharedAgentDisabledByMe)
|
r.POST("/shared-agents/disabled", g.Admin(), g.APIKeyAdmin(), orgHandler.SetSharedAgentDisabledByMe)
|
||||||
}
|
}
|
||||||
|
|
||||||
// RegisterEmbedPublicRoutes registers anonymous embed endpoints secured by publish tokens.
|
// RegisterEmbedPublicRoutes registers anonymous embed endpoints secured by publish tokens.
|
||||||
@@ -1186,12 +1186,12 @@ func RegisterEmbedChannelRoutes(r *gin.RouterGroup, embedHandler *handler.EmbedC
|
|||||||
if embedHandler == nil {
|
if embedHandler == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
agentEmbed := r.Group("/agents/:id/embed-channels")
|
agentEmbed := r.Group("/agents/:id/embed-channels", g.APIKeyAdmin())
|
||||||
{
|
{
|
||||||
agentEmbed.POST("", g.Admin(), embedHandler.CreateEmbedChannel)
|
agentEmbed.POST("", g.Admin(), embedHandler.CreateEmbedChannel)
|
||||||
agentEmbed.GET("", g.Viewer(), embedHandler.ListEmbedChannels)
|
agentEmbed.GET("", g.Viewer(), embedHandler.ListEmbedChannels)
|
||||||
}
|
}
|
||||||
channels := r.Group("/embed-channels")
|
channels := r.Group("/embed-channels", g.APIKeyAdmin())
|
||||||
{
|
{
|
||||||
channels.GET("", g.Viewer(), embedHandler.ListAllEmbedChannels)
|
channels.GET("", g.Viewer(), embedHandler.ListAllEmbedChannels)
|
||||||
channels.GET("/:channel_id", g.Viewer(), embedHandler.GetEmbedChannel)
|
channels.GET("/:channel_id", g.Viewer(), embedHandler.GetEmbedChannel)
|
||||||
@@ -1220,14 +1220,14 @@ func RegisterIMRoutes(r *gin.Engine, imHandler *handler.IMHandler) {
|
|||||||
// (which can hijack a personal WeChat session) is Admin+.
|
// (which can hijack a personal WeChat session) is Admin+.
|
||||||
func RegisterIMChannelRoutes(r *gin.RouterGroup, imHandler *handler.IMHandler, g *rbacGuards) {
|
func RegisterIMChannelRoutes(r *gin.RouterGroup, imHandler *handler.IMHandler, g *rbacGuards) {
|
||||||
// Channel CRUD under agents
|
// Channel CRUD under agents
|
||||||
agentChannels := r.Group("/agents/:id/im-channels")
|
agentChannels := r.Group("/agents/:id/im-channels", g.APIKeyAdmin())
|
||||||
{
|
{
|
||||||
agentChannels.POST("", g.Admin(), imHandler.CreateIMChannel)
|
agentChannels.POST("", g.Admin(), imHandler.CreateIMChannel)
|
||||||
agentChannels.GET("", g.Viewer(), imHandler.ListIMChannels)
|
agentChannels.GET("", g.Viewer(), imHandler.ListIMChannels)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Channel operations by channel ID
|
// Channel operations by channel ID
|
||||||
channels := r.Group("/im-channels")
|
channels := r.Group("/im-channels", g.APIKeyAdmin())
|
||||||
{
|
{
|
||||||
channels.GET("", g.Viewer(), imHandler.ListAllIMChannels)
|
channels.GET("", g.Viewer(), imHandler.ListAllIMChannels)
|
||||||
channels.PUT("/:id", g.Admin(), imHandler.UpdateIMChannel)
|
channels.PUT("/:id", g.Admin(), imHandler.UpdateIMChannel)
|
||||||
@@ -1237,7 +1237,7 @@ func RegisterIMChannelRoutes(r *gin.RouterGroup, imHandler *handler.IMHandler, g
|
|||||||
|
|
||||||
// WeChat QR code login (requires authentication) — Admin+: a successful
|
// WeChat QR code login (requires authentication) — Admin+: a successful
|
||||||
// scan binds a personal WeChat account to the tenant.
|
// scan binds a personal WeChat account to the tenant.
|
||||||
wechatGroup := r.Group("/wechat")
|
wechatGroup := r.Group("/wechat", g.APIKeyAdmin())
|
||||||
{
|
{
|
||||||
wechatGroup.POST("/qrcode", g.Admin(), imHandler.WeChatGetQRCode)
|
wechatGroup.POST("/qrcode", g.Admin(), imHandler.WeChatGetQRCode)
|
||||||
wechatGroup.POST("/qrcode/status", g.Admin(), imHandler.WeChatPollQRCodeStatus)
|
wechatGroup.POST("/qrcode/status", g.Admin(), imHandler.WeChatPollQRCodeStatus)
|
||||||
@@ -1697,7 +1697,7 @@ func RegisterDataSourceRoutes(
|
|||||||
g *rbacGuards,
|
g *rbacGuards,
|
||||||
) {
|
) {
|
||||||
// Data source routes
|
// Data source routes
|
||||||
ds := r.Group("/datasource")
|
ds := r.Group("/datasource", g.APIKeyAdmin())
|
||||||
{
|
{
|
||||||
// Get available connector types — Viewer+
|
// Get available connector types — Viewer+
|
||||||
ds.GET("/types", g.Viewer(), handler.GetAvailableConnectors)
|
ds.GET("/types", g.Viewer(), handler.GetAvailableConnectors)
|
||||||
@@ -1739,7 +1739,7 @@ func RegisterDataSourceRoutes(
|
|||||||
// management endpoints. SaveCredentials persists external SaaS keys
|
// management endpoints. SaveCredentials persists external SaaS keys
|
||||||
// for the tenant (Admin+), Status is a low-risk readiness probe (Viewer+).
|
// for the tenant (Admin+), Status is a low-risk readiness probe (Viewer+).
|
||||||
func RegisterWeKnoraCloudRoutes(r *gin.RouterGroup, handler *handler.WeKnoraCloudHandler, g *rbacGuards) {
|
func RegisterWeKnoraCloudRoutes(r *gin.RouterGroup, handler *handler.WeKnoraCloudHandler, g *rbacGuards) {
|
||||||
r.POST("/weknoracloud/credentials", g.Admin(), handler.SaveCredentials)
|
r.POST("/weknoracloud/credentials", g.Admin(), g.APIKeyAdmin(), handler.SaveCredentials)
|
||||||
r.GET("/models/weknoracloud/status", g.Viewer(), handler.Status)
|
r.GET("/models/weknoracloud/status", g.Viewer(), handler.Status)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1753,7 +1753,7 @@ func RegisterWeKnoraCloudRoutes(r *gin.RouterGroup, handler *handler.WeKnoraClou
|
|||||||
// :kb_id resolves directly to the owning KB so a Contributor who owns
|
// :kb_id resolves directly to the owning KB so a Contributor who owns
|
||||||
// the KB can manage its wiki, while a non-owner Contributor gets 403.
|
// the KB can manage its wiki, while a non-owner Contributor gets 403.
|
||||||
func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHandler, g *rbacGuards) {
|
func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHandler, g *rbacGuards) {
|
||||||
wiki := r.Group("/knowledgebase/:kb_id/wiki")
|
wiki := r.Group("/knowledgebase/:kb_id/wiki", g.APIKeyContributor())
|
||||||
{
|
{
|
||||||
// Page CRUD
|
// Page CRUD
|
||||||
wiki.GET("/pages", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListPages)
|
wiki.GET("/pages", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListPages)
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ type TenantRepository interface {
|
|||||||
type TenantAPIKeyCreateRequest struct {
|
type TenantAPIKeyCreateRequest struct {
|
||||||
TenantID uint64
|
TenantID uint64
|
||||||
Name string
|
Name string
|
||||||
Scopes []string
|
Role types.TenantRole
|
||||||
KnowledgeBaseIDs []string
|
KnowledgeBaseIDs []string
|
||||||
ExpiresAt *time.Time
|
ExpiresAt *time.Time
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,16 +6,11 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/Tencent/WeKnora/internal/errors"
|
||||||
"github.com/Tencent/WeKnora/internal/utils"
|
"github.com/Tencent/WeKnora/internal/utils"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
|
||||||
TenantAPIKeyScopeRead = "read"
|
|
||||||
TenantAPIKeyScopeWrite = "write"
|
|
||||||
TenantAPIKeyScopeAdmin = "admin"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TenantAPIKey is a revocable, per-tenant API key. KeyHash is used for
|
// TenantAPIKey is a revocable, per-tenant API key. KeyHash is used for
|
||||||
// authentication lookup; APIKey is stored encrypted when SYSTEM_AES_KEY is set
|
// authentication lookup; APIKey is stored encrypted when SYSTEM_AES_KEY is set
|
||||||
// and returned by owner-only management APIs.
|
// and returned by owner-only management APIs.
|
||||||
@@ -25,7 +20,7 @@ type TenantAPIKey struct {
|
|||||||
Name string `json:"name" gorm:"type:varchar(128);not null"`
|
Name string `json:"name" gorm:"type:varchar(128);not null"`
|
||||||
KeyHash string `json:"-" gorm:"type:varchar(64);not null;uniqueIndex"`
|
KeyHash string `json:"-" gorm:"type:varchar(64);not null;uniqueIndex"`
|
||||||
APIKey string `json:"api_key" gorm:"column:api_key;type:text;not null;default:''"`
|
APIKey string `json:"api_key" gorm:"column:api_key;type:text;not null;default:''"`
|
||||||
Scopes StringArray `json:"scopes" gorm:"type:jsonb;not null;default:'[]'"`
|
Role TenantRole `json:"role" gorm:"type:varchar(32);not null;default:'viewer'"`
|
||||||
KnowledgeBaseIDs StringArray `json:"knowledge_base_ids" gorm:"type:jsonb;not null;default:'[]'"`
|
KnowledgeBaseIDs StringArray `json:"knowledge_base_ids" gorm:"type:jsonb;not null;default:'[]'"`
|
||||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||||
@@ -59,7 +54,7 @@ func (k *TenantAPIKey) AfterFind(tx *gorm.DB) error {
|
|||||||
// TenantAPIKeyScope is the request-context projection used by middleware.
|
// TenantAPIKeyScope is the request-context projection used by middleware.
|
||||||
type TenantAPIKeyScope struct {
|
type TenantAPIKeyScope struct {
|
||||||
KeyID uint64
|
KeyID uint64
|
||||||
Scopes StringArray
|
Role TenantRole
|
||||||
KnowledgeBaseIDs StringArray
|
KnowledgeBaseIDs StringArray
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,36 +76,27 @@ func TenantAPIKeyScopeFromContext(ctx context.Context) (TenantAPIKeyScope, bool)
|
|||||||
func (s TenantAPIKeyScope) Normalize() TenantAPIKeyScope {
|
func (s TenantAPIKeyScope) Normalize() TenantAPIKeyScope {
|
||||||
return TenantAPIKeyScope{
|
return TenantAPIKeyScope{
|
||||||
KeyID: s.KeyID,
|
KeyID: s.KeyID,
|
||||||
Scopes: normalizeScopeArray(s.Scopes),
|
Role: NormalizeTenantAPIKeyRole(s.Role),
|
||||||
KnowledgeBaseIDs: normalizeIDArray(s.KnowledgeBaseIDs),
|
KnowledgeBaseIDs: normalizeIDArray(s.KnowledgeBaseIDs),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s TenantAPIKeyScope) HasScope(scope string) bool {
|
// NormalizeTenantAPIKeyRole maps stored/API role strings to tenant RBAC roles.
|
||||||
scope = strings.ToLower(strings.TrimSpace(scope))
|
func NormalizeTenantAPIKeyRole(role TenantRole) TenantRole {
|
||||||
if scope == "" {
|
switch strings.ToLower(strings.TrimSpace(string(role))) {
|
||||||
return false
|
case string(TenantRoleAdmin):
|
||||||
|
return TenantRoleAdmin
|
||||||
|
case string(TenantRoleContributor):
|
||||||
|
return TenantRoleContributor
|
||||||
|
case string(TenantRoleViewer), "":
|
||||||
|
return TenantRoleViewer
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
}
|
}
|
||||||
for _, item := range s.Normalize().Scopes {
|
|
||||||
if item == scope {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TenantRole maps API-key scopes to the tenant RBAC role carried in request
|
|
||||||
// context. Admin scope -> Admin; write -> Contributor; read-only -> Viewer.
|
|
||||||
func (s TenantAPIKeyScope) TenantRole() TenantRole {
|
func (s TenantAPIKeyScope) TenantRole() TenantRole {
|
||||||
s = s.Normalize()
|
return s.Normalize().Role
|
||||||
switch {
|
|
||||||
case s.HasScope(TenantAPIKeyScopeAdmin):
|
|
||||||
return TenantRoleAdmin
|
|
||||||
case s.HasScope(TenantAPIKeyScopeWrite):
|
|
||||||
return TenantRoleContributor
|
|
||||||
default:
|
|
||||||
return TenantRoleViewer
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s TenantAPIKeyScope) AllowsKnowledgeBase(kbID string) bool {
|
func (s TenantAPIKeyScope) AllowsKnowledgeBase(kbID string) bool {
|
||||||
@@ -150,26 +136,6 @@ func (s TenantAPIKeyScope) AllowsKnowledgeBases(kbIDs []string) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func normalizeScopeArray(in StringArray) StringArray {
|
|
||||||
out := make(StringArray, 0, len(in))
|
|
||||||
seen := map[string]struct{}{}
|
|
||||||
for _, item := range in {
|
|
||||||
item = strings.TrimSpace(strings.ToLower(item))
|
|
||||||
if item == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if _, ok := seen[item]; ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
seen[item] = struct{}{}
|
|
||||||
out = append(out, item)
|
|
||||||
}
|
|
||||||
if len(out) == 0 {
|
|
||||||
out = StringArray{TenantAPIKeyScopeRead}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
func normalizeIDArray(in StringArray) StringArray {
|
func normalizeIDArray(in StringArray) StringArray {
|
||||||
out := make(StringArray, 0, len(in))
|
out := make(StringArray, 0, len(in))
|
||||||
seen := map[string]struct{}{}
|
seen := map[string]struct{}{}
|
||||||
@@ -186,3 +152,75 @@ func normalizeIDArray(in StringArray) StringArray {
|
|||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AuthorizeTenantAPIKeyKnowledgeBases rejects KB-restricted API key callers that
|
||||||
|
// target one or more knowledge bases outside their allow-list.
|
||||||
|
func AuthorizeTenantAPIKeyKnowledgeBases(ctx context.Context, kbIDs ...string) error {
|
||||||
|
scope, ok := TenantAPIKeyScopeFromContext(ctx)
|
||||||
|
if !ok || !scope.IsKnowledgeBaseRestricted() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if !scope.AllowsKnowledgeBases(kbIDs) {
|
||||||
|
return errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AuthorizeTenantAPIKeyKnowledgeTargets rejects KB-restricted API key callers
|
||||||
|
// that reference knowledge_ids without a verified KB binding, or kb_ids outside
|
||||||
|
// the allow-list.
|
||||||
|
func AuthorizeTenantAPIKeyKnowledgeTargets(ctx context.Context, kbIDs, knowledgeIDs []string) error {
|
||||||
|
scope, ok := TenantAPIKeyScopeFromContext(ctx)
|
||||||
|
if !ok || !scope.IsKnowledgeBaseRestricted() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if len(knowledgeIDs) > 0 {
|
||||||
|
return errors.NewForbiddenError("API key scope does not allow knowledge_ids without a verified knowledge base")
|
||||||
|
}
|
||||||
|
if !scope.AllowsKnowledgeBases(kbIDs) {
|
||||||
|
return errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AuthorizeTenantAPIKeyOptionalTagIDs rejects tag_ids for KB-restricted keys
|
||||||
|
// because tag resolution can pull documents from arbitrary knowledge bases.
|
||||||
|
func AuthorizeTenantAPIKeyOptionalTagIDs(ctx context.Context, tagIDs []string) error {
|
||||||
|
scope, ok := TenantAPIKeyScopeFromContext(ctx)
|
||||||
|
if !ok || !scope.IsKnowledgeBaseRestricted() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if len(tagIDs) > 0 {
|
||||||
|
return errors.NewForbiddenError("API key scope does not allow tag_ids without a verified knowledge base")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FilterKnowledgeBasesForTenantAPIKeyScope intersects resolved KB IDs with the
|
||||||
|
// API key allow-list. When the caller supplied explicit kb_ids, every ID must
|
||||||
|
// be allowed; implicit agent defaults are intersected instead of rejected.
|
||||||
|
func FilterKnowledgeBasesForTenantAPIKeyScope(
|
||||||
|
ctx context.Context, requestedKBIDs, resolvedKBIDs []string,
|
||||||
|
) ([]string, error) {
|
||||||
|
scope, ok := TenantAPIKeyScopeFromContext(ctx)
|
||||||
|
if !ok || !scope.IsKnowledgeBaseRestricted() {
|
||||||
|
return resolvedKBIDs, nil
|
||||||
|
}
|
||||||
|
if len(requestedKBIDs) > 0 {
|
||||||
|
if !scope.AllowsKnowledgeBases(requestedKBIDs) {
|
||||||
|
return nil, errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
|
||||||
|
}
|
||||||
|
return resolvedKBIDs, nil
|
||||||
|
}
|
||||||
|
allowed := make(map[string]struct{}, len(scope.KnowledgeBaseIDs))
|
||||||
|
for _, id := range scope.KnowledgeBaseIDs {
|
||||||
|
allowed[id] = struct{}{}
|
||||||
|
}
|
||||||
|
filtered := make([]string, 0, len(resolvedKBIDs))
|
||||||
|
for _, id := range resolvedKBIDs {
|
||||||
|
if _, ok := allowed[id]; ok {
|
||||||
|
filtered = append(filtered, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return filtered, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package types
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAuthorizeTenantAPIKeyKnowledgeTargetsRejectsKnowledgeIDs(t *testing.T) {
|
||||||
|
ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
|
||||||
|
KnowledgeBaseIDs: StringArray{"kb-1"},
|
||||||
|
})
|
||||||
|
err := AuthorizeTenantAPIKeyKnowledgeTargets(ctx, []string{"kb-1"}, []string{"doc-1"})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected forbidden when knowledge_ids supplied under KB-restricted key")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAuthorizeTenantAPIKeyOptionalTagIDsRejectsTags(t *testing.T) {
|
||||||
|
ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
|
||||||
|
KnowledgeBaseIDs: StringArray{"kb-1"},
|
||||||
|
})
|
||||||
|
err := AuthorizeTenantAPIKeyOptionalTagIDs(ctx, []string{"tag-1"})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected forbidden when tag_ids supplied under KB-restricted key")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterKnowledgeBasesForTenantAPIKeyScopeIntersectsAgentDefaults(t *testing.T) {
|
||||||
|
ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
|
||||||
|
KnowledgeBaseIDs: StringArray{"kb-1", "kb-2"},
|
||||||
|
})
|
||||||
|
got, err := FilterKnowledgeBasesForTenantAPIKeyScope(ctx, nil, []string{"kb-2", "kb-3"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("FilterKnowledgeBasesForTenantAPIKeyScope returned error: %v", err)
|
||||||
|
}
|
||||||
|
if len(got) != 1 || got[0] != "kb-2" {
|
||||||
|
t.Fatalf("filtered = %#v, want only kb-2", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterKnowledgeBasesForTenantAPIKeyScopeRejectsExplicitOutOfScope(t *testing.T) {
|
||||||
|
ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
|
||||||
|
KnowledgeBaseIDs: StringArray{"kb-1"},
|
||||||
|
})
|
||||||
|
_, err := FilterKnowledgeBasesForTenantAPIKeyScope(ctx, []string{"kb-1", "kb-2"}, []string{"kb-1", "kb-2"})
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected forbidden for explicit out-of-scope kb_ids")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,30 +2,38 @@ package types
|
|||||||
|
|
||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
func TestTenantAPIKeyScopeNormalizeDefaultsEmptyScopesToRead(t *testing.T) {
|
func TestTenantAPIKeyScopeNormalizeDefaultsEmptyRoleToViewer(t *testing.T) {
|
||||||
scope := TenantAPIKeyScope{Scopes: StringArray{}}.Normalize()
|
scope := TenantAPIKeyScope{Role: ""}.Normalize()
|
||||||
if len(scope.Scopes) != 1 || scope.Scopes[0] != TenantAPIKeyScopeRead {
|
if scope.Role != TenantRoleViewer {
|
||||||
t.Fatalf("normalized scopes = %v, want [read]", scope.Scopes)
|
t.Fatalf("normalized role = %q, want viewer", scope.Role)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestTenantAPIKeyScopeTenantRoleMapping(t *testing.T) {
|
func TestNormalizeTenantAPIKeyRole(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
in StringArray
|
in TenantRole
|
||||||
want TenantRole
|
want TenantRole
|
||||||
}{
|
}{
|
||||||
{name: "read", in: StringArray{TenantAPIKeyScopeRead}, want: TenantRoleViewer},
|
{name: "viewer", in: TenantRoleViewer, want: TenantRoleViewer},
|
||||||
{name: "write", in: StringArray{TenantAPIKeyScopeWrite}, want: TenantRoleContributor},
|
{name: "contributor", in: TenantRoleContributor, want: TenantRoleContributor},
|
||||||
{name: "admin", in: StringArray{TenantAPIKeyScopeAdmin}, want: TenantRoleAdmin},
|
{name: "admin", in: TenantRoleAdmin, want: TenantRoleAdmin},
|
||||||
{name: "empty defaults read", in: StringArray{}, want: TenantRoleViewer},
|
{name: "empty defaults viewer", in: "", want: TenantRoleViewer},
|
||||||
|
{name: "invalid", in: "owner", want: ""},
|
||||||
}
|
}
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
got := TenantAPIKeyScope{Scopes: tt.in}.TenantRole()
|
got := NormalizeTenantAPIKeyRole(tt.in)
|
||||||
if got != tt.want {
|
if got != tt.want {
|
||||||
t.Fatalf("TenantRole() = %q, want %q", got, tt.want)
|
t.Fatalf("NormalizeTenantAPIKeyRole(%q) = %q, want %q", tt.in, got, tt.want)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestTenantAPIKeyScopeTenantRole(t *testing.T) {
|
||||||
|
got := TenantAPIKeyScope{Role: TenantRoleContributor}.TenantRole()
|
||||||
|
if got != TenantRoleContributor {
|
||||||
|
t.Fatalf("TenantRole() = %q, want contributor", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -756,7 +756,7 @@ CREATE TABLE IF NOT EXISTS tenant_api_keys (
|
|||||||
name TEXT NOT NULL,
|
name TEXT NOT NULL,
|
||||||
key_hash TEXT NOT NULL UNIQUE,
|
key_hash TEXT NOT NULL UNIQUE,
|
||||||
api_key TEXT NOT NULL DEFAULT '',
|
api_key TEXT NOT NULL DEFAULT '',
|
||||||
scopes TEXT NOT NULL DEFAULT '[]',
|
role TEXT NOT NULL DEFAULT 'viewer',
|
||||||
knowledge_base_ids TEXT NOT NULL DEFAULT '[]',
|
knowledge_base_ids TEXT NOT NULL DEFAULT '[]',
|
||||||
last_used_at DATETIME,
|
last_used_at DATETIME,
|
||||||
expires_at DATETIME,
|
expires_at DATETIME,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ CREATE TABLE IF NOT EXISTS tenant_api_keys (
|
|||||||
name VARCHAR(128) NOT NULL,
|
name VARCHAR(128) NOT NULL,
|
||||||
key_hash VARCHAR(64) NOT NULL UNIQUE,
|
key_hash VARCHAR(64) NOT NULL UNIQUE,
|
||||||
api_key TEXT NOT NULL DEFAULT '',
|
api_key TEXT NOT NULL DEFAULT '',
|
||||||
scopes JSONB NOT NULL DEFAULT '[]'::jsonb,
|
role VARCHAR(32) NOT NULL DEFAULT 'viewer',
|
||||||
knowledge_base_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
|
knowledge_base_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||||
last_used_at TIMESTAMP,
|
last_used_at TIMESTAMP,
|
||||||
expires_at TIMESTAMP,
|
expires_at TIMESTAMP,
|
||||||
@@ -25,7 +25,7 @@ INSERT INTO tenant_api_keys (
|
|||||||
name,
|
name,
|
||||||
key_hash,
|
key_hash,
|
||||||
api_key,
|
api_key,
|
||||||
scopes,
|
role,
|
||||||
knowledge_base_ids,
|
knowledge_base_ids,
|
||||||
created_at,
|
created_at,
|
||||||
updated_at
|
updated_at
|
||||||
@@ -35,7 +35,7 @@ SELECT
|
|||||||
'Tenant API key',
|
'Tenant API key',
|
||||||
'migrated-tenant-' || id::text,
|
'migrated-tenant-' || id::text,
|
||||||
api_key,
|
api_key,
|
||||||
'["read","write","admin"]'::jsonb,
|
'admin',
|
||||||
'[]'::jsonb,
|
'[]'::jsonb,
|
||||||
CURRENT_TIMESTAMP,
|
CURRENT_TIMESTAMP,
|
||||||
CURRENT_TIMESTAMP
|
CURRENT_TIMESTAMP
|
||||||
|
|||||||
Reference in New Issue
Block a user