Refine scoped API key capabilities
This commit is contained in:
@@ -192,18 +192,20 @@ func (r *agentShareRepository) ListSharedAgentsForTenant(ctx context.Context, te
|
||||
// source_tenant_id == excludeTenantID. Single query.
|
||||
func (r *agentShareRepository) GetShareByAgentIDForTenant(ctx context.Context, tenantID uint64, agentID string, excludeTenantID uint64) (*types.AgentShare, error) {
|
||||
var share types.AgentShare
|
||||
err := r.db.WithContext(ctx).
|
||||
tx := r.db.WithContext(ctx).
|
||||
Joins("JOIN organization_tenant_members otm ON otm.organization_id = agent_shares.organization_id").
|
||||
Where("agent_shares.agent_id = ?", agentID).
|
||||
Where("otm.tenant_id = ?", tenantID).
|
||||
Where("agent_shares.source_tenant_id != ?", excludeTenantID).
|
||||
Where("agent_shares.deleted_at IS NULL").
|
||||
First(&share).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrAgentShareNotFound
|
||||
}
|
||||
return nil, err
|
||||
Order("agent_shares.id").
|
||||
Limit(1).
|
||||
Find(&share)
|
||||
if tx.Error != nil {
|
||||
return nil, tx.Error
|
||||
}
|
||||
if tx.RowsAffected == 0 {
|
||||
return nil, ErrAgentShareNotFound
|
||||
}
|
||||
return &share, nil
|
||||
}
|
||||
|
||||
@@ -243,7 +243,12 @@ func (s *sessionService) buildAgentConfig(
|
||||
s.configureSkillsFromAgent(ctx, agentConfig, customAgent)
|
||||
|
||||
// Resolve knowledge bases using shared helper
|
||||
agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs = s.resolveKnowledgeBases(ctx, req)
|
||||
kbIDs, knowledgeIDs, err := s.resolveKnowledgeBases(ctx, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
agentConfig.KnowledgeBases = kbIDs
|
||||
agentConfig.KnowledgeIDs = knowledgeIDs
|
||||
|
||||
// Use custom agent's allowed tools if specified, otherwise use defaults
|
||||
if len(customAgent.Config.AllowedTools) > 0 {
|
||||
|
||||
@@ -45,7 +45,10 @@ func (s *sessionService) KnowledgeQA(
|
||||
ctx = setupCtx
|
||||
|
||||
// Resolve knowledge bases using shared helper
|
||||
knowledgeBaseIDs, knowledgeIDs := s.resolveKnowledgeBases(ctx, req)
|
||||
knowledgeBaseIDs, knowledgeIDs, err := s.resolveKnowledgeBases(ctx, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Resolve chat model ID using shared helper
|
||||
chatModelID, err := s.resolveChatModelID(ctx, req, knowledgeBaseIDs, knowledgeIDs)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func TestResolveKnowledgeBasesFiltersImplicitAgentDefaultsForRestrictedAPIKey(t *testing.T) {
|
||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||
KnowledgeBaseIDs: types.StringArray{"kb-allowed"},
|
||||
})
|
||||
svc := &sessionService{}
|
||||
|
||||
kbIDs, knowledgeIDs, err := svc.resolveKnowledgeBases(ctx, &types.QARequest{
|
||||
Session: &types.Session{TenantID: 10000},
|
||||
CustomAgent: &types.CustomAgent{
|
||||
TenantID: 10000,
|
||||
Config: types.CustomAgentConfig{
|
||||
KBSelectionMode: "selected",
|
||||
KnowledgeBases: []string{"kb-allowed", "kb-blocked"},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("resolveKnowledgeBases returned error: %v", err)
|
||||
}
|
||||
if len(kbIDs) != 1 || kbIDs[0] != "kb-allowed" {
|
||||
t.Fatalf("kbIDs = %#v, want only kb-allowed", kbIDs)
|
||||
}
|
||||
if len(knowledgeIDs) != 0 {
|
||||
t.Fatalf("knowledgeIDs = %#v, want empty", knowledgeIDs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveKnowledgeBasesRejectsExplicitOutOfScopeKBForRestrictedAPIKey(t *testing.T) {
|
||||
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
|
||||
KnowledgeBaseIDs: types.StringArray{"kb-allowed"},
|
||||
})
|
||||
svc := &sessionService{}
|
||||
|
||||
_, _, err := svc.resolveKnowledgeBases(ctx, &types.QARequest{
|
||||
Session: &types.Session{TenantID: 10000},
|
||||
KnowledgeBaseIDs: []string{"kb-blocked"},
|
||||
CustomAgent: &types.CustomAgent{
|
||||
TenantID: 10000,
|
||||
Config: types.CustomAgentConfig{
|
||||
KBSelectionMode: "selected",
|
||||
KnowledgeBases: []string{"kb-allowed", "kb-blocked"},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected forbidden for explicit out-of-scope knowledge_base_ids")
|
||||
}
|
||||
}
|
||||
@@ -21,9 +21,10 @@ import (
|
||||
func (s *sessionService) resolveKnowledgeBases(
|
||||
ctx context.Context,
|
||||
req *types.QARequest,
|
||||
) (kbIDs []string, knowledgeIDs []string) {
|
||||
) (kbIDs []string, knowledgeIDs []string, err error) {
|
||||
kbIDs = req.KnowledgeBaseIDs
|
||||
knowledgeIDs = req.KnowledgeIDs
|
||||
requestedKBIDs := append([]string(nil), req.KnowledgeBaseIDs...)
|
||||
customAgent := req.CustomAgent
|
||||
|
||||
hasExplicitMention := len(kbIDs) > 0 || len(knowledgeIDs) > 0 || len(req.TagScopes) > 0
|
||||
@@ -47,7 +48,15 @@ func (s *sessionService) resolveKnowledgeBases(
|
||||
} else if customAgent != nil {
|
||||
kbIDs = s.resolveKnowledgeBasesFromAgent(ctx, customAgent, req.Session.TenantID)
|
||||
}
|
||||
return kbIDs, knowledgeIDs
|
||||
|
||||
if err := types.AuthorizeTenantAPIKeyKnowledgeTargets(ctx, requestedKBIDs, req.KnowledgeIDs); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
kbIDs, err = types.FilterKnowledgeBasesForTenantAPIKeyScope(ctx, requestedKBIDs, kbIDs)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return kbIDs, knowledgeIDs, nil
|
||||
}
|
||||
|
||||
func (s *sessionService) restrictTagScopesToAgentScope(
|
||||
|
||||
@@ -50,12 +50,14 @@ func (s *tenantAPIKeyService) CreateAPIKey(
|
||||
Name: name,
|
||||
KeyHash: hashTenantAPIKey(token),
|
||||
APIKey: token,
|
||||
Role: types.NormalizeTenantAPIKeyRole(req.Role),
|
||||
FullAccess: req.FullAccess,
|
||||
KnowledgeBaseIDs: normalizeAPIKeyIDs(req.KnowledgeBaseIDs),
|
||||
Capabilities: types.NormalizeAPIKeyCapabilities(types.StringArray(req.Capabilities)),
|
||||
ExpiresAt: req.ExpiresAt,
|
||||
}
|
||||
if key.Role == "" {
|
||||
key.Role = types.TenantRoleViewer
|
||||
if key.FullAccess {
|
||||
key.KnowledgeBaseIDs = nil
|
||||
key.Capabilities = nil
|
||||
}
|
||||
if err := s.repo.CreateAPIKey(ctx, key); err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -26,7 +26,6 @@ func TestTenantAPIKeyServiceCreateAPIKeyUsesSKPrefix(t *testing.T) {
|
||||
result, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
TenantID: 42,
|
||||
Name: "integration",
|
||||
Role: types.TenantRoleViewer,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateAPIKey returned error: %v", err)
|
||||
@@ -135,11 +134,11 @@ func TestTenantAPIKeyServiceBackfillMissingKeyHashes(t *testing.T) {
|
||||
|
||||
token := "sk-legacy-token-value"
|
||||
legacy := &types.TenantAPIKey{
|
||||
TenantID: 7,
|
||||
Name: "legacy",
|
||||
KeyHash: "migrated-tenant-7",
|
||||
APIKey: token,
|
||||
Role: types.TenantRoleOwner,
|
||||
TenantID: 7,
|
||||
Name: "legacy",
|
||||
KeyHash: "migrated-tenant-7",
|
||||
APIKey: token,
|
||||
FullAccess: true,
|
||||
}
|
||||
if err := repo.CreateAPIKey(ctx, legacy); err != nil {
|
||||
t.Fatalf("CreateAPIKey returned error: %v", err)
|
||||
@@ -168,7 +167,6 @@ func TestTenantAPIKeyServiceRevokeAPIKey(t *testing.T) {
|
||||
created, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
TenantID: 42,
|
||||
Name: "integration",
|
||||
Role: types.TenantRoleViewer,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateAPIKey returned error: %v", err)
|
||||
@@ -189,7 +187,6 @@ func TestTenantAPIKeyServiceAuthenticateThrottlesLastUsedUpdates(t *testing.T) {
|
||||
created, err := svc.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
TenantID: 42,
|
||||
Name: "integration",
|
||||
Role: types.TenantRoleViewer,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateAPIKey returned error: %v", err)
|
||||
|
||||
@@ -43,10 +43,10 @@ func NewCustomAgentHandler(
|
||||
|
||||
// CreateAgentRequest defines the request body for creating an agent
|
||||
type CreateAgentRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Description string `json:"description"`
|
||||
Avatar string `json:"avatar"`
|
||||
Config types.CustomAgentConfig `json:"config"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
Description string `json:"description"`
|
||||
Avatar string `json:"avatar"`
|
||||
Config types.CustomAgentConfig `json:"config"`
|
||||
}
|
||||
|
||||
// UpdateAgentRequest defines the request body for updating an agent
|
||||
@@ -81,6 +81,10 @@ func (h *CustomAgentHandler) CreateAgent(c *gin.Context) {
|
||||
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
if err := authorizeAgentKnowledgeScope(ctx, req.Config); err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Build agent object
|
||||
agent := &types.CustomAgent{
|
||||
@@ -146,6 +150,10 @@ func (h *CustomAgentHandler) GetAgent(c *gin.Context) {
|
||||
c.Error(errors.NewNotFoundError("Agent not found"))
|
||||
return
|
||||
}
|
||||
if appErr, ok := err.(*errors.AppError); ok {
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
@@ -311,6 +319,10 @@ func (h *CustomAgentHandler) UpdateAgent(c *gin.Context) {
|
||||
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
if err := authorizeAgentKnowledgeScope(ctx, req.Config); err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Build agent object
|
||||
agent := &types.CustomAgent{
|
||||
@@ -444,6 +456,23 @@ func (h *CustomAgentHandler) CopyAgent(c *gin.Context) {
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Copying custom agent, ID: %s", secutils.SanitizeForLog(id))
|
||||
sourceAgent, err := h.service.GetAgentByID(ctx, id)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"agent_id": id,
|
||||
})
|
||||
switch err {
|
||||
case service.ErrAgentNotFound:
|
||||
c.Error(errors.NewNotFoundError("Agent not found"))
|
||||
default:
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := authorizeAgentKnowledgeScope(ctx, sourceAgent.Config); err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Copy the agent
|
||||
copiedAgent, err := h.service.CopyAgent(ctx, id)
|
||||
@@ -587,6 +616,10 @@ func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) {
|
||||
c.Error(errors.NewNotFoundError("Agent not found"))
|
||||
return
|
||||
}
|
||||
if appErr, ok := err.(*errors.AppError); ok {
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
@@ -598,3 +631,23 @@ func (h *CustomAgentHandler) GetSuggestedQuestions(c *gin.Context) {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func authorizeAgentKnowledgeScope(ctx context.Context, cfg types.CustomAgentConfig) error {
|
||||
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
|
||||
if !ok || !scope.IsKnowledgeBaseRestricted() {
|
||||
return nil
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(cfg.KBSelectionMode)) {
|
||||
case "none":
|
||||
return nil
|
||||
case "all":
|
||||
return errors.NewForbiddenError("API key scope does not allow agents that use all knowledge bases")
|
||||
case "selected":
|
||||
return types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, cfg.KnowledgeBases...)
|
||||
default:
|
||||
if len(cfg.KnowledgeBases) == 0 {
|
||||
return nil
|
||||
}
|
||||
return types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, cfg.KnowledgeBases...)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
"github.com/Tencent/WeKnora/internal/middleware"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type suggestedQuestionsAgentService struct {
|
||||
interfaces.CustomAgentService
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *suggestedQuestionsAgentService) GetSuggestedQuestions(
|
||||
context.Context,
|
||||
string,
|
||||
[]string,
|
||||
[]string,
|
||||
[]string,
|
||||
int,
|
||||
) ([]types.SuggestedQuestion, error) {
|
||||
return nil, s.err
|
||||
}
|
||||
|
||||
func TestGetSuggestedQuestionsPreservesAppErrorStatus(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
r.Use(middleware.ErrorHandler())
|
||||
|
||||
h := &CustomAgentHandler{service: &suggestedQuestionsAgentService{
|
||||
err: apperrors.NewForbiddenError("API key scope does not allow one or more knowledge bases"),
|
||||
}}
|
||||
r.GET("/agents/:id/suggested-questions", h.GetSuggestedQuestions)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/agents/agent-1/suggested-questions?knowledge_base_ids=kb-blocked", nil)
|
||||
r.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusForbidden, rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,9 @@ func (h *DataSourceHandler) getOwnedKnowledgeBase(
|
||||
if kb.TenantID != tenantID {
|
||||
return nil, http.StatusForbidden, "access denied"
|
||||
}
|
||||
if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID); err != nil {
|
||||
return nil, http.StatusForbidden, err.Error()
|
||||
}
|
||||
|
||||
return kb, http.StatusOK, ""
|
||||
}
|
||||
@@ -170,11 +173,6 @@ func (h *DataSourceHandler) ListDataSources(c *gin.Context) {
|
||||
c.JSON(status, gin.H{"error": msg})
|
||||
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)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list data sources"})
|
||||
|
||||
+18
-10
@@ -136,8 +136,9 @@ type apiPrincipalTestTokenResponse struct {
|
||||
|
||||
type tenantAPIKeyCreateRequest struct {
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
FullAccess bool `json:"full_access"`
|
||||
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
|
||||
Capabilities []string `json:"capabilities"`
|
||||
ExpiresAt *int64 `json:"expires_at_unix"`
|
||||
}
|
||||
|
||||
@@ -145,8 +146,9 @@ type tenantAPIKeyResponse struct {
|
||||
ID uint64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
APIKey string `json:"api_key"`
|
||||
Role types.TenantRole `json:"role"`
|
||||
FullAccess bool `json:"full_access"`
|
||||
KnowledgeBaseIDs types.StringArray `json:"knowledge_base_ids"`
|
||||
Capabilities types.StringArray `json:"capabilities"`
|
||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
@@ -576,10 +578,6 @@ func (h *TenantHandler) CreateAPIKey(c *gin.Context) {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
role := types.NormalizeTenantAPIKeyRole(types.TenantRole(strings.TrimSpace(req.Role)))
|
||||
if role == "" {
|
||||
role = types.TenantRoleViewer
|
||||
}
|
||||
var expiresAt *time.Time
|
||||
if req.ExpiresAt != nil {
|
||||
t := time.Unix(*req.ExpiresAt, 0)
|
||||
@@ -592,8 +590,9 @@ func (h *TenantHandler) CreateAPIKey(c *gin.Context) {
|
||||
result, err := h.apiKeyService.CreateAPIKey(ctx, interfaces.TenantAPIKeyCreateRequest{
|
||||
TenantID: id,
|
||||
Name: req.Name,
|
||||
Role: role,
|
||||
FullAccess: req.FullAccess,
|
||||
KnowledgeBaseIDs: req.KnowledgeBaseIDs,
|
||||
Capabilities: req.Capabilities,
|
||||
ExpiresAt: expiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
@@ -636,8 +635,9 @@ func tenantAPIKeyForResponse(key *types.TenantAPIKey) tenantAPIKeyResponse {
|
||||
ID: key.ID,
|
||||
Name: key.Name,
|
||||
APIKey: key.APIKey,
|
||||
Role: types.NormalizeTenantAPIKeyRole(key.Role),
|
||||
FullAccess: key.FullAccess,
|
||||
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
|
||||
Capabilities: types.NormalizeAPIKeyCapabilities(key.Capabilities),
|
||||
LastUsedAt: key.LastUsedAt,
|
||||
ExpiresAt: key.ExpiresAt,
|
||||
CreatedAt: key.CreatedAt,
|
||||
@@ -653,8 +653,16 @@ func validateTenantAPIKeyRequest(
|
||||
if strings.TrimSpace(req.Name) == "" {
|
||||
return errors.NewValidationError("name is required")
|
||||
}
|
||||
if role := types.NormalizeTenantAPIKeyRole(types.TenantRole(strings.TrimSpace(req.Role))); req.Role != "" && role == "" {
|
||||
return errors.NewValidationError("role must be one of viewer, contributor, admin, or owner")
|
||||
if req.FullAccess {
|
||||
return nil
|
||||
}
|
||||
for _, cap := range req.Capabilities {
|
||||
if strings.TrimSpace(cap) == "" {
|
||||
continue
|
||||
}
|
||||
if types.NormalizeAPIKeyCapability(types.APIKeyCapability(cap)) == "" {
|
||||
return errors.NewValidationError("capabilities contains an unknown capability")
|
||||
}
|
||||
}
|
||||
for _, kbID := range req.KnowledgeBaseIDs {
|
||||
kbID = strings.TrimSpace(kbID)
|
||||
|
||||
@@ -183,7 +183,6 @@ func TestCloneContextPreservesTenantAPIKeyScope(t *testing.T) {
|
||||
|
||||
want := types.TenantAPIKeyScope{
|
||||
KeyID: 7,
|
||||
Role: types.TenantRoleViewer,
|
||||
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||
}
|
||||
ctx := types.WithTenantAPIKeyScope(context.Background(), want)
|
||||
|
||||
@@ -21,20 +21,32 @@ var errTenantAPIKeyScopeForbidden = stderrors.New("tenant api key scope forbidde
|
||||
// default (fail-closed), which removes the old "remember to add APIKeyDeny"
|
||||
// footgun.
|
||||
type APIKeyRoutePolicy struct {
|
||||
// MinRole is the minimum tenant role an API key needs for this route.
|
||||
//
|
||||
// Data-plane routes (knowledge bases and their content) use Viewer /
|
||||
// Contributor / Admin; for those, safe reads (GET/HEAD/OPTIONS) only
|
||||
// require Viewer while writes require the declared role. Tenant-level
|
||||
// infrastructure routes (models, vector stores, MCP, data sources,
|
||||
// channels, tenant KV, ...) use Owner, which is required for EVERY
|
||||
// method — reading tenant configuration is itself a privileged action.
|
||||
//
|
||||
// KB scoping is NOT enforced here: a key's knowledge_base_ids allow-list
|
||||
// is a pure data filter applied by the KBAccess guards and the handler
|
||||
// scope checks on data-plane routes. Tenant-level routes are simply
|
||||
// gated behind the Owner role instead of being reachable by a narrow key.
|
||||
MinRole types.TenantRole
|
||||
// RequireFullAccess admits only full-access tenant API keys unless one of
|
||||
// the listed capabilities also matches. Routes with neither full-access
|
||||
// requirement nor capabilities are open to any valid API key.
|
||||
RequireFullAccess bool
|
||||
|
||||
// Capabilities is an any-of allow-list for scoped API keys. A capability
|
||||
// never widens which knowledge bases a key may touch; KB scoping is
|
||||
// enforced downstream by KBAccess guards and handler scope checks.
|
||||
Capabilities []types.APIKeyCapability
|
||||
}
|
||||
|
||||
// WithCapability returns a copy of the policy that additionally admits keys
|
||||
// carrying capability c. Multiple calls accumulate (any-of semantics);
|
||||
// duplicates are ignored.
|
||||
func (p APIKeyRoutePolicy) WithCapability(c types.APIKeyCapability) APIKeyRoutePolicy {
|
||||
for _, existing := range p.Capabilities {
|
||||
if existing == c {
|
||||
return p
|
||||
}
|
||||
}
|
||||
// Copy the slice so mutating the returned policy never aliases the
|
||||
// receiver's backing array.
|
||||
next := make([]types.APIKeyCapability, len(p.Capabilities), len(p.Capabilities)+1)
|
||||
copy(next, p.Capabilities)
|
||||
p.Capabilities = append(next, c)
|
||||
return p
|
||||
}
|
||||
|
||||
// APIKeyRouteAuthorizer is the registry of per-route API-key policies. It is
|
||||
@@ -116,23 +128,18 @@ func (a *APIKeyRouteAuthorizer) authorize(scope types.TenantAPIKeyScope, method,
|
||||
if !ok {
|
||||
return errTenantAPIKeyScopeForbidden
|
||||
}
|
||||
role := scope.Role
|
||||
if role == "" {
|
||||
role = types.TenantRoleViewer
|
||||
if scope.FullAccess {
|
||||
return nil
|
||||
}
|
||||
required := policy.MinRole
|
||||
if required == "" {
|
||||
required = types.TenantRoleViewer
|
||||
for _, cap := range policy.Capabilities {
|
||||
if cap != "" && scope.HasCapability(cap) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
// Data-plane safe reads only need a Viewer floor. Tenant-level (Owner)
|
||||
// routes require the full role even for reads, so they are never lowered.
|
||||
if isSafeHTTPMethod(method) && required != types.TenantRoleOwner {
|
||||
required = types.TenantRoleViewer
|
||||
if !policy.RequireFullAccess && len(policy.Capabilities) == 0 {
|
||||
return nil
|
||||
}
|
||||
if !role.HasPermission(required) {
|
||||
return errTenantAPIKeyScopeForbidden
|
||||
}
|
||||
return nil
|
||||
return errTenantAPIKeyScopeForbidden
|
||||
}
|
||||
|
||||
// DenyAPIKeyPrincipal returns a middleware that rejects any X-API-Key
|
||||
@@ -154,15 +161,6 @@ func DenyAPIKeyPrincipal() gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func isSafeHTTPMethod(method string) bool {
|
||||
switch method {
|
||||
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// normalizeRoutePath collapses duplicate slashes and trims a trailing slash so
|
||||
// helper-built paths (BasePath()+rel) match gin's c.FullPath() exactly.
|
||||
func normalizeRoutePath(p string) string {
|
||||
|
||||
@@ -11,20 +11,16 @@ import (
|
||||
|
||||
func newTestAuthorizer() *APIKeyRouteAuthorizer {
|
||||
a := NewAPIKeyRouteAuthorizer()
|
||||
// Data-plane routes (Viewer read, Contributor write, Admin destructive)
|
||||
// plus one tenant-level Owner route.
|
||||
a.Register(http.MethodGet, "/api/v1/knowledge-bases/:id", policyMinRole(types.TenantRoleViewer))
|
||||
a.Register(http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file", policyMinRole(types.TenantRoleContributor))
|
||||
a.Register(http.MethodDelete, "/api/v1/knowledge-bases/:id/knowledge", policyMinRole(types.TenantRoleAdmin))
|
||||
a.Register(http.MethodGet, "/api/v1/models", policyMinRole(types.TenantRoleOwner))
|
||||
a.Register(http.MethodPut, "/api/v1/tenants/kv/:key", policyMinRole(types.TenantRoleOwner))
|
||||
a.Register(http.MethodGet, "/api/v1/auth/me", APIKeyRoutePolicy{})
|
||||
a.Register(http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file",
|
||||
APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityIngest))
|
||||
a.Register(http.MethodGet, "/api/v1/models",
|
||||
APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityManageModels))
|
||||
a.Register(http.MethodPut, "/api/v1/tenants/kv/:key",
|
||||
APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityManageTenantSettings))
|
||||
return a
|
||||
}
|
||||
|
||||
func policyMinRole(r types.TenantRole) APIKeyRoutePolicy {
|
||||
return APIKeyRoutePolicy{MinRole: r}
|
||||
}
|
||||
|
||||
// runGate exercises the gate middleware with a given scope, method and route
|
||||
// full-path, returning whether the request was allowed to proceed.
|
||||
func runGate(t *testing.T, a *APIKeyRouteAuthorizer, scope *types.TenantAPIKeyScope, method, fullPath string) bool {
|
||||
@@ -56,8 +52,6 @@ func concretePath(tmpl string) string {
|
||||
return "/api/v1/knowledge-bases/kb-1"
|
||||
case "/api/v1/knowledge-bases/:id/knowledge/file":
|
||||
return "/api/v1/knowledge-bases/kb-1/knowledge/file"
|
||||
case "/api/v1/knowledge-bases/:id/knowledge":
|
||||
return "/api/v1/knowledge-bases/kb-1/knowledge"
|
||||
case "/api/v1/tenants/kv/:key":
|
||||
return "/api/v1/tenants/kv/some-key"
|
||||
default:
|
||||
@@ -67,7 +61,7 @@ func concretePath(tmpl string) string {
|
||||
|
||||
func TestGateJWTPassesThrough(t *testing.T) {
|
||||
a := newTestAuthorizer()
|
||||
// No scope => JWT principal => always allowed, even on an Owner route.
|
||||
// No scope => JWT principal => always allowed, even on a full-access route.
|
||||
if !runGate(t, a, nil, http.MethodGet, "/api/v1/models") {
|
||||
t.Fatal("JWT principal must pass the gate")
|
||||
}
|
||||
@@ -75,11 +69,11 @@ func TestGateJWTPassesThrough(t *testing.T) {
|
||||
|
||||
func TestGateDefaultDeny(t *testing.T) {
|
||||
a := newTestAuthorizer()
|
||||
owner := &types.TenantAPIKeyScope{Role: types.TenantRoleOwner}
|
||||
full := &types.TenantAPIKeyScope{FullAccess: true}
|
||||
gin.SetMode(gin.TestMode)
|
||||
engine := gin.New()
|
||||
engine.Use(func(c *gin.Context) {
|
||||
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), *owner))
|
||||
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), *full))
|
||||
c.Next()
|
||||
})
|
||||
engine.Use(a.Middleware())
|
||||
@@ -87,54 +81,80 @@ func TestGateDefaultDeny(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
engine.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/v1/agents", nil))
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("undeclared route should default-deny even an Owner key: status=%d", w.Code)
|
||||
t.Fatalf("undeclared route should default-deny even a full-access key: status=%d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateDataPlaneRoleLadder(t *testing.T) {
|
||||
func TestGateAnyPolicyAllowsScopedKey(t *testing.T) {
|
||||
a := newTestAuthorizer()
|
||||
viewer := &types.TenantAPIKeyScope{Role: types.TenantRoleViewer}
|
||||
contributor := &types.TenantAPIKeyScope{Role: types.TenantRoleContributor}
|
||||
admin := &types.TenantAPIKeyScope{Role: types.TenantRoleAdmin}
|
||||
scoped := &types.TenantAPIKeyScope{}
|
||||
|
||||
// Safe read: any data-plane key (Viewer) passes.
|
||||
if !runGate(t, a, viewer, http.MethodGet, "/api/v1/knowledge-bases/:id") {
|
||||
t.Fatal("viewer key should read a declared KB route")
|
||||
}
|
||||
// Contributor write.
|
||||
if runGate(t, a, viewer, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
|
||||
t.Fatal("viewer key must not perform a contributor write")
|
||||
}
|
||||
if !runGate(t, a, contributor, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
|
||||
t.Fatal("contributor key should perform a contributor write")
|
||||
}
|
||||
// Admin destructive.
|
||||
if runGate(t, a, contributor, http.MethodDelete, "/api/v1/knowledge-bases/:id/knowledge") {
|
||||
t.Fatal("contributor key must not perform an admin destructive op")
|
||||
}
|
||||
if !runGate(t, a, admin, http.MethodDelete, "/api/v1/knowledge-bases/:id/knowledge") {
|
||||
t.Fatal("admin key should perform an admin destructive op")
|
||||
if !runGate(t, a, scoped, http.MethodGet, "/api/v1/auth/me") {
|
||||
t.Fatal("scoped key should call a declared route with an empty policy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateTenantRoutesRequireOwner(t *testing.T) {
|
||||
func TestGateFullAccessAndCapabilityPolicies(t *testing.T) {
|
||||
a := newTestAuthorizer()
|
||||
admin := &types.TenantAPIKeyScope{Role: types.TenantRoleAdmin}
|
||||
owner := &types.TenantAPIKeyScope{Role: types.TenantRoleOwner}
|
||||
scoped := &types.TenantAPIKeyScope{}
|
||||
full := &types.TenantAPIKeyScope{FullAccess: true}
|
||||
ingest := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"ingest"}}
|
||||
models := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"manage_models"}}
|
||||
|
||||
// Even a safe GET on a tenant-level route requires Owner (no Viewer floor).
|
||||
if runGate(t, a, admin, http.MethodGet, "/api/v1/models") {
|
||||
t.Fatal("admin key must NOT read a tenant-level route")
|
||||
if runGate(t, a, scoped, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
|
||||
t.Fatal("plain scoped key must not write content")
|
||||
}
|
||||
if !runGate(t, a, owner, http.MethodGet, "/api/v1/models") {
|
||||
t.Fatal("owner key should read a tenant-level route")
|
||||
if !runGate(t, a, full, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
|
||||
t.Fatal("full-access key should write content")
|
||||
}
|
||||
// Unsafe tenant write also requires Owner.
|
||||
if runGate(t, a, admin, http.MethodPut, "/api/v1/tenants/kv/:key") {
|
||||
t.Fatal("admin key must NOT write a tenant-level route")
|
||||
if !runGate(t, a, ingest, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
|
||||
t.Fatal("ingest capability should write content")
|
||||
}
|
||||
if !runGate(t, a, owner, http.MethodPut, "/api/v1/tenants/kv/:key") {
|
||||
t.Fatal("owner key should write a tenant-level route")
|
||||
if runGate(t, a, ingest, http.MethodGet, "/api/v1/models") {
|
||||
t.Fatal("ingest capability must not read model management routes")
|
||||
}
|
||||
if !runGate(t, a, models, http.MethodGet, "/api/v1/models") {
|
||||
t.Fatal("manage_models capability should read model management routes")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGateAnyOfCapabilities(t *testing.T) {
|
||||
a := NewAPIKeyRouteAuthorizer()
|
||||
a.Register(http.MethodPost, "/api/v1/sessions",
|
||||
APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityChat))
|
||||
a.Register(http.MethodGet, "/api/v1/agents",
|
||||
APIKeyRoutePolicy{RequireFullAccess: true}.
|
||||
WithCapability(types.APIKeyCapabilityChat).
|
||||
WithCapability(types.APIKeyCapabilityManageAgents))
|
||||
a.Register(http.MethodPost, "/api/v1/agents",
|
||||
APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityManageAgents))
|
||||
a.Register(http.MethodPut, "/api/v1/knowledge-bases/:id",
|
||||
APIKeyRoutePolicy{RequireFullAccess: true}.WithCapability(types.APIKeyCapabilityManageKnowledgeBases))
|
||||
|
||||
chat := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"chat"}}
|
||||
manage := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"manage_agents"}}
|
||||
manageKBs := &types.TenantAPIKeyScope{Capabilities: types.StringArray{"manage_kbs"}}
|
||||
|
||||
// Either capability satisfies the any-of read route.
|
||||
if !runGate(t, a, chat, http.MethodGet, "/api/v1/agents") {
|
||||
t.Fatal("chat should read agents (any-of)")
|
||||
}
|
||||
if !runGate(t, a, manage, http.MethodGet, "/api/v1/agents") {
|
||||
t.Fatal("manage_agents should read agents (any-of)")
|
||||
}
|
||||
// Only manage_agents may author agents.
|
||||
if runGate(t, a, chat, http.MethodPost, "/api/v1/agents") {
|
||||
t.Fatal("chat must not author agents")
|
||||
}
|
||||
if !runGate(t, a, manage, http.MethodPost, "/api/v1/agents") {
|
||||
t.Fatal("manage_agents should author agents")
|
||||
}
|
||||
// Only manage_kbs may manage KB metadata/config.
|
||||
if runGate(t, a, manage, http.MethodPut, "/api/v1/knowledge-bases/:id") {
|
||||
t.Fatal("manage_agents must not manage knowledge bases")
|
||||
}
|
||||
if !runGate(t, a, manageKBs, http.MethodPut, "/api/v1/knowledge-bases/:id") {
|
||||
t.Fatal("manage_kbs should manage knowledge bases")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,11 +163,11 @@ func TestGateKBScopeDoesNotBlockDataPlane(t *testing.T) {
|
||||
// A KB-restricted key is NOT blocked by the gate on data-plane routes;
|
||||
// its KB allow-list is enforced downstream by KBAccess/handler checks.
|
||||
restricted := &types.TenantAPIKeyScope{
|
||||
Role: types.TenantRoleContributor,
|
||||
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||
Capabilities: types.StringArray{"ingest"},
|
||||
}
|
||||
if !runGate(t, a, restricted, http.MethodPost, "/api/v1/knowledge-bases/:id/knowledge/file") {
|
||||
t.Fatal("KB-restricted contributor key should pass the gate on a data-plane write")
|
||||
t.Fatal("KB-restricted ingest key should pass the gate on a data-plane write")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,8 +196,8 @@ func runDenyAPIKey(t *testing.T, scope *types.TenantAPIKeyScope) (reached bool,
|
||||
// engine-root routes (outside /api/v1) that rely on RequireRole must not be
|
||||
// reachable by API-key principals, since RequireRole short-circuits them.
|
||||
func TestDenyAPIKeyPrincipalBlocksAPIKeys(t *testing.T) {
|
||||
// Even an Owner-role API key must be rejected outright.
|
||||
reached, status := runDenyAPIKey(t, &types.TenantAPIKeyScope{Role: types.TenantRoleOwner})
|
||||
// Even a full-access API key must be rejected outright.
|
||||
reached, status := runDenyAPIKey(t, &types.TenantAPIKeyScope{FullAccess: true})
|
||||
if reached {
|
||||
t.Fatal("API-key principal must not reach a DenyAPIKeyPrincipal-guarded handler")
|
||||
}
|
||||
|
||||
+12
-11
@@ -250,8 +250,8 @@ func authenticateAPIKeyRequest(
|
||||
if c.IsAborted() {
|
||||
return false
|
||||
}
|
||||
// Per-route API-key authorization (role + KB scope + default-deny) is
|
||||
// enforced by middleware.APIKeyRouteAuthorizer on the /api/v1 group.
|
||||
// Per-route API-key authorization (full access + capabilities + KB scope)
|
||||
// is enforced by middleware.APIKeyRouteAuthorizer on the /api/v1 group.
|
||||
// Key-management and any other undeclared route is denied there.
|
||||
return true
|
||||
}
|
||||
@@ -299,25 +299,26 @@ func attachAPIKeyAuthContext(
|
||||
return
|
||||
}
|
||||
c.Set(types.PrincipalContextKey.String(), principal)
|
||||
apiKeyRole := types.TenantRoleViewer
|
||||
if key != nil {
|
||||
apiKeyRole = types.NormalizeTenantAPIKeyRole(key.Role)
|
||||
if apiKeyRole == "" {
|
||||
apiKeyRole = types.TenantRoleViewer
|
||||
}
|
||||
// This role context exists only for legacy guard compatibility after
|
||||
// RequireRole short-circuits API-key principals. The API key's real
|
||||
// authority is FullAccess + Capabilities + KnowledgeBaseIDs.
|
||||
apiKeyTenantRoleContext := types.TenantRoleViewer
|
||||
if key != nil && key.FullAccess {
|
||||
apiKeyTenantRoleContext = types.TenantRoleOwner
|
||||
}
|
||||
c.Set(types.TenantRoleContextKey.String(), apiKeyRole)
|
||||
c.Set(types.TenantRoleContextKey.String(), apiKeyTenantRoleContext)
|
||||
c.Set(types.SystemAdminContextKey.String(), false)
|
||||
ctx = context.WithValue(ctx, types.UserContextKey, user)
|
||||
ctx = context.WithValue(ctx, types.UserIDContextKey, user.ID)
|
||||
ctx = types.WithPrincipal(ctx, principal)
|
||||
ctx = context.WithValue(ctx, types.TenantRoleContextKey, apiKeyRole)
|
||||
ctx = context.WithValue(ctx, types.TenantRoleContextKey, apiKeyTenantRoleContext)
|
||||
ctx = context.WithValue(ctx, types.SystemAdminContextKey, false)
|
||||
if key != nil {
|
||||
ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{
|
||||
KeyID: key.ID,
|
||||
Role: apiKeyRole,
|
||||
FullAccess: key.FullAccess,
|
||||
KnowledgeBaseIDs: key.KnowledgeBaseIDs,
|
||||
Capabilities: key.Capabilities,
|
||||
})
|
||||
}
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
|
||||
@@ -12,9 +12,9 @@ import (
|
||||
)
|
||||
|
||||
// apiKeyRBACHarness seeds an API-key scope (as attachAPIKeyAuthContext would)
|
||||
// plus a deliberately-insufficient TenantRole, then runs the guard. It
|
||||
// asserts the JWT guard short-circuits for API-key principals so that
|
||||
// per-route API-key authorization is left entirely to the APIKeyGate.
|
||||
// plus a deliberately-insufficient TenantRole, then runs the guard. It asserts
|
||||
// the JWT guard short-circuits for API-key principals so that per-route
|
||||
// API-key authorization is left entirely to the APIKeyGate.
|
||||
func apiKeyRBACHarness(scope types.TenantAPIKeyScope, role types.TenantRole, mw gin.HandlerFunc) *httptest.ResponseRecorder {
|
||||
gin.SetMode(gin.TestMode)
|
||||
r := gin.New()
|
||||
@@ -32,10 +32,10 @@ func apiKeyRBACHarness(scope types.TenantAPIKeyScope, role types.TenantRole, mw
|
||||
}
|
||||
|
||||
func TestRequireRole_ShortCircuitsAPIKey(t *testing.T) {
|
||||
// Viewer-role API key against an Admin gate would 403 under the JWT
|
||||
// Scoped API key against an Admin gate would 403 under the JWT
|
||||
// ladder; the short-circuit lets it through (the gate handles it).
|
||||
w := apiKeyRBACHarness(
|
||||
types.TenantAPIKeyScope{Role: types.TenantRoleViewer},
|
||||
types.TenantAPIKeyScope{},
|
||||
types.TenantRoleViewer,
|
||||
RequireRole(types.TenantRoleAdmin, cfgRBAC(true)),
|
||||
)
|
||||
@@ -46,7 +46,7 @@ func TestRequireRole_ShortCircuitsAPIKey(t *testing.T) {
|
||||
|
||||
func TestRequireSystemAdmin_RejectsAPIKey(t *testing.T) {
|
||||
w := apiKeyRBACHarness(
|
||||
types.TenantAPIKeyScope{Role: types.TenantRoleOwner},
|
||||
types.TenantAPIKeyScope{FullAccess: true},
|
||||
types.TenantRoleOwner,
|
||||
RequireSystemAdmin(cfgRBAC(true)),
|
||||
)
|
||||
@@ -55,24 +55,27 @@ func TestRequireSystemAdmin_RejectsAPIKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRequireOwnershipOrRole_ShortCircuitsAPIKeyContributor is the core
|
||||
// regression for review #1: a Contributor API key writing to a KB it does not
|
||||
// TestRequireOwnershipOrRole_ShortCircuitsAPIKey is the core regression for
|
||||
// review #1: an API key writing to a KB it does not
|
||||
// "own" (synthetic system user never matches creator_id) must not be 403'd by
|
||||
// the OwnedKBOrAdmin guard when EnableRBAC=true. The lookup deliberately
|
||||
// returns a foreign creator to prove the guard never runs it.
|
||||
func TestRequireOwnershipOrRole_ShortCircuitsAPIKeyContributor(t *testing.T) {
|
||||
func TestRequireOwnershipOrRole_ShortCircuitsAPIKey(t *testing.T) {
|
||||
lookupCalled := false
|
||||
lookup := func(_ *gin.Context) (string, error) {
|
||||
lookupCalled = true
|
||||
return "some-other-human-user", nil
|
||||
}
|
||||
w := apiKeyRBACHarness(
|
||||
types.TenantAPIKeyScope{Role: types.TenantRoleContributor, KnowledgeBaseIDs: types.StringArray{"kb-1"}},
|
||||
types.TenantAPIKeyScope{
|
||||
KnowledgeBaseIDs: types.StringArray{"kb-1"},
|
||||
Capabilities: types.StringArray{string(types.APIKeyCapabilityIngest)},
|
||||
},
|
||||
types.TenantRoleContributor,
|
||||
RequireOwnershipOrRole(types.TenantRoleAdmin, lookup, cfgRBAC(true)),
|
||||
)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("Contributor API-key write should short-circuit OwnedKBOrAdmin, got %d", w.Code)
|
||||
t.Fatalf("API-key write should short-circuit OwnedKBOrAdmin, got %d", w.Code)
|
||||
}
|
||||
if lookupCalled {
|
||||
t.Fatal("ownership lookup must not run for API-key principals")
|
||||
|
||||
+80
-19
@@ -215,32 +215,93 @@ func (g *rbacGuards) Owner() gin.HandlerFunc {
|
||||
// it and denies any undeclared route by default. JWT sessions ignore all of
|
||||
// this (they short-circuit the gate).
|
||||
//
|
||||
// Policy constructors. A single dimension — the minimum role — decides
|
||||
// access; the key's knowledge_base_ids allow-list is a pure data filter
|
||||
// applied downstream (KBAccess guards + handler scope checks), never here.
|
||||
//
|
||||
// - apiKeyViewer : data-plane reads/searches (Viewer floor).
|
||||
// - apiKeyContributor : data-plane content writes (Contributor+).
|
||||
// - apiKeyAdmin : destructive data-plane ops, e.g. clearing a KB (Admin+).
|
||||
// - apiKeyOwner : tenant-level infrastructure (models, vector stores,
|
||||
// MCP, data sources, channels, tenant KV, ...). Requires the Owner role
|
||||
// for EVERY method, mirroring the original full-access tenant key. A key
|
||||
// below Owner can only ever touch knowledge-base data.
|
||||
// Policy constructors. API keys do not reuse tenant-member roles: a key is
|
||||
// either full-access, or it carries explicit capabilities. KB allow-lists are
|
||||
// pure data filters applied downstream by KBAccess guards and handlers.
|
||||
|
||||
func apiKeyViewer() middleware.APIKeyRoutePolicy {
|
||||
return middleware.APIKeyRoutePolicy{MinRole: types.TenantRoleViewer}
|
||||
func apiKeyAny() middleware.APIKeyRoutePolicy {
|
||||
return middleware.APIKeyRoutePolicy{}
|
||||
}
|
||||
|
||||
func apiKeyContributor() middleware.APIKeyRoutePolicy {
|
||||
return middleware.APIKeyRoutePolicy{MinRole: types.TenantRoleContributor}
|
||||
func apiKeyFullAccess() middleware.APIKeyRoutePolicy {
|
||||
return middleware.APIKeyRoutePolicy{RequireFullAccess: true}
|
||||
}
|
||||
|
||||
func apiKeyAdmin() middleware.APIKeyRoutePolicy {
|
||||
return middleware.APIKeyRoutePolicy{MinRole: types.TenantRoleAdmin}
|
||||
// apiKeyRetrieve grants read/search access to knowledge-base data.
|
||||
func apiKeyRetrieve(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityRetrieve)
|
||||
}
|
||||
|
||||
func apiKeyOwner() middleware.APIKeyRoutePolicy {
|
||||
return middleware.APIKeyRoutePolicy{MinRole: types.TenantRoleOwner}
|
||||
// apiKeyChat layers the "chat" capability on top of a base policy: keys that
|
||||
// carry the chat capability can use the conversation flow (sessions, agent
|
||||
// listing) without full tenant access.
|
||||
func apiKeyChat(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityChat)
|
||||
}
|
||||
|
||||
// apiKeyReadAgents layers the "read_agents" capability on top of a base
|
||||
// policy so scoped integrations can inspect available agents without chat or
|
||||
// authoring permissions.
|
||||
func apiKeyReadAgents(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityReadAgents)
|
||||
}
|
||||
|
||||
// apiKeyIngest layers the "ingest" capability on top of a base policy so a
|
||||
// scoped key can write content into its allowed knowledge bases (documents,
|
||||
// chunks, FAQ, tags, wiki).
|
||||
func apiKeyIngest(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityIngest)
|
||||
}
|
||||
|
||||
// apiKeyManageKnowledgeBases layers the "manage_kbs" capability on top of a
|
||||
// base policy so a scoped key can manage existing KB metadata/config within
|
||||
// its KB allow-list.
|
||||
func apiKeyManageKnowledgeBases(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityManageKnowledgeBases)
|
||||
}
|
||||
|
||||
// apiKeyManageAgents layers the "manage_agents" capability on top of a base policy.
|
||||
func apiKeyManageAgents(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityManageAgents)
|
||||
}
|
||||
|
||||
// apiKeyMessageHistory layers the "message_history" capability on top of a
|
||||
// base policy so an explicitly granted key can search or inspect tenant chat
|
||||
// history without being promoted to full Owner.
|
||||
func apiKeyMessageHistory(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityMessageHistory)
|
||||
}
|
||||
|
||||
func apiKeyManageModels(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityManageModels)
|
||||
}
|
||||
|
||||
func apiKeyManageMCPServices(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityManageMCPServices)
|
||||
}
|
||||
|
||||
func apiKeyManageDataSources(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityManageDataSources)
|
||||
}
|
||||
|
||||
func apiKeyManageChannels(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityManageChannels)
|
||||
}
|
||||
|
||||
func apiKeyManageVectorStores(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityManageVectorStores)
|
||||
}
|
||||
|
||||
func apiKeyManageWebSearch(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityManageWebSearch)
|
||||
}
|
||||
|
||||
func apiKeyRunEvaluations(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityRunEvaluations)
|
||||
}
|
||||
|
||||
func apiKeyManageTenantSettings(base middleware.APIKeyRoutePolicy) middleware.APIKeyRoutePolicy {
|
||||
return base.WithCapability(types.APIKeyCapabilityManageTenantSettings)
|
||||
}
|
||||
|
||||
// apiKeyRouteGroup wraps a *gin.RouterGroup so route registration also records
|
||||
|
||||
@@ -20,14 +20,14 @@ func TestAssertAPIKeyPoliciesMatchRoutes_TrailingSlash(t *testing.T) {
|
||||
|
||||
// Register through the apiKey helpers using both "" and "/" rel plus a
|
||||
// nested path, mirroring real route declarations.
|
||||
empty := g.apiKeyGroup(v1.Group("/knowledge-bases"), apiKeyViewer())
|
||||
empty := g.apiKeyGroup(v1.Group("/knowledge-bases"), apiKeyAny())
|
||||
empty.GET("", noop)
|
||||
|
||||
slash := g.apiKeyGroup(v1.Group("/evaluation"), apiKeyOwner())
|
||||
slash := g.apiKeyGroup(v1.Group("/evaluation"), apiKeyFullAccess())
|
||||
slash.POST("/", noop)
|
||||
slash.GET("/", noop)
|
||||
|
||||
g.apiKeyRoute(v1, http.MethodGet, "/tenants", apiKeyOwner(), noop)
|
||||
g.apiKeyRoute(v1, http.MethodGet, "/tenants", apiKeyFullAccess(), noop)
|
||||
|
||||
// Must not panic: every declared policy resolves to a real route despite
|
||||
// the trailing-slash difference on /evaluation.
|
||||
@@ -42,7 +42,7 @@ func TestAssertAPIKeyPoliciesMatchRoutes_Missing(t *testing.T) {
|
||||
|
||||
g := &rbacGuards{}
|
||||
// Declare a policy for a path that is never registered on the engine.
|
||||
g.ensureAPIKeyAuthorizer().Register(http.MethodPost, "/api/v1/does-not-exist", apiKeyOwner())
|
||||
g.ensureAPIKeyAuthorizer().Register(http.MethodPost, "/api/v1/does-not-exist", apiKeyFullAccess())
|
||||
|
||||
defer func() {
|
||||
if recover() == nil {
|
||||
|
||||
+147
-113
@@ -209,7 +209,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
// so that sub-groups inherit it.
|
||||
v1.Use(rbacGuards.apiKeyAuthorizer.Middleware())
|
||||
|
||||
RegisterAuthRoutes(v1, params.AuthHandler)
|
||||
RegisterAuthRoutes(v1, params.AuthHandler, rbacGuards)
|
||||
RegisterTenantRoutes(v1, params.TenantHandler, params.TenantMemberHandler, params.TenantInvitationHandler, params.AuditLogHandler, rbacGuards)
|
||||
RegisterMyInvitationRoutes(v1, params.TenantInvitationHandler)
|
||||
RegisterKnowledgeBaseRoutes(v1, params.KBHandler, rbacGuards)
|
||||
@@ -258,7 +258,7 @@ func NewRouter(params RouterParams) *gin.Engine {
|
||||
// has not yet expired are kept out by the role check, matching the
|
||||
// rest of the RBAC matrix in this file.
|
||||
func RegisterChunkerDebugRoutes(r *gin.RouterGroup, g *rbacGuards) {
|
||||
g.apiKeyRoute(r, http.MethodPost, "/chunker/preview", apiKeyViewer(), g.Viewer(), handler.PreviewChunking)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/chunker/preview", apiKeyAny(), g.Viewer(), handler.PreviewChunking)
|
||||
}
|
||||
|
||||
// RegisterChunkRoutes 注册分块相关的路由
|
||||
@@ -268,13 +268,15 @@ func RegisterChunkerDebugRoutes(r *gin.RouterGroup, g *rbacGuards) {
|
||||
// shared with RegisterKnowledgeRoutes via OwnedChunkKBOrAdmin so the
|
||||
// same "creator-of-the-KB OR Admin+" rule applies to chunk edits.
|
||||
func RegisterChunkRoutes(r *gin.RouterGroup, handler *handler.ChunkHandler, g *rbacGuards) {
|
||||
// 分块路由组。API key 策略:内容级写入 Contributor+ 且限定 KB 范围。
|
||||
chunks := g.apiKeyGroup(r.Group("/chunks"), apiKeyContributor())
|
||||
// 分块路由组。Scoped API key 需要 ingest 能力写内容,retrieve 能力读内容;
|
||||
// 两者仍受 KB 白名单约束。
|
||||
chunks := g.apiKeyGroup(r.Group("/chunks"), apiKeyIngest(apiKeyFullAccess()))
|
||||
chunkRead := chunks.With(apiKeyRetrieve(apiKeyFullAccess()))
|
||||
{
|
||||
// 获取分块列表 — Viewer+ 且对父 KB 有 read 权限(own / shared / via shared agent)
|
||||
chunks.GET("/:knowledge_id", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("knowledge_id"), handler.ListKnowledgeChunks)
|
||||
chunkRead.GET("/:knowledge_id", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("knowledge_id"), handler.ListKnowledgeChunks)
|
||||
// 通过chunk_id获取单个chunk(不需要knowledge_id) — Viewer+ 且对父 KB 有 read 权限
|
||||
chunks.GET("/by-id/:id", g.Viewer(), g.KBAccessReadFromChunkIDParam("id"), handler.GetChunkByIDOnly)
|
||||
chunkRead.GET("/by-id/:id", g.Viewer(), g.KBAccessReadFromChunkIDParam("id"), handler.GetChunkByIDOnly)
|
||||
// 删除分块 — KB owner OR Admin+,且对父 KB 有 write 权限
|
||||
chunks.DELETE("/:knowledge_id/:id", g.OwnedChunkKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("knowledge_id"), handler.DeleteChunk)
|
||||
// 删除知识下的所有分块 — KB owner OR Admin+,且对父 KB 有 write 权限
|
||||
@@ -301,40 +303,44 @@ func RegisterChunkRoutes(r *gin.RouterGroup, handler *handler.ChunkHandler, g *r
|
||||
// Cross-:id batch operations stay Contributor-gated — they don't have
|
||||
// a single owning KB to check against.
|
||||
func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandler, g *rbacGuards) {
|
||||
// 知识库下的知识路由组(URL :id is the KB id)。API key 默认 Contributor+ 且限 KB 范围。
|
||||
kb := g.apiKeyGroup(r.Group("/knowledge-bases/:id/knowledge"), apiKeyContributor())
|
||||
// 知识库下的知识路由组(URL :id is the KB id)。Scoped API key 需要
|
||||
// ingest 能力才能写内容,且仍受 KB 范围限制;清空 KB 只允许 full-access key。
|
||||
kb := g.apiKeyGroup(r.Group("/knowledge-bases/:id/knowledge"), apiKeyIngest(apiKeyFullAccess()))
|
||||
kbRead := kb.With(apiKeyRetrieve(apiKeyFullAccess()))
|
||||
{
|
||||
kb.POST("/file", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateKnowledgeFromFile)
|
||||
kb.POST("/url", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateKnowledgeFromURL)
|
||||
kb.POST("/manual", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateManualKnowledge)
|
||||
kb.GET("", g.Viewer(), g.KBAccessRead("id"), handler.ListKnowledge)
|
||||
kbRead.GET("", g.Viewer(), g.KBAccessRead("id"), handler.ListKnowledge)
|
||||
// Clearing all contents under a KB is a destructive op; gate
|
||||
// behind Admin instead of Contributor.
|
||||
kb.With(apiKeyAdmin()).DELETE("", g.Admin(), g.KBAccessWrite("id"), handler.ClearKnowledgeBaseContents)
|
||||
kb.With(apiKeyFullAccess()).DELETE("", g.Admin(), g.KBAccessWrite("id"), handler.ClearKnowledgeBaseContents)
|
||||
}
|
||||
|
||||
// 知识路由组(URL :id is a knowledge id; the guard walks it to the parent KB)
|
||||
kgrp := r.Group("/knowledge")
|
||||
k := g.apiKeyGroup(kgrp, apiKeyContributor())
|
||||
k := g.apiKeyGroup(kgrp, apiKeyIngest(apiKeyFullAccess()))
|
||||
kRead := k.With(apiKeyRetrieve(apiKeyFullAccess()))
|
||||
{
|
||||
// Cross-knowledge endpoints (no :id) can't be gated on a single
|
||||
// KB — they accept arbitrary knowledge IDs and the handler must
|
||||
// fan out the access check itself. So /batch and /search keep
|
||||
// the role-only floor; /move and /batch-delete stay Contributor.
|
||||
k.GET("/batch", g.Viewer(), handler.GetKnowledgeBatch)
|
||||
k.GET("/:id", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.GetKnowledge)
|
||||
k.GET("/:id/stages", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.GetKnowledgeSpans)
|
||||
k.GET("/:id/spans", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.GetKnowledgeSpans)
|
||||
// fan out the access check itself. /batch and /search are read
|
||||
// routes; /move and /batch-delete stay JWT Contributor-gated and are
|
||||
// not declared for API keys.
|
||||
kRead.GET("/batch", g.Viewer(), handler.GetKnowledgeBatch)
|
||||
kRead.GET("/:id", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.GetKnowledge)
|
||||
kRead.GET("/:id/stages", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.GetKnowledgeSpans)
|
||||
kRead.GET("/:id/spans", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.GetKnowledgeSpans)
|
||||
k.DELETE("/:id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.DeleteKnowledge)
|
||||
k.PUT("/:id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.UpdateKnowledge)
|
||||
k.PUT("/manual/:id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.UpdateManualKnowledge)
|
||||
k.POST("/:id/reparse", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.ReparseKnowledge)
|
||||
k.POST("/:id/cancel-parse", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.CancelKnowledgeParse)
|
||||
k.GET("/:id/download", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.DownloadKnowledgeFile)
|
||||
k.GET("/:id/preview", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.PreviewKnowledgeFile)
|
||||
kRead.GET("/:id/download", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.DownloadKnowledgeFile)
|
||||
kRead.GET("/:id/preview", g.Viewer(), g.KBAccessReadFromKnowledgeIDParam("id"), handler.PreviewKnowledgeFile)
|
||||
k.PUT("/image/:id/:chunk_id", g.OwnedKnowledgeKBOrAdmin(), g.KBAccessWriteFromKnowledgeIDParam("id"), handler.UpdateImageInfo)
|
||||
k.GET("/search", g.Viewer(), handler.SearchKnowledge)
|
||||
k.GET("/move/progress/:task_id", g.Viewer(), handler.GetKnowledgeMoveProgress)
|
||||
kRead.GET("/search", g.Viewer(), handler.SearchKnowledge)
|
||||
kRead.GET("/move/progress/:task_id", g.Viewer(), handler.GetKnowledgeMoveProgress)
|
||||
// Batch / cross-KB write ops stay Contributor-gated for JWT and are
|
||||
// NOT declared for API keys (default-deny): they fan out to arbitrary
|
||||
// KBs with no single owning KB to bound a key's scope against.
|
||||
@@ -358,14 +364,15 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler, g *rbacG
|
||||
// 等价于修改 KB 内容,必须遵循 KB 的"creator OR Admin+"矩阵 ——
|
||||
// 跟 chunks / wiki pages 保持一致。Viewer+ 可以读,Contributor 不能
|
||||
// 改不属于自己的 KB 的 FAQ。
|
||||
faq := g.apiKeyGroup(r.Group("/knowledge-bases/:id/faq"), apiKeyContributor())
|
||||
faq := g.apiKeyGroup(r.Group("/knowledge-bases/:id/faq"), apiKeyIngest(apiKeyFullAccess()))
|
||||
faqRead := faq.With(apiKeyRetrieve(apiKeyFullAccess()))
|
||||
{
|
||||
// KBAccessRead/Write resolve own/shared/agent-visible access and
|
||||
// rewrite the request's tenant context — handler no longer
|
||||
// carries an effectiveCtxForKB helper.
|
||||
faq.GET("/entries", g.Viewer(), g.KBAccessRead("id"), handler.ListEntries)
|
||||
faq.GET("/entries/export", g.Viewer(), g.KBAccessRead("id"), handler.ExportEntries)
|
||||
faq.GET("/entries/:entry_id", g.Viewer(), g.KBAccessRead("id"), handler.GetEntry)
|
||||
faqRead.GET("/entries", g.Viewer(), g.KBAccessRead("id"), handler.ListEntries)
|
||||
faqRead.GET("/entries/export", g.Viewer(), g.KBAccessRead("id"), handler.ExportEntries)
|
||||
faqRead.GET("/entries/:entry_id", g.Viewer(), g.KBAccessRead("id"), handler.GetEntry)
|
||||
faq.POST("/entries", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpsertEntries)
|
||||
faq.POST("/entry", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.CreateEntry)
|
||||
faq.PUT("/entries/:entry_id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateEntry)
|
||||
@@ -374,9 +381,9 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler, g *rbacG
|
||||
faq.PUT("/entries/fields", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateEntryFieldsBatch)
|
||||
faq.PUT("/entries/tags", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateEntryTagBatch)
|
||||
faq.DELETE("/entries", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.DeleteEntries)
|
||||
// Search is a read: Viewer keys may call it even though the group
|
||||
// default is Contributor (POST is otherwise an unsafe method).
|
||||
faq.With(apiKeyViewer()).POST("/search", g.Viewer(), g.KBAccessRead("id"), handler.SearchFAQ)
|
||||
// Search is a read route: scoped API keys may call it with retrieve
|
||||
// even though POST is otherwise an unsafe method.
|
||||
faqRead.POST("/search", g.Viewer(), g.KBAccessRead("id"), handler.SearchFAQ)
|
||||
// FAQ import result display status
|
||||
faq.PUT("/import/last-result/display", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateLastImportResultDisplayStatus)
|
||||
}
|
||||
@@ -389,21 +396,24 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler, g *rbacG
|
||||
|
||||
// RegisterKnowledgeBaseRoutes 注册知识库相关的路由
|
||||
func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeBaseHandler, g *rbacGuards) {
|
||||
// 知识库路由组。API key 默认可读(Viewer,限 KB 范围);写入 Contributor+;
|
||||
// 创建/拷贝 KB 不对 API key 开放(注册在原始 group 上,默认拒绝)。
|
||||
// 知识库路由组。Scoped API key 需要 retrieve 能力读取(限 KB 范围);KB 内容写入
|
||||
// 由 RegisterKnowledgeRoutes/FAQ/Tag/Wiki 等子路由的 ingest 能力控制;
|
||||
// KB 自身的元数据/生命周期管理需要 full access 或 manage_kbs。创建/拷贝
|
||||
// KB 没有单个目标 KB 可约束,继续不对 scoped API key 开放。
|
||||
kbgrp := r.Group("/knowledge-bases")
|
||||
kb := g.apiKeyGroup(kbgrp, apiKeyViewer())
|
||||
kb := g.apiKeyGroup(kbgrp, apiKeyRetrieve(apiKeyFullAccess()))
|
||||
kbManagement := kb.With(apiKeyManageKnowledgeBases(apiKeyFullAccess()))
|
||||
{
|
||||
// 创建知识库 — Contributor+ (no :id, role-only floor); API keys may not create KBs.
|
||||
// 创建知识库 — Contributor+ for JWT callers; API keys may not create KBs.
|
||||
kbgrp.POST("", g.Contributor(), handler.CreateKnowledgeBase)
|
||||
// 获取知识库列表 — Viewer+ (no :id, role-only floor)
|
||||
// 获取知识库列表 — Viewer+ for JWT callers; retrieve-capable API keys pass via the gate.
|
||||
kb.GET("", g.Viewer(), handler.ListKnowledgeBases)
|
||||
// 获取知识库详情 — Viewer+ 且对 KB 有 read 权限
|
||||
kb.GET("/:id", g.Viewer(), g.KBAccessRead("id"), handler.GetKnowledgeBase)
|
||||
// 更新知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
||||
kb.With(apiKeyContributor()).PUT("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateKnowledgeBase)
|
||||
kbManagement.PUT("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.UpdateKnowledgeBase)
|
||||
// 删除知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
||||
kb.With(apiKeyContributor()).DELETE("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.DeleteKnowledgeBase)
|
||||
kbManagement.DELETE("/:id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), handler.DeleteKnowledgeBase)
|
||||
// 置顶/取消置顶知识库 — 创建者本人 OR Admin+ 且对 KB 有 write 权限
|
||||
// Pin state is now per-(user, kb) (migration 000050). Anyone with
|
||||
// at least Viewer-level read access to the KB — including users
|
||||
@@ -411,7 +421,7 @@ func RegisterKnowledgeBaseRoutes(r *gin.RouterGroup, handler *handler.KnowledgeB
|
||||
// no edit permission is required. The OwnedKBOrAdmin guard was
|
||||
// removed accordingly. The route still requires KB read access
|
||||
// so callers can't poke at KBs they can't see.
|
||||
kb.With(apiKeyContributor()).PUT("/:id/pin", g.Viewer(), g.KBAccessRead("id"), handler.TogglePinKnowledgeBase)
|
||||
kb.PUT("/:id/pin", g.Viewer(), g.KBAccessRead("id"), handler.TogglePinKnowledgeBase)
|
||||
// 混合搜索 — Viewer+ 且对 KB 有 read 权限 (read-only)
|
||||
// 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)
|
||||
@@ -437,13 +447,14 @@ func RegisterKnowledgeTagRoutes(r *gin.RouterGroup, tagHandler *handler.TagHandl
|
||||
// Tags 是 KB 的子资源 — 创建/编辑/删除标签会改变 KB 内容的检索分类
|
||||
// 行为,应该与 KB 主体的"creator OR Admin+"矩阵一致,避免一个无
|
||||
// 关 Contributor 在他人 KB 里乱建/删标签影响 KB owner 的内容组织。
|
||||
kbTags := g.apiKeyGroup(r.Group("/knowledge-bases/:id/tags"), apiKeyContributor())
|
||||
kbTags := g.apiKeyGroup(r.Group("/knowledge-bases/:id/tags"), apiKeyIngest(apiKeyFullAccess()))
|
||||
kbTagsRead := kbTags.With(apiKeyRetrieve(apiKeyFullAccess()))
|
||||
{
|
||||
// KBAccessRead/Write resolve own/shared/agent-visible access and
|
||||
// rewrite the request's tenant context to the effective tenant
|
||||
// for the duration of the handler — so the handler no longer
|
||||
// needs its own effectiveCtxForKB helper.
|
||||
kbTags.GET("", g.Viewer(), g.KBAccessRead("id"), tagHandler.ListTags)
|
||||
kbTagsRead.GET("", g.Viewer(), g.KBAccessRead("id"), tagHandler.ListTags)
|
||||
kbTags.POST("", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), tagHandler.CreateTag)
|
||||
kbTags.PUT("/:tag_id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), tagHandler.UpdateTag)
|
||||
kbTags.DELETE("/:tag_id", g.OwnedKBOrAdmin(), g.KBAccessWrite("id"), tagHandler.DeleteTag)
|
||||
@@ -458,14 +469,20 @@ func RegisterKnowledgeTagRoutes(r *gin.RouterGroup, tagHandler *handler.TagHandl
|
||||
// reach the endpoints at all once RBAC is on.
|
||||
func RegisterMessageRoutes(r *gin.RouterGroup, handler *handler.MessageHandler, g *rbacGuards) {
|
||||
// Message history is tenant-wide and not attributable to a KB, so it is
|
||||
// a tenant-level (Owner) surface for API keys — only a full-access key
|
||||
// may read or delete it.
|
||||
messages := g.apiKeyGroup(r.Group("/messages"), apiKeyOwner())
|
||||
// a full-access surface for API keys by default. The narrow
|
||||
// exceptions are explicit capabilities:
|
||||
// - chat: load/delete messages inside the caller's own session, where
|
||||
// ownership is enforced by the message service.
|
||||
// - message_history: search/read tenant chat-history metadata without
|
||||
// granting every other full-access API.
|
||||
messages := g.apiKeyGroup(r.Group("/messages"), apiKeyFullAccess())
|
||||
chatMessages := messages.With(apiKeyChat(apiKeyFullAccess()))
|
||||
historyMessages := messages.With(apiKeyMessageHistory(apiKeyFullAccess()))
|
||||
{
|
||||
messages.POST("/search", g.Viewer(), handler.SearchMessages)
|
||||
messages.GET("/chat-history-stats", g.Viewer(), handler.GetChatHistoryKBStats)
|
||||
messages.GET("/:session_id/load", g.Viewer(), handler.LoadMessages)
|
||||
messages.DELETE("/:session_id/:id", g.Viewer(), handler.DeleteMessage)
|
||||
historyMessages.POST("/search", g.Viewer(), handler.SearchMessages)
|
||||
historyMessages.GET("/chat-history-stats", g.Viewer(), handler.GetChatHistoryKBStats)
|
||||
chatMessages.GET("/:session_id/load", g.Viewer(), handler.LoadMessages)
|
||||
chatMessages.DELETE("/:session_id/:id", g.Viewer(), handler.DeleteMessage)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -477,7 +494,10 @@ func RegisterMessageRoutes(r *gin.RouterGroup, handler *handler.MessageHandler,
|
||||
// per-session ownership in the middleware layer the same way KB/agent
|
||||
// routes do today.
|
||||
func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGuards) {
|
||||
sessions := g.apiKeyGroup(r.Group("/sessions", g.Viewer()), apiKeyContributor())
|
||||
// Sessions are per-user chat state, not knowledge-base content. The
|
||||
// chat capability lets a scoped key run the full conversation flow
|
||||
// (create/manage its own sessions) without full tenant access.
|
||||
sessions := g.apiKeyGroup(r.Group("/sessions", g.Viewer()), apiKeyChat(apiKeyFullAccess()))
|
||||
{
|
||||
sessions.POST("", handler.CreateSession)
|
||||
sessions.DELETE("/batch", handler.BatchDeleteSessions)
|
||||
@@ -503,19 +523,21 @@ func RegisterSessionRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbac
|
||||
// surfaces; Viewer+ is sufficient because per-session/per-agent
|
||||
// authorisation is enforced inside the handlers.
|
||||
func RegisterChatRoutes(r *gin.RouterGroup, handler *session.Handler, g *rbacGuards) {
|
||||
knowledgeChat := g.apiKeyGroup(r.Group("/knowledge-chat", g.Viewer()), apiKeyViewer())
|
||||
// These POST routes append messages and run generation, so a scoped key
|
||||
// needs the explicit chat capability unless it has full tenant access.
|
||||
knowledgeChat := g.apiKeyGroup(r.Group("/knowledge-chat", g.Viewer()), apiKeyChat(apiKeyFullAccess()))
|
||||
{
|
||||
knowledgeChat.POST("/:session_id", handler.KnowledgeQA)
|
||||
}
|
||||
|
||||
// Agent-based chat
|
||||
agentChat := g.apiKeyGroup(r.Group("/agent-chat", g.Viewer()), apiKeyViewer())
|
||||
agentChat := g.apiKeyGroup(r.Group("/agent-chat", g.Viewer()), apiKeyChat(apiKeyFullAccess()))
|
||||
{
|
||||
agentChat.POST("/:session_id", handler.AgentQA)
|
||||
}
|
||||
|
||||
// 新增知识检索接口,不需要session_id
|
||||
knowledgeSearch := g.apiKeyGroup(r.Group("/knowledge-search", g.Viewer()), apiKeyViewer())
|
||||
knowledgeSearch := g.apiKeyGroup(r.Group("/knowledge-search", g.Viewer()), apiKeyRetrieve(apiKeyFullAccess()))
|
||||
{
|
||||
knowledgeSearch.POST("", handler.SearchKnowledge)
|
||||
}
|
||||
@@ -577,15 +599,15 @@ func RegisterTenantRoutes(
|
||||
// 租户,所以越过 PathTenantMatch 守卫不会扩大攻击面。
|
||||
// 创建租户不对 API key 开放(注册在原始 group,默认拒绝)。
|
||||
tenantRoutes.POST("", handler.CreateTenant)
|
||||
g.apiKeyRoute(tenantRoutes, http.MethodGet, "", apiKeyOwner(), handler.ListTenants)
|
||||
g.apiKeyRoute(tenantRoutes, http.MethodGet, "", apiKeyManageTenantSettings(apiKeyFullAccess()), handler.ListTenants)
|
||||
|
||||
// Generic KV configuration management (tenant-level). Tenant ID
|
||||
// is obtained from authentication context; the URL :key is a
|
||||
// config key, not a tenant ID, so these stay outside the
|
||||
// PathTenantMatch group. Tenant-level surface: only a full-access
|
||||
// (Owner) API key may read or write it.
|
||||
g.apiKeyRoute(tenantRoutes, http.MethodGet, "/kv/:key", apiKeyOwner(), g.Viewer(), handler.GetTenantKV)
|
||||
g.apiKeyRoute(tenantRoutes, http.MethodPut, "/kv/:key", apiKeyOwner(), g.Admin(), handler.UpdateTenantKV)
|
||||
// PathTenantMatch group. Tenant-level surface: full-access keys may
|
||||
// call it, and scoped keys need manage_tenant_settings.
|
||||
g.apiKeyRoute(tenantRoutes, http.MethodGet, "/kv/:key", apiKeyManageTenantSettings(apiKeyFullAccess()), g.Viewer(), handler.GetTenantKV)
|
||||
g.apiKeyRoute(tenantRoutes, http.MethodPut, "/kv/:key", apiKeyManageTenantSettings(apiKeyFullAccess()), g.Admin(), handler.UpdateTenantKV)
|
||||
|
||||
// Per-tenant endpoints share PathTenantMatch at the group level.
|
||||
// None of the /tenants/:id/* endpoints are declared for API keys,
|
||||
@@ -659,7 +681,7 @@ func RegisterModelRoutes(
|
||||
g *rbacGuards,
|
||||
) {
|
||||
// 模型路由组。租户级基础设施:仅完全访问(Owner)API key 可访问。
|
||||
models := g.apiKeyGroup(r.Group("/models"), apiKeyOwner())
|
||||
models := g.apiKeyGroup(r.Group("/models"), apiKeyManageModels(apiKeyFullAccess()))
|
||||
{
|
||||
// 获取模型厂商列表 — Viewer+
|
||||
models.GET("/providers", g.Viewer(), handler.ListModelProviders)
|
||||
@@ -686,7 +708,7 @@ func RegisterModelRoutes(
|
||||
// tenant; gate to Admin+ until product asks for a finer-grained
|
||||
// matrix.
|
||||
func RegisterEvaluationRoutes(r *gin.RouterGroup, handler *handler.EvaluationHandler, g *rbacGuards) {
|
||||
evaluationRoutes := g.apiKeyGroup(r.Group("/evaluation"), apiKeyOwner())
|
||||
evaluationRoutes := g.apiKeyGroup(r.Group("/evaluation"), apiKeyRunEvaluations(apiKeyFullAccess()))
|
||||
{
|
||||
evaluationRoutes.POST("", g.Admin(), handler.Evaluation)
|
||||
evaluationRoutes.GET("", g.Viewer(), handler.GetEvaluationResult)
|
||||
@@ -720,7 +742,7 @@ func RegisterMyInvitationRoutes(r *gin.RouterGroup, invitationHandler *handler.T
|
||||
}
|
||||
|
||||
// RegisterAuthRoutes registers authentication routes
|
||||
func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
|
||||
func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler, g *rbacGuards) {
|
||||
r.POST("/auth/register", handler.Register)
|
||||
// Share-link surfaces are unauthenticated and accept a plaintext
|
||||
// token from the caller; rate-limit by IP to bound brute-force /
|
||||
@@ -740,7 +762,10 @@ func RegisterAuthRoutes(r *gin.RouterGroup, handler *handler.AuthHandler) {
|
||||
r.POST("/auth/refresh", handler.RefreshToken)
|
||||
r.GET("/auth/validate", handler.ValidateToken)
|
||||
r.POST("/auth/logout", handler.Logout)
|
||||
r.GET("/auth/me", handler.GetCurrentUser)
|
||||
// auth/me returns only the caller's own identity/profile, so it is safe
|
||||
// for any valid API key. Chat clients / MCP call it to discover "who am I";
|
||||
// leaving it default-deny was why scoped keys got a 403 here.
|
||||
g.apiKeyRoute(r, http.MethodGet, "/auth/me", apiKeyAny(), handler.GetCurrentUser)
|
||||
r.PUT("/auth/me/preferences", handler.UpdateMyPreferences)
|
||||
r.POST("/auth/change-password", handler.ChangePassword)
|
||||
}
|
||||
@@ -749,35 +774,35 @@ func RegisterInitializationRoutes(r *gin.RouterGroup, handler *handler.Initializ
|
||||
// 初始化接口
|
||||
// GetCurrentConfigByKB 是只读,Viewer+ 即可(KB 受限 key 可读其范围内的 KB)。
|
||||
g.apiKeyRoute(r, http.MethodGet, "/initialization/config/:kbId",
|
||||
apiKeyViewer(), g.Viewer(), g.KBAccessRead("kbId"), handler.GetCurrentConfigByKB)
|
||||
apiKeyRetrieve(apiKeyFullAccess()), g.Viewer(), g.KBAccessRead("kbId"), handler.GetCurrentConfigByKB)
|
||||
// InitializeByKB / UpdateKBConfig 都是改 KB 的核心模型/storage 配置 —
|
||||
// 跟 PUT /knowledge-bases/:id 同等敏感,挂同款 OwnedKB 矩阵 + KBAccessWrite
|
||||
//(API-key 主体短路 Owned* 守卫,KB allow-list 只能靠 KBAccess 兜底)。
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/initialize/:kbId",
|
||||
apiKeyContributor(), g.OwnedKBOrAdminFromKbIDParam(), g.KBAccessWrite("kbId"), handler.InitializeByKB)
|
||||
apiKeyManageKnowledgeBases(apiKeyFullAccess()), g.OwnedKBOrAdminFromKbIDParam(), g.KBAccessWrite("kbId"), handler.InitializeByKB)
|
||||
g.apiKeyRoute(r, http.MethodPut, "/initialization/config/:kbId",
|
||||
apiKeyContributor(), g.OwnedKBOrAdminFromKbIDParam(), g.KBAccessWrite("kbId"), handler.UpdateKBConfig)
|
||||
apiKeyManageKnowledgeBases(apiKeyFullAccess()), g.OwnedKBOrAdminFromKbIDParam(), g.KBAccessWrite("kbId"), handler.UpdateKBConfig)
|
||||
|
||||
// Ollama / 远程 API / 抽取等系统级检测/下载操作。这些不绑某个 KB,
|
||||
// 会改租户级模型配置或拉远端模型;JWT 侧只读探测 Viewer+、变更 Admin+。
|
||||
// 对 API key 均为租户级:仅完全访问(Owner)key 可用。
|
||||
g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/status", apiKeyOwner(), g.Viewer(), handler.CheckOllamaStatus)
|
||||
g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/models", apiKeyOwner(), g.Viewer(), handler.ListOllamaModels)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/ollama/models/check", apiKeyOwner(), g.Admin(), handler.CheckOllamaModels)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/ollama/models/download", apiKeyOwner(), g.Admin(), handler.DownloadOllamaModel)
|
||||
g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/download/progress/:taskId", apiKeyOwner(), g.Viewer(), handler.GetDownloadProgress)
|
||||
g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/download/tasks", apiKeyOwner(), g.Viewer(), handler.ListDownloadTasks)
|
||||
// 对 API key 均为租户级:full-access key 可用,scoped key 需要 manage_models。
|
||||
g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/status", apiKeyManageModels(apiKeyFullAccess()), g.Viewer(), handler.CheckOllamaStatus)
|
||||
g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/models", apiKeyManageModels(apiKeyFullAccess()), g.Viewer(), handler.ListOllamaModels)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/ollama/models/check", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.CheckOllamaModels)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/ollama/models/download", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.DownloadOllamaModel)
|
||||
g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/download/progress/:taskId", apiKeyManageModels(apiKeyFullAccess()), g.Viewer(), handler.GetDownloadProgress)
|
||||
g.apiKeyRoute(r, http.MethodGet, "/initialization/ollama/download/tasks", apiKeyManageModels(apiKeyFullAccess()), g.Viewer(), handler.ListDownloadTasks)
|
||||
|
||||
// 远程API相关接口
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/remote/check", apiKeyOwner(), g.Admin(), handler.CheckRemoteModel)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/embedding/test", apiKeyOwner(), g.Admin(), handler.TestEmbeddingModel)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/rerank/check", apiKeyOwner(), g.Admin(), handler.CheckRerankModel)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/asr/check", apiKeyOwner(), g.Admin(), handler.CheckASRModel)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/multimodal/test", apiKeyOwner(), g.Admin(), handler.TestMultimodalFunction)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/remote/check", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.CheckRemoteModel)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/embedding/test", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.TestEmbeddingModel)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/rerank/check", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.CheckRerankModel)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/asr/check", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.CheckASRModel)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/multimodal/test", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.TestMultimodalFunction)
|
||||
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/extract/text-relation", apiKeyOwner(), g.Admin(), handler.ExtractTextRelations)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/extract/fabri-tag", apiKeyOwner(), g.Admin(), handler.FabriTag)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/extract/fabri-text", apiKeyOwner(), g.Admin(), handler.FabriText)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/extract/text-relation", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.ExtractTextRelations)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/extract/fabri-tag", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.FabriTag)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/initialization/extract/fabri-text", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.FabriText)
|
||||
}
|
||||
|
||||
// RegisterSystemRoutes registers system information routes
|
||||
@@ -788,7 +813,7 @@ func RegisterInitializationRoutes(r *gin.RouterGroup, handler *handler.Initializ
|
||||
// remote services with tenant credentials and could trigger network
|
||||
// fanout, so they're Admin+.
|
||||
func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler, g *rbacGuards) {
|
||||
systemRoutes := g.apiKeyGroup(r.Group("/system"), apiKeyOwner())
|
||||
systemRoutes := g.apiKeyGroup(r.Group("/system"), apiKeyManageVectorStores(apiKeyFullAccess()))
|
||||
{
|
||||
systemRoutes.GET("/info", g.Viewer(), handler.GetSystemInfo)
|
||||
systemRoutes.GET("/parser-engines", g.Viewer(), handler.ListParserEngines)
|
||||
@@ -881,7 +906,7 @@ func RegisterMCPServiceRoutes(
|
||||
// redirect carries no WeKnora bearer — the single-use state authenticates.
|
||||
r.GET("/mcp-oauth/callback", oauthHandler.Callback)
|
||||
|
||||
mcpServices := g.apiKeyGroup(r.Group("/mcp-services"), apiKeyOwner())
|
||||
mcpServices := g.apiKeyGroup(r.Group("/mcp-services"), apiKeyManageMCPServices(apiKeyFullAccess()))
|
||||
{
|
||||
// Create MCP service — Admin+
|
||||
mcpServices.POST("", g.Admin(), handler.CreateMCPService)
|
||||
@@ -953,7 +978,7 @@ func RegisterWebSearchProviderRoutes(
|
||||
credHandler *handler.WebSearchProviderCredentialsHandler,
|
||||
g *rbacGuards,
|
||||
) {
|
||||
providers := g.apiKeyGroup(r.Group("/web-search-providers"), apiKeyOwner())
|
||||
providers := g.apiKeyGroup(r.Group("/web-search-providers"), apiKeyManageWebSearch(apiKeyFullAccess()))
|
||||
{
|
||||
// List available provider types (metadata for UI forms) — Viewer+
|
||||
providers.GET("/types", g.Viewer(), h.ListProviderTypes)
|
||||
@@ -979,7 +1004,7 @@ func RegisterWebSearchProviderRoutes(
|
||||
// writes (and connection tests, which probe external systems with stored
|
||||
// credentials) are Admin+.
|
||||
func RegisterVectorStoreRoutes(r *gin.RouterGroup, h *handler.VectorStoreHandler, g *rbacGuards) {
|
||||
stores := g.apiKeyGroup(r.Group("/vector-stores"), apiKeyOwner())
|
||||
stores := g.apiKeyGroup(r.Group("/vector-stores"), apiKeyManageVectorStores(apiKeyFullAccess()))
|
||||
{
|
||||
// List available engine types (metadata for UI forms) — Viewer+
|
||||
stores.GET("/types", g.Viewer(), h.ListStoreTypes)
|
||||
@@ -1003,27 +1028,35 @@ func RegisterVectorStoreRoutes(r *gin.RouterGroup, h *handler.VectorStoreHandler
|
||||
// (IsBuiltin=true) have an empty creator and are always Admin+. Reads
|
||||
// are Viewer+, copy is Contributor+ (the copy is owned by the caller).
|
||||
func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomAgentHandler, g *rbacGuards) {
|
||||
agents := g.apiKeyGroup(r.Group("/agents"), apiKeyOwner())
|
||||
agents := g.apiKeyGroup(r.Group("/agents"), apiKeyFullAccess())
|
||||
// agentsRead are the agent read endpoints. They stay full-access only for
|
||||
// plain scoped keys (agent config can carry sensitive model/MCP bindings),
|
||||
// but read_agents, chat, or manage_agents may read them.
|
||||
agentsRead := agents.With(apiKeyReadAgents(apiKeyManageAgents(apiKeyChat(apiKeyFullAccess()))))
|
||||
// agentsWrite are the agent authoring endpoints. Owner by default, but a
|
||||
// key granted manage_agents may author agents without full Owner.
|
||||
agentsWrite := agents.With(apiKeyManageAgents(apiKeyFullAccess()))
|
||||
{
|
||||
// Get placeholder definitions (must be before /:id to avoid conflict) — Viewer+
|
||||
agents.GET("/placeholders", g.Viewer(), agentHandler.GetPlaceholders)
|
||||
agentsRead.GET("/placeholders", g.Viewer(), agentHandler.GetPlaceholders)
|
||||
// List smart-reasoning agent type presets (rag-qa / wiki-qa / hybrid / custom) — Viewer+
|
||||
agents.GET("/type-presets", g.Viewer(), agentHandler.GetAgentTypePresets)
|
||||
agentsRead.GET("/type-presets", g.Viewer(), agentHandler.GetAgentTypePresets)
|
||||
// Create custom agent — Contributor+
|
||||
agents.POST("", g.Contributor(), agentHandler.CreateAgent)
|
||||
agentsWrite.POST("", g.Contributor(), agentHandler.CreateAgent)
|
||||
// List all agents (including built-in) — Viewer+
|
||||
agents.GET("", g.Viewer(), agentHandler.ListAgents)
|
||||
agentsRead.GET("", g.Viewer(), agentHandler.ListAgents)
|
||||
// Get agent by ID — Viewer+
|
||||
agents.GET("/:id", g.Viewer(), agentHandler.GetAgent)
|
||||
agentsRead.GET("/:id", g.Viewer(), agentHandler.GetAgent)
|
||||
// Update agent — creator OR Admin+
|
||||
agents.PUT("/:id", g.OwnedAgentOrAdmin(), agentHandler.UpdateAgent)
|
||||
agentsWrite.PUT("/:id", g.OwnedAgentOrAdmin(), agentHandler.UpdateAgent)
|
||||
// Delete agent — creator OR Admin+
|
||||
agents.DELETE("/:id", g.OwnedAgentOrAdmin(), agentHandler.DeleteAgent)
|
||||
agentsWrite.DELETE("/:id", g.OwnedAgentOrAdmin(), agentHandler.DeleteAgent)
|
||||
// Copy agent — Contributor+ (copy is owned by the caller)
|
||||
agents.POST("/:id/copy", g.Contributor(), agentHandler.CopyAgent)
|
||||
agentsWrite.POST("/:id/copy", g.Contributor(), agentHandler.CopyAgent)
|
||||
}
|
||||
// Registered outside the group to avoid Gin route conflict with /agents/:id/shares in organization routes
|
||||
g.apiKeyRoute(r, http.MethodGet, "/agents/:id/suggested-questions", apiKeyOwner(), g.Viewer(), agentHandler.GetSuggestedQuestions)
|
||||
g.apiKeyRoute(r, http.MethodGet, "/agents/:id/suggested-questions",
|
||||
apiKeyReadAgents(apiKeyManageAgents(apiKeyChat(apiKeyFullAccess()))), g.Viewer(), agentHandler.GetSuggestedQuestions)
|
||||
}
|
||||
|
||||
// RegisterUserFavoriteRoutes wires the per-user starred-resource endpoints.
|
||||
@@ -1059,7 +1092,7 @@ func RegisterSkillRoutes(r *gin.RouterGroup, skillHandler *handler.SkillHandler,
|
||||
// RegisterOrganizationRoutes registers organization and sharing routes
|
||||
func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.OrganizationHandler, g *rbacGuards) {
|
||||
// Organization routes
|
||||
orgs := g.apiKeyGroup(r.Group("/organizations"), apiKeyOwner())
|
||||
orgs := g.apiKeyGroup(r.Group("/organizations"), apiKeyFullAccess())
|
||||
{
|
||||
// Create organization (Admin+ in caller's tenant only)
|
||||
orgs.POST("", g.Admin(), orgHandler.CreateOrganization)
|
||||
@@ -1169,13 +1202,13 @@ func RegisterOrganizationRoutes(r *gin.RouterGroup, orgHandler *handler.Organiza
|
||||
}
|
||||
|
||||
// Shared knowledge bases route — Viewer+
|
||||
g.apiKeyRoute(r, http.MethodGet, "/shared-knowledge-bases", apiKeyOwner(), g.Viewer(), orgHandler.ListSharedKnowledgeBases)
|
||||
g.apiKeyRoute(r, http.MethodGet, "/shared-knowledge-bases", apiKeyFullAccess(), g.Viewer(), orgHandler.ListSharedKnowledgeBases)
|
||||
// Shared agents route — Viewer+
|
||||
g.apiKeyRoute(r, http.MethodGet, "/shared-agents", apiKeyOwner(), g.Viewer(), orgHandler.ListSharedAgents)
|
||||
g.apiKeyRoute(r, http.MethodGet, "/shared-agents", apiKeyFullAccess(), g.Viewer(), orgHandler.ListSharedAgents)
|
||||
// "Disable by me" 是租户级偏好(写到 tenant_disabled_shared_agents),
|
||||
// 影响整个租户在会话下拉里看到的 agent 列表。任何 Viewer 改这个表就
|
||||
// 等于替整个租户做决定 — 必须 Admin+ 才允许调整。
|
||||
g.apiKeyRoute(r, http.MethodPost, "/shared-agents/disabled", apiKeyOwner(), g.Admin(), orgHandler.SetSharedAgentDisabledByMe)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/shared-agents/disabled", apiKeyFullAccess(), g.Admin(), orgHandler.SetSharedAgentDisabledByMe)
|
||||
}
|
||||
|
||||
// RegisterEmbedPublicRoutes registers anonymous embed endpoints secured by publish tokens.
|
||||
@@ -1219,12 +1252,12 @@ func RegisterEmbedChannelRoutes(r *gin.RouterGroup, embedHandler *handler.EmbedC
|
||||
if embedHandler == nil {
|
||||
return
|
||||
}
|
||||
agentEmbed := g.apiKeyGroup(r.Group("/agents/:id/embed-channels"), apiKeyOwner())
|
||||
agentEmbed := g.apiKeyGroup(r.Group("/agents/:id/embed-channels"), apiKeyManageChannels(apiKeyFullAccess()))
|
||||
{
|
||||
agentEmbed.POST("", g.Admin(), embedHandler.CreateEmbedChannel)
|
||||
agentEmbed.GET("", g.Viewer(), embedHandler.ListEmbedChannels)
|
||||
}
|
||||
channels := g.apiKeyGroup(r.Group("/embed-channels"), apiKeyOwner())
|
||||
channels := g.apiKeyGroup(r.Group("/embed-channels"), apiKeyManageChannels(apiKeyFullAccess()))
|
||||
{
|
||||
channels.GET("", g.Viewer(), embedHandler.ListAllEmbedChannels)
|
||||
channels.GET("/:channel_id", g.Viewer(), embedHandler.GetEmbedChannel)
|
||||
@@ -1253,14 +1286,14 @@ func RegisterIMRoutes(r *gin.Engine, imHandler *handler.IMHandler) {
|
||||
// (which can hijack a personal WeChat session) is Admin+.
|
||||
func RegisterIMChannelRoutes(r *gin.RouterGroup, imHandler *handler.IMHandler, g *rbacGuards) {
|
||||
// Channel CRUD under agents
|
||||
agentChannels := g.apiKeyGroup(r.Group("/agents/:id/im-channels"), apiKeyOwner())
|
||||
agentChannels := g.apiKeyGroup(r.Group("/agents/:id/im-channels"), apiKeyManageChannels(apiKeyFullAccess()))
|
||||
{
|
||||
agentChannels.POST("", g.Admin(), imHandler.CreateIMChannel)
|
||||
agentChannels.GET("", g.Viewer(), imHandler.ListIMChannels)
|
||||
}
|
||||
|
||||
// Channel operations by channel ID
|
||||
channels := g.apiKeyGroup(r.Group("/im-channels"), apiKeyOwner())
|
||||
channels := g.apiKeyGroup(r.Group("/im-channels"), apiKeyManageChannels(apiKeyFullAccess()))
|
||||
{
|
||||
channels.GET("", g.Viewer(), imHandler.ListAllIMChannels)
|
||||
channels.PUT("/:id", g.Admin(), imHandler.UpdateIMChannel)
|
||||
@@ -1270,7 +1303,7 @@ func RegisterIMChannelRoutes(r *gin.RouterGroup, imHandler *handler.IMHandler, g
|
||||
|
||||
// WeChat QR code login (requires authentication) — Admin+: a successful
|
||||
// scan binds a personal WeChat account to the tenant.
|
||||
wechatGroup := g.apiKeyGroup(r.Group("/wechat"), apiKeyOwner())
|
||||
wechatGroup := g.apiKeyGroup(r.Group("/wechat"), apiKeyManageChannels(apiKeyFullAccess()))
|
||||
{
|
||||
wechatGroup.POST("/qrcode", g.Admin(), imHandler.WeChatGetQRCode)
|
||||
wechatGroup.POST("/qrcode/status", g.Admin(), imHandler.WeChatPollQRCodeStatus)
|
||||
@@ -1738,7 +1771,7 @@ func RegisterDataSourceRoutes(
|
||||
g *rbacGuards,
|
||||
) {
|
||||
// Data source routes
|
||||
ds := g.apiKeyGroup(r.Group("/datasource"), apiKeyOwner())
|
||||
ds := g.apiKeyGroup(r.Group("/datasource"), apiKeyManageDataSources(apiKeyFullAccess()))
|
||||
{
|
||||
// Get available connector types — Viewer+
|
||||
ds.GET("/types", g.Viewer(), handler.GetAvailableConnectors)
|
||||
@@ -1780,8 +1813,8 @@ func RegisterDataSourceRoutes(
|
||||
// management endpoints. SaveCredentials persists external SaaS keys
|
||||
// for the tenant (Admin+), Status is a low-risk readiness probe (Viewer+).
|
||||
func RegisterWeKnoraCloudRoutes(r *gin.RouterGroup, handler *handler.WeKnoraCloudHandler, g *rbacGuards) {
|
||||
g.apiKeyRoute(r, http.MethodPost, "/weknoracloud/credentials", apiKeyOwner(), g.Admin(), handler.SaveCredentials)
|
||||
g.apiKeyRoute(r, http.MethodGet, "/models/weknoracloud/status", apiKeyOwner(), g.Viewer(), handler.Status)
|
||||
g.apiKeyRoute(r, http.MethodPost, "/weknoracloud/credentials", apiKeyManageModels(apiKeyFullAccess()), g.Admin(), handler.SaveCredentials)
|
||||
g.apiKeyRoute(r, http.MethodGet, "/models/weknoracloud/status", apiKeyManageModels(apiKeyFullAccess()), g.Viewer(), handler.Status)
|
||||
}
|
||||
|
||||
// RegisterWikiPageRoutes registers wiki page related routes.
|
||||
@@ -1794,38 +1827,39 @@ func RegisterWeKnoraCloudRoutes(r *gin.RouterGroup, handler *handler.WeKnoraClou
|
||||
// :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.
|
||||
func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHandler, g *rbacGuards) {
|
||||
wiki := g.apiKeyGroup(r.Group("/knowledgebase/:kb_id/wiki"), apiKeyContributor())
|
||||
wiki := g.apiKeyGroup(r.Group("/knowledgebase/:kb_id/wiki"), apiKeyIngest(apiKeyFullAccess()))
|
||||
wikiRead := wiki.With(apiKeyRetrieve(apiKeyFullAccess()))
|
||||
{
|
||||
// Page CRUD
|
||||
wiki.GET("/pages", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListPages)
|
||||
wikiRead.GET("/pages", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListPages)
|
||||
wiki.POST("/pages", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.CreatePage)
|
||||
wiki.PUT("/move-page", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.MovePage)
|
||||
wiki.GET("/pages/*slug", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetPage)
|
||||
wikiRead.GET("/pages/*slug", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetPage)
|
||||
wiki.PUT("/pages/*slug", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.UpdatePage)
|
||||
wiki.DELETE("/pages/*slug", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.DeletePage)
|
||||
|
||||
// Folder tree (directory nodes)
|
||||
wiki.GET("/folders", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListFolders)
|
||||
wikiRead.GET("/folders", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListFolders)
|
||||
wiki.POST("/folders", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.CreateFolder)
|
||||
wiki.PUT("/folders/:folder_id", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.UpdateFolder)
|
||||
wiki.DELETE("/folders/:folder_id", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.DeleteFolder)
|
||||
|
||||
// Special pages
|
||||
wiki.GET("/index", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetIndex)
|
||||
wiki.GET("/log", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetLog)
|
||||
wikiRead.GET("/index", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetIndex)
|
||||
wikiRead.GET("/log", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetLog)
|
||||
|
||||
// Graph and stats
|
||||
wiki.GET("/graph", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetGraph)
|
||||
wiki.GET("/stats", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetStats)
|
||||
wikiRead.GET("/graph", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetGraph)
|
||||
wikiRead.GET("/stats", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.GetStats)
|
||||
|
||||
// Search and maintenance
|
||||
wiki.GET("/search", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.SearchPages)
|
||||
wikiRead.GET("/search", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.SearchPages)
|
||||
wiki.POST("/rebuild-links", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.RebuildLinks)
|
||||
wiki.GET("/lint", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.Lint)
|
||||
wikiRead.GET("/lint", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.Lint)
|
||||
wiki.POST("/auto-fix", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.AutoFix)
|
||||
|
||||
// Issues
|
||||
wiki.GET("/issues", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListIssues)
|
||||
wikiRead.GET("/issues", g.Viewer(), g.KBAccessRead("kb_id"), wikiHandler.ListIssues)
|
||||
wiki.PUT("/issues/:issue_id/status", g.OwnedWikiKBOrAdmin(), g.KBAccessWrite("kb_id"), wikiHandler.UpdateIssueStatus)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,317 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/handler"
|
||||
sessionhandler "github.com/Tencent/WeKnora/internal/handler/session"
|
||||
"github.com/Tencent/WeKnora/internal/middleware"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestConversationRoutesDeclareChatCapability(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
g := &rbacGuards{}
|
||||
v1 := gin.New().Group("/api/v1")
|
||||
|
||||
RegisterSessionRoutes(v1, &sessionhandler.Handler{}, g)
|
||||
RegisterChatRoutes(v1, &sessionhandler.Handler{}, g)
|
||||
RegisterMessageRoutes(v1, &handler.MessageHandler{}, g)
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodPost, "/api/v1/sessions"},
|
||||
{http.MethodPost, "/api/v1/knowledge-chat/:session_id"},
|
||||
{http.MethodPost, "/api/v1/agent-chat/:session_id"},
|
||||
{http.MethodGet, "/api/v1/messages/:session_id/load"},
|
||||
{http.MethodDelete, "/api/v1/messages/:session_id/:id"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
|
||||
policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)
|
||||
if !policy.RequireFullAccess {
|
||||
t.Fatal("policy should require full access without a matching capability")
|
||||
}
|
||||
if !policyHasCapability(policy, types.APIKeyCapabilityChat) {
|
||||
t.Fatalf("policy capabilities = %#v, want chat", policy.Capabilities)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageHistoryRoutesDeclareMessageHistoryCapability(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
g := &rbacGuards{}
|
||||
v1 := gin.New().Group("/api/v1")
|
||||
|
||||
RegisterMessageRoutes(v1, &handler.MessageHandler{}, g)
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodPost, "/api/v1/messages/search"},
|
||||
{http.MethodGet, "/api/v1/messages/chat-history-stats"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
|
||||
policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)
|
||||
if !policy.RequireFullAccess {
|
||||
t.Fatal("policy should require full access without a matching capability")
|
||||
}
|
||||
if !policyHasCapability(policy, types.APIKeyCapabilityMessageHistory) {
|
||||
t.Fatalf("policy capabilities = %#v, want message_history", policy.Capabilities)
|
||||
}
|
||||
if policyHasCapability(policy, types.APIKeyCapabilityChat) {
|
||||
t.Fatalf("message-history route must not be granted by chat: %#v", policy.Capabilities)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentReadRoutesDeclareReadAgentsCapability(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
g := &rbacGuards{}
|
||||
v1 := gin.New().Group("/api/v1")
|
||||
|
||||
RegisterCustomAgentRoutes(v1, &handler.CustomAgentHandler{}, g)
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodGet, "/api/v1/agents/placeholders"},
|
||||
{http.MethodGet, "/api/v1/agents/type-presets"},
|
||||
{http.MethodGet, "/api/v1/agents"},
|
||||
{http.MethodGet, "/api/v1/agents/:id"},
|
||||
{http.MethodGet, "/api/v1/agents/:id/suggested-questions"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
|
||||
policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)
|
||||
if !policy.RequireFullAccess {
|
||||
t.Fatal("policy should require full access without a matching capability")
|
||||
}
|
||||
if !policyHasCapability(policy, types.APIKeyCapabilityReadAgents) {
|
||||
t.Fatalf("policy capabilities = %#v, want read_agents", policy.Capabilities)
|
||||
}
|
||||
if !policyHasCapability(policy, types.APIKeyCapabilityChat) {
|
||||
t.Fatalf("policy capabilities = %#v, want chat for conversation clients", policy.Capabilities)
|
||||
}
|
||||
if !policyHasCapability(policy, types.APIKeyCapabilityManageAgents) {
|
||||
t.Fatalf("policy capabilities = %#v, want manage_agents for authoring clients", policy.Capabilities)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAgentWriteRoutesRequireManageAgentsCapability(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
g := &rbacGuards{}
|
||||
v1 := gin.New().Group("/api/v1")
|
||||
|
||||
RegisterCustomAgentRoutes(v1, &handler.CustomAgentHandler{}, g)
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodPost, "/api/v1/agents"},
|
||||
{http.MethodPut, "/api/v1/agents/:id"},
|
||||
{http.MethodDelete, "/api/v1/agents/:id"},
|
||||
{http.MethodPost, "/api/v1/agents/:id/copy"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
|
||||
policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)
|
||||
if !policy.RequireFullAccess {
|
||||
t.Fatal("policy should require full access without a matching capability")
|
||||
}
|
||||
if !policyHasCapability(policy, types.APIKeyCapabilityManageAgents) {
|
||||
t.Fatalf("policy capabilities = %#v, want manage_agents", policy.Capabilities)
|
||||
}
|
||||
if policyHasCapability(policy, types.APIKeyCapabilityReadAgents) {
|
||||
t.Fatalf("agent write route must not be granted by read_agents: %#v", policy.Capabilities)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeBaseManagementRoutesDeclareManageKBsCapability(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
g := &rbacGuards{}
|
||||
v1 := gin.New().Group("/api/v1")
|
||||
|
||||
RegisterKnowledgeBaseRoutes(v1, &handler.KnowledgeBaseHandler{}, g)
|
||||
RegisterInitializationRoutes(v1, &handler.InitializationHandler{}, g)
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodPut, "/api/v1/knowledge-bases/:id"},
|
||||
{http.MethodDelete, "/api/v1/knowledge-bases/:id"},
|
||||
{http.MethodPost, "/api/v1/initialization/initialize/:kbId"},
|
||||
{http.MethodPut, "/api/v1/initialization/config/:kbId"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
|
||||
policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)
|
||||
if !policy.RequireFullAccess {
|
||||
t.Fatal("policy should require full access without a matching capability")
|
||||
}
|
||||
if !policyHasCapability(policy, types.APIKeyCapabilityManageKnowledgeBases) {
|
||||
t.Fatalf("policy capabilities = %#v, want manage_kbs", policy.Capabilities)
|
||||
}
|
||||
if policyHasCapability(policy, types.APIKeyCapabilityIngest) {
|
||||
t.Fatalf("KB management route must not be granted by ingest: %#v", policy.Capabilities)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeBaseCreateAndCopyRemainDefaultDenyForAPIKeys(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
g := &rbacGuards{}
|
||||
v1 := gin.New().Group("/api/v1")
|
||||
|
||||
RegisterKnowledgeBaseRoutes(v1, &handler.KnowledgeBaseHandler{}, g)
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodPost, "/api/v1/knowledge-bases"},
|
||||
{http.MethodPost, "/api/v1/knowledge-bases/copy"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
|
||||
if _, ok := g.apiKeyAuthorizer.Lookup(tc.method, tc.path); ok {
|
||||
t.Fatalf("route should remain default-deny for API keys: %s %s", tc.method, tc.path)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeReadRoutesDeclareRetrieveCapability(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
g := &rbacGuards{}
|
||||
v1 := gin.New().Group("/api/v1")
|
||||
|
||||
RegisterKnowledgeBaseRoutes(v1, &handler.KnowledgeBaseHandler{}, g)
|
||||
RegisterKnowledgeRoutes(v1, &handler.KnowledgeHandler{}, g)
|
||||
RegisterFAQRoutes(v1, &handler.FAQHandler{}, g)
|
||||
RegisterKnowledgeTagRoutes(v1, &handler.TagHandler{}, g)
|
||||
RegisterChatRoutes(v1, &sessionhandler.Handler{}, g)
|
||||
RegisterInitializationRoutes(v1, &handler.InitializationHandler{}, g)
|
||||
RegisterWikiPageRoutes(v1, &handler.WikiPageHandler{}, g)
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodGet, "/api/v1/knowledge-bases"},
|
||||
{http.MethodGet, "/api/v1/knowledge-bases/:id"},
|
||||
{http.MethodPost, "/api/v1/knowledge-bases/:id/hybrid-search"},
|
||||
{http.MethodGet, "/api/v1/knowledge-bases/:id/knowledge"},
|
||||
{http.MethodGet, "/api/v1/knowledge/:id"},
|
||||
{http.MethodPost, "/api/v1/knowledge-bases/:id/faq/search"},
|
||||
{http.MethodGet, "/api/v1/knowledge-bases/:id/tags"},
|
||||
{http.MethodPost, "/api/v1/knowledge-search"},
|
||||
{http.MethodGet, "/api/v1/initialization/config/:kbId"},
|
||||
{http.MethodGet, "/api/v1/knowledgebase/:kb_id/wiki/pages"},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
|
||||
policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)
|
||||
if !policy.RequireFullAccess {
|
||||
t.Fatal("policy should require full access without a matching capability")
|
||||
}
|
||||
if !policyHasCapability(policy, types.APIKeyCapabilityRetrieve) {
|
||||
t.Fatalf("policy capabilities = %#v, want retrieve", policy.Capabilities)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTenantInfrastructureRoutesDeclareSpecificCapabilities(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
g := &rbacGuards{}
|
||||
v1 := gin.New().Group("/api/v1")
|
||||
|
||||
RegisterTenantRoutes(v1, &handler.TenantHandler{}, nil, nil, nil, g)
|
||||
RegisterModelRoutes(v1, &handler.ModelHandler{}, &handler.ModelCredentialsHandler{}, g)
|
||||
RegisterEvaluationRoutes(v1, &handler.EvaluationHandler{}, g)
|
||||
RegisterSystemRoutes(v1, &handler.SystemHandler{}, g)
|
||||
RegisterMCPServiceRoutes(v1, &handler.MCPServiceHandler{}, &handler.MCPCredentialsHandler{}, &handler.MCPOAuthHandler{}, g)
|
||||
RegisterWebSearchProviderRoutes(v1, &handler.WebSearchProviderHandler{}, &handler.WebSearchProviderCredentialsHandler{}, g)
|
||||
RegisterVectorStoreRoutes(v1, &handler.VectorStoreHandler{}, g)
|
||||
RegisterEmbedChannelRoutes(v1, &handler.EmbedChannelHandler{}, g)
|
||||
RegisterIMChannelRoutes(v1, &handler.IMHandler{}, g)
|
||||
RegisterDataSourceRoutes(v1, &handler.DataSourceHandler{}, &handler.DataSourceCredentialsHandler{}, g)
|
||||
RegisterWeKnoraCloudRoutes(v1, &handler.WeKnoraCloudHandler{}, g)
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
cap types.APIKeyCapability
|
||||
}{
|
||||
{http.MethodGet, "/api/v1/tenants", types.APIKeyCapabilityManageTenantSettings},
|
||||
{http.MethodGet, "/api/v1/models", types.APIKeyCapabilityManageModels},
|
||||
{http.MethodPost, "/api/v1/evaluation", types.APIKeyCapabilityRunEvaluations},
|
||||
{http.MethodGet, "/api/v1/system/info", types.APIKeyCapabilityManageVectorStores},
|
||||
{http.MethodGet, "/api/v1/mcp-services", types.APIKeyCapabilityManageMCPServices},
|
||||
{http.MethodGet, "/api/v1/web-search-providers", types.APIKeyCapabilityManageWebSearch},
|
||||
{http.MethodGet, "/api/v1/vector-stores", types.APIKeyCapabilityManageVectorStores},
|
||||
{http.MethodGet, "/api/v1/embed-channels", types.APIKeyCapabilityManageChannels},
|
||||
{http.MethodGet, "/api/v1/im-channels", types.APIKeyCapabilityManageChannels},
|
||||
{http.MethodGet, "/api/v1/datasource", types.APIKeyCapabilityManageDataSources},
|
||||
{http.MethodGet, "/api/v1/models/weknoracloud/status", types.APIKeyCapabilityManageModels},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
|
||||
policy := mustLookupAPIKeyPolicy(t, g, tc.method, tc.path)
|
||||
if !policy.RequireFullAccess {
|
||||
t.Fatal("policy should require full access without a matching capability")
|
||||
}
|
||||
if !policyHasCapability(policy, tc.cap) {
|
||||
t.Fatalf("policy capabilities = %#v, want %s", policy.Capabilities, tc.cap)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func mustLookupAPIKeyPolicy(
|
||||
t *testing.T,
|
||||
g *rbacGuards,
|
||||
method string,
|
||||
path string,
|
||||
) middleware.APIKeyRoutePolicy {
|
||||
t.Helper()
|
||||
policy, ok := g.apiKeyAuthorizer.Lookup(method, path)
|
||||
if !ok {
|
||||
t.Fatalf("missing API-key policy for %s %s", method, path)
|
||||
}
|
||||
return policy
|
||||
}
|
||||
|
||||
func policyHasCapability(policy middleware.APIKeyRoutePolicy, cap types.APIKeyCapability) bool {
|
||||
for _, got := range policy.Capabilities {
|
||||
if got == cap {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
// TestAPIKeyGateDeniesTenantKeyManagementPaths guards the default-deny
|
||||
// contract: tenant lifecycle, key management and API-principal config routes
|
||||
// are registered without apiKeyRoute/apiKeyGroup, so even an Owner-role API
|
||||
// are registered without apiKeyRoute/apiKeyGroup, so even a full-access API
|
||||
// key must receive 403 from the gate before JWT-only handlers run.
|
||||
func TestAPIKeyGateDeniesTenantKeyManagementPaths(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
@@ -20,7 +20,7 @@ func TestAPIKeyGateDeniesTenantKeyManagementPaths(t *testing.T) {
|
||||
gate := middleware.NewAPIKeyRouteAuthorizer()
|
||||
engine := gin.New()
|
||||
engine.Use(func(c *gin.Context) {
|
||||
scope := types.TenantAPIKeyScope{Role: types.TenantRoleOwner}
|
||||
scope := types.TenantAPIKeyScope{FullAccess: true}
|
||||
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), scope))
|
||||
c.Next()
|
||||
})
|
||||
@@ -66,17 +66,17 @@ func TestAPIKeyGateDeniesTenantKeyManagementPaths(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestAPIKeyGateAllowsDeclaredTenantKVRead confirms the gate still permits
|
||||
// routes that are explicitly declared for Owner API keys (sanity check).
|
||||
// routes that are explicitly declared for full-access API keys (sanity check).
|
||||
func TestAPIKeyGateAllowsDeclaredTenantKVRead(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
g := &rbacGuards{}
|
||||
v1 := gin.New().Group("/api/v1")
|
||||
g.apiKeyRoute(v1.Group("/tenants"), http.MethodGet, "/kv/:key", apiKeyOwner(), reachedOK)
|
||||
g.apiKeyRoute(v1.Group("/tenants"), http.MethodGet, "/kv/:key", apiKeyFullAccess(), reachedOK)
|
||||
|
||||
engine := gin.New()
|
||||
engine.Use(func(c *gin.Context) {
|
||||
scope := types.TenantAPIKeyScope{Role: types.TenantRoleOwner}
|
||||
scope := types.TenantAPIKeyScope{FullAccess: true}
|
||||
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), scope))
|
||||
c.Next()
|
||||
})
|
||||
|
||||
@@ -168,7 +168,7 @@ func TestServeFilesRejectsAPIKeyPrincipal(t *testing.T) {
|
||||
filePath := "local://42/docs/example.txt"
|
||||
req := httptest.NewRequest(http.MethodGet, "/files?file_path="+url.QueryEscape(filePath), nil)
|
||||
ctx := context.WithValue(req.Context(), types.TenantInfoContextKey, &types.Tenant{ID: 42})
|
||||
ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{Role: types.TenantRoleOwner})
|
||||
ctx = types.WithTenantAPIKeyScope(ctx, types.TenantAPIKeyScope{FullAccess: true})
|
||||
req = req.WithContext(ctx)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
@@ -66,9 +66,8 @@ func newKBRouteTestEngine(
|
||||
role := types.TenantRoleViewer
|
||||
if apiKeyScope != nil {
|
||||
ctx = types.WithTenantAPIKeyScope(ctx, *apiKeyScope)
|
||||
role = apiKeyScope.Role
|
||||
if role == "" {
|
||||
role = types.TenantRoleViewer
|
||||
if apiKeyScope.FullAccess {
|
||||
role = types.TenantRoleOwner
|
||||
}
|
||||
}
|
||||
ctx = context.WithValue(ctx, types.TenantRoleContextKey, role)
|
||||
@@ -142,8 +141,8 @@ func TestWikiReadRoutesDenyCrossTenantKB(t *testing.T) {
|
||||
func TestInitializationWriteRoutesDenyOutOfScopeAPIKeyKB(t *testing.T) {
|
||||
kbLookup := tenantKBLookupFixture()
|
||||
scope := &types.TenantAPIKeyScope{
|
||||
Role: types.TenantRoleContributor,
|
||||
KnowledgeBaseIDs: types.StringArray{"kb-allowed"},
|
||||
Capabilities: types.StringArray{string(types.APIKeyCapabilityManageKnowledgeBases)},
|
||||
}
|
||||
engine := newKBRouteTestEngine(t, 1, kbLookup, scope, func(r *gin.RouterGroup, guards *rbacGuards) {
|
||||
RegisterInitializationRoutes(r, &handler.InitializationHandler{}, guards)
|
||||
@@ -172,8 +171,8 @@ func TestInitializationWriteRoutesDenyOutOfScopeAPIKeyKB(t *testing.T) {
|
||||
func TestWikiWriteRoutesDenyOutOfScopeAPIKeyKB(t *testing.T) {
|
||||
kbLookup := tenantKBLookupFixture()
|
||||
scope := &types.TenantAPIKeyScope{
|
||||
Role: types.TenantRoleContributor,
|
||||
KnowledgeBaseIDs: types.StringArray{"kb-allowed"},
|
||||
Capabilities: types.StringArray{string(types.APIKeyCapabilityIngest)},
|
||||
}
|
||||
engine := newKBRouteTestEngine(t, 1, kbLookup, scope, func(r *gin.RouterGroup, guards *rbacGuards) {
|
||||
RegisterWikiPageRoutes(r, &handler.WikiPageHandler{}, guards)
|
||||
|
||||
@@ -65,8 +65,9 @@ type TenantRepository interface {
|
||||
type TenantAPIKeyCreateRequest struct {
|
||||
TenantID uint64
|
||||
Name string
|
||||
Role types.TenantRole
|
||||
FullAccess bool
|
||||
KnowledgeBaseIDs []string
|
||||
Capabilities []string
|
||||
ExpiresAt *time.Time
|
||||
}
|
||||
|
||||
|
||||
@@ -20,19 +20,148 @@ type TenantAPIKey struct {
|
||||
Name string `json:"name" gorm:"type:varchar(128);not null"`
|
||||
KeyHash string `json:"-" gorm:"type:varchar(64);not null;uniqueIndex"`
|
||||
APIKey string `json:"api_key" gorm:"column:api_key;type:text;not null;default:''"`
|
||||
Role TenantRole `json:"role" gorm:"type:varchar(32);not null;default:'viewer'"`
|
||||
FullAccess bool `json:"full_access" gorm:"not null;default:false"`
|
||||
KnowledgeBaseIDs StringArray `json:"knowledge_base_ids" gorm:"type:jsonb;not null;default:'[]'"`
|
||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
RevokedAt *time.Time `json:"revoked_at,omitempty" gorm:"index"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
// Capabilities are bounded grants for non-full-access keys. Each
|
||||
// capability maps to an integration persona (retrieval, chat, ingest,
|
||||
// tenant infrastructure management, and history access). KB scoping
|
||||
// (KnowledgeBaseIDs) still applies on top where a route targets knowledge
|
||||
// bases.
|
||||
Capabilities StringArray `json:"capabilities" gorm:"type:jsonb;not null;default:'[]'"`
|
||||
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
|
||||
ExpiresAt *time.Time `json:"expires_at,omitempty"`
|
||||
RevokedAt *time.Time `json:"revoked_at,omitempty" gorm:"index"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (TenantAPIKey) TableName() string {
|
||||
return "tenant_api_keys"
|
||||
}
|
||||
|
||||
// APIKeyCapability is a bounded grant on a tenant API key. See
|
||||
// TenantAPIKey.Capabilities.
|
||||
type APIKeyCapability string
|
||||
|
||||
const (
|
||||
// APIKeyCapabilityRetrieve lets a key read and search knowledge-base data
|
||||
// within its allowed KB scope without granting chat or content writes.
|
||||
APIKeyCapabilityRetrieve APIKeyCapability = "retrieve"
|
||||
// APIKeyCapabilityChat lets a scoped key run the conversation flow
|
||||
// (sessions + agent listing + self identity) without granting broader
|
||||
// tenant management access.
|
||||
APIKeyCapabilityChat APIKeyCapability = "chat"
|
||||
// APIKeyCapabilityReadAgents lets a scoped key list and inspect agents
|
||||
// without allowing chat sessions or agent authoring.
|
||||
APIKeyCapabilityReadAgents APIKeyCapability = "read_agents"
|
||||
// APIKeyCapabilityIngest lets a key write content into its allowed
|
||||
// knowledge bases (upload documents, edit chunks/FAQ/tags/wiki). It only
|
||||
// lifts the content-write routes: it never allows creating new knowledge
|
||||
// bases or agents, nor destructive KB clears, and the key's
|
||||
// knowledge_base_ids allow-list still bounds every write.
|
||||
APIKeyCapabilityIngest APIKeyCapability = "ingest"
|
||||
// APIKeyCapabilityManageKnowledgeBases lets a scoped key manage existing
|
||||
// knowledge-base metadata/configuration within its allowed KB scope. It is
|
||||
// separate from ingest: uploading or editing KB contents does not imply
|
||||
// permission to rename, reconfigure, or delete the KB itself.
|
||||
APIKeyCapabilityManageKnowledgeBases APIKeyCapability = "manage_kbs"
|
||||
// APIKeyCapabilityManageAgents lets a key create/read/update/delete/copy
|
||||
// agents. Agent config can carry sensitive model/MCP bindings, so this is
|
||||
// opt-in and off by default.
|
||||
APIKeyCapabilityManageAgents APIKeyCapability = "manage_agents"
|
||||
// APIKeyCapabilityMessageHistory lets a key search and inspect the
|
||||
// tenant-level chat-history knowledge base without granting full Owner
|
||||
// access. It is separate from chat: chat only covers the caller's own
|
||||
// live conversation flow, while message_history can expose historical
|
||||
// messages across the tenant.
|
||||
APIKeyCapabilityMessageHistory APIKeyCapability = "message_history"
|
||||
// APIKeyCapabilityManageModels lets a key manage tenant model
|
||||
// definitions, credentials, model checks, and WeKnoraCloud credentials.
|
||||
APIKeyCapabilityManageModels APIKeyCapability = "manage_models"
|
||||
// APIKeyCapabilityManageMCPServices lets a key manage tenant MCP service
|
||||
// definitions, credentials, tool policies, and per-principal OAuth state.
|
||||
APIKeyCapabilityManageMCPServices APIKeyCapability = "manage_mcp_services"
|
||||
// APIKeyCapabilityManageDataSources lets a key manage data-source
|
||||
// connectors and sync jobs. KB scoping applies to data sources bound to a
|
||||
// knowledge base.
|
||||
APIKeyCapabilityManageDataSources APIKeyCapability = "manage_datasources"
|
||||
// APIKeyCapabilityManageChannels lets a key manage embed and IM channel
|
||||
// integrations for agents.
|
||||
APIKeyCapabilityManageChannels APIKeyCapability = "manage_channels"
|
||||
// APIKeyCapabilityManageVectorStores lets a key manage retrieval
|
||||
// infrastructure such as vector stores, parser engines, and storage checks.
|
||||
APIKeyCapabilityManageVectorStores APIKeyCapability = "manage_vector_stores"
|
||||
// APIKeyCapabilityManageWebSearch lets a key manage tenant web-search
|
||||
// provider configurations and credentials.
|
||||
APIKeyCapabilityManageWebSearch APIKeyCapability = "manage_web_search"
|
||||
// APIKeyCapabilityRunEvaluations lets a key run and inspect evaluation
|
||||
// jobs without full tenant ownership.
|
||||
APIKeyCapabilityRunEvaluations APIKeyCapability = "run_evaluations"
|
||||
// APIKeyCapabilityManageTenantSettings lets a key read and update
|
||||
// tenant-scoped integration settings exposed under /tenants, such as API
|
||||
// principal mode, request headers, and tenant KV. It does not include API
|
||||
// key management, member management, tenant deletion, or ownership transfer.
|
||||
APIKeyCapabilityManageTenantSettings APIKeyCapability = "manage_tenant_settings"
|
||||
)
|
||||
|
||||
// NormalizeAPIKeyCapability maps an input capability string to a known
|
||||
// capability, returning "" for anything unrecognised so callers can drop it.
|
||||
func NormalizeAPIKeyCapability(c APIKeyCapability) APIKeyCapability {
|
||||
switch APIKeyCapability(strings.ToLower(strings.TrimSpace(string(c)))) {
|
||||
case APIKeyCapabilityRetrieve:
|
||||
return APIKeyCapabilityRetrieve
|
||||
case APIKeyCapabilityChat:
|
||||
return APIKeyCapabilityChat
|
||||
case APIKeyCapabilityReadAgents:
|
||||
return APIKeyCapabilityReadAgents
|
||||
case APIKeyCapabilityIngest:
|
||||
return APIKeyCapabilityIngest
|
||||
case APIKeyCapabilityManageKnowledgeBases:
|
||||
return APIKeyCapabilityManageKnowledgeBases
|
||||
case APIKeyCapabilityManageAgents:
|
||||
return APIKeyCapabilityManageAgents
|
||||
case APIKeyCapabilityMessageHistory:
|
||||
return APIKeyCapabilityMessageHistory
|
||||
case APIKeyCapabilityManageModels:
|
||||
return APIKeyCapabilityManageModels
|
||||
case APIKeyCapabilityManageMCPServices:
|
||||
return APIKeyCapabilityManageMCPServices
|
||||
case APIKeyCapabilityManageDataSources:
|
||||
return APIKeyCapabilityManageDataSources
|
||||
case APIKeyCapabilityManageChannels:
|
||||
return APIKeyCapabilityManageChannels
|
||||
case APIKeyCapabilityManageVectorStores:
|
||||
return APIKeyCapabilityManageVectorStores
|
||||
case APIKeyCapabilityManageWebSearch:
|
||||
return APIKeyCapabilityManageWebSearch
|
||||
case APIKeyCapabilityRunEvaluations:
|
||||
return APIKeyCapabilityRunEvaluations
|
||||
case APIKeyCapabilityManageTenantSettings:
|
||||
return APIKeyCapabilityManageTenantSettings
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// NormalizeAPIKeyCapabilities dedups and drops unknown capabilities.
|
||||
func NormalizeAPIKeyCapabilities(in StringArray) StringArray {
|
||||
out := make(StringArray, 0, len(in))
|
||||
seen := map[string]struct{}{}
|
||||
for _, item := range in {
|
||||
norm := NormalizeAPIKeyCapability(APIKeyCapability(item))
|
||||
if norm == "" {
|
||||
continue
|
||||
}
|
||||
s := string(norm)
|
||||
if _, ok := seen[s]; ok {
|
||||
continue
|
||||
}
|
||||
seen[s] = struct{}{}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (k *TenantAPIKey) BeforeSave(tx *gorm.DB) error {
|
||||
if key := utils.GetAESKey(); key != nil && k.APIKey != "" {
|
||||
encrypted, err := utils.EncryptAESGCM(k.APIKey, key)
|
||||
@@ -59,8 +188,9 @@ func (k *TenantAPIKey) AfterFind(tx *gorm.DB) error {
|
||||
// TenantAPIKeyScope is the request-context projection used by middleware.
|
||||
type TenantAPIKeyScope struct {
|
||||
KeyID uint64
|
||||
Role TenantRole
|
||||
FullAccess bool
|
||||
KnowledgeBaseIDs StringArray
|
||||
Capabilities StringArray
|
||||
}
|
||||
|
||||
func WithTenantAPIKeyScope(ctx context.Context, scope TenantAPIKeyScope) context.Context {
|
||||
@@ -81,29 +211,24 @@ func TenantAPIKeyScopeFromContext(ctx context.Context) (TenantAPIKeyScope, bool)
|
||||
func (s TenantAPIKeyScope) Normalize() TenantAPIKeyScope {
|
||||
return TenantAPIKeyScope{
|
||||
KeyID: s.KeyID,
|
||||
Role: NormalizeTenantAPIKeyRole(s.Role),
|
||||
FullAccess: s.FullAccess,
|
||||
KnowledgeBaseIDs: normalizeIDArray(s.KnowledgeBaseIDs),
|
||||
Capabilities: NormalizeAPIKeyCapabilities(s.Capabilities),
|
||||
}
|
||||
}
|
||||
|
||||
// NormalizeTenantAPIKeyRole maps stored/API role strings to tenant RBAC roles.
|
||||
func NormalizeTenantAPIKeyRole(role TenantRole) TenantRole {
|
||||
switch strings.ToLower(strings.TrimSpace(string(role))) {
|
||||
case string(TenantRoleOwner):
|
||||
return TenantRoleOwner
|
||||
case string(TenantRoleAdmin):
|
||||
return TenantRoleAdmin
|
||||
case string(TenantRoleContributor):
|
||||
return TenantRoleContributor
|
||||
case string(TenantRoleViewer), "":
|
||||
return TenantRoleViewer
|
||||
default:
|
||||
return ""
|
||||
// HasCapability reports whether the scope carries the given additive grant.
|
||||
func (s TenantAPIKeyScope) HasCapability(c APIKeyCapability) bool {
|
||||
c = NormalizeAPIKeyCapability(c)
|
||||
if c == "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (s TenantAPIKeyScope) TenantRole() TenantRole {
|
||||
return s.Normalize().Role
|
||||
for _, item := range NormalizeAPIKeyCapabilities(s.Capabilities) {
|
||||
if item == string(c) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s TenantAPIKeyScope) AllowsKnowledgeBase(kbID string) bool {
|
||||
@@ -167,7 +292,7 @@ func AuthorizeTenantAPIKeyKnowledgeBases(ctx context.Context, kbIDs ...string) e
|
||||
if !ok || !scope.IsKnowledgeBaseRestricted() {
|
||||
return nil
|
||||
}
|
||||
if !scope.AllowsKnowledgeBases(kbIDs) {
|
||||
if len(kbIDs) > 0 && !scope.AllowsKnowledgeBases(kbIDs) {
|
||||
return errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
|
||||
}
|
||||
return nil
|
||||
@@ -184,7 +309,7 @@ func AuthorizeTenantAPIKeyKnowledgeTargets(ctx context.Context, kbIDs, knowledge
|
||||
if len(knowledgeIDs) > 0 {
|
||||
return errors.NewForbiddenError("API key scope does not allow knowledge_ids without a verified knowledge base")
|
||||
}
|
||||
if !scope.AllowsKnowledgeBases(kbIDs) {
|
||||
if len(kbIDs) > 0 && !scope.AllowsKnowledgeBases(kbIDs) {
|
||||
return errors.NewForbiddenError("API key scope does not allow one or more knowledge bases")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -15,6 +15,16 @@ func TestAuthorizeTenantAPIKeyKnowledgeTargetsRejectsKnowledgeIDs(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeTenantAPIKeyKnowledgeTargetsAllowsUnspecifiedTargets(t *testing.T) {
|
||||
ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
|
||||
KnowledgeBaseIDs: StringArray{"kb-1"},
|
||||
})
|
||||
err := AuthorizeTenantAPIKeyKnowledgeTargets(ctx, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("expected unspecified targets to be allowed, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeTenantAPIKeyOptionalTagIDsRejectsTags(t *testing.T) {
|
||||
ctx := WithTenantAPIKeyScope(context.Background(), TenantAPIKeyScope{
|
||||
KnowledgeBaseIDs: StringArray{"kb-1"},
|
||||
@@ -47,3 +57,39 @@ func TestFilterKnowledgeBasesForTenantAPIKeyScopeRejectsExplicitOutOfScope(t *te
|
||||
t.Fatal("expected forbidden for explicit out-of-scope kb_ids")
|
||||
}
|
||||
}
|
||||
|
||||
func TestScopeHasCapability(t *testing.T) {
|
||||
s := TenantAPIKeyScope{Capabilities: StringArray{"chat"}}
|
||||
if !s.HasCapability(APIKeyCapabilityChat) {
|
||||
t.Fatal("expected chat capability to be present")
|
||||
}
|
||||
if (TenantAPIKeyScope{}).HasCapability(APIKeyCapabilityChat) {
|
||||
t.Fatal("empty scope must not report chat capability")
|
||||
}
|
||||
// Unknown capability is never satisfied.
|
||||
if s.HasCapability(APIKeyCapability("bogus")) {
|
||||
t.Fatal("unknown capability must not be satisfied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeAPIKeyCapabilities(t *testing.T) {
|
||||
got := NormalizeAPIKeyCapabilities(StringArray{
|
||||
" Retrieve ",
|
||||
"chat",
|
||||
"read_agents",
|
||||
"manage_kbs",
|
||||
"message_history",
|
||||
"manage_mcp_services",
|
||||
"bogus",
|
||||
"",
|
||||
})
|
||||
want := []string{"retrieve", "chat", "read_agents", "manage_kbs", "message_history", "manage_mcp_services"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("normalized = %#v, want %#v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("normalized = %#v, want %#v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,39 +2,31 @@ package types
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestTenantAPIKeyScopeNormalizeDefaultsEmptyRoleToViewer(t *testing.T) {
|
||||
scope := TenantAPIKeyScope{Role: ""}.Normalize()
|
||||
if scope.Role != TenantRoleViewer {
|
||||
t.Fatalf("normalized role = %q, want viewer", scope.Role)
|
||||
func TestTenantAPIKeyScopeNormalizePreservesFullAccess(t *testing.T) {
|
||||
scope := TenantAPIKeyScope{FullAccess: true}.Normalize()
|
||||
if !scope.FullAccess {
|
||||
t.Fatal("normalized scope lost full access")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeTenantAPIKeyRole(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in TenantRole
|
||||
want TenantRole
|
||||
}{
|
||||
{name: "viewer", in: TenantRoleViewer, want: TenantRoleViewer},
|
||||
{name: "contributor", in: TenantRoleContributor, want: TenantRoleContributor},
|
||||
{name: "admin", in: TenantRoleAdmin, want: TenantRoleAdmin},
|
||||
{name: "owner", in: TenantRoleOwner, want: TenantRoleOwner},
|
||||
{name: "empty defaults viewer", in: "", want: TenantRoleViewer},
|
||||
{name: "invalid", in: "superuser", want: ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := NormalizeTenantAPIKeyRole(tt.in)
|
||||
if got != tt.want {
|
||||
t.Fatalf("NormalizeTenantAPIKeyRole(%q) = %q, want %q", tt.in, got, tt.want)
|
||||
}
|
||||
})
|
||||
func TestTenantAPIKeyScopeNormalizeDefaultsToScopedAccess(t *testing.T) {
|
||||
scope := TenantAPIKeyScope{}.Normalize()
|
||||
if scope.FullAccess {
|
||||
t.Fatal("empty scope must not become full access")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTenantAPIKeyScopeTenantRole(t *testing.T) {
|
||||
got := TenantAPIKeyScope{Role: TenantRoleContributor}.TenantRole()
|
||||
if got != TenantRoleContributor {
|
||||
t.Fatalf("TenantRole() = %q, want contributor", got)
|
||||
func TestTenantAPIKeyScopeNormalizeDropsInvalidCapabilities(t *testing.T) {
|
||||
scope := TenantAPIKeyScope{
|
||||
Capabilities: StringArray{"chat", "bogus", "retrieve", "chat"},
|
||||
}.Normalize()
|
||||
want := StringArray{"chat", "retrieve"}
|
||||
if len(scope.Capabilities) != len(want) {
|
||||
t.Fatalf("capabilities = %#v, want %#v", scope.Capabilities, want)
|
||||
}
|
||||
for i := range want {
|
||||
if scope.Capabilities[i] != want[i] {
|
||||
t.Fatalf("capabilities = %#v, want %#v", scope.Capabilities, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ type TenantRole string
|
||||
|
||||
const (
|
||||
// TenantRoleOwner has full control over the tenant, including tenant
|
||||
// deletion, ownership transfer, and rotating the tenant API key.
|
||||
// deletion, ownership transfer, and managing tenant API keys.
|
||||
TenantRoleOwner TenantRole = "owner"
|
||||
// TenantRoleAdmin manages users, integrations, and tenant-scoped
|
||||
// configuration such as model providers, vector stores, MCP services
|
||||
|
||||
Reference in New Issue
Block a user