Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

46.0 KB
Raw Blame
package router

import (
	"context"
	"io"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"
	"time"

	"github.com/Tencent/WeKnora/internal/middleware"
	"github.com/Tencent/WeKnora/internal/types"
	"github.com/Tencent/WeKnora/internal/types/interfaces"
	"github.com/gin-gonic/gin"
)

var _ interfaces.FileService = (*stubFileService)(nil)

type stubFileService struct {
	getFile func(ctx context.Context, filePath string) (io.ReadCloser, error)
}

type stubResourceCatalog struct {
	resource     *types.StoredResource
	fileBindings *types.MessageFileBindings
	bound        func(context.Context, uint64, string, string) (bool, error)
}

type stubMessageFileLookup struct {
	get func(ctx context.Context, sessionID, messageID string) (*types.Message, error)
}

func (s *stubMessageFileLookup) GetMessage(
	ctx context.Context,
	sessionID, messageID string,
) (*types.Message, error) {
	return s.get(ctx, sessionID, messageID)
}

type stubSharedAgentFileLookup struct {
	get func(
		ctx context.Context,
		tenantID uint64,
		callerTenantRole types.TenantRole,
		agentID string,
		sourceTenantID ...uint64,
	) (*types.CustomAgent, error)
}

func (s *stubSharedAgentFileLookup) GetSharedAgentForTenant(
	ctx context.Context,
	tenantID uint64,
	callerTenantRole types.TenantRole,
	agentID string,
	sourceTenantID ...uint64,
) (*types.CustomAgent, error) {
	return s.get(ctx, tenantID, callerTenantRole, agentID, sourceTenantID...)
}

func (s *stubResourceCatalog) IsReferencedByKnowledgeBase(
	ctx context.Context,
	tenant uint64,
	kb, ref string,
) (bool, error) {
	if s.bound == nil {
		return false, nil
	}
	return s.bound(ctx, tenant, kb, ref)
}

func (s *stubResourceCatalog) Register(
	context.Context,
	uint64,
	string,
	interfaces.ResourceRegistration,
) (string, error) {
	panic("unexpected Register")
}

// ReuseByContentHash stays a miss: these handlers serve existing references and
// never reach the payload-sharing path.
func (s *stubResourceCatalog) ReuseByContentHash(context.Context, uint64, string) (string, bool, error) {
	return "", false, nil
}

func (s *stubResourceCatalog) Resolve(context.Context, string) (*types.StoredResource, error) {
	return s.resource, nil
}

func (s *stubResourceCatalog) ResolvePath(_ context.Context, value string) (string, *types.StoredResource, error) {
	if _, ok := types.ParseResourcePath(value); ok && s.resource != nil {
		return s.resource.PhysicalPath, s.resource, nil
	}
	return value, nil, nil
}

func (s *stubResourceCatalog) Bind(context.Context, string, string, string, string) error {
	panic("unexpected Bind")
}

func (s *stubResourceCatalog) Release(context.Context, string, string, string) (int64, error) {
	panic("unexpected Release")
}

func (s *stubResourceCatalog) ListReferencesByOwner(context.Context, string, ...string) ([]string, error) {
	return nil, nil
}

func (s *stubResourceCatalog) MarkDeleted(context.Context, string) error {
	panic("unexpected MarkDeleted")
}

func (s *stubResourceCatalog) CreateAccessGrant(context.Context, string, time.Duration) (string, error) {
	panic("unexpected CreateAccessGrant")
}

func (s *stubResourceCatalog) ResolveAccessGrant(context.Context, string) (*types.StoredResource, error) {
	return s.resource, nil
}

func (s *stubFileService) CheckConnectivity(ctx context.Context) error {
	return nil
}

func (s *stubFileService) SaveFile(ctx context.Context, file *multipart.FileHeader, tenantID uint64, knowledgeID string) (string, error) {
	panic("unexpected call to SaveFile")
}

func (s *stubFileService) SaveBytes(ctx context.Context, data []byte, tenantID uint64, fileName string, temp bool) (string, error) {
	panic("unexpected call to SaveBytes")
}

func (s *stubFileService) GetFile(ctx context.Context, filePath string) (io.ReadCloser, error) {
	if s.getFile == nil {
		panic("unexpected call to GetFile")
	}
	return s.getFile(ctx, filePath)
}

func (s *stubFileService) GetFileURL(ctx context.Context, filePath string) (string, error) {
	panic("unexpected call to GetFileURL")
}

func (s *stubFileService) DeleteFile(ctx context.Context, filePath string) error {
	panic("unexpected call to DeleteFile")
}

