feat(embed): add backend embed channels with auth and rate limiting (#1657)

Introduce embed_channels storage, publish-token and session-token auth,
origin allowlist enforcement, shared Redis rate limiter, public embed API
routes, webhooks with SSRF validation, and session listing by embed source.
This commit is contained in:
wizardchen
2026-06-12 22:40:18 +08:00
committed by lyingbug
parent a0786b6fe7
commit ed9802ff2b
30 changed files with 4070 additions and 216 deletions
+681
View File
@@ -0,0 +1,681 @@
package handler
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/application/service"
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"
"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
redis *redis.Client
}
func NewEmbedChannelHandler(
embedSvc interfaces.EmbedChannelService,
sessionService interfaces.SessionService,
sessionHandler *session.Handler,
messageHandler *MessageHandler,
redisClient *redis.Client,
) *EmbedChannelHandler {
return &EmbedChannelHandler{
embedSvc: embedSvc,
sessionService: sessionService,
sessionHandler: sessionHandler,
messageHandler: messageHandler,
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"`
AllowMemory *bool `json:"allow_memory"`
AllowFileUpload *bool `json:"allow_file_upload"`
DefaultLocale *string `json:"default_locale"`
WebhookURL *string `json:"webhook_url"`
WebhookSecret *string `json:"webhook_secret"`
}
// 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 enforces that a public embed channel declares an
// explicit origin allowlist. An empty list means "allow any origin" in the
// auth middleware, which is unsafe for a publicly reachable widget, so it is
// rejected. In production a wildcard ("*") is also rejected; each entry must be
// a well-formed http(s) origin (optionally a "*." subdomain wildcard).
func validateAllowedOrigins(origins []string) error {
cleaned := make([]string, 0, len(origins))
for _, o := range origins {
o = strings.TrimSpace(o)
if o == "" {
continue
}
cleaned = append(cleaned, o)
}
if len(cleaned) == 0 {
return fmt.Errorf("at least one allowed origin is required")
}
for _, o := range cleaned {
if o == "*" {
if isProductionMode() {
return fmt.Errorf("wildcard origin '*' is not allowed in production")
}
continue
}
host := o
if strings.HasPrefix(o, "*.") {
host = "https://" + strings.TrimPrefix(o, "*.")
}
u, err := url.Parse(host)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return fmt.Errorf("invalid allowed origin: %q", o)
}
}
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
}
allowMemory := false
if req.AllowMemory != nil {
allowMemory = *req.AllowMemory
}
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,
AllowMemory: allowMemory,
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,
}
ch, err := h.embedSvc.Update(c.Request.Context(), tenantID, channelID, update, req.Enabled, req.ShowSuggestedQuestions, req.AllowWebSearch, req.AllowMemory, 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
}
if chunk.Content != "" {
chunk.Content = secutils.SanitizeForDisplay(chunk.Content)
}
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 := 6
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) {
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
}
// 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)
}
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.GetSession(c.Request.Context(), 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")
}
// 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")
}
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
payload["knowledge_base_ids"] = []string{}
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
// Embed memory UI is disabled for now; always off regardless of channel flag.
payload["enable_memory"] = false
if !ch.AllowFileUpload {
delete(payload, "images")
delete(payload, "attachment_uploads")
}
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
}
// 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.ListSessions(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 := int64(0)
if result != nil {
total = result.Total
}
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_memory": ch.AllowMemory,
"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"})
}
}
@@ -0,0 +1,152 @@
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
type exchangeEmbedSvc struct {
sessionToken string
expiresIn int
err error
}
func (f *exchangeEmbedSvc) Create(context.Context, uint64, string, *types.EmbedChannel) (*types.EmbedChannel, string, error) {
return nil, "", nil
}
func (f *exchangeEmbedSvc) ListByAgent(context.Context, uint64, string) ([]*types.EmbedChannel, error) {
return nil, nil
}
func (f *exchangeEmbedSvc) ListByTenant(context.Context, uint64) ([]*types.EmbedChannel, error) {
return nil, nil
}
func (f *exchangeEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
return nil, nil
}
func (f *exchangeEmbedSvc) GetOwnedChannel(context.Context, uint64, string) (*types.EmbedChannel, error) {
return nil, service.ErrEmbedChannelNotFound
}
func (f *exchangeEmbedSvc) Delete(context.Context, uint64, string) error { return nil }
func (f *exchangeEmbedSvc) RotateToken(context.Context, uint64, string) (*types.EmbedChannel, string, error) {
return nil, "", nil
}
func (f *exchangeEmbedSvc) LookupForEmbed(context.Context, string, string) (*types.EmbedChannel, error) {
return nil, nil
}
func (f *exchangeEmbedSvc) LookupEnabledChannel(context.Context, string) (*types.EmbedChannel, error) {
return nil, nil
}
func (f *exchangeEmbedSvc) IssueSessionToken(context.Context, string) (string, int, error) {
if f.err != nil {
return "", 0, f.err
}
return f.sessionToken, f.expiresIn, nil
}
func (f *exchangeEmbedSvc) IssuePreviewSession(context.Context, uint64, string) (string, int, error) {
return f.IssueSessionToken(context.Background(), "")
}
func (f *exchangeEmbedSvc) ResolveSessionToken(context.Context, string) (string, error) {
return "", nil
}
func (f *exchangeEmbedSvc) PublicConfig(context.Context, *types.EmbedChannel) types.EmbedChannelPublicConfig {
return types.EmbedChannelPublicConfig{}
}
func (f *exchangeEmbedSvc) SuggestedQuestions(context.Context, *types.EmbedChannel, int) ([]types.SuggestedQuestion, error) {
return nil, nil
}
func (f *exchangeEmbedSvc) EmbedChunk(context.Context, *types.EmbedChannel, string) (*types.Chunk, error) {
return nil, nil
}
func (f *exchangeEmbedSvc) EmbedDisplayTitle(context.Context, *types.EmbedChannel) string {
return "AI Assistant"
}
func TestExchangeEmbedSessionSuccess(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &EmbedChannelHandler{embedSvc: &exchangeEmbedSvc{
sessionToken: "ems_test_token",
expiresIn: 1800,
}}
r := gin.New()
r.POST("/exchange", func(c *gin.Context) {
ch := &types.EmbedChannel{ID: "channel-1", Enabled: true}
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
h.ExchangeEmbedSession(c)
})
req := httptest.NewRequest(http.MethodPost, "/exchange", nil)
req.Header.Set("Authorization", "Embed em_publish_token")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
var resp struct {
Success bool `json:"success"`
Data struct {
SessionToken string `json:"session_token"`
ExpiresIn int `json:"expires_in"`
} `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatal(err)
}
if !resp.Success || resp.Data.SessionToken != "ems_test_token" || resp.Data.ExpiresIn != 1800 {
t.Fatalf("unexpected response: %#v", resp)
}
}
func TestExchangeEmbedSessionUnavailable(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &EmbedChannelHandler{embedSvc: &exchangeEmbedSvc{err: service.ErrEmbedSessionUnavailable}}
r := gin.New()
r.POST("/exchange", func(c *gin.Context) {
ch := &types.EmbedChannel{ID: "channel-1", Enabled: true}
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
h.ExchangeEmbedSession(c)
})
req := httptest.NewRequest(http.MethodPost, "/exchange", nil)
req.Header.Set("Authorization", "Embed em_publish_token")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", w.Code)
}
}
func TestExchangeEmbedSessionRejectsSessionToken(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &EmbedChannelHandler{embedSvc: &exchangeEmbedSvc{sessionToken: "ems_new", expiresIn: 1800}}
r := gin.New()
r.POST("/exchange", func(c *gin.Context) {
ch := &types.EmbedChannel{ID: "channel-1", Enabled: true}
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
h.ExchangeEmbedSession(c)
})
req := httptest.NewRequest(http.MethodPost, "/exchange", nil)
req.Header.Set("Authorization", "Embed ems_existing_session")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, want 403", w.Code)
}
}
+305
View File
@@ -0,0 +1,305 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
type flowEmbedSvc struct {
sessionToken string
expiresIn int
issueErr error
channels map[string]*types.EmbedChannel
}
func (f *flowEmbedSvc) Create(context.Context, uint64, string, *types.EmbedChannel) (*types.EmbedChannel, string, error) {
return nil, "", nil
}
func (f *flowEmbedSvc) ListByAgent(context.Context, uint64, string) ([]*types.EmbedChannel, error) {
return nil, nil
}
func (f *flowEmbedSvc) ListByTenant(context.Context, uint64) ([]*types.EmbedChannel, error) {
return nil, nil
}
func (f *flowEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
return nil, nil
}
func (f *flowEmbedSvc) GetOwnedChannel(_ context.Context, tenantID uint64, id string) (*types.EmbedChannel, error) {
ch := f.channels[id]
if ch == nil || ch.TenantID != tenantID {
return nil, service.ErrEmbedChannelNotFound
}
return ch, nil
}
func (f *flowEmbedSvc) Delete(context.Context, uint64, string) error { return nil }
func (f *flowEmbedSvc) RotateToken(context.Context, uint64, string) (*types.EmbedChannel, string, error) {
return nil, "", nil
}
func (f *flowEmbedSvc) LookupForEmbed(_ context.Context, channelID, token string) (*types.EmbedChannel, error) {
ch := f.channels[channelID]
if ch == nil || ch.PublishToken != token {
return nil, service.ErrEmbedTokenInvalid
}
if !ch.Enabled {
return nil, service.ErrEmbedChannelDisabled
}
return ch, nil
}
func (f *flowEmbedSvc) LookupEnabledChannel(context.Context, string) (*types.EmbedChannel, error) {
return nil, nil
}
func (f *flowEmbedSvc) IssueSessionToken(context.Context, string) (string, int, error) {
if f.issueErr != nil {
return "", 0, f.issueErr
}
return f.sessionToken, f.expiresIn, nil
}
func (f *flowEmbedSvc) IssuePreviewSession(context.Context, uint64, string) (string, int, error) {
return f.IssueSessionToken(context.Background(), "")
}
func (f *flowEmbedSvc) ResolveSessionToken(context.Context, string) (string, error) {
return "", nil
}
func (f *flowEmbedSvc) PublicConfig(context.Context, *types.EmbedChannel) types.EmbedChannelPublicConfig {
return types.EmbedChannelPublicConfig{}
}
func (f *flowEmbedSvc) SuggestedQuestions(context.Context, *types.EmbedChannel, int) ([]types.SuggestedQuestion, error) {
return nil, nil
}
func (f *flowEmbedSvc) EmbedChunk(context.Context, *types.EmbedChannel, string) (*types.Chunk, error) {
return nil, nil
}
func (f *flowEmbedSvc) EmbedDisplayTitle(context.Context, *types.EmbedChannel) string {
return "AI Assistant"
}
type flowTenantSvc struct {
tenant *types.Tenant
}
func (f *flowTenantSvc) GetTenantByID(context.Context, uint64) (*types.Tenant, error) {
return f.tenant, nil
}
func (f *flowTenantSvc) CreateTenant(context.Context, *types.Tenant) (*types.Tenant, error) {
return nil, nil
}
func (f *flowTenantSvc) GetTenantsByIDs(context.Context, []uint64) (map[uint64]*types.Tenant, error) {
return nil, nil
}
func (f *flowTenantSvc) UpdateTenant(context.Context, *types.Tenant) (*types.Tenant, error) {
return nil, nil
}
func (f *flowTenantSvc) DeleteTenant(context.Context, uint64) error { return nil }
func (f *flowTenantSvc) ListTenants(context.Context) ([]*types.Tenant, error) {
return nil, nil
}
func (f *flowTenantSvc) UpdateAPIKey(context.Context, uint64) (string, error) {
return "", nil
}
func (f *flowTenantSvc) ExtractTenantIDFromAPIKey(string) (uint64, error) { return 0, nil }
func (f *flowTenantSvc) ListAllTenants(context.Context) ([]*types.Tenant, error) {
return nil, nil
}
func (f *flowTenantSvc) BulkSetStorageQuota(context.Context, int64) (int64, error) {
return 0, nil
}
func (f *flowTenantSvc) SearchTenants(context.Context, string, uint64, int, int) ([]*types.Tenant, int64, error) {
return nil, 0, nil
}
func (f *flowTenantSvc) GetTenantByIDForUser(context.Context, uint64, string) (*types.Tenant, error) {
return f.tenant, nil
}
func (f *flowTenantSvc) GetWeKnoraCloudCredentials(context.Context) *types.WeKnoraCloudCredentials {
return nil
}
func TestEmbedExchangeFlowIntegration(t *testing.T) {
gin.SetMode(gin.TestMode)
const (
channelID = "ch-flow-1"
publishToken = "em_publish_valid"
)
svc := &flowEmbedSvc{
sessionToken: "ems_integration_token",
expiresIn: 1800,
channels: map[string]*types.EmbedChannel{
channelID: {
ID: channelID,
TenantID: 7,
AgentID: "agent-flow-1",
Enabled: true,
PublishToken: publishToken,
AllowedOrigins: []byte(`["https://partner.example.com"]`),
RateLimitPerMinute: 0,
},
},
}
h := &EmbedChannelHandler{embedSvc: svc}
tenantSvc := &flowTenantSvc{tenant: &types.Tenant{ID: 7}}
r := gin.New()
r.POST(
"/api/v1/embed/:channel_id/exchange",
middleware.EmbedAuth(svc, tenantSvc, nil),
h.ExchangeEmbedSession,
)
req := httptest.NewRequest(http.MethodPost, "/api/v1/embed/"+channelID+"/exchange", nil)
req.Header.Set("Authorization", "Embed "+publishToken)
req.Header.Set("Origin", "https://partner.example.com")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
var resp struct {
Success bool `json:"success"`
Data struct {
SessionToken string `json:"session_token"`
ExpiresIn int `json:"expires_in"`
} `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatal(err)
}
if !resp.Success {
t.Fatalf("expected success, got %#v", resp)
}
if !strings.HasPrefix(resp.Data.SessionToken, "ems_") {
t.Fatalf("session_token = %q, want ems_ prefix", resp.Data.SessionToken)
}
if resp.Data.SessionToken != "ems_integration_token" || resp.Data.ExpiresIn != 1800 {
t.Fatalf("unexpected exchange payload: %#v", resp.Data)
}
}
func TestPatchEmbedChatPayloadInjectsAgentID(t *testing.T) {
ch := &types.EmbedChannel{AgentID: "agent-embed-42"}
body := `{"query":"hello","agent_id":"client-override","web_search_enabled":true}`
patched, err := patchEmbedChatPayload(strings.NewReader(body), ch, false)
if err != nil {
t.Fatal(err)
}
var payload map[string]any
if err := json.Unmarshal(patched, &payload); err != nil {
t.Fatal(err)
}
if payload["agent_id"] != "agent-embed-42" {
t.Fatalf("agent_id = %v, want channel agent", payload["agent_id"])
}
if payload["query"] != "hello" {
t.Fatalf("query = %v, want preserved client field", payload["query"])
}
if payload["web_search_enabled"] != false {
t.Fatalf("web_search_enabled = %v, want false", payload["web_search_enabled"])
}
if payload["agent_enabled"] != false {
t.Fatalf("agent_enabled = %v, want false for knowledge mode", payload["agent_enabled"])
}
kbIDs, ok := payload["knowledge_base_ids"].([]any)
if !ok || len(kbIDs) != 0 {
t.Fatalf("knowledge_base_ids = %v, want empty slice", payload["knowledge_base_ids"])
}
}
func TestPatchEmbedChatPayloadWebSearchRequiresClientOptIn(t *testing.T) {
ch := &types.EmbedChannel{AgentID: "agent-1", AllowWebSearch: true}
body := `{"query":"hello","web_search_enabled":false,"enable_memory":true}`
patched, err := patchEmbedChatPayload(strings.NewReader(body), ch, false)
if err != nil {
t.Fatal(err)
}
var payload map[string]any
if err := json.Unmarshal(patched, &payload); err != nil {
t.Fatal(err)
}
if payload["web_search_enabled"] != false {
t.Fatalf("web_search_enabled = %v, want false when visitor did not opt in", payload["web_search_enabled"])
}
if payload["enable_memory"] != false {
t.Fatalf("enable_memory = %v, want false (embed memory is disabled)", payload["enable_memory"])
}
bodyOn := `{"query":"hello","web_search_enabled":true}`
patchedOn, err := patchEmbedChatPayload(strings.NewReader(bodyOn), ch, false)
if err != nil {
t.Fatal(err)
}
var payloadOn map[string]any
if err := json.Unmarshal(patchedOn, &payloadOn); err != nil {
t.Fatal(err)
}
if payloadOn["web_search_enabled"] != true {
t.Fatalf("web_search_enabled = %v, want true when channel allows and visitor opted in", payloadOn["web_search_enabled"])
}
}
func TestPatchEmbedChatPayloadWebSearchBlockedWhenChannelDisabled(t *testing.T) {
ch := &types.EmbedChannel{AgentID: "agent-1", AllowWebSearch: false}
body := `{"query":"hello","web_search_enabled":true}`
patched, err := patchEmbedChatPayload(strings.NewReader(body), ch, false)
if err != nil {
t.Fatal(err)
}
var payload map[string]any
if err := json.Unmarshal(patched, &payload); err != nil {
t.Fatal(err)
}
if payload["web_search_enabled"] != false {
t.Fatalf("web_search_enabled = %v, want false when channel disallows web search", payload["web_search_enabled"])
}
}
func TestPatchEmbedChatPayloadAgentMode(t *testing.T) {
ch := &types.EmbedChannel{AgentID: "agent-embed-99"}
patched, err := patchEmbedChatPayload(bytes.NewReader(nil), ch, true)
if err != nil {
t.Fatal(err)
}
var payload map[string]any
if err := json.Unmarshal(patched, &payload); err != nil {
t.Fatal(err)
}
if payload["agent_id"] != "agent-embed-99" {
t.Fatalf("agent_id = %v", payload["agent_id"])
}
if payload["agent_enabled"] != true {
t.Fatalf("agent_enabled = %v, want true", payload["agent_enabled"])
}
}
func TestPatchEmbedChatPayloadInvalidJSON(t *testing.T) {
ch := &types.EmbedChannel{AgentID: "agent-1"}
_, err := patchEmbedChatPayload(strings.NewReader("{not-json"), ch, false)
if err == nil || !strings.Contains(err.Error(), "invalid embed chat json") {
t.Fatalf("expected invalid json error, got %v", err)
}
}
func TestPatchEmbedChatPayloadInvalidBody(t *testing.T) {
ch := &types.EmbedChannel{AgentID: "agent-1"}
_, err := patchEmbedChatPayload(badReader{}, ch, false)
if err == nil || !strings.Contains(err.Error(), "invalid embed chat request body") {
t.Fatalf("expected invalid body error, got %v", err)
}
}
type badReader struct{}
func (badReader) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
+369
View File
@@ -0,0 +1,369 @@
package handler
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/handler/session"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
const (
testEmbedChannelID = "ch-session-test"
testEmbedTenantID = uint64(42)
testEmbedSessionID = "11111111-2222-3333-4444-555555555555"
testEmbedPublishTok = "em_publish_session_test"
)
type stubSessionServiceForEmbed struct {
interfaces.SessionService
sessions map[string]*types.Session
created *types.Session
}
func (s *stubSessionServiceForEmbed) GetSession(_ context.Context, id string) (*types.Session, error) {
sess, ok := s.sessions[id]
if !ok {
return nil, errors.New("session not found")
}
return sess, nil
}
func (s *stubSessionServiceForEmbed) CreateSession(_ context.Context, session *types.Session) (*types.Session, error) {
created := *session
if created.ID == "" {
created.ID = testEmbedSessionID
}
s.created = &created
return &created, nil
}
type sessionEmbedSvc struct {
interfaces.EmbedChannelService
embedChunk func(context.Context, *types.EmbedChannel, string) (*types.Chunk, error)
}
func (s *sessionEmbedSvc) Create(context.Context, uint64, string, *types.EmbedChannel) (*types.EmbedChannel, string, error) {
return nil, "", nil
}
func (s *sessionEmbedSvc) ListByAgent(context.Context, uint64, string) ([]*types.EmbedChannel, error) {
return nil, nil
}
func (s *sessionEmbedSvc) ListByTenant(context.Context, uint64) ([]*types.EmbedChannel, error) {
return nil, nil
}
func (s *sessionEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
return nil, nil
}
func (s *sessionEmbedSvc) GetOwnedChannel(context.Context, uint64, string) (*types.EmbedChannel, error) {
return nil, service.ErrEmbedChannelNotFound
}
func (s *sessionEmbedSvc) Delete(context.Context, uint64, string) error { return nil }
func (s *sessionEmbedSvc) RotateToken(context.Context, uint64, string) (*types.EmbedChannel, string, error) {
return nil, "", nil
}
func (s *sessionEmbedSvc) LookupForEmbed(context.Context, string, string) (*types.EmbedChannel, error) {
return nil, nil
}
func (s *sessionEmbedSvc) LookupEnabledChannel(context.Context, string) (*types.EmbedChannel, error) {
return nil, nil
}
func (s *sessionEmbedSvc) IssueSessionToken(context.Context, string) (string, int, error) {
return "", 0, nil
}
func (s *sessionEmbedSvc) IssuePreviewSession(context.Context, uint64, string) (string, int, error) {
return "", 0, nil
}
func (s *sessionEmbedSvc) ResolveSessionToken(context.Context, string) (string, error) {
return "", nil
}
func (s *sessionEmbedSvc) PublicConfig(context.Context, *types.EmbedChannel) types.EmbedChannelPublicConfig {
return types.EmbedChannelPublicConfig{}
}
func (s *sessionEmbedSvc) SuggestedQuestions(context.Context, *types.EmbedChannel, int) ([]types.SuggestedQuestion, error) {
return nil, nil
}
func (s *sessionEmbedSvc) EmbedChunk(ctx context.Context, ch *types.EmbedChannel, chunkID string) (*types.Chunk, error) {
if s.embedChunk != nil {
return s.embedChunk(ctx, ch, chunkID)
}
return nil, nil
}
func (s *sessionEmbedSvc) EmbedDisplayTitle(context.Context, *types.EmbedChannel) string {
return ""
}
func testEmbedChannel() *types.EmbedChannel {
return &types.EmbedChannel{
ID: testEmbedChannelID,
TenantID: testEmbedTenantID,
PublishToken: testEmbedPublishTok,
Enabled: true,
}
}
func validEmbedSession(ch *types.EmbedChannel) *types.Session {
return &types.Session{
ID: testEmbedSessionID,
TenantID: ch.TenantID,
Description: service.EmbedSessionDescription(ch.ID),
}
}
func newEnsureEmbedSessionCtx(ch *types.EmbedChannel, sessionID, sig string) (*gin.Context, *httptest.ResponseRecorder) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/sessions/"+sessionID+"/messages", nil)
if sig != "" {
c.Request.Header.Set("X-Embed-Session", sig)
}
c.Params = gin.Params{{Key: "session_id", Value: sessionID}}
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
return c, w
}
func TestEnsureEmbedSessionValid(t *testing.T) {
ch := testEmbedChannel()
sig := service.SignEmbedSessionHandle(ch, testEmbedSessionID)
h := &EmbedChannelHandler{
sessionService: &stubSessionServiceForEmbed{
sessions: map[string]*types.Session{
testEmbedSessionID: validEmbedSession(ch),
},
},
}
c, w := newEnsureEmbedSessionCtx(ch, testEmbedSessionID, sig)
if err := h.ensureEmbedSession(c); err != nil {
t.Fatalf("ensureEmbedSession() = %v, want nil", err)
}
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want no response written on success", w.Code)
}
}
func TestEnsureEmbedSessionWrongTenant(t *testing.T) {
ch := testEmbedChannel()
sig := service.SignEmbedSessionHandle(ch, testEmbedSessionID)
h := &EmbedChannelHandler{
sessionService: &stubSessionServiceForEmbed{
sessions: map[string]*types.Session{
testEmbedSessionID: {
ID: testEmbedSessionID,
TenantID: 999,
Description: service.EmbedSessionDescription(ch.ID),
},
},
},
}
c, w := newEnsureEmbedSessionCtx(ch, testEmbedSessionID, sig)
if err := h.ensureEmbedSession(c); err == nil {
t.Fatal("expected error for cross-tenant session")
}
if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}
func TestEnsureEmbedSessionWrongDescription(t *testing.T) {
ch := testEmbedChannel()
sig := service.SignEmbedSessionHandle(ch, testEmbedSessionID)
h := &EmbedChannelHandler{
sessionService: &stubSessionServiceForEmbed{
sessions: map[string]*types.Session{
testEmbedSessionID: {
ID: testEmbedSessionID,
TenantID: ch.TenantID,
Description: "not-an-embed-session",
},
},
},
}
c, w := newEnsureEmbedSessionCtx(ch, testEmbedSessionID, sig)
if err := h.ensureEmbedSession(c); err == nil {
t.Fatal("expected error for wrong description marker")
}
if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}
func TestEnsureEmbedSessionInvalidSig(t *testing.T) {
ch := testEmbedChannel()
h := &EmbedChannelHandler{
sessionService: &stubSessionServiceForEmbed{
sessions: map[string]*types.Session{
testEmbedSessionID: validEmbedSession(ch),
},
},
}
c, w := newEnsureEmbedSessionCtx(ch, testEmbedSessionID, "invalid-signature")
if err := h.ensureEmbedSession(c); err == nil {
t.Fatal("expected error for invalid signature")
}
if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}
func TestEnsureEmbedSessionNotFound(t *testing.T) {
ch := testEmbedChannel()
h := &EmbedChannelHandler{sessionService: &stubSessionServiceForEmbed{sessions: map[string]*types.Session{}}}
c, w := newEnsureEmbedSessionCtx(ch, testEmbedSessionID, "anything")
if err := h.ensureEmbedSession(c); err == nil {
t.Fatal("expected error for missing session")
}
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}
func TestCreateEmbedSessionSuccess(t *testing.T) {
gin.SetMode(gin.TestMode)
ch := testEmbedChannel()
stub := &stubSessionServiceForEmbed{sessions: map[string]*types.Session{}}
h := &EmbedChannelHandler{sessionService: stub}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/sessions", nil)
c.Set(types.TenantIDContextKey.String(), ch.TenantID)
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
h.CreateEmbedSession(c)
if w.Code != http.StatusCreated {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
var resp struct {
Success bool `json:"success"`
Data struct {
ID string `json:"id"`
Sig string `json:"sig"`
} `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatal(err)
}
if !resp.Success || resp.Data.ID != testEmbedSessionID {
t.Fatalf("unexpected response: %#v", resp)
}
if stub.created == nil || stub.created.Description != service.EmbedSessionDescription(ch.ID) {
t.Fatalf("created session marker = %q", stub.created.Description)
}
if !service.VerifyEmbedSessionHandle(ch, resp.Data.ID, resp.Data.Sig) {
t.Fatal("returned sig must verify against created session")
}
}
func TestGetEmbedChunkForbidden(t *testing.T) {
gin.SetMode(gin.TestMode)
ch := testEmbedChannel()
h := &EmbedChannelHandler{
embedSvc: &sessionEmbedSvc{
embedChunk: func(_ context.Context, _ *types.EmbedChannel, _ string) (*types.Chunk, error) {
return nil, service.ErrEmbedChunkForbidden
},
},
}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/chunks/chunk-1", nil)
c.Params = gin.Params{{Key: "chunk_id", Value: "chunk-1"}}
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
h.GetEmbedChunk(c)
if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}
func TestGetEmbedChunkSuccess(t *testing.T) {
gin.SetMode(gin.TestMode)
ch := testEmbedChannel()
h := &EmbedChannelHandler{
embedSvc: &sessionEmbedSvc{
embedChunk: func(_ context.Context, _ *types.EmbedChannel, chunkID string) (*types.Chunk, error) {
return &types.Chunk{ID: chunkID, Content: "hello"}, nil
},
},
}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodGet, "/chunks/chunk-ok", nil)
c.Params = gin.Params{{Key: "chunk_id", Value: "chunk-ok"}}
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
h.GetEmbedChunk(c)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}
func newEmbedStopSessionCtx(ch *types.EmbedChannel, sessionID, sig, body string) (*gin.Context, *httptest.ResponseRecorder) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/sessions/"+sessionID+"/stop", strings.NewReader(body))
c.Request.Header.Set("Content-Type", "application/json")
if sig != "" {
c.Request.Header.Set("X-Embed-Session", sig)
}
c.Params = gin.Params{{Key: "session_id", Value: sessionID}}
c.Set(types.TenantIDContextKey.String(), ch.TenantID)
ctx := context.WithValue(c.Request.Context(), middleware.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
return c, w
}
func TestEmbedStopSessionInvalidSig(t *testing.T) {
ch := testEmbedChannel()
h := &EmbedChannelHandler{
sessionService: &stubSessionServiceForEmbed{
sessions: map[string]*types.Session{
testEmbedSessionID: validEmbedSession(ch),
},
},
sessionHandler: &session.Handler{},
}
c, w := newEmbedStopSessionCtx(ch, testEmbedSessionID, "bad-sig", `{"message_id":"msg-1"}`)
h.EmbedStopSession(c)
if w.Code != http.StatusForbidden {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}
func TestEmbedStopSessionMissingMessageID(t *testing.T) {
ch := testEmbedChannel()
sig := service.SignEmbedSessionHandle(ch, testEmbedSessionID)
h := &EmbedChannelHandler{
sessionService: &stubSessionServiceForEmbed{
sessions: map[string]*types.Session{
testEmbedSessionID: validEmbedSession(ch),
},
},
sessionHandler: &session.Handler{},
}
c, w := newEmbedStopSessionCtx(ch, testEmbedSessionID, sig, `{}`)
h.EmbedStopSession(c)
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}