From eb6ac0110c7c34d654ec1d6f80e06d38cf341cee Mon Sep 17 00:00:00 2001 From: wizardchen Date: Tue, 4 Aug 2026 23:46:54 +0800 Subject: [PATCH] fix(api): close the resource_urls=public gaps found in review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up on resource_urls=public. Review turned up one authorization gap plus a set of correctness problems in the streaming path. Authorization: - Embed channels were documented as excluded, but nothing enforced it. The delegating handlers hand the visitor's own gin context to the shared handlers, so ?resource_urls=public — and a deployment-wide RESOURCE_URL_MODE=public — reached anonymous traffic and produced shareable, credential-free URLs that bypass the channel-scoped /embed/:channel_id/files proxy. ensureEmbedSession now pins the request context to handle mode, which covers every delegated endpoint including future ones. The downgrade is silent so a client that forwards the parameter keeps working. - A knowledge-base-restricted API key is refused with 403. Such a key is already denied /files because a raw storage path cannot be bound to its allow-list, so handing it anonymous file URLs would reopen that hole from the other side. The default handle mode stays available to it. Streaming: - Rewriter.ref holds its lock across resolution. Resolver implementations keep an unsynchronised per-provider cache, so the previous unlocked window was a real data race for any caller sharing a StreamRewriter between goroutines — which its own doc comment invited. Serialising also collapses a concurrent duplicate into one signature. - Release the holdback buffer on every path that ends a stream while the client is still connected: a user-requested stop, an error event, and giving up on the event store. Only completion flushed before, so the tail generated just before a stop was silently dropped. - A released tail carries the metadata of the event it was cut from instead of a bare event_id. - The maxHeldBytes safety valve aligns to a UTF-8 boundary rather than cutting a character in half, and an unclosed "![…](" only holds back a whitespace-free destination under 2048 bytes, so prose that merely mentions Markdown image syntax no longer stalls the stream behind the buffer. Also resolves the mode before running a knowledge search instead of after, so an invalid value no longer costs a full retrieval, and warns once per distinct bad RESOURCE_URL_MODE value instead of once per process. Co-authored-by: lyingbug --- .env.example | 1 + docs/api/README.md | 7 +- internal/handler/embed_channel.go | 10 +- internal/handler/embed_resource_urls_test.go | 84 +++++++++++++++++ internal/handler/message.go | 12 ++- .../handler/message_resource_urls_test.go | 32 +++++++ internal/handler/session/qa.go | 19 ++-- internal/handler/session/resource_urls.go | 68 +++++++++++--- .../handler/session/resource_urls_test.go | 51 ++++++++++ internal/handler/session/stream.go | 11 ++- internal/storageurl/mode.go | 92 +++++++++++++++++-- internal/storageurl/request_test.go | 45 +++++++++ internal/storageurl/storageurl.go | 18 ++-- internal/storageurl/stream.go | 67 +++++++++++--- internal/storageurl/stream_test.go | 78 +++++++++++++--- 15 files changed, 520 insertions(+), 75 deletions(-) create mode 100644 internal/handler/embed_resource_urls_test.go diff --git a/.env.example b/.env.example index f33e4aca..f31f5b08 100644 --- a/.env.example +++ b/.env.example @@ -97,6 +97,7 @@ DOCREADER_TRANSPORT=grpc # public 依赖上面的 APP_EXTERNAL_URL(或存储后端本身公网可达)才能生成外链; # 无法生成时该引用保持 resource:// 原样,客户端仍可回退到 /files。 # 注意:public 会为每个被引用文件签发限时(WeKnora 2 小时 / MinIO 24 小时)的匿名可读链接。 +# 匿名的 embed 渠道与限定知识库的 API Key 不受本变量影响,始终返回 handle。 # RESOURCE_URL_MODE=handle # 对外暴露的 MCP Server 端口(默认 8082)。 # MCP_PORT=8082 diff --git a/docs/api/README.md b/docs/api/README.md index b191744a..a705f500 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -99,7 +99,12 @@ X-Request-ID: unique_request_id 仍可回退到 `/files` 代理。详见 `.env.example` 中的 `APP_EXTERNAL_URL` 说明。 - **直链是限时匿名可读的**(WeKnora 签发的 grant 2 小时,MinIO 预签名 24 小时)。任何拿到链接的 人在过期前都能读取该文件,请勿写入日志或转发给不应看到该文件的一方。 -- **嵌入式(embed)渠道不支持该参数。** 其访客是匿名的,图片仍走渠道维度的鉴权代理。 +- **嵌入式(embed)渠道不支持该参数。** 其访客是匿名的,`/api/v1/embed/...` 下的接口会强制使用 + `handle`(即使传了 `?resource_urls=public`、或部署默认是 `public`),图片仍走渠道维度的鉴权代理。 +- **限定知识库的 API Key 不能使用 `public`**,返回 `403`。这类 Key 本身也被拒绝访问 `/files` + 代理,若能拿到匿名直链等于绕过同一道限制。改用 `handle` 即可正常调用。 +- **同一文件的直链会在有效期内复用**:重复请求不会反复签发凭证,也不会每次都拿到不同的 URL,客户端 + 和 CDN 的缓存因此可以命中。凭证被吊销或过期后链接立即失效。 ## API 概览 diff --git a/internal/handler/embed_channel.go b/internal/handler/embed_channel.go index df60f51e..b7579e97 100644 --- a/internal/handler/embed_channel.go +++ b/internal/handler/embed_channel.go @@ -17,6 +17,7 @@ import ( "github.com/Tencent/WeKnora/internal/handler/session" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/middleware" + "github.com/Tencent/WeKnora/internal/storageurl" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" secutils "github.com/Tencent/WeKnora/internal/utils" @@ -671,7 +672,14 @@ func (h *EmbedChannelHandler) ensureEmbedSession(c *gin.Context) error { ctx = types.WithEmbedVisitorID(ctx, visitorID) } c.Set(types.PrincipalContextKey.String(), principal) - c.Request = c.Request.WithContext(types.WithPrincipal(ctx, principal)) + // Embed visitors are anonymous, so every delegated handler must keep + // returning `resource://` handles: their images stay behind the + // channel-scoped /embed/:channel_id/files proxy instead of being handed out + // as shareable, credential-free URLs. Pinning it here covers both the + // `?resource_urls=public` query parameter and a deployment-wide + // RESOURCE_URL_MODE=public default. + ctx = storageurl.WithForcedHandleMode(types.WithPrincipal(ctx, principal)) + c.Request = c.Request.WithContext(ctx) return nil } diff --git a/internal/handler/embed_resource_urls_test.go b/internal/handler/embed_resource_urls_test.go new file mode 100644 index 00000000..24330a88 --- /dev/null +++ b/internal/handler/embed_resource_urls_test.go @@ -0,0 +1,84 @@ +package handler + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/Tencent/WeKnora/internal/application/service" + "github.com/Tencent/WeKnora/internal/middleware" + "github.com/Tencent/WeKnora/internal/types" +) + +// newEmbedLoadMessagesCtx builds a signed embed request for the message history +// endpoint, with query carrying whatever the visitor asked for. +func newEmbedLoadMessagesCtx( + ch *types.EmbedChannel, query string, +) (*gin.Context, *httptest.ResponseRecorder) { + gin.SetMode(gin.TestMode) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest( + http.MethodGet, "/messages/"+testEmbedSessionID+"/load"+query, nil) + c.Request.Header.Set("X-Embed-Session", service.SignEmbedSessionHandle(ch, testEmbedSessionID)) + c.Params = gin.Params{{Key: "session_id", Value: testEmbedSessionID}} + ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch) + c.Request = c.Request.WithContext(ctx) + return c, w +} + +func newEmbedHandlerWithMessage(ch *types.EmbedChannel, content string) *EmbedChannelHandler { + return &EmbedChannelHandler{ + sessionService: &stubSessionServiceForEmbed{ + sessions: map[string]*types.Session{testEmbedSessionID: validEmbedSession(ch)}, + }, + messageHandler: &MessageHandler{ + MessageService: &stubMessageService{ + getRecent: func(context.Context, string, int) ([]*types.Message, error) { + return []*types.Message{{ + Content: content, + Images: types.MessageImages{{URL: testResourceHandle}}, + }}, nil + }, + }, + FileService: &stubResourceFileService{url: "https://cdn.example.com/signed.png"}, + }, + } +} + +// Embed visitors are anonymous: their images must stay behind the +// channel-scoped /embed/:channel_id/files proxy. A visitor asking for public +// URLs is downgraded rather than rejected, so an embed client that forwards the +// parameter keeps working. +func TestEmbedLoadMessages_IgnoresPublicResourceURLRequest(t *testing.T) { + ch := testEmbedChannel() + h := newEmbedHandlerWithMessage(ch, "see ![fig]("+testResourceHandle+")") + + c, w := newEmbedLoadMessagesCtx(ch, "?resource_urls=public") + h.EmbedLoadMessages(c) + + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + assert.Contains(t, w.Body.String(), testResourceHandle) + assert.NotContains(t, w.Body.String(), "cdn.example.com") +} + +// The deployment-wide default must not leak public URLs into embed traffic +// either: switching an integration over is a decision about authenticated API +// callers, not about anonymous website visitors. +func TestEmbedLoadMessages_IgnoresDeploymentPublicDefault(t *testing.T) { + t.Setenv("RESOURCE_URL_MODE", "public") + ch := testEmbedChannel() + h := newEmbedHandlerWithMessage(ch, "see ![fig]("+testResourceHandle+")") + + c, w := newEmbedLoadMessagesCtx(ch, "") + h.EmbedLoadMessages(c) + + require.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + assert.Contains(t, w.Body.String(), testResourceHandle) + assert.NotContains(t, w.Body.String(), "cdn.example.com") +} diff --git a/internal/handler/message.go b/internal/handler/message.go index 133410f9..90fc16fa 100644 --- a/internal/handler/message.go +++ b/internal/handler/message.go @@ -51,12 +51,16 @@ func NewMessageHandler( // resolveResourceRewriter builds the storage-reference rewriter for one response // from the request's `resource_urls` parameter, falling back to the deployment -// default. An invalid value is a client error the caller must turn into a 400. +// default. The returned error is already an AppError the caller can hand to +// c.Error: a rejected scope is a 403, a typo in the parameter is a 400. func (h *MessageHandler) resolveResourceRewriter(c *gin.Context) (*storageurl.Rewriter, error) { ctx := c.Request.Context() mode, err := storageurl.ResolveMode(ctx, c.Query(storageurl.QueryParam)) if err != nil { - return nil, err + if stderrors.Is(err, storageurl.ErrPublicModeForbidden) { + return nil, errors.NewForbiddenError(err.Error()) + } + return nil, errors.NewBadRequestError(err.Error()) } return storageurl.NewRequestRewriter(ctx, mode, h.FileService, h.StorageResolver), nil } @@ -91,8 +95,8 @@ func (h *MessageHandler) LoadMessages(c *gin.Context) { rewriter, err := h.resolveResourceRewriter(c) if err != nil { - logger.Warnf(ctx, "Invalid resource URL mode: %v", err) - _ = c.Error(errors.NewBadRequestError(err.Error())) + logger.Warnf(ctx, "Rejected resource URL mode: %v", err) + _ = c.Error(err) return } diff --git a/internal/handler/message_resource_urls_test.go b/internal/handler/message_resource_urls_test.go index a0f403a4..606cce0f 100644 --- a/internal/handler/message_resource_urls_test.go +++ b/internal/handler/message_resource_urls_test.go @@ -134,3 +134,35 @@ func TestLoadMessages_ParameterOverridesDeploymentDefault(t *testing.T) { assert.Equal(t, "see ![fig]("+testResourceHandle+")", loadMessageContent(t, router, "?resource_urls=handle")) } + +// A knowledge-base-restricted API key is denied the /files proxy because a raw +// storage path cannot be bound to its allow-list. Handing it anonymous file URLs +// instead would reopen exactly that hole, so public mode is refused outright. +func TestLoadMessages_RejectsPublicModeForKBRestrictedAPIKey(t *testing.T) { + router := newResourceURLTestRouter(t, nil) + req := httptest.NewRequest(http.MethodGet, "/messages/sess1/load?resource_urls=public", nil) + req = req.WithContext(types.WithTenantAPIKeyScope(req.Context(), types.TenantAPIKeyScope{ + Capabilities: types.StringArray{string(types.APIKeyCapabilityRetrieve)}, + KnowledgeBaseIDs: types.StringArray{"kb-1"}, + })) + + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + assert.Equal(t, http.StatusForbidden, w.Code, "body=%s", w.Body.String()) +} + +// A KB-restricted key keeps working in the default mode: only the public URLs +// are off limits, not the endpoint. +func TestLoadMessages_KBRestrictedAPIKeyStillReadsHandles(t *testing.T) { + router := newResourceURLTestRouter(t, []*types.Message{ + {Content: "see ![fig](" + testResourceHandle + ")"}, + }) + req := httptest.NewRequest(http.MethodGet, "/messages/sess1/load", nil) + req = req.WithContext(types.WithTenantAPIKeyScope(req.Context(), + types.TenantAPIKeyScope{KnowledgeBaseIDs: types.StringArray{"kb-1"}})) + + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + assert.Equal(t, http.StatusOK, w.Code, "body=%s", w.Body.String()) + assert.Contains(t, w.Body.String(), "resource://") +} diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go index 0b519c3b..a9ef0ad0 100644 --- a/internal/handler/session/qa.go +++ b/internal/handler/session/qa.go @@ -119,8 +119,8 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo // has started an invalid value can no longer be reported as a 400. resourceRewriter, err := h.resolveStreamRewriter(c) if err != nil { - logger.Warnf(ctx, "Invalid resource URL mode: %v", err) - return nil, nil, errors.NewBadRequestError(err.Error()) + logger.Warnf(ctx, "Rejected resource URL mode: %v", err) + return nil, nil, err } if h.suggestionService != nil && request.SuggestionAttribution != nil { if err := h.suggestionService.ValidateAttribution(ctx, sessionID, request.Query, request.SuggestionAttribution); err != nil { @@ -664,6 +664,15 @@ func (h *Handler) SearchKnowledge(c *gin.Context) { return } + // Resolve the storage-reference representation before retrieving, so a typo + // or a rejected scope costs nothing. + rewriter, err := h.resolveResourceRewriter(c) + if err != nil { + logger.Warnf(ctx, "Rejected resource URL mode: %v", err) + _ = c.Error(err) + return + } + // Merge single knowledge_base_id into knowledge_base_ids for backward compatibility knowledgeBaseIDs := request.KnowledgeBaseIDs if request.KnowledgeBaseID != "" { @@ -717,12 +726,6 @@ func (h *Handler) SearchKnowledge(c *gin.Context) { } logger.Infof(ctx, "Knowledge search completed, found %d results", len(searchResults)) - rewriter, err := h.resolveResourceRewriter(c) - if err != nil { - logger.Warnf(ctx, "Invalid resource URL mode: %v", err) - _ = c.Error(errors.NewBadRequestError(err.Error())) - return - } c.JSON(http.StatusOK, gin.H{ "success": true, "data": rewriter.CopyReferences(ctx, searchResults), diff --git a/internal/handler/session/resource_urls.go b/internal/handler/session/resource_urls.go index 73315a2b..9fe099f1 100644 --- a/internal/handler/session/resource_urls.go +++ b/internal/handler/session/resource_urls.go @@ -2,8 +2,10 @@ package session import ( "context" + stderrors "errors" "strings" + "github.com/Tencent/WeKnora/internal/errors" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/storageurl" "github.com/Tencent/WeKnora/internal/types" @@ -11,9 +13,19 @@ import ( "github.com/gin-gonic/gin" ) +// resourceModeError turns a mode-resolution failure into the response the client +// should see: a rejected scope is a 403, a typo in the parameter is a 400. +func resourceModeError(err error) error { + if stderrors.Is(err, storageurl.ErrPublicModeForbidden) { + return errors.NewForbiddenError(err.Error()) + } + return errors.NewBadRequestError(err.Error()) +} + // resolveResourceRewriter builds the storage-reference rewriter for one response // from the request's `resource_urls` parameter, falling back to the deployment -// default. An invalid value is a client error the caller must turn into a 400. +// default. The returned error is already an AppError the caller can hand to +// c.Error. // // In the default handle mode the returned rewriter is disabled, so responses are // left exactly as before. @@ -21,7 +33,7 @@ func (h *Handler) resolveResourceRewriter(c *gin.Context) (*storageurl.Rewriter, ctx := c.Request.Context() mode, err := storageurl.ResolveMode(ctx, c.Query(storageurl.QueryParam)) if err != nil { - return nil, err + return nil, resourceModeError(err) } return storageurl.NewRequestRewriter(ctx, mode, h.fileService, h.storageResolver), nil } @@ -29,7 +41,7 @@ func (h *Handler) resolveResourceRewriter(c *gin.Context) (*storageurl.Rewriter, // resolveStreamRewriter is resolveResourceRewriter plus the holdback buffer an // SSE response needs, because a storage reference can straddle two deltas. It // must be called before any SSE header is written so an invalid value is still -// reportable as a normal 400. +// reportable as a normal JSON error. func (h *Handler) resolveStreamRewriter(c *gin.Context) (*storageurl.StreamRewriter, error) { rewriter, err := h.resolveResourceRewriter(c) if err != nil { @@ -47,6 +59,15 @@ var deltaResponseTypes = map[types.ResponseType]bool{ types.ResponseTypeReflection: true, } +// terminalResponseTypes end the message as far as the client is concerned, so +// any buffered tail must be released just before them. An error can be the last +// event a run produces, and a completion may or may not follow it; flushing an +// already-empty buffer is a no-op, so covering both is safe. +var terminalResponseTypes = map[types.ResponseType]bool{ + types.ResponseTypeComplete: true, + types.ResponseTypeError: true, +} + // holdbackKey identifies one delta stream. The event id is the key clients // accumulate on, so interleaved answer and thinking streams hold back // independently; the type prefix lets a flushed remainder be re-emitted as the @@ -73,13 +94,16 @@ func buildStreamResponseFor( return response } + response.KnowledgeReferences = rewriter.Rewriter().CopyReferences(ctx, response.KnowledgeReferences) + response.Data = rewriter.Rewriter().CopyData(ctx, response.Data) if deltaResponseTypes[evt.Type] { - response.Content = rewriter.Push(ctx, holdbackKey(evt.Type, evt.ID), response.Content, evt.Done) + // The rewritten Data rides along with the held tail so a late release + // carries the same metadata as the event it was cut from. + response.Content = rewriter.Push( + ctx, holdbackKey(evt.Type, evt.ID), response.Content, evt.Done, response.Data) } else { response.Content = rewriter.Rewriter().String(ctx, response.Content) } - response.KnowledgeReferences = rewriter.Rewriter().CopyReferences(ctx, response.KnowledgeReferences) - response.Data = rewriter.Rewriter().CopyData(ctx, response.Data) return response } @@ -94,7 +118,7 @@ func emitStreamEvent( rewriter *storageurl.StreamRewriter, ) { response := buildStreamResponseFor(ctx, evt, requestID, rewriter) - if evt.Type == types.ResponseTypeComplete { + if terminalResponseTypes[evt.Type] { flushHeldStreamContent(ctx, c, requestID, rewriter) } c.SSEvent("message", response) @@ -103,8 +127,10 @@ func emitStreamEvent( // flushHeldStreamContent emits whatever the holdback buffer still retains, so a // trailing reference is not dropped when a delta stream ends without a terminal -// chunk. Callers invoke it once the stream is over; if the client has already -// gone there is nobody left to receive it. +// chunk. Every path that stops streaming while the client is still connected +// must call it — completion, a user-requested stop, or giving up on the event +// store — otherwise the tail is silently lost. If the client has already gone +// there is nobody left to receive it. func flushHeldStreamContent( ctx context.Context, c *gin.Context, @@ -115,8 +141,8 @@ func flushHeldStreamContent( if len(held) == 0 || c.Request.Context().Err() != nil { return } - for key, content := range held { - if content == "" { + for key, fragment := range held { + if fragment.Content == "" { continue } responseType, eventID := parseHoldbackKey(key) @@ -124,9 +150,25 @@ func flushHeldStreamContent( c.SSEvent("message", &types.StreamResponse{ ID: requestID, ResponseType: responseType, - Content: content, - Data: map[string]interface{}{"event_id": eventID}, + Content: fragment.Content, + Data: heldFragmentData(fragment.Meta, eventID), }) c.Writer.Flush() } } + +// heldFragmentData rebuilds the metadata for a released tail from the event it +// was cut from, so a client keying off `event_id` — or off anything else the +// original event carried, such as `is_fallback` — sees the same shape. The map +// is copied because an unchanged rewrite returns the stream buffer's own map. +func heldFragmentData(meta interface{}, eventID string) map[string]interface{} { + original, _ := meta.(map[string]interface{}) + data := make(map[string]interface{}, len(original)+1) + for key, value := range original { + data[key] = value + } + if _, ok := data["event_id"]; !ok { + data["event_id"] = eventID + } + return data +} diff --git a/internal/handler/session/resource_urls_test.go b/internal/handler/session/resource_urls_test.go index de020276..302c5bd7 100644 --- a/internal/handler/session/resource_urls_test.go +++ b/internal/handler/session/resource_urls_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/Tencent/WeKnora/internal/event" "github.com/Tencent/WeKnora/internal/storageurl" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" @@ -189,6 +190,56 @@ func TestEmitStreamEvent_FlushesHeldContentBeforeCompletion(t *testing.T) { ) } +// An error can be the last event of a run, so it must release the buffer too — +// otherwise the tail generated before the failure is lost. +func TestEmitStreamEvent_FlushesHeldContentOnError(t *testing.T) { + rewriter := publicStreamRewriter() + ctx := context.Background() + c, recorder := newTestGinContext(t, "?resource_urls=public") + + buildStreamResponseFor(ctx, interfaces.StreamEvent{ + ID: "answer-1", + Type: types.ResponseTypeAnswer, + Content: "tail ![fig](resource://xifDo7", + Data: map[string]interface{}{"event_id": "answer-1", "is_fallback": true}, + }, "req-1", rewriter) + + emitStreamEvent(ctx, c, interfaces.StreamEvent{ + ID: "err-1", Type: types.ResponseTypeError, Content: "upstream failed", Done: true, + }, "req-1", rewriter) + + body := recorder.Body.String() + assert.Contains(t, body, `![fig](resource://xifDo7`, "the tail must not be swallowed") + assert.Contains(t, body, `"is_fallback":true`, + "a released tail must carry the metadata of the event it was cut from") + assert.Less(t, + indexOf(body, `"response_type":"answer"`), + indexOf(body, `"response_type":"error"`), + "held content must precede the error", + ) +} + +// A user-requested stop ends the stream without a completion event, and the text +// generated before it is still the user's content. +func TestHandleAgentEventsForSSE_FlushesHeldContentOnStop(t *testing.T) { + h := &Handler{streamManager: &stubStreamManager{events: []interfaces.StreamEvent{ + {ID: "answer-1", Type: types.ResponseTypeAnswer, Content: "tail ![fig](resource://xifDo7"}, + {ID: "stop-1", Type: types.ResponseType(event.EventStop), Done: true}, + }}} + c, recorder := newTestGinContext(t, "?resource_urls=public") + + h.handleAgentEventsForSSE( + context.Background(), c, "sess1", "msg1", "req-1", nil, false, publicStreamRewriter()) + + body := recorder.Body.String() + assert.Contains(t, body, `![fig](resource://xifDo7`, "the tail must not be swallowed") + assert.Less(t, + indexOf(body, `"response_type":"answer"`), + indexOf(body, `"response_type":"stop"`), + "held content must precede the stop notification", + ) +} + func TestHoldbackKeyRoundTrip(t *testing.T) { responseType, eventID := parseHoldbackKey(holdbackKey(types.ResponseTypeThinking, "think-1")) assert.Equal(t, types.ResponseTypeThinking, responseType) diff --git a/internal/handler/session/stream.go b/internal/handler/session/stream.go index d73b88c3..af5d6ea5 100644 --- a/internal/handler/session/stream.go +++ b/internal/handler/session/stream.go @@ -59,8 +59,8 @@ func (h *Handler) ContinueStream(c *gin.Context) { // is still reportable as a normal 400 JSON error. resourceRewriter, err := h.resolveStreamRewriter(c) if err != nil { - logger.Warnf(ctx, "Invalid resource URL mode: %v", err) - _ = c.Error(errors.NewBadRequestError(err.Error())) + logger.Warnf(ctx, "Rejected resource URL mode: %v", err) + _ = c.Error(err) return } @@ -175,6 +175,7 @@ func (h *Handler) ContinueStream(c *gin.Context) { newEvents, newOffset, err := h.streamManager.GetEvents(ctx, sessionID, messageID, currentOffset) if err != nil { logger.Errorf(ctx, "Failed to get new events: %v", err) + flushHeldStreamContent(ctx, c, message.RequestID, resourceRewriter) return } @@ -382,6 +383,12 @@ func (h *Handler) handleAgentEventsForSSE( }) } + // Release any buffered tail first: the answer generated + // before the stop is still the user's content, and in + // public resource URL mode part of it may be sitting in + // the holdback buffer. + flushHeldStreamContent(ctx, c, requestID, resourceRewriter) + // Send stop notification to frontend c.SSEvent("message", &types.StreamResponse{ ID: requestID, diff --git a/internal/storageurl/mode.go b/internal/storageurl/mode.go index f94c063e..c25f6515 100644 --- a/internal/storageurl/mode.go +++ b/internal/storageurl/mode.go @@ -2,12 +2,14 @@ package storageurl import ( "context" + "errors" "fmt" "os" "strings" "sync" "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" ) // Mode selects how stored files are referenced in an API response. @@ -34,6 +36,33 @@ const ( EnvVar = "RESOURCE_URL_MODE" ) +// ErrPublicModeForbidden is returned when the caller asked for ModePublic but +// its credentials must not receive anonymous, time-limited file URLs. Callers +// map it to 403 rather than 400: the request is well-formed, the scope is not. +var ErrPublicModeForbidden = errors.New( + "resource_urls=public is not available for a knowledge-base-restricted API key") + +// forcedHandleKey marks a request that must never receive public URLs, whatever +// the query parameter or the deployment default says. +type forcedHandleKey struct{} + +// WithForcedHandleMode pins a request to ModeHandle. Anonymous surfaces use it: +// an embed visitor is authorized only by the channel's session handle, so it +// must keep fetching images through the channel-scoped `/embed/…/files` proxy +// instead of receiving a shareable, credential-free URL. +func WithForcedHandleMode(ctx context.Context) context.Context { + return context.WithValue(ctx, forcedHandleKey{}, true) +} + +// HandleModeForced reports whether ctx was pinned by WithForcedHandleMode. +func HandleModeForced(ctx context.Context) bool { + if ctx == nil { + return false + } + forced, _ := ctx.Value(forcedHandleKey{}).(bool) + return forced +} + // ParseMode validates a mode supplied by a client or by configuration. An empty // value yields ModeHandle so an unset parameter or setting keeps the default. func ParseMode(raw string) (Mode, error) { @@ -50,10 +79,27 @@ func ParseMode(raw string) (Mode, error) { } } -// badDefaultOnce keeps a misconfigured EnvVar to a single log line instead of one -// per request. The value itself is re-read every time so operators can roll a -// change out without a restart. -var badDefaultOnce sync.Once +// badDefault keeps a misconfigured EnvVar to a single log line per distinct bad +// value instead of one per request, while still warning again if an operator +// rolls out a second typo. The value itself is re-read every time so a fix takes +// effect without a restart. +var badDefault struct { + sync.Mutex + warned map[string]bool +} + +func warnBadDefaultOnce(ctx context.Context, raw string, err error) { + badDefault.Lock() + defer badDefault.Unlock() + if badDefault.warned[raw] { + return + } + if badDefault.warned == nil { + badDefault.warned = make(map[string]bool) + } + badDefault.warned[raw] = true + logger.Warnf(ctx, "ignoring %s: %v; falling back to %q", EnvVar, err, ModeHandle) +} // DefaultMode returns the deployment-wide default from EnvVar. An unset or // unparseable value yields ModeHandle, so a typo degrades to the safe default @@ -65,18 +111,44 @@ func DefaultMode(ctx context.Context) Mode { } mode, err := ParseMode(raw) if err != nil { - badDefaultOnce.Do(func() { - logger.Warnf(ctx, "ignoring %s: %v; falling back to %q", EnvVar, err, ModeHandle) - }) + warnBadDefaultOnce(ctx, raw, err) return ModeHandle } return mode } -// ResolveMode combines the per-request query value with the deployment default. -// An explicit query value always wins; an invalid one is returned as an error so -// integrators find their typo instead of silently receiving handles. +// ResolveMode combines the per-request query value with the deployment default, +// then applies the two limits that no caller may opt out of. +// +// An explicit query value wins over the deployment default; an invalid one is +// returned as an error so integrators find their typo instead of silently +// receiving handles. +// +// Limits: +// - A ctx pinned by WithForcedHandleMode (anonymous embed traffic) is silently +// downgraded rather than rejected, so an embed client that happens to send +// the parameter keeps working — it just never gets a public URL. +// - A knowledge-base-restricted API key is rejected with +// ErrPublicModeForbidden. Such a key is already denied the `/files` proxy, +// so handing it anonymous file URLs would widen its scope from "chunk text" +// to "file bytes" through the back door. func ResolveMode(ctx context.Context, queryValue string) (Mode, error) { + if HandleModeForced(ctx) { + return ModeHandle, nil + } + mode, err := requestedMode(ctx, queryValue) + if err != nil { + return ModeHandle, err + } + if mode == ModePublic { + if scope, ok := types.TenantAPIKeyScopeFromContext(ctx); ok && scope.IsKnowledgeBaseRestricted() { + return ModeHandle, ErrPublicModeForbidden + } + } + return mode, nil +} + +func requestedMode(ctx context.Context, queryValue string) (Mode, error) { if strings.TrimSpace(queryValue) != "" { return ParseMode(queryValue) } diff --git a/internal/storageurl/request_test.go b/internal/storageurl/request_test.go index 7bdbeee4..96bcd85a 100644 --- a/internal/storageurl/request_test.go +++ b/internal/storageurl/request_test.go @@ -181,6 +181,51 @@ func TestDefaultMode(t *testing.T) { assert.Equal(t, ModeHandle, DefaultMode(ctx), "a typo must degrade to the safe default") } +// Anonymous surfaces (embed channels) pin the mode: neither the query parameter +// nor the deployment default may hand a visitor a credential-free URL. The +// downgrade is silent so a client that forwards the parameter keeps working. +func TestResolveMode_ForcedHandleModeWins(t *testing.T) { + t.Setenv(EnvVar, "public") + ctx := WithForcedHandleMode(context.Background()) + + for _, queryValue := range []string{"", "public", "handle", "nonsense"} { + mode, err := ResolveMode(ctx, queryValue) + require.NoError(t, err, "queryValue=%q", queryValue) + assert.Equal(t, ModeHandle, mode, "queryValue=%q", queryValue) + } +} + +// A KB-restricted API key is denied the /files proxy, so it must not receive +// anonymous file URLs through this parameter either. +func TestResolveMode_RejectsPublicForKBRestrictedKey(t *testing.T) { + ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ + KnowledgeBaseIDs: types.StringArray{"kb-1"}, + }) + + _, err := ResolveMode(ctx, "public") + assert.ErrorIs(t, err, ErrPublicModeForbidden) + + // The deployment default must not smuggle it in either. + t.Setenv(EnvVar, "public") + _, err = ResolveMode(ctx, "") + assert.ErrorIs(t, err, ErrPublicModeForbidden) + + // The default mode stays available: only public URLs are off limits. + mode, err := ResolveMode(ctx, "handle") + require.NoError(t, err) + assert.Equal(t, ModeHandle, mode) +} + +// A full-access or tenant-wide key is unaffected. +func TestResolveMode_AllowsPublicForUnrestrictedKey(t *testing.T) { + ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{ + Capabilities: types.StringArray{string(types.APIKeyCapabilityRetrieve)}, + }) + mode, err := ResolveMode(ctx, "public") + require.NoError(t, err) + assert.Equal(t, ModePublic, mode) +} + func TestResolveMode_QueryWinsOverDeployment(t *testing.T) { ctx := context.Background() t.Setenv(EnvVar, "public") diff --git a/internal/storageurl/storageurl.go b/internal/storageurl/storageurl.go index e1e1dd28..3ebf2dda 100644 --- a/internal/storageurl/storageurl.go +++ b/internal/storageurl/storageurl.go @@ -56,6 +56,11 @@ type Resolver interface { // or per outbound message: a `resource://` handle costs one access-grant row per // resolution, and a streamed answer repeats the same image across many chunks. // +// Safe for concurrent use: mu covers both the memo and the resolver, which is +// itself single-threaded. Resolution therefore serialises across goroutines, +// which is what we want — two chunks naming the same image must not each pay for +// a signature. +// // Logging policy: // - A successful rewrite logs at INFO with the full signed URL so operators // can copy it out of logs and verify public reachability directly. The @@ -109,19 +114,18 @@ func (w *Rewriter) Ref(ctx context.Context, ref string) string { return w.String(ctx, ref) } +// ref resolves one reference. The lock is held across resolve because Resolver +// implementations (FileServiceResolver in particular) keep an unsynchronised +// per-provider cache, and because it collapses a concurrent duplicate into one +// signature instead of two. func (w *Rewriter) ref(ctx context.Context, ref string) string { w.mu.Lock() - cached, ok := w.memo[ref] - w.mu.Unlock() - if ok { + defer w.mu.Unlock() + if cached, ok := w.memo[ref]; ok { return cached } - resolved := w.resolve(ctx, ref) - - w.mu.Lock() w.memo[ref] = resolved - w.mu.Unlock() return resolved } diff --git a/internal/storageurl/stream.go b/internal/storageurl/stream.go index 44914594..f54dd041 100644 --- a/internal/storageurl/stream.go +++ b/internal/storageurl/stream.go @@ -5,6 +5,7 @@ import ( "regexp" "strings" "sync" + "unicode/utf8" ) // ── Incomplete-reference detection ── @@ -35,7 +36,18 @@ func FindIncompleteRef(s string) int { // (the parenthesized part) is not yet closed — e.g. "![alt](minio://part" or // "![alt](". Holding back only from "minio://" would flush "![alt](" to the // client and break the image once the URL arrives in the next chunk. -var incompleteMarkdownImageSuffixRe = regexp.MustCompile(`!\[[^\]]*\]\([^)]*$`) +// +// The destination must be whitespace-free, and FindIncompleteMarkdownImage caps +// its length: a URL contains neither whitespace nor a newline, and even a +// presigned URL stays well under the cap. Without those limits, prose that +// merely mentions an unclosed "…](" (an answer explaining Markdown syntax, or a +// code sample) would look forever-unclosed and stall the rest of the stream. +var incompleteMarkdownImageSuffixRe = regexp.MustCompile(`!\[[^\]]*\]\([^)\s]*$`) + +// maxIncompleteImageBytes bounds how much trailing text may be treated as an +// unfinished Markdown image. Beyond it the text is not plausibly a link, so it +// is flushed instead of buffered. +const maxIncompleteImageBytes = 2048 // FindIncompleteMarkdownImage returns the byte offset of an unclosed // `![alt](url` suffix at the end of s, or -1 if none. @@ -50,7 +62,7 @@ func FindIncompleteMarkdownImage(s string) int { } } loc := incompleteMarkdownImageSuffixRe.FindStringIndex(s) - if loc == nil { + if loc == nil || len(s)-loc[0] > maxIncompleteImageBytes { return -1 } return loc[0] @@ -87,12 +99,27 @@ type StreamRewriter struct { rewriter *Rewriter mu sync.Mutex - held map[string]string + held map[string]heldContent +} + +// heldContent is a retained tail plus the metadata of the event it came from, so +// a tail released after its stream ended can be re-emitted as an equivalent +// event rather than a bare fragment. +type heldContent struct { + content string + meta interface{} +} + +// Held is one released tail: the rewritten content and the metadata carried by +// the last Push that contributed to it. +type Held struct { + Content string + Meta interface{} } // NewStreamRewriter wraps rewriter with per-stream holdback state. func NewStreamRewriter(rewriter *Rewriter) *StreamRewriter { - return &StreamRewriter{rewriter: rewriter, held: make(map[string]string)} + return &StreamRewriter{rewriter: rewriter, held: make(map[string]heldContent)} } // Enabled reports whether this StreamRewriter can rewrite anything. @@ -111,14 +138,16 @@ func (s *StreamRewriter) Rewriter() *Rewriter { // Push feeds the next chunk of the stream identified by key and returns the // rewritten content that is ready to emit. Set flush on the stream's terminal -// chunk to release any held tail. -func (s *StreamRewriter) Push(ctx context.Context, key, chunk string, flush bool) string { +// chunk to release any held tail. meta is retained opaquely alongside the tail +// and handed back by FlushAll so a late release can carry the same metadata as +// the event it was cut from. +func (s *StreamRewriter) Push(ctx context.Context, key, chunk string, flush bool, meta interface{}) string { if !s.Enabled() { return chunk } s.mu.Lock() - pending := s.held[key] + chunk + pending := s.held[key].content + chunk cutoff := len(pending) if !flush { cutoff = HoldbackCutoff(pending) @@ -126,24 +155,34 @@ func (s *StreamRewriter) Push(ctx context.Context, key, chunk string, flush bool // contain a partial reference, which is what an un-rewritten stream // would have shown anyway. if len(pending)-cutoff > maxHeldBytes { - cutoff = len(pending) - maxHeldBytes + cutoff = runeStart(pending, len(pending)-maxHeldBytes) } } emit := pending[:cutoff] if remainder := pending[cutoff:]; remainder == "" { delete(s.held, key) } else { - s.held[key] = remainder + s.held[key] = heldContent{content: remainder, meta: meta} } s.mu.Unlock() return s.rewriter.String(ctx, emit) } +// runeStart moves idx back to the nearest UTF-8 sequence boundary so a byte-based +// cut never splits a character in half. Pattern-derived cutoffs already land on +// ASCII delimiters; this only matters for the maxHeldBytes safety valve. +func runeStart(s string, idx int) int { + for idx > 0 && !utf8.RuneStart(s[idx]) { + idx-- + } + return idx +} + // FlushAll releases every held tail, rewritten, keyed by stream. Callers use it // when a stream ends without a terminal chunk (for example a client // disconnect) so buffered content is not silently dropped. -func (s *StreamRewriter) FlushAll(ctx context.Context) map[string]string { +func (s *StreamRewriter) FlushAll(ctx context.Context) map[string]Held { if !s.Enabled() { return nil } @@ -153,12 +192,12 @@ func (s *StreamRewriter) FlushAll(ctx context.Context) map[string]string { return nil } pending := s.held - s.held = make(map[string]string) + s.held = make(map[string]heldContent) s.mu.Unlock() - out := make(map[string]string, len(pending)) - for key, content := range pending { - out[key] = s.rewriter.String(ctx, content) + out := make(map[string]Held, len(pending)) + for key, held := range pending { + out[key] = Held{Content: s.rewriter.String(ctx, held.content), Meta: held.meta} } return out } diff --git a/internal/storageurl/stream_test.go b/internal/storageurl/stream_test.go index 7ca7552f..e12058d3 100644 --- a/internal/storageurl/stream_test.go +++ b/internal/storageurl/stream_test.go @@ -2,8 +2,11 @@ package storageurl import ( "context" + "strconv" "strings" + "sync" "testing" + "unicode/utf8" "github.com/stretchr/testify/assert" ) @@ -80,6 +83,12 @@ func TestFindIncompleteMarkdownImage(t *testing.T) { {"two images complete", "![a](local://1/a.png) ![b](local://1/b.png)", -1}, {"first complete second incomplete", "![a](local://1/a.png) ![b](minio://part", 22}, {"bracket inside alt text", "![a[b]](minio://wizard-test/10000/part", 0}, + {"destination with whitespace is prose, not a link", "![alt](see the figure below", -1}, + { + "destination too long to be a link", + "![alt](" + strings.Repeat("x", maxIncompleteImageBytes), + -1, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -117,13 +126,13 @@ func TestStreamRewriter_HoldsSplitReference(t *testing.T) { sr := NewStreamRewriter(NewRewriter(stubResolver("https://cdn.example.com/x.png"), "TEST")) ctx := context.Background() - first := sr.Push(ctx, "answer-1", "here it is: ![img](resource://xifDo7", false) + first := sr.Push(ctx, "answer-1", "here it is: ![img](resource://xifDo7", false, nil) assert.Equal(t, "here it is: ", first, "the incomplete image must be held back") - second := sr.Push(ctx, "answer-1", "NTSL300Lp1goVutw) done", false) + second := sr.Push(ctx, "answer-1", "NTSL300Lp1goVutw) done", false, nil) assert.Equal(t, "![img](https://cdn.example.com/x.png) done", second) - assert.Empty(t, sr.Push(ctx, "answer-1", "", true)) + assert.Empty(t, sr.Push(ctx, "answer-1", "", true, nil)) assert.Empty(t, sr.FlushAll(ctx), "nothing should remain held") } @@ -133,11 +142,11 @@ func TestStreamRewriter_KeysAreIndependent(t *testing.T) { sr := NewStreamRewriter(NewRewriter(stubResolver("https://cdn.example.com/x.png"), "TEST")) ctx := context.Background() - assert.Empty(t, sr.Push(ctx, "a", "![x](resource://aaaa", false)) - assert.Equal(t, "plain b", sr.Push(ctx, "b", "plain b", false)) + assert.Empty(t, sr.Push(ctx, "a", "![x](resource://aaaa", false, nil)) + assert.Equal(t, "plain b", sr.Push(ctx, "b", "plain b", false, nil)) assert.Equal(t, "![x](https://cdn.example.com/x.png)", - sr.Push(ctx, "a", "bbbbccccdddddd)", false), + sr.Push(ctx, "a", "bbbbccccdddddd)", false, nil), ) } @@ -146,27 +155,42 @@ func TestStreamRewriter_FlushAllReleasesHeldTail(t *testing.T) { sr := NewStreamRewriter(NewRewriter(stubResolver("https://cdn.example.com/x.png"), "TEST")) ctx := context.Background() - assert.Equal(t, "tail ", sr.Push(ctx, "answer-1", "tail ![img](resource://partial", false)) + meta := map[string]interface{}{"event_id": "answer-1", "is_fallback": true} + assert.Equal(t, "tail ", + sr.Push(ctx, "answer-1", "tail ![img](resource://partial", false, meta)) assert.Equal(t, - map[string]string{"answer-1": "![img](https://cdn.example.com/x.png"}, + map[string]Held{"answer-1": { + Content: "![img](https://cdn.example.com/x.png", + Meta: meta, + }}, sr.FlushAll(ctx), - "the held tail must still reach the client, rewritten where possible", + "the held tail must still reach the client, rewritten, with its metadata", ) } -// Holdback must be bounded so a stream that never closes a Markdown image -// cannot buffer the whole answer. +// Text that merely looks like an unfinished image must not stall the stream: +// prose can contain a literal "](", and a URL never runs this long. +func TestStreamRewriter_LongUnclosedImageIsNotHeld(t *testing.T) { + sr := NewStreamRewriter(NewRewriter(stubResolver("https://cdn.example.com/x.png"), "TEST")) + chunk := "![never closed](" + strings.Repeat("x", maxIncompleteImageBytes) + assert.Equal(t, chunk, sr.Push(context.Background(), "answer-1", chunk, false, nil)) +} + +// Holdback must be bounded so a stream that never terminates a reference cannot +// buffer the whole answer, and the byte-based release must not split a rune. func TestStreamRewriter_HoldbackIsBounded(t *testing.T) { sr := NewStreamRewriter(NewRewriter(stubResolver("https://cdn.example.com/x.png"), "TEST")) ctx := context.Background() var emitted strings.Builder - emitted.WriteString(sr.Push(ctx, "answer-1", "![never closed](", false)) + emitted.WriteString(sr.Push(ctx, "answer-1", "开头 resource://", false, nil)) for i := 0; i < 20; i++ { - emitted.WriteString(sr.Push(ctx, "answer-1", strings.Repeat("x", 1024), false)) + emitted.WriteString(sr.Push(ctx, "answer-1", strings.Repeat("中", 1024), false, nil)) } assert.Greater(t, emitted.Len(), 0, "bounded holdback must release the excess") - assert.LessOrEqual(t, len(sr.held["answer-1"]), maxHeldBytes) + assert.LessOrEqual(t, len(sr.held["answer-1"].content), maxHeldBytes) + assert.True(t, utf8.ValidString(emitted.String()), "the release must not split a rune") + assert.True(t, utf8.ValidString(sr.held["answer-1"].content), "the retained tail must stay valid") } // A disabled rewriter is a pass-through: the default API mode must not add @@ -174,6 +198,30 @@ func TestStreamRewriter_HoldbackIsBounded(t *testing.T) { func TestStreamRewriter_DisabledIsPassThrough(t *testing.T) { sr := NewStreamRewriter(NewRewriter(nil, "TEST")) in := "![img](resource://xifDo7" - assert.Equal(t, in, sr.Push(context.Background(), "answer-1", in, false)) + assert.Equal(t, in, sr.Push(context.Background(), "answer-1", in, false, nil)) assert.False(t, sr.Enabled()) } + +// Two goroutines pushing different streams share one resolver, so resolution +// must be serialised — this fails under -race if it is not. +func TestStreamRewriter_ConcurrentPushIsSafe(t *testing.T) { + sr := NewStreamRewriter(NewRewriter(stubResolver("https://cdn.example.com/x.png"), "TEST")) + ctx := context.Background() + + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + key := "answer-" + strconv.Itoa(i) + for j := 0; j < 20; j++ { + // A distinct reference per push so every call really reaches the + // resolver instead of hitting the memo. + ref := "minio://bucket/10000/" + strconv.Itoa(i) + "-" + strconv.Itoa(j) + ".png" + sr.Push(ctx, key, "![x]("+ref+") ", false, nil) + } + }(i) + } + wg.Wait() + assert.Empty(t, sr.FlushAll(ctx)) +}