func (s *stubFileService) CopyFile(ctx context.Context, srcPath string, tenantID uint64, knowledgeID string) (string, error) {
	panic("unexpected call to CopyFile")
}

func TestServeFilesFallsBackToGlobalFileService(t *testing.T) {
	gin.SetMode(gin.TestMode)
	t.Setenv("STORAGE_TYPE", "local")

	engine := gin.New()
	var requestedPath string
	serveFiles(engine, &stubFileService{
		getFile: func(ctx context.Context, filePath string) (io.ReadCloser, error) {
			requestedPath = filePath
			return io.NopCloser(strings.NewReader("fallback-body")), nil
		},
	})

	filePath := "local://42/docs/example.txt"
	req := httptest.NewRequest(http.MethodGet, "/files?file_path="+url.QueryEscape(filePath), nil)
	req = req.WithContext(context.WithValue(req.Context(), types.TenantInfoContextKey, &types.Tenant{ID: 42}))

	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if got, want := recorder.Code, http.StatusOK; got != want {
		t.Fatalf("status = %d, want %d", got, want)
	}
	if requestedPath != filePath {
		t.Fatalf("requested path = %q, want %q", requestedPath, filePath)
	}
	if body := recorder.Body.String(); body != "fallback-body" {
		t.Fatalf("body = %q, want %q", body, "fallback-body")
	}
}

func TestServeFilesResolvesShortResourceReference(t *testing.T) {
	gin.SetMode(gin.TestMode)
	t.Setenv("STORAGE_TYPE", "local")
	const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
	const physical = "local://42/exports/a.png"

	engine := gin.New()
	var requestedPath string
	serveFilesWithResources(engine, &stubFileService{getFile: func(_ context.Context, path string) (io.ReadCloser, error) {
		requestedPath = path
		return io.NopCloser(strings.NewReader("image")), nil
	}}, nil, &stubResourceCatalog{resource: &types.StoredResource{TenantID: 42, PhysicalPath: physical}})

	req := httptest.NewRequest(http.MethodGet, "/files?file_path="+url.QueryEscape(ref), nil)
	req = req.WithContext(context.WithValue(req.Context(), types.TenantInfoContextKey, &types.Tenant{ID: 42}))
	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if recorder.Code != http.StatusOK {
		t.Fatalf("status = %d, body=%s", recorder.Code, recorder.Body.String())
	}
	if requestedPath != physical {
		t.Fatalf("requested path = %q, want %q", requestedPath, physical)
	}
}

func TestServeFilesRejectsCrossTenantResourceReference(t *testing.T) {
	gin.SetMode(gin.TestMode)
	const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
	engine := gin.New()
	serveFilesWithResources(engine, &stubFileService{getFile: func(context.Context, string) (io.ReadCloser, error) {
		t.Fatal("GetFile should not be called")
		return nil, nil
	}}, nil, &stubResourceCatalog{resource: &types.StoredResource{TenantID: 7, PhysicalPath: "local://7/exports/a.png"}})

	req := httptest.NewRequest(http.MethodGet, "/files?file_path="+url.QueryEscape(ref), nil)
	req = req.WithContext(context.WithValue(req.Context(), types.TenantInfoContextKey, &types.Tenant{ID: 42}))
	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if recorder.Code != http.StatusForbidden {
		t.Fatalf("status = %d, want %d", recorder.Code, http.StatusForbidden)
	}
}

func TestResourceGrantServesShortPublicURL(t *testing.T) {
	gin.SetMode(gin.TestMode)
	physical := "local://42/exports/a.png"
	engine := gin.New()
	serveResourceGrants(
		engine,
		&stubResourceCatalog{resource: &types.StoredResource{
			ID:           "resource-1",
			TenantID:     42,
			PhysicalPath: physical,
			OriginalName: "a.png",
			MimeType:     "image/png",
		}},
		&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) {
			if path != physical {
				t.Fatalf("path = %q, want %q", path, physical)
			}
			return io.NopCloser(strings.NewReader("image")), nil
		}},
		nil,
	)

	req := httptest.NewRequest(http.MethodGet, "/r/GrantTokenAbCdEfGhIjKlM", nil)
	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)
	if recorder.Code != http.StatusOK || recorder.Body.String() != "image" {
		t.Fatalf("status=%d body=%q", recorder.Code, recorder.Body.String())
	}
	if got := recorder.Header().Get("X-Content-Type-Options"); got != "nosniff" {
		t.Fatalf("X-Content-Type-Options = %q", got)
	}
	if got := recorder.Header().Get("Content-Disposition"); !strings.Contains(got, "a.png") {
		t.Fatalf("Content-Disposition = %q, want original filename a.png", got)
	}
}

