fix(knowledge): bind extracted images to their document and unscope shared-KB parent lookups

Org-shared KB viewers got 403 for extracted images on current main even
though the retrieving chunk text carried the resource:// handle and the
share grant was valid (#3342, second report after #3022/#3069).

Root cause is a mismatch between ingestion and authorization: document
parses store extracted images through SaveBytes, which registers the
resource but never claims it, while both file proxies (ResolveKBFile and
the message fallback via resourceAccessibleViaSharedKB) authorize through
IsReferencedByKnowledgeBase — which accepts explicit resource_bindings
rows only. The binding-only hardening landed without adding the missing
bindings, so every extracted image became invisible cross-workspace.

Ingestion: bindStoredImages claims each stored image for its knowledge
(ResourceRelationExtractedImage), mirroring bindContentResources — best
effort, same-workspace resources only. Wired into both the file-parse
path (knowledge_process) and manual knowledge (triggerManualProcessing).

Merge: resolveParentChunks fetched parents, grandparents, and image_info
children with the caller's tenant, so shared-KB hits from the sharing
workspace resolved none of them and lost parent context and image_info
(the second defect in the #3342 audit). Those lookups now use the
existing *Only unscoped variants, matching their shared-KB precedent.

Historical documents parsed before this change still carry no bindings;
a backfill is tracked as the follow-up slice.

Verified end-to-end on a fresh stack: publishing a manual document with
an embedded image now records kind=image plus an extracted_image binding
alongside the content-derived attachment binding.
main
vicfei 2026-09-21 09:57:17 +08:00 committed by lyingbug
parent 3a8ce97c29
commit 2dd36212d6
9 changed files with 322 additions and 18 deletions

View File

@ -376,6 +376,24 @@ func (r *chunkRepository) ListChunksByParentIDs(
return chunks, nil
}
// ListChunksByParentIDsOnly retrieves chunks by parent IDs without tenant
// filter, for expansions whose parent IDs come from org-shared KB retrieval
// results owned by another workspace (#3342).
func (r *chunkRepository) ListChunksByParentIDsOnly(
ctx context.Context, parentIDs []string,
) ([]*types.Chunk, error) {
if len(parentIDs) == 0 {
return nil, nil
}
var chunks []*types.Chunk
if err := r.db.WithContext(ctx).
Where("parent_chunk_id IN ?", parentIDs).
Find(&chunks).Error; err != nil {
return nil, err
}
return chunks, nil
}
// UpdateChunk updates a chunk using GORM Save, which updates ALL fields
// except SeqID (auto-increment, must not be overwritten).
// Make sure the chunk object is complete (e.g., fetched from DB) before calling this method.

View File

@ -224,17 +224,6 @@ func (p *PluginMerge) resolveParentChunks(
return results
}
tenantID, _ := types.TenantIDFromContext(ctx)
if tenantID == 0 && chatManage != nil {
tenantID = chatManage.TenantID
}
if tenantID == 0 {
pipelineWarn(ctx, "Merge", "parent_resolve_skip", map[string]interface{}{
"reason": "missing_tenant",
})
return results
}
// Collect unique parent chunk IDs
parentIDs := make(map[string]struct{})
for _, r := range results {
@ -247,12 +236,17 @@ func (p *PluginMerge) resolveParentChunks(
return results
}
// Batch fetch parent chunks
// Batch fetch parent chunks. The lookup is intentionally not tenant
// scoped: retrieval results can come from an org-shared KB whose chunks
// belong to the sharing workspace, and a caller-tenant filter made every
// parent (and the image_info enrichment that hangs off it) invisible for
// shared hits (#3342). The IDs come from retrieval results, not client
// input, matching ListChunksByIDOnly's existing shared-KB usage.
ids := make([]string, 0, len(parentIDs))
for id := range parentIDs {
ids = append(ids, id)
}
parentChunks, err := p.chunkRepo.ListChunksByID(ctx, tenantID, ids)
parentChunks, err := p.chunkRepo.ListChunksByIDOnly(ctx, ids)
if err != nil {
pipelineWarn(ctx, "Merge", "parent_resolve_failed", map[string]interface{}{
"error": err.Error(),
@ -294,7 +288,7 @@ func (p *PluginMerge) resolveParentChunks(
grandparentIDs = append(grandparentIDs, parent.ParentChunkID)
}
if len(grandparentIDs) > 0 {
grandparents, fetchErr := p.chunkRepo.ListChunksByID(ctx, tenantID, grandparentIDs)
grandparents, fetchErr := p.chunkRepo.ListChunksByIDOnly(ctx, grandparentIDs)
if fetchErr != nil {
pipelineWarn(ctx, "Merge", "grandparent_fetch_failed", map[string]interface{}{
"error": fetchErr.Error(),
@ -307,11 +301,12 @@ func (p *PluginMerge) resolveParentChunks(
}
}
// Batch-fetch image_info scoped to matched text children only.
// Batch-fetch image_info scoped to matched text children only. Not
// tenant scoped, for the same shared-KB reason as the parent fetch above.
textChildIDs := collectScopedTextChildIDs(results, parentMap)
var scopedImageInfo map[string]string
if len(textChildIDs) > 0 {
scopedImageInfo = searchutil.CollectImageInfoByChunkIDs(ctx, p.chunkRepo, tenantID, textChildIDs)
scopedImageInfo = searchutil.CollectImageInfoByChunkIDsOnly(ctx, p.chunkRepo, textChildIDs)
}
for _, r := range results {

View File

@ -37,6 +37,28 @@ func (r *expandChunkRepo) ListChunksByID(
return chunks, nil
}
func (r *expandChunkRepo) ListChunksByIDOnly(
_ context.Context, ids []string,
) ([]*types.Chunk, error) {
chunks := make([]*types.Chunk, 0, len(ids))
for _, id := range ids {
if chunk := r.chunks[id]; chunk != nil {
chunks = append(chunks, chunk)
}
}
return chunks, nil
}
func (r *expandChunkRepo) ListChunksByParentIDsOnly(
_ context.Context, parentIDs []string,
) ([]*types.Chunk, error) {
var chunks []*types.Chunk
for _, parentID := range parentIDs {
chunks = append(chunks, r.children[parentID]...)
}
return chunks, nil
}
func TestExpandShortContextKeepsSourceCoordinates(t *testing.T) {
repo := &expandChunkRepo{chunks: map[string]*types.Chunk{
"prev": {ID: "prev", KnowledgeID: "doc", ChunkType: types.ChunkTypeText, Content: "edited previous body", NextChunkID: "base"},

View File

@ -0,0 +1,91 @@
package chatpipeline
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
// tenantScopedChunkRepo makes the tenant-scoped lookups behave like the SQL
// repository (WHERE tenant_id = ?), while the *Only lookups stay unscoped.
// With the pre-#3342 code every parent fetch went through the scoped variant,
// so shared-KB parents (owned by the sharing workspace) never resolved.
type tenantScopedChunkRepo struct {
*expandChunkRepo
}
func filterByTenant(chunks []*types.Chunk, tenantID uint64) []*types.Chunk {
out := make([]*types.Chunk, 0, len(chunks))
for _, chunk := range chunks {
if chunk.TenantID == tenantID {
out = append(out, chunk)
}
}
return out
}
func (r *tenantScopedChunkRepo) ListChunksByID(
ctx context.Context, tenantID uint64, ids []string,
) ([]*types.Chunk, error) {
all, err := r.expandChunkRepo.ListChunksByID(ctx, tenantID, ids)
if err != nil {
return nil, err
}
return filterByTenant(all, tenantID), nil
}
func (r *tenantScopedChunkRepo) ListChunksByParentIDs(
ctx context.Context, tenantID uint64, parentIDs []string,
) ([]*types.Chunk, error) {
all, err := r.expandChunkRepo.ListChunksByParentIDs(ctx, tenantID, parentIDs)
if err != nil {
return nil, err
}
return filterByTenant(all, tenantID), nil
}
// TestResolveParentChunksResolvesSharedKBParentsAcrossTenants pins the merge
// half of #3342: retrieval hits from an org-shared KB belong to the sharing
// workspace, and the caller-tenant filter made both the parent_text context
// and the image_info enrichment invisible for those hits.
func TestResolveParentChunksResolvesSharedKBParentsAcrossTenants(t *testing.T) {
imageInfo, err := json.Marshal([]types.ImageInfo{{URL: "resource://sharedImage", OCRText: "shared image text"}})
if err != nil {
t.Fatal(err)
}
// All chunks belong to workspace 2; the caller is workspace 1.
repo := &tenantScopedChunkRepo{expandChunkRepo: &expandChunkRepo{
chunks: map[string]*types.Chunk{
"parent": {ID: "parent", TenantID: 2, ChunkType: types.ChunkTypeParentText,
Content: "shared parent body with ![img](resource://sharedImage)"},
"child": {ID: "child", TenantID: 2, ChunkType: types.ChunkTypeText,
ParentChunkID: "parent", Content: "shared child body"},
},
children: map[string][]*types.Chunk{
"child": {
{ID: "imageChild", TenantID: 2, ParentChunkID: "child",
ChunkType: types.ChunkTypeImageOCR, ImageInfo: string(imageInfo), IsEnabled: true},
},
},
}}
plugin := &PluginMerge{chunkRepo: repo}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
result := &types.SearchResult{
ID: "child", KnowledgeID: "doc", ChunkType: string(types.ChunkTypeText),
ParentChunkID: "parent", Content: "shared child body",
}
got := plugin.resolveParentChunks(ctx, &types.ChatManage{}, []*types.SearchResult{result})
if len(got) != 1 {
t.Fatalf("result count = %d, want 1", len(got))
}
if !strings.Contains(got[0].Content, "shared parent body") {
t.Fatalf("cross-tenant parent content was not resolved: %q", got[0].Content)
}
if !strings.Contains(got[0].ImageInfo, "resource://sharedImage") {
t.Fatalf("cross-tenant image_info was not enriched: %q", got[0].ImageInfo)
}
}

View File

@ -0,0 +1,99 @@
package service
import (
"context"
"fmt"
"testing"
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// fakeBindCatalog records Bind calls and simulates the parts of the resource
// catalog bindStoredImages depends on. The interface is embedded so unrelated
// methods never run.
type fakeBindCatalog struct {
interfaces.ResourceCatalog
resources map[string]*types.StoredResource
bindErr map[string]error
binds []string // "ref|ownerType|ownerID|relation"
}
func (f *fakeBindCatalog) Resolve(_ context.Context, reference string) (*types.StoredResource, error) {
resource, ok := f.resources[reference]
if !ok {
return nil, fmt.Errorf("resource not found: %s", reference)
}
return resource, nil
}
func (f *fakeBindCatalog) Bind(_ context.Context, reference, ownerType, ownerID, relation string) error {
if err, ok := f.bindErr[reference]; ok {
return err
}
f.binds = append(f.binds, reference+"|"+ownerType+"|"+ownerID+"|"+relation)
return nil
}
// TestBindStoredImagesClaimsExtractedImagesForTheDocument pins the ingestion
// half of #3342: extracted images are registered as resources but were never
// claimed, and the file proxies authorize through exactly those claims.
func TestBindStoredImagesClaimsExtractedImagesForTheDocument(t *testing.T) {
catalog := &fakeBindCatalog{
resources: map[string]*types.StoredResource{
"resource://ownImage": {ID: "r1", TenantID: 7},
"resource://secondOwnImage": {ID: "r2", TenantID: 7},
"resource://foreignImage": {ID: "r3", TenantID: 99},
"resource://bindFailsImage": {ID: "r4", TenantID: 7},
"local://images/physicalRef": {ID: "r5", TenantID: 7},
},
bindErr: map[string]error{
"resource://bindFailsImage": fmt.Errorf("boom"),
},
}
s := &knowledgeService{resourceCatalog: catalog}
knowledge := &types.Knowledge{ID: "doc-1", TenantID: 7}
s.bindStoredImages(context.Background(), knowledge, []docparser.StoredImage{
{ServingURL: "resource://ownImage"},
{ServingURL: "resource://secondOwnImage"},
{ServingURL: " "}, // blank ref is skipped
{ServingURL: "resource://unknownImage"}, // unresolvable is skipped
{ServingURL: "resource://foreignImage"}, // cross-workspace is skipped
{ServingURL: "resource://bindFailsImage"}, // bind error does not abort the loop
{ServingURL: "local://images/physicalRef"}, // provider:// refs resolve and bind too
})
want := []string{
"resource://ownImage|knowledge|doc-1|extracted_image",
"resource://secondOwnImage|knowledge|doc-1|extracted_image",
"local://images/physicalRef|knowledge|doc-1|extracted_image",
}
if len(catalog.binds) != len(want) {
t.Fatalf("binds = %v, want exactly %v", catalog.binds, want)
}
for i := range want {
if catalog.binds[i] != want[i] {
t.Errorf("bind[%d] = %q, want %q", i, catalog.binds[i], want[i])
}
}
}
// TestBindStoredImagesNilCatalogAndEmptyInputs guards the no-op paths: a
// deployment without the resource catalog, or a parse without images, must
// not panic or log noise.
func TestBindStoredImagesNilCatalogAndEmptyInputs(t *testing.T) {
s := &knowledgeService{}
s.bindStoredImages(context.Background(), &types.Knowledge{ID: "d", TenantID: 1}, []docparser.StoredImage{
{ServingURL: "resource://x"},
})
catalog := &fakeBindCatalog{resources: map[string]*types.StoredResource{}}
s2 := &knowledgeService{resourceCatalog: catalog}
s2.bindStoredImages(context.Background(), &types.Knowledge{ID: "d", TenantID: 1}, nil)
s2.bindStoredImages(context.Background(), nil, []docparser.StoredImage{{ServingURL: "resource://x"}})
if len(catalog.binds) != 0 {
t.Fatalf("binds = %v, want none", catalog.binds)
}
}

View File

@ -1234,6 +1234,49 @@ func (s *knowledgeService) bindContentResources(
}
}
// bindStoredImages claims the images a document parse extracted and stored,
// so file authorization can later prove which knowledge owns each image. The
// KB- and message-scoped file proxies only serve resources with a live
// binding (#3342): an extracted image without one stays invisible to
// cross-workspace viewers no matter what the retrieving chunk text says.
//
// Best-effort by design, mirroring bindContentResources: a parse is expensive
// to redo, and a missed claim degrades to same-workspace rendering instead of
// failing the document.
func (s *knowledgeService) bindStoredImages(
ctx context.Context, knowledge *types.Knowledge, images []docparser.StoredImage,
) {
if s.resourceCatalog == nil || knowledge == nil || len(images) == 0 {
return
}
bound := 0
for _, img := range images {
ref := strings.TrimSpace(img.ServingURL)
if ref == "" {
continue
}
resource, err := s.resourceCatalog.Resolve(ctx, ref)
if err != nil || resource == nil {
logger.Warnf(ctx, "Skip binding unknown stored image %s to knowledge %s: %v", ref, knowledge.ID, err)
continue
}
if resource.TenantID != knowledge.TenantID {
logger.Warnf(ctx, "Skip binding cross-workspace stored image %s to knowledge %s", ref, knowledge.ID)
continue
}
if err := s.resourceCatalog.Bind(
ctx, ref, types.ResourceOwnerKnowledge, knowledge.ID, types.ResourceRelationExtractedImage,
); err != nil {
logger.Warnf(ctx, "Failed to bind stored image %s to knowledge %s: %v", ref, knowledge.ID, err)
continue
}
bound++
}
if bound > 0 {
logger.Infof(ctx, "Bound %d/%d stored images to knowledge %s", bound, len(images), knowledge.ID)
}
}
func (s *knowledgeService) triggerManualProcessing(ctx context.Context,
kb *types.KnowledgeBase, knowledge *types.Knowledge, content string, doSync bool,
) {
@ -1268,6 +1311,10 @@ func (s *knowledgeService) triggerManualProcessing(ctx context.Context,
// released the previous run's claims, so a republished document keeps the
// files its new body still references.
s.bindContentResources(ctx, knowledge.TenantID, knowledge.ID, clean)
// bindContentResources only sees resource:// handles in the final text;
// freshly resolved images may still carry provider:// URLs, so claim them
// from the resolver's own list as well.
s.bindStoredImages(ctx, knowledge, resolvedImages)
// Keep manually entered CRLF text aligned with the LF values sent by the
// chunking preview endpoint.

View File

@ -3778,6 +3778,11 @@ func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) e
logger.Infof(ctx, "Resolved %d total images for knowledge %s", len(storedImages), knowledge.ID)
}
// Claim the stored images for this document before chunking proceeds:
// the file proxies authorize images through resource bindings, and an
// unbound extracted image renders broken for org-shared KB viewers (#3342).
s.bindStoredImages(ctx, knowledge, storedImages)
// Step 3: Split into chunks using Go chunker. Line endings and inline
// HTML tables were normalized before image resolution above.
chunkCfg := buildSplitterConfigFromChunking(eff.ChunkingConfig)

View File

@ -57,12 +57,36 @@ func CollectImageInfoByChunkIDs(
chunkRepo interfaces.ChunkRepository,
tenantID uint64,
chunkIDs []string,
) map[string]string {
return collectImageInfoByChunkIDs(ctx, chunkIDs, func(parentIDs []string) ([]*types.Chunk, error) {
return chunkRepo.ListChunksByParentIDs(ctx, tenantID, parentIDs)
})
}
// CollectImageInfoByChunkIDsOnly is the shared-KB variant of
// CollectImageInfoByChunkIDs: the chunk IDs can belong to an org-shared KB
// owned by another workspace, so the child lookup must not filter by the
// caller's tenant (#3342).
func CollectImageInfoByChunkIDsOnly(
ctx context.Context,
chunkRepo interfaces.ChunkRepository,
chunkIDs []string,
) map[string]string {
return collectImageInfoByChunkIDs(ctx, chunkIDs, func(parentIDs []string) ([]*types.Chunk, error) {
return chunkRepo.ListChunksByParentIDsOnly(ctx, parentIDs)
})
}
func collectImageInfoByChunkIDs(
ctx context.Context,
chunkIDs []string,
listChildren func(parentIDs []string) ([]*types.Chunk, error),
) map[string]string {
if len(chunkIDs) == 0 {
return nil
}
children, err := chunkRepo.ListChunksByParentIDs(ctx, tenantID, chunkIDs)
children, err := listChildren(chunkIDs)
if err != nil || len(children) == 0 {
return nil
}
@ -125,7 +149,7 @@ func CollectImageInfoByChunkIDs(
}
if len(textChildIDs) > 0 {
grandChildren, err := chunkRepo.ListChunksByParentIDs(ctx, tenantID, textChildIDs)
grandChildren, err := listChildren(textChildIDs)
if err == nil {
for _, gc := range grandChildren {
if !gc.IsEnabled {

View File

@ -80,6 +80,9 @@ type ChunkRepository interface {
) ([]*types.Chunk, error)
// ListChunksByParentIDs lists chunks whose parent_chunk_id is in the given list
ListChunksByParentIDs(ctx context.Context, tenantID uint64, parentIDs []string) ([]*types.Chunk, error)
// ListChunksByParentIDsOnly lists chunks by parent IDs without tenant filter
// (for shared KB resolution).
ListChunksByParentIDsOnly(ctx context.Context, parentIDs []string) ([]*types.Chunk, error)
// UpdateChunk updates a chunk
UpdateChunk(ctx context.Context, chunk *types.Chunk) error
// CreateChunkRevision stores an immutable snapshot of a superseded revision.