Refine scoped API key capabilities
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user