func TestServeFilesDoesNotFallbackWhenProviderDoesNotMatchGlobalStorage(t *testing.T) {
	gin.SetMode(gin.TestMode)
	t.Setenv("STORAGE_TYPE", "minio")

	engine := gin.New()
	serveFiles(engine, &stubFileService{
		getFile: func(ctx context.Context, filePath string) (io.ReadCloser, error) {
			t.Fatalf("GetFile should not be called for mismatched provider, got %q", filePath)
			return nil, nil
		},
	})

	req := httptest.NewRequest(http.MethodGet, "/files?file_path="+url.QueryEscape("local://42/docs/example.txt"), nil)
	req = req.WithContext(context.WithValue(req.Context(), types.TenantInfoContextKey, &types.Tenant{ID: 42}))

	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if got, want := recorder.Code, http.StatusBadRequest; got != want {
		t.Fatalf("status = %d, want %d", got, want)
	}
}

func TestServeFilesRejectsCrossTenantPath(t *testing.T) {
	gin.SetMode(gin.TestMode)
	t.Setenv("STORAGE_TYPE", "local")

	engine := gin.New()
	serveFiles(engine, &stubFileService{
		getFile: func(ctx context.Context, filePath string) (io.ReadCloser, error) {
			t.Fatalf("GetFile should not be called for cross-tenant path, got %q", filePath)
			return nil, nil
		},
	})

	req := httptest.NewRequest(http.MethodGet, "/files?file_path="+url.QueryEscape("local://7/knowledge/secret.pdf"), nil)
	req = req.WithContext(context.WithValue(req.Context(), types.TenantInfoContextKey, &types.Tenant{ID: 42}))

	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if got, want := recorder.Code, http.StatusForbidden; got != want {
		t.Fatalf("status = %d, want %d", got, want)
	}
}

func TestServeFilesRejectsPathWithoutTenantSegment(t *testing.T) {
	gin.SetMode(gin.TestMode)
	t.Setenv("STORAGE_TYPE", "local")

	engine := gin.New()
	serveFiles(engine, &stubFileService{
		getFile: func(ctx context.Context, filePath string) (io.ReadCloser, error) {
			t.Fatalf("GetFile should not be called without tenant segment, got %q", filePath)
			return nil, nil
		},
	})

	req := httptest.NewRequest(http.MethodGet, "/files?file_path="+url.QueryEscape("local://docs/example.txt"), nil)
	req = req.WithContext(context.WithValue(req.Context(), types.TenantInfoContextKey, &types.Tenant{ID: 42}))

	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if got, want := recorder.Code, http.StatusForbidden; got != want {
		t.Fatalf("status = %d, want %d", got, want)
	}
}

// /files carries its own API-key guard (middleware.AllowFileServeAPIKey):
// full-access and tenant-wide retrieve keys may serve tenant-bounded paths,
// but KB-restricted keys (and keys lacking retrieve) are denied because a raw
// storage path cannot be bounded to a KB allow-list.
func TestServeFilesAPIKeyScopeMatrix(t *testing.T) {
	gin.SetMode(gin.TestMode)
	t.Setenv("STORAGE_TYPE", "local")

	const filePath = "local://42/docs/example.txt"

	cases := []struct {
		name     string
		scope    types.TenantAPIKeyScope
		wantCode int
	}{
		{
			name:     "full access allowed",
			scope:    types.TenantAPIKeyScope{FullAccess: true},
			wantCode: http.StatusOK,
		},
		{
			name: "tenant-wide retrieve allowed",
			scope: types.TenantAPIKeyScope{
				Capabilities: types.StringArray{string(types.APIKeyCapabilityRetrieve)},
			},
			wantCode: http.StatusOK,
		},
		{
			name: "kb-restricted retrieve denied",
			scope: types.TenantAPIKeyScope{
				KnowledgeBaseIDs: types.StringArray{"kb-1"},
				Capabilities:     types.StringArray{string(types.APIKeyCapabilityRetrieve)},
			},
			wantCode: http.StatusForbidden,
		},
		{
			name: "non-retrieve capability denied",
			scope: types.TenantAPIKeyScope{
				Capabilities: types.StringArray{string(types.APIKeyCapabilityChat)},
			},
			wantCode: http.StatusForbidden,
		},
	}

	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			engine := gin.New()
			serveFiles(engine, &stubFileService{
				getFile: func(_ context.Context, _ string) (io.ReadCloser, error) {
					return io.NopCloser(strings.NewReader("body")), nil
				},
			})

			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, tc.scope)
			req = req.WithContext(ctx)

			recorder := httptest.NewRecorder()
			engine.ServeHTTP(recorder, req)

			if got := recorder.Code; got != tc.wantCode {
				t.Fatalf("status = %d, want %d body=%s", got, tc.wantCode, recorder.Body.String())
			}
		})
	}
}

