WeKnora/internal/handler/embed_channel.go

834 lines
29 KiB
Go
Raw Normal View History

package handler
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/embedpolicy"
apperrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/handler/session"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/middleware"
fix(api): close the resource_urls=public gaps found in review 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 <lyingbug@users.noreply.github.com>
2026-08-04 15:46:54 +00:00
"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"
"github.com/gin-gonic/gin"
"github.com/redis/go-redis/v9"
)
// EmbedChannelHandler manages web embed channel CRUD and public embed endpoints.
type EmbedChannelHandler struct {
embedSvc interfaces.EmbedChannelService
sessionService interfaces.SessionService
sessionHandler *session.Handler
messageHandler *MessageHandler
suggestionHandler *MessageSuggestionHandler
mcpOAuthHandler *MCPOAuthHandler
mcpServiceHandler *MCPServiceHandler
redis *redis.Client
}
func NewEmbedChannelHandler(
embedSvc interfaces.EmbedChannelService,
sessionService interfaces.SessionService,
sessionHandler *session.Handler,
messageHandler *MessageHandler,
suggestionHandler *MessageSuggestionHandler,
mcpOAuthHandler *MCPOAuthHandler,
mcpServiceHandler *MCPServiceHandler,
redisClient *redis.Client,
) *EmbedChannelHandler {
return &EmbedChannelHandler{
embedSvc: embedSvc,
sessionService: sessionService,
sessionHandler: sessionHandler,
messageHandler: messageHandler,
suggestionHandler: suggestionHandler,
mcpOAuthHandler: mcpOAuthHandler,
mcpServiceHandler: mcpServiceHandler,
redis: redisClient,
}
}
type embedChannelRequest struct {
Name string `json:"name"`
Enabled *bool `json:"enabled"`
AllowedOrigins []string `json:"allowed_origins"`
WelcomeMessage string `json:"welcome_message"`
RateLimitPerMinute int `json:"rate_limit_per_minute"`
RateLimitPerDay int `json:"rate_limit_per_day"`
PrimaryColor string `json:"primary_color"`
PageTitle string `json:"page_title"`
HeaderTitleMode string `json:"header_title_mode"`
ShowSuggestedQuestions *bool `json:"show_suggested_questions"`
WidgetPosition string `json:"widget_position"`
AllowWebSearch *bool `json:"allow_web_search"`
AllowFileUpload *bool `json:"allow_file_upload"`
DefaultLocale *string `json:"default_locale"`
WebhookURL *string `json:"webhook_url"`
WebhookSecret *string `json:"webhook_secret"`
AgentID *string `json:"agent_id"`
}
// isProductionMode reports whether the server runs in a hardened (release) mode.
func isProductionMode() bool {
return strings.EqualFold(strings.TrimSpace(os.Getenv("GIN_MODE")), "release")
}
func stringOrEmpty(v *string) string {
if v == nil {
return ""
}
return *v
}
// validateAllowedOrigins validates host-page origins before using them in CSP.
func validateAllowedOrigins(origins []string) error {
if len(origins) == 0 {
return fmt.Errorf("at least one allowed origin is required")
}
count := 0
for _, raw := range origins {
if strings.TrimSpace(raw) == "" {
continue
}
pattern, err := embedpolicy.NormalizePattern(raw)
if err != nil {
return err
}
if pattern == "*" && isProductionMode() {
return fmt.Errorf("wildcard origin '*' is not allowed in production")
}
count++
}
if count == 0 {
return fmt.Errorf("at least one allowed origin is required")
}
return nil
}
func (h *EmbedChannelHandler) CreateEmbedChannel(c *gin.Context) {
agentID := secutils.SanitizeForLog(c.Param("id"))
tenantID := c.GetUint64(types.TenantIDContextKey.String())
var req embedChannelRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := validateAllowedOrigins(req.AllowedOrigins); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
originsJSON, _ := json.Marshal(req.AllowedOrigins)
enabled := true
if req.Enabled != nil {
enabled = *req.Enabled
}
showSuggested := true
if req.ShowSuggestedQuestions != nil {
showSuggested = *req.ShowSuggestedQuestions
}
allowWebSearch := false
if req.AllowWebSearch != nil {
allowWebSearch = *req.AllowWebSearch
}
allowFileUpload := false
if req.AllowFileUpload != nil {
allowFileUpload = *req.AllowFileUpload
}
ch, token, err := h.embedSvc.Create(c.Request.Context(), tenantID, agentID, &types.EmbedChannel{
Name: req.Name,
Enabled: enabled,
AllowedOrigins: originsJSON,
WelcomeMessage: req.WelcomeMessage,
RateLimitPerMinute: req.RateLimitPerMinute,
RateLimitPerDay: req.RateLimitPerDay,
PrimaryColor: req.PrimaryColor,
PageTitle: req.PageTitle,
HeaderTitleMode: req.HeaderTitleMode,
ShowSuggestedQuestions: showSuggested,
WidgetPosition: req.WidgetPosition,
AllowWebSearch: allowWebSearch,
AllowFileUpload: allowFileUpload,
DefaultLocale: types.NormalizeEmbedDefaultLocale(stringOrEmpty(req.DefaultLocale)),
})
if err != nil {
writeEmbedMgmtError(c, err)
return
}
c.JSON(http.StatusCreated, gin.H{
"success": true,
"data": embedChannelResponse(ch, token),
})
}
func (h *EmbedChannelHandler) ListEmbedChannels(c *gin.Context) {
agentID := secutils.SanitizeForLog(c.Param("id"))
tenantID := c.GetUint64(types.TenantIDContextKey.String())
rows, err := h.embedSvc.ListByAgent(c.Request.Context(), tenantID, agentID)
if err != nil {
writeEmbedMgmtError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": embedChannelsResponse(rows)})
}
// ListAllEmbedChannels lists every embed channel in the current tenant, across
// agents, for sidebar session grouping. Publish tokens are never included.
func (h *EmbedChannelHandler) ListAllEmbedChannels(c *gin.Context) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
rows, err := h.embedSvc.ListByTenant(c.Request.Context(), tenantID)
if err != nil {
writeEmbedMgmtError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": embedChannelsResponse(rows)})
}
func embedChannelsResponse(rows []*types.EmbedChannel) []gin.H {
data := make([]gin.H, 0, len(rows))
for _, ch := range rows {
data = append(data, embedChannelResponse(ch, ""))
}
return data
}
func (h *EmbedChannelHandler) UpdateEmbedChannel(c *gin.Context) {
channelID := secutils.SanitizeForLog(c.Param("channel_id"))
tenantID := c.GetUint64(types.TenantIDContextKey.String())
var req embedChannelRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Only validate when the caller intends to change the allowlist. A nil slice
// means "leave unchanged"; a present slice must still be a valid allowlist.
if req.AllowedOrigins != nil {
if err := validateAllowedOrigins(req.AllowedOrigins); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
}
if req.WebhookURL != nil {
if err := service.ValidateEmbedWebhookURL(*req.WebhookURL); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
}
originsJSON, _ := json.Marshal(req.AllowedOrigins)
update := &types.EmbedChannel{
Name: req.Name,
AllowedOrigins: originsJSON,
WelcomeMessage: req.WelcomeMessage,
RateLimitPerMinute: req.RateLimitPerMinute,
RateLimitPerDay: req.RateLimitPerDay,
PrimaryColor: req.PrimaryColor,
PageTitle: req.PageTitle,
HeaderTitleMode: req.HeaderTitleMode,
WidgetPosition: req.WidgetPosition,
}
if req.AgentID != nil {
update.AgentID = strings.TrimSpace(*req.AgentID)
}
ch, err := h.embedSvc.Update(c.Request.Context(), tenantID, channelID, update, req.Enabled, req.ShowSuggestedQuestions, req.AllowWebSearch, req.AllowFileUpload, req.DefaultLocale, req.WebhookURL, req.WebhookSecret)
if err != nil {
writeEmbedMgmtError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": embedChannelResponse(ch, "")})
}
func (h *EmbedChannelHandler) DeleteEmbedChannel(c *gin.Context) {
channelID := secutils.SanitizeForLog(c.Param("channel_id"))
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if err := h.embedSvc.Delete(c.Request.Context(), tenantID, channelID); err != nil {
writeEmbedMgmtError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
func (h *EmbedChannelHandler) RotateEmbedToken(c *gin.Context) {
channelID := secutils.SanitizeForLog(c.Param("channel_id"))
tenantID := c.GetUint64(types.TenantIDContextKey.String())
ch, token, err := h.embedSvc.RotateToken(c.Request.Context(), tenantID, channelID)
if err != nil {
writeEmbedMgmtError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": embedChannelResponse(ch, token)})
}
func (h *EmbedChannelHandler) IssuePreviewSession(c *gin.Context) {
channelID := secutils.SanitizeForLog(c.Param("channel_id"))
tenantID := c.GetUint64(types.TenantIDContextKey.String())
sessionToken, expiresIn, err := h.embedSvc.IssuePreviewSession(c.Request.Context(), tenantID, channelID)
if err != nil {
if errors.Is(err, service.ErrEmbedChannelDisabled) {
c.JSON(http.StatusForbidden, gin.H{"error": "embed channel is disabled"})
return
}
writeEmbedMgmtError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"session_token": sessionToken,
"expires_in": expiresIn,
},
})
}
func (h *EmbedChannelHandler) ExchangeEmbedSession(c *gin.Context) {
ctx := c.Request.Context()
ch, ok := middleware.EmbedChannelFromContext(ctx)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
// Only the long-lived publish token may mint session tokens. Accepting a
// session token here would let a holder renew it indefinitely without ever
// re-presenting the publish token.
if auth := strings.TrimSpace(c.GetHeader("Authorization")); !strings.HasPrefix(auth, "Embed ") ||
service.IsEmbedSessionToken(strings.TrimPrefix(auth, "Embed ")) {
c.JSON(http.StatusForbidden, gin.H{"error": "publish token required"})
return
}
sessionToken, expiresIn, err := h.embedSvc.IssueSessionToken(ctx, ch.ID)
if err != nil {
if errors.Is(err, service.ErrEmbedSessionUnavailable) {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "session tokens unavailable"})
return
}
logger.ErrorWithFields(ctx, err, nil)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to issue session token"})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"session_token": sessionToken,
"expires_in": expiresIn,
},
})
}
func (h *EmbedChannelHandler) GetEmbedConfig(c *gin.Context) {
ch, ok := middleware.EmbedChannelFromContext(c.Request.Context())
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": h.embedSvc.PublicConfig(c.Request.Context(), ch)})
}
func (h *EmbedChannelHandler) GetEmbedChunk(c *gin.Context) {
ch, ok := middleware.EmbedChannelFromContext(c.Request.Context())
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
chunkID := secutils.SanitizeForLog(c.Param("chunk_id"))
if chunkID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "chunk_id is required"})
return
}
chunk, err := h.embedSvc.EmbedChunk(c.Request.Context(), ch, chunkID)
if err != nil {
switch {
case errors.Is(err, service.ErrEmbedChunkForbidden):
c.JSON(http.StatusForbidden, gin.H{"error": "chunk not accessible"})
case errors.Is(err, service.ErrEmbedChunkNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": "chunk not found"})
default:
logger.Error(c.Request.Context(), "embed chunk lookup failed", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load chunk"})
}
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": chunk})
}
func (h *EmbedChannelHandler) GetEmbedSuggestedQuestions(c *gin.Context) {
ch, ok := middleware.EmbedChannelFromContext(c.Request.Context())
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
if !ch.ShowSuggestedQuestions {
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"questions": []types.SuggestedQuestion{}}})
return
}
// limit == 0 signals "unspecified" so the channel agent's starter count
// applies. A provided value is honored up to the embed cap.
limit := 0
if raw := c.Query("limit"); raw != "" {
if n, err := strconv.Atoi(raw); err == nil && n > 0 {
limit = n
if limit > 12 {
limit = 12
}
}
}
questions, err := h.embedSvc.SuggestedQuestions(c.Request.Context(), ch, limit)
if err != nil {
logger.Error(c.Request.Context(), "embed suggested questions failed", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to load suggested questions"})
return
}
if questions == nil {
questions = []types.SuggestedQuestion{}
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{"questions": questions}})
}
func (h *EmbedChannelHandler) CreateEmbedSession(c *gin.Context) {
if len(secutils.SystemHMACKey()) == 0 {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "embed session signing key is not configured"})
return
}
ctx := c.Request.Context()
ch, ok := middleware.EmbedChannelFromContext(ctx)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
tenantID := c.GetUint64(types.TenantIDContextKey.String())
// Leave Title empty so the first visitor message triggers the same async
// title generation as normal chat (see setupSSEStream in session/qa.go).
// Channel display name belongs on the embed page chrome, not every session row.
createdSession := &types.Session{
TenantID: tenantID,
Title: "",
Description: service.EmbedSessionDescription(ch.ID),
}
created, err := h.sessionService.CreateSession(ctx, createdSession)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create session"})
return
}
ownerID := types.EmbedSessionPrincipal(tenantID, ch.ID, created.ID).StorageID()
if err := h.sessionService.SetSessionOwnerID(ctx, tenantID, created.ID, ownerID); err != nil {
logger.Warnf(ctx, "failed to assign embed session owner for %s: %v", created.ID, err)
} else {
created.UserID = ownerID
}
// Hand back a signed handle bound to this session; the widget must echo it
// (X-Embed-Session header) on every subsequent load/chat call.
sig := service.SignEmbedSessionHandle(ch, created.ID)
c.JSON(http.StatusCreated, gin.H{"success": true, "data": gin.H{"id": created.ID, "sig": sig}})
}
func (h *EmbedChannelHandler) EmbedKnowledgeChat(c *gin.Context) {
h.delegateEmbedChat(c, false)
}
func (h *EmbedChannelHandler) EmbedAgentChat(c *gin.Context) {
h.delegateEmbedChat(c, true)
}
func (h *EmbedChannelHandler) EmbedLoadMessages(c *gin.Context) {
if err := h.ensureEmbedSession(c); err != nil {
return
}
h.messageHandler.LoadMessages(c)
}
func (h *EmbedChannelHandler) EmbedStopSession(c *gin.Context) {
if err := h.ensureEmbedSession(c); err != nil {
return
}
h.sessionHandler.StopSession(c)
}
func (h *EmbedChannelHandler) EmbedEnsureMessageSuggestions(c *gin.Context) {
if err := h.ensureEmbedSession(c); err != nil {
return
}
ch, _ := middleware.EmbedChannelFromContext(c.Request.Context())
if ch == nil || !ch.ShowSuggestedQuestions || h.suggestionHandler == nil {
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{
"status": "suppressed", "suppression_reason": "channel_disabled", "questions": []any{},
}})
return
}
h.suggestionHandler.Ensure(c)
}
func (h *EmbedChannelHandler) EmbedGetMessageSuggestions(c *gin.Context) {
if err := h.ensureEmbedSession(c); err != nil {
return
}
ch, _ := middleware.EmbedChannelFromContext(c.Request.Context())
if ch == nil || !ch.ShowSuggestedQuestions || h.suggestionHandler == nil {
c.JSON(http.StatusOK, gin.H{"success": true, "data": gin.H{
"status": "suppressed", "suppression_reason": "channel_disabled", "questions": []any{},
}})
return
}
h.suggestionHandler.Get(c)
}
func (h *EmbedChannelHandler) EmbedRecordSuggestionEvent(c *gin.Context) {
if err := h.ensureEmbedSession(c); err != nil {
return
}
if h.suggestionHandler == nil {
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "suggestion service unavailable"})
return
}
h.suggestionHandler.RecordEvent(c)
}
func (h *EmbedChannelHandler) EmbedResolveMCPOAuth(c *gin.Context) {
if err := h.ensureEmbedSession(c); err != nil {
return
}
if h.mcpOAuthHandler == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "oauth handler unavailable"})
return
}
h.mcpOAuthHandler.ResolveMCPOAuth(c)
}
func (h *EmbedChannelHandler) EmbedCancelMCPOAuth(c *gin.Context) {
if err := h.ensureEmbedSession(c); err != nil {
return
}
if h.mcpOAuthHandler == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "oauth handler unavailable"})
return
}
h.mcpOAuthHandler.CancelMCPOAuth(c)
}
func (h *EmbedChannelHandler) EmbedMCPOAuthAuthorizeURL(c *gin.Context) {
if err := h.ensureEmbedSession(c); err != nil {
return
}
if h.mcpOAuthHandler == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "oauth handler unavailable"})
return
}
h.mcpOAuthHandler.AuthorizeURL(c)
}
func (h *EmbedChannelHandler) EmbedMCPOAuthStatus(c *gin.Context) {
if err := h.ensureEmbedSession(c); err != nil {
return
}
if h.mcpOAuthHandler == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "oauth handler unavailable"})
return
}
h.mcpOAuthHandler.Status(c)
}
func (h *EmbedChannelHandler) EmbedResolveToolApproval(c *gin.Context) {
if err := h.ensureEmbedSession(c); err != nil {
return
}
if h.mcpServiceHandler == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "tool approval handler unavailable"})
return
}
h.mcpServiceHandler.ResolveToolApproval(c)
}
type embedWebhookEventRequest struct {
Type string `json:"type"`
SessionID string `json:"session_id"`
Query string `json:"query"`
Content string `json:"content"`
}
// EmbedRelayWebhookEvent forwards a visitor chat event to the channel webhook URL.
func (h *EmbedChannelHandler) EmbedRelayWebhookEvent(c *gin.Context) {
ch, ok := middleware.EmbedChannelFromContext(c.Request.Context())
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
if err := h.ensureEmbedSession(c); err != nil {
return
}
var req embedWebhookEventRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return
}
eventType := strings.TrimSpace(req.Type)
switch eventType {
case "message_sent", "message_received":
default:
c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported event type"})
return
}
payload := map[string]any{}
if q := strings.TrimSpace(req.Query); q != "" {
payload["query"] = q
}
if content := strings.TrimSpace(req.Content); content != "" {
payload["content"] = content
}
sessionID := strings.TrimSpace(req.SessionID)
if sessionID == "" {
sessionID = secutils.SanitizeForLog(c.Param("session_id"))
}
service.DispatchEmbedWebhook(ch, eventType, sessionID, payload)
c.JSON(http.StatusOK, gin.H{"success": true})
}
func (h *EmbedChannelHandler) delegateEmbedChat(c *gin.Context, agentMode bool) {
ch, ok := middleware.EmbedChannelFromContext(c.Request.Context())
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
if err := h.ensureEmbedSession(c); err != nil {
return
}
patched, err := patchEmbedChatPayload(c.Request.Body, ch, agentMode)
if err != nil {
switch {
case errors.Is(err, errInvalidEmbedChatBody):
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
case errors.Is(err, errInvalidEmbedChatJSON):
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid json"})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to prepare request"})
}
return
}
c.Request.Body = io.NopCloser(bytes.NewReader(patched))
c.Request.ContentLength = int64(len(patched))
if agentMode && ch.AgentID != types.BuiltinQuickAnswerID {
h.sessionHandler.AgentQA(c)
return
}
h.sessionHandler.KnowledgeQA(c)
}
func (h *EmbedChannelHandler) ensureEmbedSession(c *gin.Context) error {
ch, ok := middleware.EmbedChannelFromContext(c.Request.Context())
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return apperrors.NewUnauthorizedError("unauthorized")
}
sessionID := secutils.SanitizeForLog(c.Param("session_id"))
if sessionID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "session_id is required"})
return apperrors.NewBadRequestError("session_id is required")
}
sess, err := h.sessionService.GetSessionByID(c.Request.Context(), ch.TenantID, sessionID)
if err != nil || sess == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "session not found"})
return apperrors.NewNotFoundError("session not found")
}
marker := service.EmbedSessionDescription(ch.ID)
if sess.TenantID != ch.TenantID || sess.Description != marker {
c.JSON(http.StatusForbidden, gin.H{"error": "session not allowed for this embed channel"})
return apperrors.NewForbiddenError("session not allowed")
}
ownerID := types.EmbedSessionPrincipal(ch.TenantID, ch.ID, sessionID).StorageID()
if strings.TrimSpace(sess.UserID) == "" {
if err := h.sessionService.SetSessionOwnerID(c.Request.Context(), ch.TenantID, sessionID, ownerID); err != nil {
logger.Warnf(c.Request.Context(), "failed to backfill embed session owner for %s: %v", sessionID, err)
}
}
// Require the signed handle minted at creation. This is the per-visitor
// authorization secret: knowing the session id alone (e.g. from a leaked
// access log) is insufficient without the matching signature.
sig := c.GetHeader("X-Embed-Session")
if !service.VerifyEmbedSessionHandle(ch, sessionID, sig) {
c.JSON(http.StatusForbidden, gin.H{"error": "session signature invalid"})
return apperrors.NewForbiddenError("session signature invalid")
}
principal := types.EmbedSessionPrincipal(ch.TenantID, ch.ID, sessionID)
ctx := c.Request.Context()
if visitorID := strings.TrimSpace(c.GetHeader(types.EmbedVisitorHeader)); visitorID != "" {
if err := types.ValidateEmbedVisitorID(visitorID); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid embed visitor id"})
return apperrors.NewBadRequestError("invalid embed visitor id")
}
ctx = types.WithEmbedVisitorID(ctx, visitorID)
2026-06-30 01:21:49 +00:00
}
c.Set(types.PrincipalContextKey.String(), principal)
fix(api): close the resource_urls=public gaps found in review 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 <lyingbug@users.noreply.github.com>
2026-08-04 15:46:54 +00:00
// 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
}
var (
errInvalidEmbedChatBody = errors.New("invalid embed chat request body")
errInvalidEmbedChatJSON = errors.New("invalid embed chat json")
)
// patchEmbedChatPayload merges embed-channel constraints into the client QA body.
func patchEmbedChatPayload(body io.Reader, ch *types.EmbedChannel, agentMode bool) ([]byte, error) {
raw, err := io.ReadAll(body)
if err != nil {
return nil, fmt.Errorf("%w: %v", errInvalidEmbedChatBody, err)
}
var payload map[string]any
if len(raw) > 0 {
if err := json.Unmarshal(raw, &payload); err != nil {
return nil, fmt.Errorf("%w: %v", errInvalidEmbedChatJSON, err)
}
}
if payload == nil {
payload = make(map[string]any)
}
payload["agent_id"] = ch.AgentID
fix(security): close cross-workspace access paths in shared spaces (#3408) * fix(security): close cross-workspace access paths in shared spaces A review of how shared-space (organization) members reach each other's resources found six paths that bypass the org-share permission model: - presigned-preview signed any resource handle or storage path, turning a known resource:// handle into an anonymous /r/ URL that outlives share revocation. It now requires the path to belong to the caller's tenant, like /files. - POST /initialization/initialize let a shared-KB editor rewrite the owner workspace's models (base URL, API key) in place. Only the KB's own workspace may call it, and rewriting a stored model needs the same authority as PUT /models/:id. - KB JSON carried the legacy inline credentials (storage_config secret_id/secret_key, which initialization fills with the MinIO env keys, and vlm_config api_key) to every share receiver. They are withheld from JSON; their DB columns are unchanged. - A chat without agent_source_tenant_id resolved shares before the caller's own agent, so a member sharing a same-ID built-in agent took over other workspaces' default agent. Own agents now win, built-in agents can no longer be shared (existing such shares no longer resolve), and embed channels drop a visitor-supplied source workspace. - Any org-admin tenant (even a tenant Viewer inside it) could raise another workspace's KB share to editor/admin, and the route guard was bypassable via an unrelated :id. Share management is now: the sharer from the source tenant (Contributor+), source-tenant Admin+, or an org-admin tenant's Admin+ that may only remove or lower. share_id must belong to :id. - Wiki write tools were registered for every wiki KB in the search targets, which only need read access, so a viewer share (e.g. via the built-in wiki fixer) could edit or delete another workspace's wiki pages. They now act only on KBs the caller may edit. * fix(security): close the KB settings path and owner details for share receivers Follow-up to the shared-space review: - PUT /initialization/config shares the route guard that admits share editors, so an editor could still rebind the owner's KB models, chunking and storage, and storage backends resolved against the caller's workspace let it bind the owner's KB to its own backend. Another workspace now needs an admin share (the only share level the frontend offers settings to) and may not change the storage binding at all. - GET /initialization/config showed model base URLs and bucket locations to any admin of the caller's own workspace, including share receivers. They now only see whether credentials are configured. - Wiki write tools on the caller's own KBs had no role floor, so a tenant Viewer (and the IM, embed and MCP endpoint principals that run as Viewer) could write through an agent what the HTTP routes deny. Writes now need Contributor+, or the ingest capability for a scoped API key, following the RBAC rollout switch. - resolveAgent logs the share lookup error instead of a nil own-agent error when a shared selector fails. * fix(security): close the medium shared-space access findings Follow-up to the high-risk fixes, from the same review: - Wiki fixer moved into a shared KB's workspace ran with the caller's own config there: an unset MCP mode registered all of the owner's MCP services, and an "all" KB scope reached the owner's other KBs. The scoped run now uses the built-in config pinned to that one KB, without MCP, skills, sandbox or web search, and falls back to the KB's own model. - An unset MCP mode means "all" at runtime but is shown as none in the share scope; shared runs now treat it as none. - Quick-answer mode used the request's web_search_enabled alone, so a receiver could turn on search the agent disables and spend the owner's provider quota. It now requires the agent setting too, as agent mode does. - summary_model_id picked any model of the workspace a run executes in. It is ignored for shared agents and the relocated wiki fixer. - A workspace that left or was removed from an organization kept sharing its KBs and agents. Its shares are revoked on departure, and share queries and permission checks require the source workspace's membership and a live organization, which also covers rows left behind earlier. - Sharing an agent exposes its KB scope to all members, so a Contributor could share colleagues' KBs (or "all") through an agent. The sharer must now be able to share each KB directly (creator or Admin+; "all" needs Admin+), also when a shared agent's scope is widened later. - A scoped API key with manage_channels could mint an MCP endpoint token wider than itself. Endpoints it creates, updates or rotates must stay within its KB allow-list and capabilities. - A shared agent's run indexed the receiver's Q&A into the owner's chat history KB; indexing now uses the session owner's configuration. - Sharing an agent with skills keeps injecting the owner's skill environment values (product decision); the share panel now warns that members can read them. Preview of originals through read-only shares is kept as designed and documented.
2026-09-18 14:00:02 +00:00
// The channel's agent belongs to the channel's workspace; a visitor-supplied
// source workspace would switch it to another workspace's share of that ID.
delete(payload, types.AgentSourceTenantIDParam)
payload["knowledge_base_ids"] = []string{}
fix(security): close the low-severity shared-space findings (#3416) * fix(security): close the low-severity shared-space findings Verified and fixed from the shared-space permission review: - Embed channels kept knowledge_ids, tag_ids, mentioned_items, skill_names and summary_model_id from anonymous visitors. Mentions are only scoped for shared agents, so a visitor could query any KB (and pick any model) of the channel workspace by ID. The payload now drops them; the widget never sends them. - PUT /knowledgebase/:kb_id/wiki/issues/:issue_id/status updated any issue by ID. The update is now scoped to the path's KB (404 otherwise). - A direct org invite let the inviter attach any user of the target workspace (or any user by ID) as its representative, whose username and email the roster then showed to all members. Direct adds attach no representative, and the roster returns emails only for the caller's own workspace. - COS and KS3 dropped the bucket (and COS the region) segment when turning a path into an object key, while the tenant check scans every segment: cos://42/<region>/prefix/7/... passed as tenant 42 and read tenant 7's object from a shared bucket. Both must now match the service's config. - Shared agent listings returned the full agent to receivers. Prompts and the creator's user ID are withheld; capabilities and scope stay visible. - Temporary document uploads let the caller pick the parser engine (and its credentials) of a shared agent's workspace; only the agent's rules choose one there now. - Suggested questions used request / message-snapshot knowledge_ids without a permission check. Each document is now resolved to its KB and checked like KB IDs, including a shared agent's scope. - IM channels accepted any knowledge_base_id (and any agent ID on create). Both must belong to the channel's workspace, the KB also to a restricted API key's allow-list. - KB-restricted API keys could list org-shared KBs outside their allow-list in the organization views; those listings are now filtered. - With enable_rbac=false, RequireKBAccess let cross-workspace denials through. That switch is for roles inside a workspace; the guard now always denies another workspace's KB, since handlers behind it load by ID without a tenant filter. - The org member limit was counted before and enforced apart from the insert; it is now checked in the insert's transaction with the organization row locked (SQLite serializes writers instead). - The UpdateOrganization route comment and API doc said owner-only; the service and UI allow org admins. Comment and doc corrected. Documented, not changed: issued /r/ and presigned links stay valid until they expire after a share is revoked. * fix(security): address review of the low-severity shared-space fixes - Embed payloads also drop question_origin. It selects a KB like an @mention for agents that retrieve only when mentioned, and the widget never sends it; the selection stays inside the agent's scope, but an anonymous visitor should not pick among its KBs. suggestion_attribution is kept (the widget sends it and it is validated). - The receiver view of a shared agent also withholds the follow-up suggestion instruction, a prompt like the others. Starter questions are shown to receivers anyway, and the sharer's name is displayed by design. - Follow-up suggestion generation moves into the agent's workspace with types.WithExecutionTenant instead of a bare tenant rewrite, so the caller is pinned before the document permission check runs. The auth middleware and the shared run already pinned it; this removes the dependency on that. - KS3 CopyFile copies only from the service's own bucket (as COS and S3 do); another bucket's path is a cross-backend copy. Tests cover the dropped question_origin, the follow-up instruction and the /shared-agents listing, a follow-up context with the tenant switched, a repeated wiki issue status update, and the KS3 copy source.
2026-09-18 14:58:46 +00:00
// Visitors are anonymous and run as Viewer of the whole channel workspace.
// Explicit targets (documents, tags, @mentions) and a model override are
// only honored within an agent's scope for shared agents, so for a
// channel's own agent they would reach any KB or model of the workspace by
// ID. A question origin selects a KB like an @mention for agents that
// retrieve only when mentioned. The widget never sends any of them;
// retrieval follows the channel agent. (suggestion_attribution is sent,
// and is validated against the session's recorded suggestions.)
payload["knowledge_ids"] = []string{}
payload["tag_ids"] = []string{}
payload["mentioned_items"] = []any{}
payload["skill_names"] = []string{}
delete(payload, "summary_model_id")
delete(payload, "question_origin")
clientWebSearch := false
if v, ok := payload["web_search_enabled"].(bool); ok {
clientWebSearch = v
}
// Channel allow_web_search only exposes the visitor toggle; the client must opt in.
payload["web_search_enabled"] = ch.AllowWebSearch && clientWebSearch
if !ch.AllowFileUpload {
delete(payload, "images")
delete(payload, "attachment_uploads")
delete(payload, "attachment_ids")
}
payload["mcp_service_ids"] = []string{}
if agentMode {
payload["agent_enabled"] = true
} else {
payload["agent_enabled"] = false
}
patched, err := json.Marshal(payload)
if err != nil {
return nil, err
}
return patched, nil
}
// GetEmbedChannel returns a single embed channel for management, including the
// publish token so admins can copy deploy snippets at any time.
func (h *EmbedChannelHandler) GetEmbedChannel(c *gin.Context) {
channelID := strings.TrimSpace(c.Param("channel_id"))
tenantID := c.GetUint64(types.TenantIDContextKey.String())
ch, err := h.embedSvc.GetOwnedChannel(c.Request.Context(), tenantID, channelID)
if err != nil {
writeEmbedMgmtError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": embedChannelResponse(ch, ch.PublishToken),
})
}
// GetEmbedChannelStats returns lightweight usage stats for an embed channel.
func (h *EmbedChannelHandler) GetEmbedChannelStats(c *gin.Context) {
channelID := strings.TrimSpace(c.Param("channel_id"))
tenantID := c.GetUint64(types.TenantIDContextKey.String())
ctx := c.Request.Context()
if _, err := h.embedSvc.GetOwnedChannel(ctx, tenantID, channelID); err != nil {
writeEmbedMgmtError(c, err)
return
}
result, err := h.sessionService.CountSessionsBySource(ctx, &types.SessionListQuery{
TenantID: tenantID,
Source: "embed:" + channelID,
Page: 1,
PageSize: 1,
})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
total := result
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"session_count": total,
},
})
}
func embedChannelResponse(ch *types.EmbedChannel, publishToken string) gin.H {
row := gin.H{
"id": ch.ID,
"tenant_id": ch.TenantID,
"agent_id": ch.AgentID,
"name": ch.Name,
"enabled": ch.Enabled,
"allowed_origins": ch.AllowedOriginsList(),
"welcome_message": ch.WelcomeMessage,
"rate_limit_per_minute": ch.RateLimitPerMinute,
"rate_limit_per_day": ch.RateLimitPerDay,
"primary_color": ch.PrimaryColor,
"page_title": ch.PageTitle,
"header_title_mode": types.NormalizeEmbedHeaderTitleMode(ch.HeaderTitleMode),
"show_suggested_questions": ch.ShowSuggestedQuestions,
"widget_position": ch.WidgetPosition,
"allow_web_search": ch.AllowWebSearch,
"allow_file_upload": ch.AllowFileUpload,
"default_locale": ch.DefaultLocale,
"webhook_url": ch.WebhookURL,
"has_webhook_secret": ch.WebhookSecret != "",
"created_at": ch.CreatedAt,
"updated_at": ch.UpdatedAt,
}
if publishToken != "" {
row["publish_token"] = publishToken
}
return row
}
func writeEmbedMgmtError(c *gin.Context, err error) {
switch {
case errors.Is(err, service.ErrEmbedChannelNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": "embed channel not found"})
case errors.Is(err, service.ErrEmbedWebhookURLInvalid):
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
default:
var appErr *apperrors.AppError
if errors.As(err, &appErr) && appErr.Code == apperrors.ErrNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": appErr.Message})
return
}
logger.Error(c.Request.Context(), "embed channel management failed", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "operation failed"})
}
}