feat(files): add message-scoped proxy for shared-agent chat images
Shared-agent replies can reference resources in the source workspace. Route those images through a session/message file proxy that derives authorization from the persisted message and active share, and align the chat renderer to use the assistant message ID during streaming hydration.main
parent
7ef8e03751
commit
18739bb1a3
|
|
@ -878,6 +878,7 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
const assistantId = data.assistant_message_id as string | undefined
|
||||
existingMessage = {
|
||||
id: assistantId || data.id,
|
||||
assistant_message_id: assistantId,
|
||||
request_id: data.id,
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
|
|
@ -896,6 +897,10 @@ export function useChatStreamHandler(options: UseChatStreamHandlerOptions) {
|
|||
log('[Agent Query] Created agent placeholder message')
|
||||
} else {
|
||||
ensureAgentMessageShell(existingMessage, data.id as string | undefined)
|
||||
if (data.assistant_message_id) {
|
||||
existingMessage.id = data.assistant_message_id as string
|
||||
existingMessage.assistant_message_id = data.assistant_message_id
|
||||
}
|
||||
log('[Agent Query] Continuing stream for existing message')
|
||||
}
|
||||
onAgentQuery?.(data, existingMessage, created)
|
||||
|
|
|
|||
|
|
@ -42,6 +42,19 @@ test('knowledge-base access routes through the KB-scoped proxy', () => {
|
|||
)
|
||||
})
|
||||
|
||||
test('message access routes through the session-message-scoped proxy', () => {
|
||||
const request = buildProtectedFileRequest(RESOURCE, {
|
||||
mode: 'message',
|
||||
sessionId: 'session 1',
|
||||
messageId: 'message/1',
|
||||
})
|
||||
|
||||
assert.equal(
|
||||
request?.url,
|
||||
`/api/v1/sessions/session%201/messages/message%2F1/files?file_path=${encodeURIComponent(RESOURCE)}`,
|
||||
)
|
||||
})
|
||||
|
||||
test('an embed context without a token yields no request instead of an unauthenticated one', () => {
|
||||
const request = buildProtectedFileRequest(RESOURCE, { mode: 'embed', channelId: 'ch-1', token: '' })
|
||||
|
||||
|
|
@ -72,11 +85,16 @@ test('a component scope refines the default tenant plane', () => {
|
|||
resolveProtectedFileAccess({ mode: 'knowledgeBase', kbId: ' ' }),
|
||||
{ mode: 'tenant' },
|
||||
)
|
||||
assert.deepEqual(
|
||||
resolveProtectedFileAccess({ mode: 'message', sessionId: 'session-1', messageId: ' ' }),
|
||||
{ mode: 'tenant' },
|
||||
)
|
||||
})
|
||||
|
||||
test('all three file proxies are recognized as protected proxy paths', () => {
|
||||
test('all file proxies are recognized as protected proxy paths', () => {
|
||||
assert.equal(isProtectedFileProxyPath('/files'), true)
|
||||
assert.equal(isProtectedFileProxyPath('/api/v1/knowledge-bases/kb-1/files'), true)
|
||||
assert.equal(isProtectedFileProxyPath('/api/v1/sessions/session-1/messages/message-1/files'), true)
|
||||
assert.equal(isProtectedFileProxyPath('/api/v1/embed/ch-1/files'), true)
|
||||
assert.equal(isProtectedFileProxyPath('/api/v1/embed/ch-1/config'), false)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
/**
|
||||
* 受保护文件(provider:// / resource:// 等)的访问上下文。
|
||||
*
|
||||
* 后端按访问主体拆了三条文件代理,鉴权模型互不相同:
|
||||
* 后端按访问主体拆分文件代理,鉴权模型互不相同:
|
||||
* - `/files` → 登录态 Bearer + X-Tenant-ID
|
||||
* - `/api/v1/knowledge-bases/:id/files` → 知识库访问权限(跨租户共享库)
|
||||
* - `/api/v1/sessions/:id/messages/:mid/files` → 会话消息归属 + 共享智能体权限
|
||||
* - `/api/v1/embed/:channel_id/files` → 嵌入访客的 Embed token
|
||||
*
|
||||
* 选哪条代理取决于当前请求的鉴权平面,而不是取决于哪个组件在渲染图片。
|
||||
|
|
@ -20,6 +21,7 @@ const STORAGE_BACKEND_FILE_SCHEME_RE = new RegExp(
|
|||
|
||||
const KB_FILE_PROXY_PATH_RE = /^\/api\/v1\/knowledge-bases\/[^/]+\/files$/;
|
||||
const EMBED_FILE_PROXY_PATH_RE = /^\/api\/v1\/embed\/[^/]+\/files$/;
|
||||
const MESSAGE_FILE_PROXY_PATH_RE = /^\/api\/v1\/sessions\/[^/]+\/messages\/[^/]+\/files$/;
|
||||
|
||||
export type ProtectedFileAccessContext =
|
||||
/** 登录态用户:Bearer + 选中租户。 */
|
||||
|
|
@ -27,7 +29,9 @@ export type ProtectedFileAccessContext =
|
|||
/** 嵌入访客:只持有 Embed token,无 Bearer、无租户上下文。 */
|
||||
| { mode: 'embed'; channelId: string; token: string }
|
||||
/** 知识库作用域:登录态用户读取共享库中归属其他租户的对象。 */
|
||||
| { mode: 'knowledgeBase'; kbId: string };
|
||||
| { mode: 'knowledgeBase'; kbId: string }
|
||||
/** 消息作用域:登录态用户读取共享智能体回复中的源空间资源。 */
|
||||
| { mode: 'message'; sessionId: string; messageId: string };
|
||||
|
||||
export interface ProtectedFileRequest {
|
||||
url: string;
|
||||
|
|
@ -80,6 +84,9 @@ export function resolveProtectedFileAccess(
|
|||
if (fallback.mode === 'embed') return fallback;
|
||||
if (!override) return fallback;
|
||||
if (override.mode === 'knowledgeBase' && !override.kbId.trim()) return fallback;
|
||||
if (override.mode === 'message' && (!override.sessionId.trim() || !override.messageId.trim())) {
|
||||
return fallback;
|
||||
}
|
||||
return override;
|
||||
}
|
||||
|
||||
|
|
@ -89,11 +96,12 @@ export function isProviderFileURL(url: string): boolean {
|
|||
return PROVIDER_FILE_SCHEME_RE.test(trimmed) || STORAGE_BACKEND_FILE_SCHEME_RE.test(trimmed);
|
||||
}
|
||||
|
||||
/** 是否为三条受保护文件代理之一的路径。 */
|
||||
/** 是否为受保护文件代理之一的路径。 */
|
||||
export function isProtectedFileProxyPath(pathname: string): boolean {
|
||||
return (
|
||||
pathname === '/files'
|
||||
|| KB_FILE_PROXY_PATH_RE.test(pathname)
|
||||
|| MESSAGE_FILE_PROXY_PATH_RE.test(pathname)
|
||||
|| EMBED_FILE_PROXY_PATH_RE.test(pathname)
|
||||
);
|
||||
}
|
||||
|
|
@ -154,5 +162,12 @@ export function buildProtectedFileRequest(
|
|||
};
|
||||
}
|
||||
|
||||
if (access.mode === 'message') {
|
||||
return {
|
||||
url: `/api/v1/sessions/${encodeURIComponent(access.sessionId.trim())}/messages/${encodeURIComponent(access.messageId.trim())}/files?${query}`,
|
||||
headers: tenantRequestHeaders(),
|
||||
};
|
||||
}
|
||||
|
||||
return { url: `/files?${query}`, headers: tenantRequestHeaders() };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -780,6 +780,7 @@ import thinkingIcon from '@/assets/img/Frame3718.svg';
|
|||
|
||||
interface SessionData {
|
||||
id?: string;
|
||||
assistant_message_id?: string;
|
||||
request_id?: string;
|
||||
debugRequest?: Record<string, unknown>;
|
||||
isAgentMode?: boolean;
|
||||
|
|
@ -818,13 +819,41 @@ const showRequestInfo = computed(
|
|||
() => !props.embeddedMode && !!(props.session?.request_id || props.session?.id),
|
||||
);
|
||||
|
||||
const resolveAssistantMessageId = (session?: SessionData) =>
|
||||
String(session?.assistant_message_id || session?.id || '').trim();
|
||||
|
||||
// Agent answers embed exported charts and knowledge-base images as
|
||||
// `resource://` handles. An embed visitor has no Bearer token, so they must be
|
||||
// fetched through the channel-scoped proxy rather than the tenant one.
|
||||
const protectedFileAccess = computed<ProtectedFileAccessContext | undefined>(() =>
|
||||
props.embeddedMode && props.embedChannelId && props.embedToken
|
||||
? { mode: 'embed', channelId: props.embedChannelId, token: props.embedToken }
|
||||
: undefined,
|
||||
// `resource://` handles. Embed visitors use the channel-scoped proxy. Logged-in
|
||||
// users use the persisted assistant message as the authorization anchor, which
|
||||
// also covers resources owned by a shared agent's source workspace.
|
||||
const protectedFileAccess = computed<ProtectedFileAccessContext | undefined>(() => {
|
||||
if (props.embeddedMode && props.embedChannelId && props.embedToken) {
|
||||
return { mode: 'embed', channelId: props.embedChannelId, token: props.embedToken };
|
||||
}
|
||||
const messageId = resolveAssistantMessageId(props.session);
|
||||
if (props.sessionId && messageId) {
|
||||
return { mode: 'message', sessionId: props.sessionId, messageId };
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
// Re-hydrate when the message authorization anchor becomes available or is
|
||||
// corrected (e.g. request_id → persisted assistant_message_id after agent_query).
|
||||
watch(
|
||||
() => {
|
||||
const access = protectedFileAccess.value;
|
||||
if (access?.mode === 'message') {
|
||||
return `${access.sessionId}\0${access.messageId}`;
|
||||
}
|
||||
return '';
|
||||
},
|
||||
(scopeKey, previousScopeKey) => {
|
||||
if (!scopeKey || scopeKey === previousScopeKey) return;
|
||||
clearProtectedFileFailureCache();
|
||||
nextTick(async () => {
|
||||
await hydrateProtectedFileImages(rootElement.value, protectedFileAccess.value);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const {
|
||||
|
|
|
|||
|
|
@ -338,7 +338,7 @@ const handleSuggestedQuestionClick = (question) => {
|
|||
}
|
||||
};
|
||||
|
||||
const resolveAssistantMessageId = (message) => message?.id || message?.assistant_message_id;
|
||||
const resolveAssistantMessageId = (message) => message?.assistant_message_id || message?.id;
|
||||
|
||||
const handleAnswerRenderComplete = (message, ready) => {
|
||||
message.answerFullyRendered = Boolean(ready);
|
||||
|
|
|
|||
|
|
@ -24,6 +24,8 @@ import (
|
|||
//
|
||||
// - /files tenant-scoped raw storage proxy
|
||||
// - /api/v1/knowledge-bases/:id/files KB-scoped proxy (shared-KB images)
|
||||
// - /api/v1/sessions/:id/messages/:message_id/files
|
||||
// message-scoped proxy (shared-agent output)
|
||||
// - /api/v1/files/presigned HMAC-signed anonymous access (IM)
|
||||
// - /api/v1/files/presigned-preview Admin-only URL diagnostics
|
||||
// - /r/:token short-lived capability URLs
|
||||
|
|
@ -39,6 +41,26 @@ type getRouteRegistrar interface {
|
|||
GET(string, ...gin.HandlerFunc) gin.IRoutes
|
||||
}
|
||||
|
||||
// messageFileLookup is the narrow message-service surface needed by the
|
||||
// message-scoped file proxy. Keeping it small makes the authorization boundary
|
||||
// independently testable.
|
||||
type messageFileLookup interface {
|
||||
GetMessage(ctx context.Context, sessionID, messageID string) (*types.Message, error)
|
||||
}
|
||||
|
||||
// sharedAgentFileLookup verifies that a source workspace's agent is still
|
||||
// shared to the caller. Revoking the share therefore also revokes historical
|
||||
// message-file access.
|
||||
type sharedAgentFileLookup interface {
|
||||
GetSharedAgentForTenant(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
callerTenantRole types.TenantRole,
|
||||
agentID string,
|
||||
sourceTenantID ...uint64,
|
||||
) (*types.CustomAgent, error)
|
||||
}
|
||||
|
||||
// localStorageBaseDir resolves LOCAL_STORAGE_BASE_DIR with the container
|
||||
// default.
|
||||
func localStorageBaseDir() string {
|
||||
|
|
@ -486,6 +508,173 @@ 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.
|
||||
//
|
||||
// The owner tenant comes from the resource registry whenever possible. This
|
||||
// also keeps old messages (written before agent_tenant_id was populated)
|
||||
// readable without accepting a client-provided source workspace ID.
|
||||
func newMessageScopedFileServeHandler(
|
||||
messageService messageFileLookup,
|
||||
agentShareService sharedAgentFileLookup,
|
||||
tenantService interfaces.TenantService,
|
||||
globalFileService interfaces.FileService,
|
||||
storageResolver interfaces.StorageBackendResolver,
|
||||
resourceCatalog interfaces.ResourceCatalog,
|
||||
) gin.HandlerFunc {
|
||||
absDir := localStorageAbsDir()
|
||||
|
||||
return func(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
filePath, ok := requireFilePathQuery(c)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
callerTenantID, ok := types.TenantIDFromContext(ctx)
|
||||
if !ok || callerTenantID == 0 {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: workspace context missing"})
|
||||
return
|
||||
}
|
||||
if messageService == nil {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
message, err := messageService.GetMessage(ctx, c.Param("id"), c.Param("message_id"))
|
||||
if err != nil || message == nil {
|
||||
// Do not reveal whether a message exists outside the caller's session.
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
resolvedPath := filePath
|
||||
var resource *types.StoredResource
|
||||
if resourceCatalog != nil {
|
||||
resolvedPath, resource, err = resourceCatalog.ResolvePath(ctx, filePath)
|
||||
if err != nil {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
ownerTenantID := message.AgentTenantID
|
||||
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.
|
||||
if message.AgentTenantID != 0 && message.AgentTenantID != ownerTenantID {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden: resource not accessible from this message"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if ownerTenantID == 0 {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden: message resource workspace missing"})
|
||||
return
|
||||
}
|
||||
|
||||
if ownerTenantID != callerTenantID {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// Registered resources carry authoritative tenant ownership. Legacy
|
||||
// provider paths must still encode the authorized owner tenant.
|
||||
if resource == nil {
|
||||
if err := secutils.ValidateStoragePathTenant(resolvedPath, ownerTenantID); err != nil {
|
||||
logger.Warnf(ctx,
|
||||
"[Router] message files denied cross-tenant or invalid path: owner_tenant_id=%d file_path=%q err=%v",
|
||||
ownerTenantID, resolvedPath, err)
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "forbidden: file path not accessible"})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
ownerTenant, err := tenantService.GetTenantByID(ctx, ownerTenantID)
|
||||
if err != nil || ownerTenant == nil {
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
backendID, provider := parseStorageTarget(resolvedPath)
|
||||
fileSvc, resolvedProvider, ok := resolveTenantFileServiceWithFallback(
|
||||
ctx,
|
||||
"/sessions/:id/messages/:message_id/files",
|
||||
ownerTenant,
|
||||
backendID,
|
||||
provider,
|
||||
absDir,
|
||||
storageResolver,
|
||||
globalFileService,
|
||||
)
|
||||
if !ok {
|
||||
c.Status(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
reader, err := fileSvc.GetFile(ctx, resolvedPath)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx,
|
||||
"[Router] message files get file failed: owner_tenant_id=%d provider=%s path=%q err=%v",
|
||||
ownerTenantID, resolvedProvider, resolvedPath, err)
|
||||
c.Status(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
contentType, inline := secutils.SafeContentTypeByFilename(resolvedPath)
|
||||
if resource != nil && resource.MimeType != "" && inline {
|
||||
contentType = resource.MimeType
|
||||
}
|
||||
streamStoredFile(c, reader, contentType, inline, "private, max-age=86400", "message files")
|
||||
}
|
||||
}
|
||||
|
||||
// serveMessageScopedFiles registers the authenticated proxy used by the chat
|
||||
// renderer for assistant-message resources. The chat API-key capability is
|
||||
// sufficient because GetMessage enforces ownership of the API key's session.
|
||||
func serveMessageScopedFiles(
|
||||
r *gin.RouterGroup,
|
||||
g *rbacGuards,
|
||||
messageService interfaces.MessageService,
|
||||
agentShareService interfaces.AgentShareService,
|
||||
tenantService interfaces.TenantService,
|
||||
globalFileService interfaces.FileService,
|
||||
storageResolver interfaces.StorageBackendResolver,
|
||||
resourceCatalog interfaces.ResourceCatalog,
|
||||
) {
|
||||
g.apiKeyRoute(
|
||||
r,
|
||||
http.MethodGet,
|
||||
"/sessions/:id/messages/:message_id/files",
|
||||
apiKeyChat(apiKeyFullAccess()),
|
||||
g.Viewer(),
|
||||
newMessageScopedFileServeHandler(
|
||||
messageService,
|
||||
agentShareService,
|
||||
tenantService,
|
||||
globalFileService,
|
||||
storageResolver,
|
||||
resourceCatalog,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// servePresignedFiles serves files via HMAC-signed URLs without requiring authentication.
|
||||
// This is used by IM channels to serve images that are embedded in bot replies.
|
||||
//
|
||||
|
|
|
|||
|
|
@ -240,6 +240,20 @@ func NewRouter(params RouterParams) *gin.Engine {
|
|||
params.StorageBackendResolver,
|
||||
params.ResourceCatalog,
|
||||
)
|
||||
// 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.
|
||||
serveMessageScopedFiles(
|
||||
v1,
|
||||
rbacGuards,
|
||||
params.MessageService,
|
||||
params.AgentShareService,
|
||||
params.TenantService,
|
||||
params.FileService,
|
||||
params.StorageBackendResolver,
|
||||
params.ResourceCatalog,
|
||||
)
|
||||
RegisterKnowledgeTagRoutes(v1, params.TagHandler, rbacGuards)
|
||||
RegisterKnowledgeRoutes(v1, params.KnowledgeHandler, rbacGuards)
|
||||
RegisterFAQRoutes(v1, params.FAQHandler, rbacGuards)
|
||||
|
|
|
|||
|
|
@ -27,6 +27,37 @@ type stubResourceCatalog struct {
|
|||
resource *types.StoredResource
|
||||
}
|
||||
|
||||
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) Register(
|
||||
context.Context,
|
||||
uint64,
|
||||
|
|
@ -477,6 +508,230 @@ func TestKBScopedFilesRequiresFilePath(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func newMessageScopedFilesTestEngine(
|
||||
callerTenantID uint64,
|
||||
messageService messageFileLookup,
|
||||
agentShareService sharedAgentFileLookup,
|
||||
tenantService interfaces.TenantService,
|
||||
global interfaces.FileService,
|
||||
resourceCatalog interfaces.ResourceCatalog,
|
||||
) *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,
|
||||
),
|
||||
)
|
||||
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
|
||||
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{AgentID: "agent-1", AgentTenantID: ownerTenantID}, 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)
|
||||
}
|
||||
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) {
|
||||
requestedPath = filePath
|
||||
return io.NopCloser(strings.NewReader("shared-agent-image")), nil
|
||||
}},
|
||||
&stubResourceCatalog{resource: &types.StoredResource{
|
||||
TenantID: ownerTenantID,
|
||||
PhysicalPath: physical,
|
||||
MimeType: "image/png",
|
||||
}},
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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}, 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",
|
||||
}},
|
||||
)
|
||||
|
||||
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{},
|
||||
)
|
||||
|
||||
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}, 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"}},
|
||||
)
|
||||
|
||||
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 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}, 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"}},
|
||||
)
|
||||
|
||||
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 TestServeFilesForcesActiveContentDownload(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
t.Setenv("STORAGE_TYPE", "local")
|
||||
|
|
|
|||
Loading…
Reference in New Issue