// newKBScopedFilesTestEngine wires newKBScopedFileServeHandler behind a
// middleware that carries the exact KB grant and owner execution tenant,
// mirroring RequireKBAccess without the full RBAC stack.
func newKBScopedFilesTestEngine(
	effectiveTenantID uint64,
	tenantSvc interfaces.TenantService,
	global interfaces.FileService,
) *gin.Engine {
	engine := gin.New()
	engine.GET("/knowledge-bases/:id/files",
		func(c *gin.Context) {
			ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, effectiveTenantID)
			grant := &middleware.KBAccess{
				KnowledgeBase:     &types.KnowledgeBase{ID: "kb-1", TenantID: effectiveTenantID},
				Caller:            types.CallerFromContext(ctx),
				EffectiveTenantID: effectiveTenantID,
				Permission:        types.OrgRoleViewer,
			}
			c.Set(middleware.KBAccessContextKey, grant)
			c.Request = c.Request.WithContext(grant.Context(ctx))
			c.Next()
		},
		newKBScopedFileServeHandlerWithResources(
			tenantSvc,
			global,
			nil,
			&stubResourceCatalog{bound: func(_ context.Context, _ uint64, kb, ref string) (bool, error) {
				return kb == "kb-1" && ref == "local://10008/exports/img.jpg", nil
			}},
		),
	)
	return engine
}

// A tenant whose owner-tenant (10008) storage objects are requested by a
// borrowing tenant via a shared KB: the effective tenant in context is the
// owner, so the path validates and the file is served.
func TestKBScopedFilesServesOwnerTenantPath(t *testing.T) {
	gin.SetMode(gin.TestMode)
	t.Setenv("STORAGE_TYPE", "local")

	const ownerTenantID = uint64(10008)
	var requestedPath string
	engine := newKBScopedFilesTestEngine(
		ownerTenantID,
		&stubTenantService{get: func(_ context.Context, id uint64) (*types.Tenant, error) {
			return &types.Tenant{ID: id}, nil
		}},
		&stubFileService{getFile: func(_ context.Context, filePath string) (io.ReadCloser, error) {
			requestedPath = filePath
			return io.NopCloser(strings.NewReader("shared-body")), nil
		}},
	)

	filePath := "local://10008/exports/img.jpg"
	req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/files?file_path="+url.QueryEscape(filePath), nil)
	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if got, want := recorder.Code, http.StatusOK; got != want {
		t.Fatalf("status = %d, want %d body=%s", got, want, recorder.Body.String())
	}
	if requestedPath != filePath {
		t.Fatalf("requested path = %q, want %q", requestedPath, filePath)
	}
	if body := recorder.Body.String(); body != "shared-body" {
		t.Fatalf("body = %q, want %q", body, "shared-body")
	}
}

// The path must belong to the effective (owner) tenant. A path pointing at a
// different tenant than the resolved KB owner is still rejected, so the guard
// cannot be used to reach arbitrary tenants' files.
func TestKBScopedFilesRejectsPathNotOwnedByKBTenant(t *testing.T) {
	gin.SetMode(gin.TestMode)
	t.Setenv("STORAGE_TYPE", "local")

	const ownerTenantID = uint64(10008)
	engine := newKBScopedFilesTestEngine(
		ownerTenantID,
		&stubTenantService{get: func(_ context.Context, id uint64) (*types.Tenant, error) {
			t.Fatalf("GetTenantByID should not be called for mismatched path, got %d", id)
			return nil, nil
		}},
		&stubFileService{getFile: func(_ context.Context, filePath string) (io.ReadCloser, error) {
			t.Fatalf("GetFile should not be called for mismatched path, got %q", filePath)
			return nil, nil
		}},
	)

	req := httptest.NewRequest(http.MethodGet,
		"/knowledge-bases/kb-1/files?file_path="+url.QueryEscape("local://9999/exports/other.jpg"), nil)
	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if got, want := recorder.Code, http.StatusForbidden; got != want {
		t.Fatalf("status = %d, want %d", got, want)
	}
}

