fix: harden shared agent source selector validation
Reject invalid agent_source_tenant_id instead of silently falling back, fix a resolveAgent nil panic when a shared selector fails, and add regression tests for wiki write-tool filtering and agent resolution.main
parent
ab9f705843
commit
cc846d8e29
|
|
@ -24,3 +24,14 @@ test('selecting an agent leaves web search off until the user enables it', () =>
|
|||
assert.doesNotMatch(handleSelectAgent, /agentWebSearch/)
|
||||
assert.doesNotMatch(handleSelectAgent, /settingsStore\.toggleWebSearch/)
|
||||
})
|
||||
|
||||
test('shared-agent web search button waits for source readiness metadata', () => {
|
||||
const showWebSearchStart = inputField.indexOf('const showWebSearchButton = computed')
|
||||
const showWebSearchEnd = inputField.indexOf('const showImageUploadButton', showWebSearchStart)
|
||||
const showWebSearchButton = inputField.slice(showWebSearchStart, showWebSearchEnd)
|
||||
|
||||
assert.notEqual(showWebSearchStart, -1)
|
||||
assert.notEqual(showWebSearchEnd, -1)
|
||||
assert.match(showWebSearchButton, /isWebSearchReadinessKnown/)
|
||||
assert.match(showWebSearchButton, /selectedSharedAgent\.value\?\.web_search_ready/)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -442,6 +442,9 @@ const isImageUploadEnabledByAgent = computed(() => {
|
|||
|
||||
// Input 工具栏:仅当智能体已启用且搜索引擎可用时才显示
|
||||
const showWebSearchButton = computed(() => {
|
||||
if (hasAgentConfig.value && settingsStore.selectedAgentSourceTenantId && !isWebSearchReadinessKnown.value) {
|
||||
return false;
|
||||
}
|
||||
if (!hasAgentConfig.value) {
|
||||
return isTenantWebSearchReady(webSearchProviders.value);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package service
|
|||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent/tools"
|
||||
|
|
@ -89,3 +90,24 @@ func TestFilterSharedAgentWriteTools(t *testing.T) {
|
|||
tools.ToolWebSearch,
|
||||
}, got)
|
||||
}
|
||||
|
||||
func TestFilterSharedAgentWriteToolsCoversAllWikiMutations(t *testing.T) {
|
||||
readOnlyWikiTools := map[string]bool{
|
||||
tools.ToolWikiReadPage: true,
|
||||
tools.ToolWikiSearch: true,
|
||||
tools.ToolWikiReadSourceDoc: true,
|
||||
tools.ToolWikiReadIssue: true,
|
||||
}
|
||||
|
||||
for _, definition := range tools.AvailableToolDefinitions() {
|
||||
if !strings.HasPrefix(definition.Name, "wiki_") {
|
||||
continue
|
||||
}
|
||||
filtered := filterSharedAgentWriteTools([]string{definition.Name})
|
||||
if readOnlyWikiTools[definition.Name] {
|
||||
require.Equal(t, []string{definition.Name}, filtered, "read-only wiki tool %q should remain available", definition.Name)
|
||||
continue
|
||||
}
|
||||
require.Empty(t, filtered, "wiki mutation tool %q must be filtered for shared agents", definition.Name)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -188,7 +188,10 @@ func (h *KnowledgeHandler) resolveKnowledgeAndValidateKBAccess(c *gin.Context, k
|
|||
if h.agentShareService != nil && requiredPermission == types.OrgRoleViewer {
|
||||
agentID := c.Query("agent_id")
|
||||
if agentID != "" {
|
||||
sourceTenantID, _ := strconv.ParseUint(c.Query("agent_source_tenant_id"), 10, 64)
|
||||
sourceTenantID, parseErr := types.ParseAgentSourceTenantID(c.Query(types.AgentSourceTenantIDParam))
|
||||
if parseErr != nil {
|
||||
return nil, ctx, errors.NewBadRequestError(parseErr.Error())
|
||||
}
|
||||
agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, tenantID, callerTenantRole, agentID, sourceTenantID)
|
||||
if err == nil && agent != nil {
|
||||
if knowledge.TenantID != agent.TenantID {
|
||||
|
|
@ -1422,6 +1425,10 @@ func (h *KnowledgeHandler) GetKnowledgeBatch(c *gin.Context) {
|
|||
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
|
||||
return
|
||||
}
|
||||
if _, parseErr := types.ParseAgentSourceTenantID(c.Query(types.AgentSourceTenantIDParam)); parseErr != nil {
|
||||
c.Error(errors.NewBadRequestError(parseErr.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
// agentAllowedKBIDs restricts results to the agent's configured KB scope.
|
||||
// nil = no agent restriction; empty slice = agent has no KB access (none mode).
|
||||
|
|
@ -1994,7 +2001,11 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||
requestedSourceTenantID, _ := strconv.ParseUint(c.Query("agent_source_tenant_id"), 10, 64)
|
||||
requestedSourceTenantID, parseErr := types.ParseAgentSourceTenantID(c.Query(types.AgentSourceTenantIDParam))
|
||||
if parseErr != nil {
|
||||
c.Error(errors.NewBadRequestError(parseErr.Error()))
|
||||
return
|
||||
}
|
||||
agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID, requestedSourceTenantID)
|
||||
if err != nil {
|
||||
if goerrors.Is(err, service.ErrAgentShareNotFound) || goerrors.Is(err, service.ErrAgentSharePermission) || goerrors.Is(err, service.ErrAgentNotFoundForShare) {
|
||||
|
|
|
|||
|
|
@ -474,7 +474,10 @@ func (h *KnowledgeBaseHandler) validateAndGetKnowledgeBase(c *gin.Context) (*typ
|
|||
currentTenantID := tenantID.(uint64)
|
||||
agentID := c.Query("agent_id")
|
||||
if agentID != "" {
|
||||
sourceTenantID, _ := strconv.ParseUint(c.Query("agent_source_tenant_id"), 10, 64)
|
||||
sourceTenantID, parseErr := types.ParseAgentSourceTenantID(c.Query(types.AgentSourceTenantIDParam))
|
||||
if parseErr != nil {
|
||||
return kb, id, 0, types.OrgMemberRole(""), apperrors.NewBadRequestError(parseErr.Error())
|
||||
}
|
||||
agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID, sourceTenantID)
|
||||
if err == nil && agent != nil {
|
||||
if kb.TenantID != agent.TenantID {
|
||||
|
|
@ -582,7 +585,11 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
callerTenantRole := types.TenantRoleFromContext(ctx)
|
||||
requestedSourceTenantID, _ := strconv.ParseUint(c.Query("agent_source_tenant_id"), 10, 64)
|
||||
requestedSourceTenantID, parseErr := types.ParseAgentSourceTenantID(c.Query(types.AgentSourceTenantIDParam))
|
||||
if parseErr != nil {
|
||||
c.Error(apperrors.NewBadRequestError(parseErr.Error()))
|
||||
return
|
||||
}
|
||||
agent, err := h.agentShareService.GetSharedAgentForTenant(ctx, currentTenantID, callerTenantRole, agentID, requestedSourceTenantID)
|
||||
if err != nil {
|
||||
if stderrors.Is(err, service.ErrAgentShareNotFound) || stderrors.Is(err, service.ErrAgentSharePermission) || stderrors.Is(err, service.ErrAgentNotFoundForShare) {
|
||||
|
|
|
|||
|
|
@ -502,7 +502,7 @@ func (h *Handler) resolveAgent(
|
|||
logger.Warnf(ctx, "Failed to get custom agent, agent ID: %s, error: %v, using default config",
|
||||
secutils.SanitizeForLog(agentID), err)
|
||||
}
|
||||
} else {
|
||||
} else if customAgent != nil {
|
||||
logger.Infof(ctx, "Using custom agent: ID=%s, Name=%s, IsBuiltin=%v, AgentMode=%s, effectiveTenantID=%d",
|
||||
customAgent.ID, customAgent.Name, customAgent.IsBuiltin, customAgent.Config.AgentMode, effectiveTenantID)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,158 @@
|
|||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type resolveAgentShareStub struct {
|
||||
agent *types.CustomAgent
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *resolveAgentShareStub) GetSharedAgentForTenant(
|
||||
_ context.Context,
|
||||
_ uint64,
|
||||
_ types.TenantRole,
|
||||
_ string,
|
||||
_ ...uint64,
|
||||
) (*types.CustomAgent, error) {
|
||||
return s.agent, s.err
|
||||
}
|
||||
|
||||
func (s *resolveAgentShareStub) ShareAgent(context.Context, string, string, string, uint64, types.OrgMemberRole) (*types.AgentShare, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveAgentShareStub) RemoveShare(context.Context, string, string, uint64) error {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveAgentShareStub) ListSharesByAgent(context.Context, string, uint64) ([]*types.AgentShare, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveAgentShareStub) ListSharesByOrganization(context.Context, string) ([]*types.AgentShare, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveAgentShareStub) ListSharedAgents(context.Context, uint64, types.TenantRole) ([]*types.SharedAgentInfo, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveAgentShareStub) ListSharedAgentsInOrganization(context.Context, string, uint64, types.TenantRole) ([]*types.OrganizationSharedAgentItem, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveAgentShareStub) ListSharedAgentsInOrganizations(context.Context, []string, uint64, types.TenantRole) (map[string][]*types.OrganizationSharedAgentItem, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveAgentShareStub) SetSharedAgentDisabledByMe(context.Context, uint64, string, uint64, bool) error {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveAgentShareStub) TenantCanAccessKBViaSomeSharedAgent(context.Context, uint64, types.TenantRole, *types.KnowledgeBase) (bool, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveAgentShareStub) GetShare(context.Context, string) (*types.AgentShare, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveAgentShareStub) GetShareByAgentAndOrg(context.Context, string, string) (*types.AgentShare, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveAgentShareStub) GetShareByAgentIDForTenant(context.Context, uint64, string, uint64) (*types.AgentShare, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveAgentShareStub) CountByOrganizations(context.Context, []string) (map[string]int64, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
|
||||
type resolveOwnAgentStub struct {
|
||||
agent *types.CustomAgent
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *resolveOwnAgentStub) GetAgentByID(context.Context, string) (*types.CustomAgent, error) {
|
||||
return s.agent, s.err
|
||||
}
|
||||
|
||||
func (s *resolveOwnAgentStub) CreateAgent(context.Context, *types.CustomAgent) (*types.CustomAgent, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveOwnAgentStub) GetAgentByIDAndTenant(context.Context, string, uint64) (*types.CustomAgent, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveOwnAgentStub) ListAgents(context.Context) ([]*types.CustomAgent, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveOwnAgentStub) UpdateAgent(context.Context, *types.CustomAgent) (*types.CustomAgent, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveOwnAgentStub) DeleteAgent(context.Context, string) error {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveOwnAgentStub) CopyAgent(context.Context, string) (*types.CustomAgent, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveOwnAgentStub) GetSuggestedQuestions(context.Context, string, []string, []string, []types.TagScope, int) ([]types.SuggestedQuestion, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
func (s *resolveOwnAgentStub) GetKnowledgeSuggestedQuestions(context.Context, string, []string, []string, []types.TagScope, int) ([]types.SuggestedQuestion, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
|
||||
func newResolveAgentTestContext(tenantID uint64) (*gin.Context, context.Context) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
rec := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
|
||||
c.Set(types.UserIDContextKey.String(), "user-1")
|
||||
c.Set(types.TenantIDContextKey.String(), tenantID)
|
||||
ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, tenantID)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
return c, ctx
|
||||
}
|
||||
|
||||
func TestResolveAgent_RejectsInvalidSharedSelectorWithoutLocalFallback(t *testing.T) {
|
||||
c, ctx := newResolveAgentTestContext(7)
|
||||
localAgent := &types.CustomAgent{ID: "builtin-smart-reasoning", TenantID: 7, Name: "Local"}
|
||||
h := &Handler{
|
||||
agentShareService: &resolveAgentShareStub{},
|
||||
customAgentService: &resolveOwnAgentStub{agent: localAgent},
|
||||
}
|
||||
|
||||
agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, "builtin-smart-reasoning", 84)
|
||||
|
||||
require.Nil(t, agent)
|
||||
require.Equal(t, uint64(0), effectiveTenantID)
|
||||
require.False(t, sharedReadOnly)
|
||||
}
|
||||
|
||||
func TestResolveAgent_UsesSharedAgentWhenSourceSelectorMatches(t *testing.T) {
|
||||
c, ctx := newResolveAgentTestContext(7)
|
||||
sharedAgent := &types.CustomAgent{ID: "builtin-smart-reasoning", TenantID: 84, Name: "Shared"}
|
||||
h := &Handler{
|
||||
agentShareService: &resolveAgentShareStub{agent: sharedAgent},
|
||||
customAgentService: &resolveOwnAgentStub{agent: &types.CustomAgent{ID: "builtin-smart-reasoning", TenantID: 7}},
|
||||
}
|
||||
|
||||
agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, "builtin-smart-reasoning", 84)
|
||||
|
||||
require.Equal(t, sharedAgent, agent)
|
||||
require.Equal(t, uint64(84), effectiveTenantID)
|
||||
require.True(t, sharedReadOnly)
|
||||
}
|
||||
|
||||
func TestResolveAgent_FallsBackToLocalAgentWithoutSourceSelector(t *testing.T) {
|
||||
c, ctx := newResolveAgentTestContext(7)
|
||||
localAgent := &types.CustomAgent{ID: "builtin-smart-reasoning", TenantID: 7, Name: "Local"}
|
||||
h := &Handler{
|
||||
agentShareService: &resolveAgentShareStub{},
|
||||
customAgentService: &resolveOwnAgentStub{agent: localAgent},
|
||||
}
|
||||
|
||||
agent, effectiveTenantID, sharedReadOnly := h.resolveAgent(ctx, c, "builtin-smart-reasoning", 0)
|
||||
|
||||
require.Equal(t, localAgent, agent)
|
||||
require.Equal(t, uint64(0), effectiveTenantID)
|
||||
require.False(t, sharedReadOnly)
|
||||
}
|
||||
|
|
@ -6,7 +6,6 @@ import (
|
|||
"mime"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
apperrors "github.com/Tencent/WeKnora/internal/errors"
|
||||
|
|
@ -41,7 +40,11 @@ func (h *Handler) UploadTemporaryDocument(c *gin.Context) {
|
|||
}
|
||||
defer file.Close()
|
||||
|
||||
sourceTenantID, _ := strconv.ParseUint(strings.TrimSpace(c.PostForm("agent_source_tenant_id")), 10, 64)
|
||||
sourceTenantID, parseErr := types.ParseAgentSourceTenantID(c.PostForm(types.AgentSourceTenantIDParam))
|
||||
if parseErr != nil {
|
||||
c.Error(apperrors.NewBadRequestError(parseErr.Error()))
|
||||
return
|
||||
}
|
||||
agent, resourceTenantID, _ := h.resolveAgent(ctx, c, c.PostForm("agent_id"), sourceTenantID)
|
||||
if sourceTenantID != 0 && agent == nil {
|
||||
c.Error(apperrors.NewNotFoundError("Shared agent not found"))
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ package middleware
|
|||
import (
|
||||
"context"
|
||||
stderrors "errors"
|
||||
"strconv"
|
||||
|
||||
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
|
|
@ -283,6 +282,10 @@ func RequireKBAccess(
|
|||
_ = c.Error(apperrors.NewForbiddenError("Permission denied to access this knowledge base"))
|
||||
c.Abort()
|
||||
return
|
||||
case stderrors.Is(err, errKBAccessBadRequest):
|
||||
_ = c.Error(apperrors.NewBadRequestError("invalid agent_source_tenant_id"))
|
||||
c.Abort()
|
||||
return
|
||||
case err != nil:
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
// Transient/internal -> 503 so monitoring catches the
|
||||
|
|
@ -370,7 +373,11 @@ func resolveKBAccessOnce(
|
|||
|
||||
// 3. Shared agent that carries this KB — only ever grants read.
|
||||
if requiredPermission == types.OrgRoleViewer && agentShareService != nil {
|
||||
if access := resolveSharedAgentAccess(ctx, c, tenantID, callerTenantRole, kb, agentShareService); access != nil {
|
||||
access, agentErr := resolveSharedAgentAccess(ctx, c, tenantID, callerTenantRole, kb, agentShareService)
|
||||
if agentErr != nil {
|
||||
return nil, agentErr
|
||||
}
|
||||
if access != nil {
|
||||
return access, nil
|
||||
}
|
||||
}
|
||||
|
|
@ -397,18 +404,21 @@ func resolveSharedAgentAccess(
|
|||
callerTenantRole types.TenantRole,
|
||||
kb *types.KnowledgeBase,
|
||||
agentShareService interfaces.AgentShareService,
|
||||
) *KBAccess {
|
||||
) (*KBAccess, error) {
|
||||
agentID := c.Query("agent_id")
|
||||
if agentID != "" {
|
||||
sourceTenantID, _ := strconv.ParseUint(c.Query("agent_source_tenant_id"), 10, 64)
|
||||
sourceTenantID, err := types.ParseAgentSourceTenantID(c.Query(types.AgentSourceTenantIDParam))
|
||||
if err != nil {
|
||||
return nil, errKBAccessBadRequest
|
||||
}
|
||||
agent, err := agentShareService.GetSharedAgentForTenant(ctx, tenantID, callerTenantRole, agentID, sourceTenantID)
|
||||
if err != nil || agent == nil {
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
if kb.TenantID != agent.TenantID {
|
||||
logger.Warnf(ctx, "[kb_access] shared agent workspace mismatch: kb=%s kb.tenant=%d agent.tenant=%d",
|
||||
kb.ID, kb.TenantID, agent.TenantID)
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
switch agent.Config.KBSelectionMode {
|
||||
case "all":
|
||||
|
|
@ -418,7 +428,7 @@ func resolveSharedAgentAccess(
|
|||
KnowledgeBase: kb,
|
||||
EffectiveTenantID: kb.TenantID,
|
||||
Permission: types.OrgRoleViewer,
|
||||
}
|
||||
}, nil
|
||||
case "selected":
|
||||
for _, allowedID := range agent.Config.KnowledgeBases {
|
||||
if allowedID == kb.ID {
|
||||
|
|
@ -428,11 +438,11 @@ func resolveSharedAgentAccess(
|
|||
KnowledgeBase: kb,
|
||||
EffectiveTenantID: kb.TenantID,
|
||||
Permission: types.OrgRoleViewer,
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
can, err := agentShareService.TenantCanAccessKBViaSomeSharedAgent(ctx, tenantID, callerTenantRole, kb)
|
||||
|
|
@ -442,13 +452,14 @@ func resolveSharedAgentAccess(
|
|||
KnowledgeBase: kb,
|
||||
EffectiveTenantID: kb.TenantID,
|
||||
Permission: types.OrgRoleViewer,
|
||||
}
|
||||
}, nil
|
||||
}
|
||||
return nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
var (
|
||||
errKBAccessUnauthorized = stderrors.New("kb_access: unauthorized")
|
||||
errKBAccessNotFound = stderrors.New("kb_access: not found")
|
||||
errKBAccessForbidden = stderrors.New("kb_access: forbidden")
|
||||
errKBAccessBadRequest = stderrors.New("kb_access: bad request")
|
||||
)
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"errors"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
apprepo "github.com/Tencent/WeKnora/internal/application/repository"
|
||||
|
|
@ -157,8 +158,9 @@ func (s *stubAgentShareForGuard) CountByOrganizations(context.Context, []string)
|
|||
// guardOpts collects optional knobs for runGuard. Keeps the call site
|
||||
// readable when most tests only care about a couple of dimensions.
|
||||
type guardOpts struct {
|
||||
agentID string // ?agent_id query param
|
||||
agentShare *stubAgentShareForGuard // nil means "no agent-share service"
|
||||
agentID string // ?agent_id query param
|
||||
agentSourceTenantID string // ?agent_source_tenant_id query param
|
||||
agentShare *stubAgentShareForGuard // nil means "no agent-share service"
|
||||
}
|
||||
|
||||
// runGuard fires a single request through the guard and returns the
|
||||
|
|
@ -181,8 +183,15 @@ func runGuard(
|
|||
c.Params = gin.Params{{Key: "id", Value: kbID}}
|
||||
|
||||
url := "/"
|
||||
query := make([]string, 0, 2)
|
||||
if opts.agentID != "" {
|
||||
url = "/?agent_id=" + opts.agentID
|
||||
query = append(query, "agent_id="+opts.agentID)
|
||||
}
|
||||
if opts.agentSourceTenantID != "" {
|
||||
query = append(query, "agent_source_tenant_id="+opts.agentSourceTenantID)
|
||||
}
|
||||
if len(query) > 0 {
|
||||
url = "/?" + strings.Join(query, "&")
|
||||
}
|
||||
req := httptest.NewRequest("GET", url, nil)
|
||||
ctx := context.WithValue(req.Context(), types.TenantIDContextKey, tenantID)
|
||||
|
|
@ -530,3 +539,18 @@ func TestRequireKBAccess_NotFound_FiresEvenWhenRBACDisabled(t *testing.T) {
|
|||
require.True(t, c.IsAborted(), "404 still fires with enforcement off")
|
||||
_ = rec
|
||||
}
|
||||
|
||||
func TestRequireKBAccess_InvalidAgentSourceTenantID(t *testing.T) {
|
||||
_, c := runGuard(t, 100, "kb-1",
|
||||
types.OrgRoleViewer,
|
||||
&types.KnowledgeBase{ID: "kb-1", TenantID: 200},
|
||||
nil,
|
||||
guardOpts{
|
||||
agentID: "agent-1",
|
||||
agentSourceTenantID: "not-a-number",
|
||||
agentShare: &stubAgentShareForGuard{},
|
||||
},
|
||||
)
|
||||
require.True(t, c.IsAborted())
|
||||
require.NotEmpty(t, c.Errors)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
package types
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const AgentSourceTenantIDParam = "agent_source_tenant_id"
|
||||
|
||||
// ParseAgentSourceTenantID parses the optional shared-agent source workspace selector.
|
||||
// Empty or whitespace input is treated as absent (0, nil). Non-empty but invalid
|
||||
// values return an error so callers fail closed instead of silently falling back.
|
||||
func ParseAgentSourceTenantID(raw string) (uint64, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return 0, nil
|
||||
}
|
||||
value, err := strconv.ParseUint(raw, 10, 64)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid %s: %w", AgentSourceTenantIDParam, err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
package types
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParseAgentSourceTenantIDEmpty(t *testing.T) {
|
||||
value, err := ParseAgentSourceTenantID("")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uint64(0), value)
|
||||
|
||||
value, err = ParseAgentSourceTenantID(" ")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uint64(0), value)
|
||||
}
|
||||
|
||||
func TestParseAgentSourceTenantIDValid(t *testing.T) {
|
||||
value, err := ParseAgentSourceTenantID("42")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, uint64(42), value)
|
||||
}
|
||||
|
||||
func TestParseAgentSourceTenantIDInvalid(t *testing.T) {
|
||||
_, err := ParseAgentSourceTenantID("abc")
|
||||
require.Error(t, err)
|
||||
|
||||
_, err = ParseAgentSourceTenantID("42abc")
|
||||
require.Error(t, err)
|
||||
}
|
||||
Loading…
Reference in New Issue