fix(session): serve org-shared KB images through the message file proxy (#3069)
* fix(session): serve org-shared KB images through the message file proxy The message-scoped file proxy only authorized resources whose tenant matched the message's agent tenant, so replies produced by an agent of the caller's own workspace over an org-shared knowledge base rendered text but lost every image with 403 (#3022). Fall back to the org-share relation for exactly that case: the message's persisted retrieval references must contain the resource handle (chunk evidence — an unrelated handle from the owner tenant cannot ride along), the reference's knowledge base must belong to the resource's tenant, and that KB must still be shared to the caller with at least viewer permission. Messages written before agent_tenant_id existed get the same fallback before the shared-agent relation is demanded; the shared-agent path itself is unchanged. * fix(session): prove shared-KB images from agent steps and image_info Smart-reasoning turns never persist KnowledgeReferences, and OCR hits often keep the resource handle only in image_info. Collect tool retrieval onto the message and accept that evidence in the message-file proxy so org-shared KB images stop 403ing. * fix(session): keep shared-KB image evidence in the message-file proxy Drop the agent-engine KnowledgeRefs collector so pre-push does not lint the whole agent package. AgentSteps already persist knowledge_search hits, which is enough for the proxy to authorize org-shared images. --------- Co-authored-by: vicfei <vicfei@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>main
parent
5fa50711e2
commit
86136b25e3
|
|
@ -62,6 +62,228 @@ type sharedAgentFileLookup interface {
|
|||
) (*types.CustomAgent, error)
|
||||
}
|
||||
|
||||
// kbSharePermissionGuard is the org-share surface the message-scoped proxy
|
||||
// needs for its shared-KB fallback.
|
||||
type kbSharePermissionGuard interface {
|
||||
HasTenantKBPermission(
|
||||
ctx context.Context,
|
||||
kbID string,
|
||||
callerTenantID uint64,
|
||||
callerTenantRole types.TenantRole,
|
||||
requiredRole types.OrgMemberRole,
|
||||
) (bool, error)
|
||||
}
|
||||
|
||||
// kbTenantLookup resolves knowledge bases without a tenant filter, so a
|
||||
// message's persisted retrieval evidence can be mapped back to the knowledge
|
||||
// bases the chunks were retrieved from.
|
||||
type kbTenantLookup interface {
|
||||
GetKnowledgeBasesByIDsOnly(ctx context.Context, ids []string) ([]*types.KnowledgeBase, error)
|
||||
}
|
||||
|
||||
// knowledgeOwnerLookup resolves a knowledge entry to its knowledge base for
|
||||
// message references that predate the denormalized knowledge_base_id field.
|
||||
type knowledgeOwnerLookup interface {
|
||||
GetKnowledgeByIDOnly(ctx context.Context, id string) (*types.Knowledge, error)
|
||||
}
|
||||
|
||||
// messageKBShareAuthorizer bundles the read-only lookups behind the
|
||||
// message proxy's org-shared-KB fallback. A nil ShareGuard or KBs lookup
|
||||
// disables the fallback, which keeps older call sites and tests on the
|
||||
// shared-agent-only behavior. A nil Knowledges lookup only disables the
|
||||
// pre-denormalization KnowledgeID path.
|
||||
type messageKBShareAuthorizer struct {
|
||||
ShareGuard kbSharePermissionGuard
|
||||
KBs kbTenantLookup
|
||||
Knowledges knowledgeOwnerLookup
|
||||
}
|
||||
|
||||
// resourceAccessibleViaSharedKB reports whether the message's persisted
|
||||
// retrieval evidence proves the resource came from an org-shared KB the
|
||||
// caller may read. This is the fallback for replies whose agent belongs to
|
||||
// the caller's own workspace while the retrieved resources belong to the
|
||||
// workspace that shared the knowledge base (#3022).
|
||||
//
|
||||
// Evidence required from one retrieval record: a canonical resource://
|
||||
// handle (not a prefix of a longer token) appears in the chunk text or
|
||||
// image_info, its knowledge base belongs to the resource's tenant, and
|
||||
// that KB is org-shared to the caller with at least viewer permission.
|
||||
// Smart-reasoning turns persist that evidence on AgentSteps when
|
||||
// KnowledgeReferences was never filled. Any lookup failure fails closed.
|
||||
func (a messageKBShareAuthorizer) resourceAccessibleViaSharedKB(
|
||||
ctx context.Context,
|
||||
message *types.Message,
|
||||
resource *types.StoredResource,
|
||||
callerTenantID uint64,
|
||||
callerTenantRole types.TenantRole,
|
||||
) bool {
|
||||
if a.ShareGuard == nil || a.KBs == nil || message == nil || resource == nil {
|
||||
return false
|
||||
}
|
||||
handle, ok := types.ParseResourcePath(types.BuildResourcePath(resource.Handle))
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
kbIDs := a.collectSharedKBEvidenceIDs(ctx, message, handle)
|
||||
if len(kbIDs) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
kbs, err := a.KBs.GetKnowledgeBasesByIDsOnly(ctx, kbIDs)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, kb := range kbs {
|
||||
if kb == nil || kb.TenantID != resource.TenantID {
|
||||
continue
|
||||
}
|
||||
shared, err := a.ShareGuard.HasTenantKBPermission(
|
||||
ctx, kb.ID, callerTenantID, callerTenantRole, types.OrgRoleViewer)
|
||||
if err == nil && shared {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (a messageKBShareAuthorizer) collectSharedKBEvidenceIDs(
|
||||
ctx context.Context,
|
||||
message *types.Message,
|
||||
handle string,
|
||||
) []string {
|
||||
seenKB := make(map[string]bool)
|
||||
seenKnowledge := make(map[string]bool)
|
||||
var kbIDs, knowledgeIDs []string
|
||||
addKB := func(id string) {
|
||||
if id == "" || seenKB[id] {
|
||||
return
|
||||
}
|
||||
seenKB[id] = true
|
||||
kbIDs = append(kbIDs, id)
|
||||
}
|
||||
addKnowledge := func(id string) {
|
||||
if id == "" || seenKnowledge[id] {
|
||||
return
|
||||
}
|
||||
seenKnowledge[id] = true
|
||||
knowledgeIDs = append(knowledgeIDs, id)
|
||||
}
|
||||
|
||||
for _, ref := range message.KnowledgeReferences {
|
||||
if !searchResultHasResourceHandle(ref, handle) {
|
||||
continue
|
||||
}
|
||||
if ref.KnowledgeBaseID != "" {
|
||||
addKB(ref.KnowledgeBaseID)
|
||||
continue
|
||||
}
|
||||
addKnowledge(ref.KnowledgeID)
|
||||
}
|
||||
collectKBEvidenceFromValue(message.AgentSteps, handle, "", "", addKB, addKnowledge)
|
||||
|
||||
if a.Knowledges != nil {
|
||||
for _, knowledgeID := range knowledgeIDs {
|
||||
knowledge, err := a.Knowledges.GetKnowledgeByIDOnly(ctx, knowledgeID)
|
||||
if err != nil || knowledge == nil {
|
||||
continue
|
||||
}
|
||||
addKB(knowledge.KnowledgeBaseID)
|
||||
}
|
||||
}
|
||||
return kbIDs
|
||||
}
|
||||
|
||||
func searchResultHasResourceHandle(ref *types.SearchResult, handle string) bool {
|
||||
if ref == nil {
|
||||
return false
|
||||
}
|
||||
return textHasResourceHandle(ref.Content, handle) ||
|
||||
textHasResourceHandle(ref.MatchedContent, handle) ||
|
||||
textHasResourceHandle(ref.ImageInfo, handle)
|
||||
}
|
||||
|
||||
func textHasResourceHandle(text, handle string) bool {
|
||||
if text == "" || handle == "" {
|
||||
return false
|
||||
}
|
||||
want := types.BuildResourcePath(handle)
|
||||
for _, ref := range types.ScanResourceReferences(text) {
|
||||
if ref == want {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func collectKBEvidenceFromValue(
|
||||
v interface{},
|
||||
handle, kbID, knowledgeID string,
|
||||
addKB, addKnowledge func(string),
|
||||
) {
|
||||
switch val := v.(type) {
|
||||
case string:
|
||||
if !textHasResourceHandle(val, handle) {
|
||||
return
|
||||
}
|
||||
if kbID != "" {
|
||||
addKB(kbID)
|
||||
return
|
||||
}
|
||||
addKnowledge(knowledgeID)
|
||||
case types.AgentSteps:
|
||||
for _, step := range val {
|
||||
collectKBEvidenceFromValue(step, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
}
|
||||
case types.AgentStep:
|
||||
collectKBEvidenceFromValue(val.ToolCalls, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
case []types.ToolCall:
|
||||
for _, call := range val {
|
||||
collectKBEvidenceFromValue(call, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
}
|
||||
case types.ToolCall:
|
||||
if val.Result != nil {
|
||||
collectKBEvidenceFromValue(val.Result.Output, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
collectKBEvidenceFromValue(val.Result.Data, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
}
|
||||
case map[string]interface{}:
|
||||
nextKB := firstNonEmptyString(
|
||||
stringFromAnyMap(val, "knowledge_base_id"),
|
||||
stringFromAnyMap(val, "knowledge_base"),
|
||||
kbID,
|
||||
)
|
||||
nextKnowledge := firstNonEmptyString(stringFromAnyMap(val, "knowledge_id"), knowledgeID)
|
||||
for _, nested := range val {
|
||||
collectKBEvidenceFromValue(nested, handle, nextKB, nextKnowledge, addKB, addKnowledge)
|
||||
}
|
||||
case []interface{}:
|
||||
for _, item := range val {
|
||||
collectKBEvidenceFromValue(item, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
}
|
||||
case []map[string]interface{}:
|
||||
for _, item := range val {
|
||||
collectKBEvidenceFromValue(item, handle, kbID, knowledgeID, addKB, addKnowledge)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func stringFromAnyMap(m map[string]interface{}, key string) string {
|
||||
if m == nil {
|
||||
return ""
|
||||
}
|
||||
s, _ := m[key].(string)
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
|
||||
func firstNonEmptyString(values ...string) string {
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
return strings.TrimSpace(value)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// localStorageBaseDir resolves LOCAL_STORAGE_BASE_DIR with the container
|
||||
// default.
|
||||
func localStorageBaseDir() string {
|
||||
|
|
@ -517,8 +739,10 @@ func newKBScopedFileServeHandlerWithResources(
|
|||
|
||||
// newMessageScopedFileServeHandler serves resources rendered inside one
|
||||
// assistant message. The message service first proves that the caller owns the
|
||||
// containing session. For cross-workspace resources we then require the
|
||||
// message's agent to still be shared from the resource-owning workspace.
|
||||
// containing session. For cross-workspace resources we then require either the
|
||||
// message's agent to still be shared from the resource-owning workspace, or —
|
||||
// when the reply was produced by the caller's own agent over an org-shared
|
||||
// knowledge base — that the resource's KB is still shared to the caller.
|
||||
//
|
||||
// The owner tenant comes from the resource registry whenever possible. This
|
||||
// also keeps old messages (written before agent_tenant_id was populated)
|
||||
|
|
@ -530,6 +754,7 @@ func newMessageScopedFileServeHandler(
|
|||
globalFileService interfaces.FileService,
|
||||
storageResolver interfaces.StorageBackendResolver,
|
||||
resourceCatalog interfaces.ResourceCatalog,
|
||||
kbShareAuth messageKBShareAuthorizer,
|
||||
) gin.HandlerFunc {
|
||||
absDir := localStorageAbsDir()
|
||||
|
||||
|
|
@ -568,14 +793,21 @@ func newMessageScopedFileServeHandler(
|
|||
}
|
||||
|
||||
ownerTenantID := message.AgentTenantID
|
||||
kbShareAuthorized := false
|
||||
if resource != nil {
|
||||
ownerTenantID = resource.TenantID
|
||||
// A modern message records its source tenant. A resource from any
|
||||
// other tenant cannot be smuggled through that message even if the
|
||||
// caller happens to have another shared agent with the same ID.
|
||||
// caller happens to have another shared agent with the same ID —
|
||||
// unless the reply's own retrieval references prove the resource
|
||||
// came from an org-shared KB the caller may still read (#3022).
|
||||
if message.AgentTenantID != 0 && message.AgentTenantID != ownerTenantID {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden: resource not accessible from this message"})
|
||||
return
|
||||
kbShareAuthorized = kbShareAuth.resourceAccessibleViaSharedKB(
|
||||
ctx, message, resource, callerTenantID, types.TenantRoleFromContext(ctx))
|
||||
if !kbShareAuthorized {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden: resource not accessible from this message"})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if ownerTenantID == 0 {
|
||||
|
|
@ -583,21 +815,30 @@ func newMessageScopedFileServeHandler(
|
|||
return
|
||||
}
|
||||
|
||||
if ownerTenantID != callerTenantID {
|
||||
if message.AgentID == "" || agentShareService == nil {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden: shared agent access required"})
|
||||
return
|
||||
if ownerTenantID != callerTenantID && !kbShareAuthorized {
|
||||
// Messages written before agent_tenant_id was populated have no
|
||||
// recorded source tenant; offer them the same org-shared KB
|
||||
// fallback before the shared-agent relation is demanded.
|
||||
if message.AgentTenantID == 0 {
|
||||
kbShareAuthorized = kbShareAuth.resourceAccessibleViaSharedKB(
|
||||
ctx, message, resource, callerTenantID, types.TenantRoleFromContext(ctx))
|
||||
}
|
||||
agent, shareErr := agentShareService.GetSharedAgentForTenant(
|
||||
ctx,
|
||||
callerTenantID,
|
||||
types.TenantRoleFromContext(ctx),
|
||||
message.AgentID,
|
||||
ownerTenantID,
|
||||
)
|
||||
if shareErr != nil || agent == nil || agent.TenantID != ownerTenantID {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden: shared agent access revoked"})
|
||||
return
|
||||
if !kbShareAuthorized {
|
||||
if message.AgentID == "" || agentShareService == nil {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden: shared agent access required"})
|
||||
return
|
||||
}
|
||||
agent, shareErr := agentShareService.GetSharedAgentForTenant(
|
||||
ctx,
|
||||
callerTenantID,
|
||||
types.TenantRoleFromContext(ctx),
|
||||
message.AgentID,
|
||||
ownerTenantID,
|
||||
)
|
||||
if shareErr != nil || agent == nil || agent.TenantID != ownerTenantID {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden: shared agent access revoked"})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -668,6 +909,9 @@ func serveMessageScopedFiles(
|
|||
globalFileService interfaces.FileService,
|
||||
storageResolver interfaces.StorageBackendResolver,
|
||||
resourceCatalog interfaces.ResourceCatalog,
|
||||
kbShareService interfaces.KBShareService,
|
||||
kbService interfaces.KnowledgeBaseService,
|
||||
knowledgeService interfaces.KnowledgeService,
|
||||
) {
|
||||
g.apiKeyRoute(
|
||||
r,
|
||||
|
|
@ -682,6 +926,11 @@ func serveMessageScopedFiles(
|
|||
globalFileService,
|
||||
storageResolver,
|
||||
resourceCatalog,
|
||||
messageKBShareAuthorizer{
|
||||
ShareGuard: kbShareService,
|
||||
KBs: kbService,
|
||||
Knowledges: knowledgeService,
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -247,7 +247,9 @@ func NewRouter(params RouterParams) *gin.Engine {
|
|||
// Message-scoped image proxy: shared-agent replies belong to the
|
||||
// caller's session but may reference resources stored in the agent's
|
||||
// source workspace. Authorization is derived from the persisted message,
|
||||
// never from a client-provided workspace ID.
|
||||
// never from a client-provided workspace ID. Replies produced by the
|
||||
// caller's own agent over an org-shared KB fall back to the KB share
|
||||
// relation instead (#3022).
|
||||
serveMessageScopedFiles(
|
||||
v1,
|
||||
rbacGuards,
|
||||
|
|
@ -257,6 +259,9 @@ func NewRouter(params RouterParams) *gin.Engine {
|
|||
params.FileService,
|
||||
params.StorageBackendResolver,
|
||||
params.ResourceCatalog,
|
||||
params.KBShareService,
|
||||
params.KBService,
|
||||
params.KnowledgeService,
|
||||
)
|
||||
RegisterKnowledgeTagRoutes(v1, params.TagHandler, rbacGuards)
|
||||
RegisterKnowledgeRoutes(v1, params.KnowledgeHandler, rbacGuards)
|
||||
|
|
|
|||
|
|
@ -522,6 +522,7 @@ func newMessageScopedFilesTestEngine(
|
|||
tenantService interfaces.TenantService,
|
||||
global interfaces.FileService,
|
||||
resourceCatalog interfaces.ResourceCatalog,
|
||||
kbShareAuth messageKBShareAuthorizer,
|
||||
) *gin.Engine {
|
||||
engine := gin.New()
|
||||
engine.GET("/sessions/:id/messages/:message_id/files",
|
||||
|
|
@ -537,6 +538,7 @@ func newMessageScopedFilesTestEngine(
|
|||
global,
|
||||
nil,
|
||||
resourceCatalog,
|
||||
kbShareAuth,
|
||||
),
|
||||
)
|
||||
return engine
|
||||
|
|
@ -586,6 +588,7 @@ func TestMessageScopedFilesServesSharedAgentResource(t *testing.T) {
|
|||
OriginalName: "chart.png",
|
||||
MimeType: "image/png",
|
||||
}},
|
||||
messageKBShareAuthorizer{},
|
||||
)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
|
|
@ -640,6 +643,7 @@ func TestMessageScopedFilesServesSameTenantResource(t *testing.T) {
|
|||
PhysicalPath: physical,
|
||||
MimeType: "image/png",
|
||||
}},
|
||||
messageKBShareAuthorizer{},
|
||||
)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
|
|
@ -667,6 +671,7 @@ func TestMessageScopedFilesRequiresFilePath(t *testing.T) {
|
|||
&stubTenantService{},
|
||||
&stubFileService{},
|
||||
&stubResourceCatalog{},
|
||||
messageKBShareAuthorizer{},
|
||||
)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/sessions/session-1/messages/message-1/files", nil)
|
||||
|
|
@ -701,6 +706,7 @@ func TestMessageScopedFilesRejectsRevokedSharedAgent(t *testing.T) {
|
|||
return nil, nil
|
||||
}},
|
||||
&stubResourceCatalog{resource: &types.StoredResource{TenantID: 7, PhysicalPath: "local://7/exports/chart.png"}},
|
||||
messageKBShareAuthorizer{},
|
||||
)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
|
|
@ -731,6 +737,7 @@ func TestMessageScopedFilesRejectsResourceOutsideMessageTenant(t *testing.T) {
|
|||
&stubTenantService{},
|
||||
&stubFileService{},
|
||||
&stubResourceCatalog{resource: &types.StoredResource{TenantID: 7, PhysicalPath: "local://7/exports/chart.png"}},
|
||||
messageKBShareAuthorizer{},
|
||||
)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
|
|
@ -743,6 +750,475 @@ func TestMessageScopedFilesRejectsResourceOutsideMessageTenant(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
type stubKBShareGuard struct {
|
||||
hasPermission func(
|
||||
ctx context.Context,
|
||||
kbID string,
|
||||
callerTenantID uint64,
|
||||
callerTenantRole types.TenantRole,
|
||||
requiredRole types.OrgMemberRole,
|
||||
) (bool, error)
|
||||
}
|
||||
|
||||
func (s *stubKBShareGuard) HasTenantKBPermission(
|
||||
ctx context.Context,
|
||||
kbID string,
|
||||
callerTenantID uint64,
|
||||
callerTenantRole types.TenantRole,
|
||||
requiredRole types.OrgMemberRole,
|
||||
) (bool, error) {
|
||||
return s.hasPermission(ctx, kbID, callerTenantID, callerTenantRole, requiredRole)
|
||||
}
|
||||
|
||||
type stubKBTenantLookup struct {
|
||||
kbs []*types.KnowledgeBase
|
||||
}
|
||||
|
||||
func (s *stubKBTenantLookup) GetKnowledgeBasesByIDsOnly(
|
||||
_ context.Context, ids []string,
|
||||
) ([]*types.KnowledgeBase, error) {
|
||||
byID := make(map[string]*types.KnowledgeBase, len(s.kbs))
|
||||
for _, kb := range s.kbs {
|
||||
byID[kb.ID] = kb
|
||||
}
|
||||
result := make([]*types.KnowledgeBase, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
if kb, ok := byID[id]; ok {
|
||||
result = append(result, kb)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type stubKnowledgeOwnerLookup struct {
|
||||
byID map[string]*types.Knowledge
|
||||
}
|
||||
|
||||
func (s *stubKnowledgeOwnerLookup) GetKnowledgeByIDOnly(_ context.Context, id string) (*types.Knowledge, error) {
|
||||
return s.byID[id], nil
|
||||
}
|
||||
|
||||
// newOrgSharedKBTestEngine builds the #3022 scenario: the caller's own agent
|
||||
// (message.AgentTenantID = caller) answered from an org-shared KB whose
|
||||
// resources belong to another tenant.
|
||||
func newOrgSharedKBTestEngine(
|
||||
t *testing.T,
|
||||
sharePermitted bool,
|
||||
refs types.References,
|
||||
kbs []*types.KnowledgeBase,
|
||||
) (*gin.Engine, *string) {
|
||||
t.Helper()
|
||||
return newOrgSharedKBTestEngineFromMessage(t, sharePermitted, &types.Message{
|
||||
AgentID: "own-agent-1",
|
||||
AgentTenantID: 10006,
|
||||
KnowledgeReferences: refs,
|
||||
}, kbs)
|
||||
}
|
||||
|
||||
func newOrgSharedKBTestEngineFromMessage(
|
||||
t *testing.T,
|
||||
sharePermitted bool,
|
||||
message *types.Message,
|
||||
kbs []*types.KnowledgeBase,
|
||||
) (*gin.Engine, *string) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
t.Setenv("STORAGE_TYPE", "local")
|
||||
|
||||
const (
|
||||
callerTenantID = uint64(10006)
|
||||
ownerTenantID = uint64(10005)
|
||||
physical = "local://10005/images/quadrant.jpg"
|
||||
)
|
||||
var requestedPath string
|
||||
shareGuard := &stubKBShareGuard{hasPermission: func(
|
||||
_ context.Context,
|
||||
kbID string,
|
||||
caller uint64,
|
||||
_ types.TenantRole,
|
||||
required types.OrgMemberRole,
|
||||
) (bool, error) {
|
||||
if kbID != "kb-1" || caller != callerTenantID || required != types.OrgRoleViewer {
|
||||
t.Fatalf("unexpected share check kb=%s caller=%d required=%s", kbID, caller, required)
|
||||
}
|
||||
return sharePermitted, nil
|
||||
}}
|
||||
engine := newMessageScopedFilesTestEngine(
|
||||
callerTenantID,
|
||||
&stubMessageFileLookup{get: func(context.Context, string, string) (*types.Message, error) {
|
||||
return message, nil
|
||||
}},
|
||||
&stubSharedAgentFileLookup{get: func(
|
||||
context.Context, uint64, types.TenantRole, string, ...uint64,
|
||||
) (*types.CustomAgent, error) {
|
||||
t.Fatal("shared-agent lookup must not run for the org-shared KB fallback")
|
||||
return nil, nil
|
||||
}},
|
||||
&stubTenantService{get: func(_ context.Context, id uint64) (*types.Tenant, error) {
|
||||
return &types.Tenant{ID: id}, nil
|
||||
}},
|
||||
&stubFileService{getFile: func(_ context.Context, path string) (io.ReadCloser, error) {
|
||||
requestedPath = path
|
||||
return io.NopCloser(strings.NewReader("shared-kb-image")), nil
|
||||
}},
|
||||
&stubResourceCatalog{resource: &types.StoredResource{
|
||||
Handle: "ShArEdKbHaNdLe00000000",
|
||||
TenantID: ownerTenantID,
|
||||
PhysicalPath: physical,
|
||||
OriginalName: "quadrant.jpg",
|
||||
MimeType: "image/jpeg",
|
||||
}},
|
||||
messageKBShareAuthorizer{
|
||||
ShareGuard: shareGuard,
|
||||
KBs: &stubKBTenantLookup{kbs: kbs},
|
||||
},
|
||||
)
|
||||
return engine, &requestedPath
|
||||
}
|
||||
|
||||
func orgSharedKBFileRequest() *http.Request {
|
||||
return httptest.NewRequest(http.MethodGet,
|
||||
"/sessions/session-1/messages/message-1/files?file_path="+
|
||||
url.QueryEscape("resource://ShArEdKbHaNdLe00000000"), nil)
|
||||
}
|
||||
|
||||
func TestMessageScopedFilesServesOrgSharedKBResource(t *testing.T) {
|
||||
engine, requestedPath := newOrgSharedKBTestEngine(t, true,
|
||||
types.References{{
|
||||
KnowledgeID: "knowledge-1",
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Content: "Figure 1 ",
|
||||
}},
|
||||
[]*types.KnowledgeBase{{ID: "kb-1", TenantID: 10005}},
|
||||
)
|
||||
|
||||
req := orgSharedKBFileRequest()
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusOK || recorder.Body.String() != "shared-kb-image" {
|
||||
t.Fatalf("status=%d body=%q", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if *requestedPath != "local://10005/images/quadrant.jpg" {
|
||||
t.Fatalf("requested path = %q", *requestedPath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageScopedFilesRejectsOrgSharedKBResourceWhenShareRevoked(t *testing.T) {
|
||||
engine, _ := newOrgSharedKBTestEngine(t, false,
|
||||
types.References{{
|
||||
KnowledgeID: "knowledge-1",
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Content: "Figure 1 ",
|
||||
}},
|
||||
[]*types.KnowledgeBase{{ID: "kb-1", TenantID: 10005}},
|
||||
)
|
||||
|
||||
req := orgSharedKBFileRequest()
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusForbidden {
|
||||
t.Fatalf("status=%d, want %d", recorder.Code, http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageScopedFilesOrgSharedKBRequiresChunkEvidence(t *testing.T) {
|
||||
// The message's references do not contain the requested handle: a
|
||||
// resource from the owner tenant cannot ride along on an unrelated
|
||||
// shared KB.
|
||||
engine, _ := newOrgSharedKBTestEngine(t, true,
|
||||
types.References{{
|
||||
KnowledgeID: "knowledge-1",
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Content: "Figure 1 ",
|
||||
}},
|
||||
[]*types.KnowledgeBase{{ID: "kb-1", TenantID: 10005}},
|
||||
)
|
||||
|
||||
req := orgSharedKBFileRequest()
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusForbidden {
|
||||
t.Fatalf("status=%d, want %d (no chunk evidence)", recorder.Code, http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageScopedFilesOrgSharedKBRequiresResourceTenantMatch(t *testing.T) {
|
||||
// The referenced KB belongs to a third tenant, so the resource owner and
|
||||
// the shared KB must not be conflated.
|
||||
engine, _ := newOrgSharedKBTestEngine(t, true,
|
||||
types.References{{
|
||||
KnowledgeID: "knowledge-1",
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Content: "Figure 1 ",
|
||||
}},
|
||||
[]*types.KnowledgeBase{{ID: "kb-1", TenantID: 99999}},
|
||||
)
|
||||
|
||||
req := orgSharedKBFileRequest()
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusForbidden {
|
||||
t.Fatalf("status=%d, want %d (tenant mismatch)", recorder.Code, http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageScopedFilesServesLegacyMessageViaOrgSharedKB(t *testing.T) {
|
||||
// Messages written before agent_tenant_id was populated record no source
|
||||
// tenant; the org-shared KB evidence still authorizes the resource.
|
||||
gin.SetMode(gin.TestMode)
|
||||
t.Setenv("STORAGE_TYPE", "local")
|
||||
|
||||
const (
|
||||
callerTenantID = uint64(10006)
|
||||
ownerTenantID = uint64(10005)
|
||||
)
|
||||
engine := newMessageScopedFilesTestEngine(
|
||||
callerTenantID,
|
||||
&stubMessageFileLookup{get: func(context.Context, string, string) (*types.Message, error) {
|
||||
return &types.Message{
|
||||
KnowledgeReferences: types.References{{
|
||||
KnowledgeID: "knowledge-1",
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Content: "",
|
||||
}},
|
||||
}, nil
|
||||
}},
|
||||
&stubSharedAgentFileLookup{get: func(
|
||||
context.Context, uint64, types.TenantRole, string, ...uint64,
|
||||
) (*types.CustomAgent, error) {
|
||||
t.Fatal("shared-agent lookup must not run when the org-shared KB fallback applies")
|
||||
return nil, nil
|
||||
}},
|
||||
&stubTenantService{get: func(_ context.Context, id uint64) (*types.Tenant, error) {
|
||||
return &types.Tenant{ID: id}, nil
|
||||
}},
|
||||
&stubFileService{getFile: func(_ context.Context, _ string) (io.ReadCloser, error) {
|
||||
return io.NopCloser(strings.NewReader("legacy-shared-kb-image")), nil
|
||||
}},
|
||||
&stubResourceCatalog{resource: &types.StoredResource{
|
||||
Handle: "ShArEdKbHaNdLe00000000",
|
||||
TenantID: ownerTenantID,
|
||||
PhysicalPath: "local://10005/images/quadrant.jpg",
|
||||
MimeType: "image/jpeg",
|
||||
}},
|
||||
messageKBShareAuthorizer{
|
||||
ShareGuard: &stubKBShareGuard{hasPermission: func(
|
||||
context.Context, string, uint64, types.TenantRole, types.OrgMemberRole,
|
||||
) (bool, error) {
|
||||
return true, nil
|
||||
}},
|
||||
KBs: &stubKBTenantLookup{kbs: []*types.KnowledgeBase{{ID: "kb-1", TenantID: 10005}}},
|
||||
},
|
||||
)
|
||||
|
||||
req := orgSharedKBFileRequest()
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusOK || recorder.Body.String() != "legacy-shared-kb-image" {
|
||||
t.Fatalf("status=%d body=%q", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageScopedFilesOrgSharedKBResolvesKnowledgeOwner(t *testing.T) {
|
||||
// Older references predate the denormalized knowledge_base_id field; the
|
||||
// fallback still resolves their KB through the knowledge entry.
|
||||
gin.SetMode(gin.TestMode)
|
||||
t.Setenv("STORAGE_TYPE", "local")
|
||||
|
||||
const callerTenantID = uint64(10006)
|
||||
engine := newMessageScopedFilesTestEngine(
|
||||
callerTenantID,
|
||||
&stubMessageFileLookup{get: func(context.Context, string, string) (*types.Message, error) {
|
||||
return &types.Message{
|
||||
AgentID: "own-agent-1",
|
||||
AgentTenantID: callerTenantID,
|
||||
KnowledgeReferences: types.References{{
|
||||
KnowledgeID: "knowledge-1",
|
||||
Content: "",
|
||||
}},
|
||||
}, nil
|
||||
}},
|
||||
&stubSharedAgentFileLookup{get: func(
|
||||
context.Context, uint64, types.TenantRole, string, ...uint64,
|
||||
) (*types.CustomAgent, error) {
|
||||
t.Fatal("shared-agent lookup must not run for the org-shared KB fallback")
|
||||
return nil, nil
|
||||
}},
|
||||
&stubTenantService{get: func(_ context.Context, id uint64) (*types.Tenant, error) {
|
||||
return &types.Tenant{ID: id}, nil
|
||||
}},
|
||||
&stubFileService{getFile: func(_ context.Context, _ string) (io.ReadCloser, error) {
|
||||
return io.NopCloser(strings.NewReader("resolved-kb-image")), nil
|
||||
}},
|
||||
&stubResourceCatalog{resource: &types.StoredResource{
|
||||
Handle: "ShArEdKbHaNdLe00000000",
|
||||
TenantID: 10005,
|
||||
PhysicalPath: "local://10005/images/quadrant.jpg",
|
||||
MimeType: "image/jpeg",
|
||||
}},
|
||||
messageKBShareAuthorizer{
|
||||
ShareGuard: &stubKBShareGuard{hasPermission: func(
|
||||
context.Context, string, uint64, types.TenantRole, types.OrgMemberRole,
|
||||
) (bool, error) {
|
||||
return true, nil
|
||||
}},
|
||||
KBs: &stubKBTenantLookup{kbs: []*types.KnowledgeBase{{ID: "kb-1", TenantID: 10005}}},
|
||||
Knowledges: &stubKnowledgeOwnerLookup{byID: map[string]*types.Knowledge{
|
||||
"knowledge-1": {ID: "knowledge-1", KnowledgeBaseID: "kb-1"},
|
||||
}},
|
||||
},
|
||||
)
|
||||
|
||||
req := orgSharedKBFileRequest()
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusOK || recorder.Body.String() != "resolved-kb-image" {
|
||||
t.Fatalf("status=%d body=%q", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageScopedFilesOrgSharedKBAcceptsImageInfoEvidence(t *testing.T) {
|
||||
engine, requestedPath := newOrgSharedKBTestEngine(t, true,
|
||||
types.References{{
|
||||
KnowledgeID: "knowledge-1",
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Content: "scanned page OCR without markdown images",
|
||||
ImageInfo: `[{"url":"resource://ShArEdKbHaNdLe00000000","ocr_text":"quadrant"}]`,
|
||||
}},
|
||||
[]*types.KnowledgeBase{{ID: "kb-1", TenantID: 10005}},
|
||||
)
|
||||
|
||||
req := orgSharedKBFileRequest()
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusOK || recorder.Body.String() != "shared-kb-image" {
|
||||
t.Fatalf("status=%d body=%q", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if *requestedPath != "local://10005/images/quadrant.jpg" {
|
||||
t.Fatalf("requested path = %q", *requestedPath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageScopedFilesOrgSharedKBRejectsHandlePrefix(t *testing.T) {
|
||||
engine, _ := newOrgSharedKBTestEngine(t, true,
|
||||
types.References{{
|
||||
KnowledgeID: "knowledge-1",
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Content: "",
|
||||
}},
|
||||
[]*types.KnowledgeBase{{ID: "kb-1", TenantID: 10005}},
|
||||
)
|
||||
|
||||
req := orgSharedKBFileRequest()
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusForbidden {
|
||||
t.Fatalf("status=%d, want %d (prefix is not a canonical handle)", recorder.Code, http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageScopedFilesServesOrgSharedKBResourceFromAgentSteps(t *testing.T) {
|
||||
engine, requestedPath := newOrgSharedKBTestEngineFromMessage(t, true,
|
||||
&types.Message{
|
||||
AgentID: "own-agent-1",
|
||||
AgentTenantID: 10006,
|
||||
AgentSteps: types.AgentSteps{{
|
||||
ToolCalls: []types.ToolCall{{
|
||||
Name: "knowledge_search",
|
||||
Result: &types.ToolResult{
|
||||
Success: true,
|
||||
Data: map[string]interface{}{
|
||||
"display_type": "search_results",
|
||||
"results": []map[string]interface{}{{
|
||||
"content": "ocr text only",
|
||||
"knowledge_base_id": "kb-1",
|
||||
"images": []map[string]interface{}{{
|
||||
"url": "resource://ShArEdKbHaNdLe00000000",
|
||||
}},
|
||||
}},
|
||||
},
|
||||
},
|
||||
}},
|
||||
}},
|
||||
},
|
||||
[]*types.KnowledgeBase{{ID: "kb-1", TenantID: 10005}},
|
||||
)
|
||||
|
||||
req := orgSharedKBFileRequest()
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusOK || recorder.Body.String() != "shared-kb-image" {
|
||||
t.Fatalf("status=%d body=%q", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if *requestedPath != "local://10005/images/quadrant.jpg" {
|
||||
t.Fatalf("requested path = %q", *requestedPath)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageScopedFilesOrgSharedKBFailsClosedOnShareError(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
t.Setenv("STORAGE_TYPE", "local")
|
||||
|
||||
engine := newMessageScopedFilesTestEngine(
|
||||
10006,
|
||||
&stubMessageFileLookup{get: func(context.Context, string, string) (*types.Message, error) {
|
||||
return &types.Message{
|
||||
AgentID: "own-agent-1",
|
||||
AgentTenantID: 10006,
|
||||
KnowledgeReferences: types.References{{
|
||||
KnowledgeBaseID: "kb-1",
|
||||
Content: "",
|
||||
}},
|
||||
}, nil
|
||||
}},
|
||||
&stubSharedAgentFileLookup{get: func(
|
||||
context.Context, uint64, types.TenantRole, string, ...uint64,
|
||||
) (*types.CustomAgent, error) {
|
||||
t.Fatal("shared-agent lookup must not run when the org-shared KB fallback fails closed")
|
||||
return nil, nil
|
||||
}},
|
||||
&stubTenantService{get: func(context.Context, uint64) (*types.Tenant, error) {
|
||||
t.Fatal("tenant lookup should not run after share lookup error")
|
||||
return nil, nil
|
||||
}},
|
||||
&stubFileService{getFile: func(context.Context, string) (io.ReadCloser, error) {
|
||||
t.Fatal("GetFile should not run after share lookup error")
|
||||
return nil, nil
|
||||
}},
|
||||
&stubResourceCatalog{resource: &types.StoredResource{
|
||||
Handle: "ShArEdKbHaNdLe00000000",
|
||||
TenantID: 10005,
|
||||
PhysicalPath: "local://10005/images/quadrant.jpg",
|
||||
MimeType: "image/jpeg",
|
||||
}},
|
||||
messageKBShareAuthorizer{
|
||||
ShareGuard: &stubKBShareGuard{hasPermission: func(
|
||||
context.Context, string, uint64, types.TenantRole, types.OrgMemberRole,
|
||||
) (bool, error) {
|
||||
return false, io.ErrUnexpectedEOF
|
||||
}},
|
||||
KBs: &stubKBTenantLookup{kbs: []*types.KnowledgeBase{{ID: "kb-1", TenantID: 10005}}},
|
||||
},
|
||||
)
|
||||
|
||||
req := orgSharedKBFileRequest()
|
||||
recorder := httptest.NewRecorder()
|
||||
engine.ServeHTTP(recorder, req)
|
||||
|
||||
if recorder.Code != http.StatusForbidden {
|
||||
t.Fatalf("status=%d, want %d", recorder.Code, http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServeFilesForcesActiveContentDownload(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
t.Setenv("STORAGE_TYPE", "local")
|
||||
|
|
|
|||
Loading…
Reference in New Issue