// KB-scoped proxy is for embedded exports/ images only; raw knowledge uploads
// must use /knowledge/:id/download even when the tenant matches.
func TestKBScopedFilesRejectsNonExportsPath(t *testing.T) {
	gin.SetMode(gin.TestMode)
	t.Setenv("STORAGE_TYPE", "local")

	const ownerTenantID = uint64(10008)
	engine := newKBScopedFilesTestEngine(
		ownerTenantID,
		&stubTenantService{get: func(_ context.Context, id uint64) (*types.Tenant, error) {
			t.Fatalf("GetTenantByID should not be called for non-exports path, got %d", id)
			return nil, nil
		}},
		&stubFileService{getFile: func(_ context.Context, filePath string) (io.ReadCloser, error) {
			t.Fatalf("GetFile should not be called for non-exports path, got %q", filePath)
			return nil, nil
		}},
	)

	req := httptest.NewRequest(http.MethodGet,
		"/knowledge-bases/kb-1/files?file_path="+url.QueryEscape("local://10008/knowledge-id/123.pdf"), nil)
	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if got, want := recorder.Code, http.StatusForbidden; got != want {
		t.Fatalf("status = %d, want %d", got, want)
	}
}

func TestKBScopedFilesRequiresFilePath(t *testing.T) {
	gin.SetMode(gin.TestMode)

	engine := newKBScopedFilesTestEngine(
		10008,
		&stubTenantService{},
		&stubFileService{},
	)

	req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/files", nil)
	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if got, want := recorder.Code, http.StatusBadRequest; got != want {
		t.Fatalf("status = %d, want %d", got, want)
	}
}

func TestKBScopedFilesRejectsUnboundFileBeforeStorage(t *testing.T) {
	gin.SetMode(gin.TestMode)
	engine := newKBScopedFilesTestEngine(10008,
		&stubTenantService{get: func(context.Context, uint64) (*types.Tenant, error) {
			t.Fatal("an unbound file must be rejected before resolving storage")
			return nil, nil
		}},
		&stubFileService{getFile: func(context.Context, string) (io.ReadCloser, error) {
			t.Fatal("an unbound file must never be opened")
			return nil, nil
		}},
	)
	w := httptest.NewRecorder()
	engine.ServeHTTP(w, httptest.NewRequest(http.MethodGet,
		"/knowledge-bases/kb-1/files?file_path="+url.QueryEscape("local://10008/exports/another-kb.png"), nil))
	if w.Code != http.StatusForbidden {
		t.Fatalf("status=%d, want 403", w.Code)
	}
}

func newMessageScopedFilesTestEngine(
	callerTenantID uint64,
	messageService messageFileLookup,
	agentShareService sharedAgentFileLookup,
	tenantService interfaces.TenantService,
	global interfaces.FileService,
	resourceCatalog interfaces.ResourceCatalog,
	kbShareAuth messageKBShareAuthorizer,
) *gin.Engine {
	engine := gin.New()
	engine.GET("/sessions/:id/messages/:message_id/files",
		func(c *gin.Context) {
			ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, callerTenantID)
			c.Request = c.Request.WithContext(ctx)
			c.Next()
		},
		newMessageScopedFileServeHandler(
			messageService,
			agentShareService,
			tenantService,
			global,
			nil,
			resourceCatalog,
			kbShareAuth,
		),
	)
	return engine
}

func TestMessageScopedFilesServesSharedAgentResource(t *testing.T) {
	gin.SetMode(gin.TestMode)
	t.Setenv("STORAGE_TYPE", "local")

	const (
		callerTenantID = uint64(42)
		ownerTenantID  = uint64(7)
		ref            = "resource://AbCdEfGhIjKlMnOpQrStUv"
		physical       = "local://7/exports/chart.png"
	)
	var requestedPath string
	revoked := false
	storageCalls := 0
	engine := newMessageScopedFilesTestEngine(
		callerTenantID,
		&stubMessageFileLookup{get: func(_ context.Context, sessionID, messageID string) (*types.Message, error) {
			if sessionID != "session-1" || messageID != "message-1" {
				t.Fatalf("unexpected message scope %s/%s", sessionID, messageID)
			}
			return &types.Message{ID: "message-1", AgentID: "agent-1", AgentTenantID: ownerTenantID, Content: ref}, nil
		}},
		&stubSharedAgentFileLookup{get: func(
			_ context.Context,
			tenantID uint64,
			_ types.TenantRole,
			agentID string,
			sourceTenantID ...uint64,
		) (*types.CustomAgent, error) {
			if tenantID != callerTenantID || agentID != "agent-1" || len(sourceTenantID) != 1 || sourceTenantID[0] != ownerTenantID {
				t.Fatalf("unexpected shared-agent lookup tenant=%d agent=%s source=%v", tenantID, agentID, sourceTenantID)
			}
			if revoked {
				return nil, nil
			}
			return &types.CustomAgent{ID: agentID, TenantID: ownerTenantID}, nil
		}},
		&stubTenantService{get: func(_ context.Context, id uint64) (*types.Tenant, error) {
			return &types.Tenant{ID: id}, nil
		}},
		&stubFileService{getFile: func(_ context.Context, filePath string) (io.ReadCloser, error) {
			storageCalls++
			requestedPath = filePath
			return io.NopCloser(strings.NewReader("shared-agent-image")), nil
		}},
		&stubResourceCatalog{
			fileBindings: &types.MessageFileBindings{MessageArtifact: true},
			resource: &types.StoredResource{
				TenantID:     ownerTenantID,
				PhysicalPath: physical,
				OriginalName: "chart.png",
				MimeType:     "image/png",
			},
		},
		messageKBShareAuthorizer{},
	)

	req := httptest.NewRequest(http.MethodGet,
		"/sessions/session-1/messages/message-1/files?file_path="+url.QueryEscape(ref), nil)
	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if recorder.Code != http.StatusOK || recorder.Body.String() != "shared-agent-image" {
		t.Fatalf("status=%d body=%q", recorder.Code, recorder.Body.String())
	}
	if requestedPath != physical {
		t.Fatalf("requested path = %q, want %q", requestedPath, physical)
	}
	if got := recorder.Header().Get("Content-Disposition"); !strings.Contains(got, "chart.png") {
		t.Fatalf("Content-Disposition = %q, want original filename chart.png", got)
	}
	if got := recorder.Header().Get("Cache-Control"); got != "private, no-store" {
		t.Fatalf("Cache-Control = %q, want private, no-store", got)
	}
	revoked = true
	recorder = httptest.NewRecorder()
	engine.ServeHTTP(recorder, req.Clone(context.Background()))
	if recorder.Code != http.StatusForbidden || storageCalls != 1 {
		t.Fatalf("revoked request: status=%d storage calls=%d", recorder.Code, storageCalls)
	}
}

func TestMessageScopedFilesServesSameTenantResource(t *testing.T) {
	gin.SetMode(gin.TestMode)
	t.Setenv("STORAGE_TYPE", "local")

	const (
		tenantID = uint64(42)
		ref      = "resource://AbCdEfGhIjKlMnOpQrStUv"
		physical = "local://42/exports/chart.png"
	)
	var requestedPath string
	engine := newMessageScopedFilesTestEngine(
		tenantID,
		&stubMessageFileLookup{get: func(_ context.Context, sessionID, messageID string) (*types.Message, error) {
			if sessionID != "session-1" || messageID != "message-1" {
				t.Fatalf("unexpected message scope %s/%s", sessionID, messageID)
			}
			return &types.Message{AgentTenantID: tenantID, Content: ref}, nil
		}},
		&stubSharedAgentFileLookup{get: func(
			context.Context, uint64, types.TenantRole, string, ...uint64,
		) (*types.CustomAgent, error) {
			t.Fatal("shared-agent lookup should not run for same-tenant resources")
			return nil, nil
		}},
		&stubTenantService{get: func(_ context.Context, id uint64) (*types.Tenant, error) {
			return &types.Tenant{ID: id}, nil
		}},
		&stubFileService{getFile: func(_ context.Context, filePath string) (io.ReadCloser, error) {
			requestedPath = filePath
			return io.NopCloser(strings.NewReader("same-tenant-image")), nil
		}},
		&stubResourceCatalog{resource: &types.StoredResource{
			TenantID:     tenantID,
			PhysicalPath: physical,
			MimeType:     "image/png",
		}},
		messageKBShareAuthorizer{},
	)

	req := httptest.NewRequest(http.MethodGet,
		"/sessions/session-1/messages/message-1/files?file_path="+url.QueryEscape(ref), nil)
	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if recorder.Code != http.StatusOK || recorder.Body.String() != "same-tenant-image" {
		t.Fatalf("status=%d body=%q", recorder.Code, recorder.Body.String())
	}
	if requestedPath != physical {
		t.Fatalf("requested path = %q, want %q", requestedPath, physical)
	}
}

func TestMessageScopedFilesRequiresFilePath(t *testing.T) {
	gin.SetMode(gin.TestMode)

	engine := newMessageScopedFilesTestEngine(
		42,
		&stubMessageFileLookup{get: func(context.Context, string, string) (*types.Message, error) {
			return &types.Message{AgentTenantID: 42}, nil
		}},
		&stubSharedAgentFileLookup{},
		&stubTenantService{},
		&stubFileService{},
		&stubResourceCatalog{},
		messageKBShareAuthorizer{},
	)

	req := httptest.NewRequest(http.MethodGet, "/sessions/session-1/messages/message-1/files", nil)
	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if got, want := recorder.Code, http.StatusBadRequest; got != want {
		t.Fatalf("status = %d, want %d", got, want)
	}
}

func TestMessageScopedFilesRejectsRevokedSharedAgent(t *testing.T) {
	gin.SetMode(gin.TestMode)
	const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"

	engine := newMessageScopedFilesTestEngine(
		42,
		&stubMessageFileLookup{get: func(context.Context, string, string) (*types.Message, error) {
			return &types.Message{AgentID: "agent-1", AgentTenantID: 7, Content: ref}, nil
		}},
		&stubSharedAgentFileLookup{get: func(
			context.Context, uint64, types.TenantRole, string, ...uint64,
		) (*types.CustomAgent, error) {
			return nil, nil
		}},
		&stubTenantService{get: func(context.Context, uint64) (*types.Tenant, error) {
			t.Fatal("tenant lookup should not run after share revocation")
			return nil, nil
		}},
		&stubFileService{getFile: func(context.Context, string) (io.ReadCloser, error) {
			t.Fatal("GetFile should not run after share revocation")
			return nil, nil
		}},
		&stubResourceCatalog{resource: &types.StoredResource{TenantID: 7, PhysicalPath: "local://7/exports/chart.png"}},
		messageKBShareAuthorizer{},
	)

	req := httptest.NewRequest(http.MethodGet,
		"/sessions/session-1/messages/message-1/files?file_path="+url.QueryEscape(ref), nil)
	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if recorder.Code != http.StatusForbidden {
		t.Fatalf("status=%d, want %d", recorder.Code, http.StatusForbidden)
	}
}

func TestMessageScopedFilesRejectsUnreferencedFilesBeforeStorage(t *testing.T) {
	gin.SetMode(gin.TestMode)
	const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
	for _, content := range []string{"", ref + "suffix"} {
		t.Run(content, func(t *testing.T) {
			engine := newMessageScopedFilesTestEngine(
				42,
				&stubMessageFileLookup{get: func(context.Context, string, string) (*types.Message, error) {
					return &types.Message{
						AgentID: "agent-1", AgentTenantID: 7, Content: content,
						AgentSteps: types.AgentSteps{
							{ToolCalls: []types.ToolCall{{Args: map[string]interface{}{"file": ref}}}},
						},
					}, nil
				}},
				&stubSharedAgentFileLookup{
					get: func(context.Context,
						uint64,
						types.TenantRole,
						string,
						...uint64) (*types.CustomAgent,
						error,
					) {
						t.Fatal("tool arguments and handle prefixes must not authorize a message file")
						return nil, nil
					},
				},
				&stubTenantService{get: func(context.Context, uint64) (*types.Tenant, error) {
					t.Fatal("unreferenced files must be denied before resolving storage")
					return nil, nil
				}},
				&stubFileService{getFile: func(context.Context, string) (io.ReadCloser, error) {
					t.Fatal("unreferenced files must never be opened")
					return nil, nil
				}},
				&stubResourceCatalog{
					resource: &types.StoredResource{TenantID: 7, PhysicalPath: "local://7/exports/chart.png"},
				},
				messageKBShareAuthorizer{},
			)
			w := httptest.NewRecorder()
			engine.ServeHTTP(w, httptest.NewRequest(http.MethodGet,
				"/sessions/session-1/messages/message-1/files?file_path="+url.QueryEscape(ref), nil))
			if w.Code != http.StatusForbidden {
				t.Fatalf("status=%d, want 403", w.Code)
			}
		})
	}
}

func TestMessageScopedFilesRejectsResourceOutsideMessageTenant(t *testing.T) {
	gin.SetMode(gin.TestMode)
	const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"

	engine := newMessageScopedFilesTestEngine(
		42,
		&stubMessageFileLookup{get: func(context.Context, string, string) (*types.Message, error) {
			return &types.Message{AgentID: "agent-1", AgentTenantID: 8, Content: ref}, nil
		}},
		&stubSharedAgentFileLookup{get: func(
			context.Context, uint64, types.TenantRole, string, ...uint64,
		) (*types.CustomAgent, error) {
			t.Fatal("shared-agent lookup should not run for a mismatched resource tenant")
			return nil, nil
		}},
		&stubTenantService{},
		&stubFileService{},
		&stubResourceCatalog{resource: &types.StoredResource{TenantID: 7, PhysicalPath: "local://7/exports/chart.png"}},
		messageKBShareAuthorizer{},
	)

	req := httptest.NewRequest(http.MethodGet,
		"/sessions/session-1/messages/message-1/files?file_path="+url.QueryEscape(ref), nil)
	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if recorder.Code != http.StatusForbidden {
		t.Fatalf("status=%d, want %d", recorder.Code, http.StatusForbidden)
	}
}

type stubKBShareGuard struct {
	hasPermission func(
		ctx context.Context,
		kbID string,
		callerTenantID uint64,
		callerTenantRole types.TenantRole,
		requiredRole types.OrgMemberRole,
	) (bool, error)
}

func (s *stubKBShareGuard) CheckTenantKBPermission(
	ctx context.Context, kbID string, callerTenantID uint64, callerTenantRole types.TenantRole,
) (types.OrgMemberRole, bool, error) {
	allowed, err := s.hasPermission(ctx, kbID, callerTenantID, callerTenantRole, types.OrgRoleViewer)
	return types.OrgRoleViewer, allowed, err
}

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{
			bound: func(context.Context, uint64, string, string) (bool, error) { return true, nil },
			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 ![quadrant](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 TestMessageScopedFilesRejectsOrgSharedKBResourceWhenShareRevoked(t *testing.T) {
	engine, _ := newOrgSharedKBTestEngine(t, false,
		types.References{{
			KnowledgeID:     "knowledge-1",
			KnowledgeBaseID: "kb-1",
			Content:         "Figure 1 ![quadrant](resource://ShArEdKbHaNdLe00000000)",
		}},
		[]*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 ![other](resource://AnOtHeRhAnDLe0000000)",
		}},
		[]*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 ![quadrant](resource://ShArEdKbHaNdLe00000000)",
		}},
		[]*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:         "![quadrant](resource://ShArEdKbHaNdLe00000000)",
				}},
			}, 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{
			bound: func(context.Context, uint64, string, string) (bool, error) { return true, nil },
			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:     "![quadrant](resource://ShArEdKbHaNdLe00000000)",
				}},
			}, 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{
			bound: func(context.Context, uint64, string, string) (bool, error) { return true, nil },
			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:         "![x](resource://ShArEdKbHaNdLe00000000EXTRA)",
		}},
		[]*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:         "![quadrant](resource://ShArEdKbHaNdLe00000000)",
				}},
			}, 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{
			bound: func(context.Context, uint64, string, string) (bool, error) { return true, nil },
			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")

	engine := gin.New()
	serveFiles(engine, &stubFileService{
		getFile: func(_ context.Context, _ string) (io.ReadCloser, error) {
			return io.NopCloser(strings.NewReader(`<svg onload="alert(1)"></svg>`)), nil
		},
	})

	filePath := "local://42/docs/payload.svg"
	req := httptest.NewRequest(http.MethodGet, "/files?file_path="+url.QueryEscape(filePath), nil)
	req = req.WithContext(context.WithValue(req.Context(), types.TenantInfoContextKey, &types.Tenant{ID: 42}))

	recorder := httptest.NewRecorder()
	engine.ServeHTTP(recorder, req)

	if got, want := recorder.Code, http.StatusOK; got != want {
		t.Fatalf("status = %d, want %d", got, want)
	}
	if got := recorder.Header().Get("Content-Type"); got != "application/octet-stream" {
		t.Fatalf("Content-Type = %q, want application/octet-stream", got)
	}
	if got := recorder.Header().Get("Content-Disposition"); got != "attachment; filename=payload.svg" {
		t.Fatalf("Content-Disposition = %q, want attachment with filename", got)
	}
	if got := recorder.Header().Get("X-Content-Type-Options"); got != "nosniff" {
		t.Fatalf("X-Content-Type-Options = %q, want nosniff", got)
	}
}

func (s *stubResourceCatalog) GetMessageFileBindings(
	context.Context,
	uint64,
	string,
	string,
) (*types.MessageFileBindings, error) {
	return s.fileBindings, nil
}