chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
package handler
import (
"net/http"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// Keeps types imported so swag can resolve AcademyCloudStatusResult.
var _ types.AcademyCloudStatusResult
// AcademyCloudHandler 处理 AcademyCloud 凭证管理
type AcademyCloudHandler struct {
svc interfaces.AcademyCloudService
}
// NewAcademyCloudHandler 构造函数
func NewAcademyCloudHandler(svc interfaces.AcademyCloudService) *AcademyCloudHandler {
return &AcademyCloudHandler{svc: svc}
}
type academyCloudCredentialsRequest struct {
AppID string `json:"app_id" binding:"required"`
AppSecret string `json:"app_secret" binding:"required"`
}
// SaveCredentials POST /api/v1/academycloud/credentials
// 仅保存 APPID/APPSECRET 凭证到空间配置,不自动创建模型
//
// SaveCredentials godoc
// @Summary 保存 AcademyCloud 凭证
// @Description 保存 APPID/APPSECRET 到当前空间配置(不自动创建模型)
// @Tags AcademyCloud
// @Accept json
// @Produce json
// @Param request body map[string]interface{} true "{app_id, app_secret}"
// @Success 200 {object} handler.MessageResponse "success: true"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /academycloud/credentials [post]
func (h *AcademyCloudHandler) SaveCredentials(c *gin.Context) {
var req academyCloudCredentialsRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := h.svc.SaveCredentials(c.Request.Context(), req.AppID, req.AppSecret); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "message": "凭证保存成功"})
}
// Status GET /api/v1/models/academycloud/status
// 检查当前空间的 AcademyCloud 凭证是否完好,如需重新初始化则返回 needs_reinit=true
//
// Status godoc
// @Summary 检查 AcademyCloud 凭证状态
// @Description 检查当前空间的 AcademyCloud 凭证是否完好;needs_reinit=true 表示需要重新保存
// @Tags AcademyCloud
// @Produce json
// @Success 200 {object} types.AcademyCloudStatusResult "凭证状态"
// @Failure 500 {object} map[string]interface{} "服务器错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /models/academycloud/status [get]
func (h *AcademyCloudHandler) Status(c *gin.Context) {
result, err := h.svc.CheckStatus(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, result)
}
+100
View File
@@ -0,0 +1,100 @@
package handler
import (
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// WithGrants lets the handler list and revoke the caller's agent grants.
func (h *MCPServiceHandler) WithGrants(grants interfaces.AgentGrantRepository) *MCPServiceHandler {
h.grants = grants
return h
}
// grantOwner is the caller as grants record it.
func grantOwner(c *gin.Context) (uint64, string, bool) {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
principal, _ := types.PrincipalFromContext(c.Request.Context())
userID := principal.StorageID()
return tenantID, userID, tenantID != 0 && strings.TrimSpace(userID) != ""
}
// ListAgentGrants godoc
// @Summary 列出会话内的 Agent 授权
// @Description 列出当前用户在某个会话(根会话)中通过“本会话允许”记住的授权,包括其委派子任务上批准的授权。
// @Tags Agent
// @Produce json
// @Param session_id query string true "根会话 ID"
// @Success 200 {object} map[string]interface{} "授权列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Router /agent/grants [get]
func (h *MCPServiceHandler) ListAgentGrants(c *gin.Context) {
ctx := c.Request.Context()
if h.grants == nil {
_ = c.Error(errors.NewInternalServerError("agent grants are not configured"))
return
}
tenantID, userID, ok := grantOwner(c)
if !ok {
_ = c.Error(errors.NewUnauthorizedError("a signed-in user is required"))
return
}
sessionID := strings.TrimSpace(c.Query("session_id"))
if sessionID == "" {
_ = c.Error(errors.NewBadRequestError("session_id is required"))
return
}
grants, err := h.grants.ListGrants(ctx, tenantID, userID, types.AgentGrantScopeSession, sessionID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"session_id": sessionID})
_ = c.Error(errors.NewInternalServerError(err.Error()))
return
}
if grants == nil {
grants = []*types.AgentGrant{}
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": grants})
}
// RevokeAgentGrant godoc
// @Summary 撤销 Agent 授权
// @Description 撤销当前用户的一条授权;之后同类调用会重新询问。
// @Tags Agent
// @Produce json
// @Param id path string true "授权 ID"
// @Success 200 {object} map[string]interface{} "撤销结果"
// @Failure 404 {object} errors.AppError "授权不存在"
// @Security Bearer
// @Router /agent/grants/{id} [delete]
func (h *MCPServiceHandler) RevokeAgentGrant(c *gin.Context) {
ctx := c.Request.Context()
if h.grants == nil {
_ = c.Error(errors.NewInternalServerError("agent grants are not configured"))
return
}
tenantID, userID, ok := grantOwner(c)
if !ok {
_ = c.Error(errors.NewUnauthorizedError("a signed-in user is required"))
return
}
revoked, err := h.grants.RevokeGrant(ctx, tenantID, userID, c.Param("id"), time.Now())
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
_ = c.Error(errors.NewInternalServerError(err.Error()))
return
}
if !revoked {
_ = c.Error(errors.NewNotFoundError("grant not found"))
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
+90
View File
@@ -0,0 +1,90 @@
package handler
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"academy/internal/agent/approval"
"academy/internal/config"
"academy/internal/errors"
"academy/internal/event"
"academy/internal/types"
)
type recordingResumer struct{ prompts []*types.AgentPrompt }
func (r *recordingResumer) ResumeSuspendedRun(_ *gin.Context, p *types.AgentPrompt, _ bool, _ *time.Time) {
r.prompts = append(r.prompts, p)
}
func postAgentPrompt(
h *MCPServiceHandler, promptID, body string, principal types.Principal,
) (*httptest.ResponseRecorder, *gin.Context) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
req := httptest.NewRequest(http.MethodPost, "/agent/prompts/"+promptID, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
c.Request = req.WithContext(types.WithPrincipal(req.Context(), principal))
c.Params = gin.Params{{Key: "prompt_id", Value: promptID}}
c.Set(types.TenantIDContextKey.String(), uint64(1))
h.ResolveAgentPrompt(c)
return w, c
}
func appErrorCode(t *testing.T, c *gin.Context) int {
t.Helper()
require.NotEmpty(t, c.Errors)
var appErr *errors.AppError
require.ErrorAs(t, c.Errors.Last().Err, &appErr)
return appErr.HTTPCode
}
func TestResolveAgentPrompt(t *testing.T) {
gin.SetMode(gin.TestMode)
gate := approval.NewGate(&config.Config{Agent: &config.AgentConfig{
ToolApprovalTimeoutSeconds: 60, PromptHotWaitSeconds: 1,
}}, nil, nil)
resumer := &recordingResumer{}
h := &MCPServiceHandler{toolApprovalGate: gate, runResumer: resumer}
owner := types.Principal{Type: "user", ID: "u1"}
ans, err := gate.AskUser(context.Background(), approval.AskRequest{
TenantID: 1, UserID: owner.StorageID(), SessionID: "s1", AssistantMessageID: "m1", ToolCallID: "tc1",
EventBus: event.NewEventBus(), Question: types.AskUserPromptRequest{Question: "color?"},
Snapshot: []byte(`{"version":1}`), SnapshotVersion: 1,
})
require.NoError(t, err)
require.NotNil(t, ans.Suspended)
id := ans.PromptID
_, c := postAgentPrompt(h, id, `{"kind":"tool_approval","response":{"approved":true}}`, owner)
assert.Equal(t, http.StatusNotFound, appErrorCode(t, c), "a mismatched kind hides the prompt")
_, c = postAgentPrompt(h, id, `{"kind":"mcp_oauth","response":{"authorized":true}}`, owner)
assert.Equal(t, http.StatusBadRequest, appErrorCode(t, c), "OAuth cannot be claimed by the user")
_, c = postAgentPrompt(h, id, `{"kind":"ask_user","response":{}}`, owner)
assert.Equal(t, http.StatusBadRequest, appErrorCode(t, c), "an empty answer is invalid")
_, c = postAgentPrompt(h, id, `{"kind":"ask_user","response":{"text":"red"}}`,
types.Principal{Type: "user", ID: "u2"})
assert.Equal(t, http.StatusBadRequest, appErrorCode(t, c), "only the prompt's user may answer")
assert.Empty(t, resumer.prompts)
w, c := postAgentPrompt(h, id, `{"kind":"ask_user","response":{"text":"red"}}`, owner)
require.Empty(t, c.Errors)
assert.JSONEq(t, `{"success":true,"resumed":true}`, w.Body.String())
require.Len(t, resumer.prompts, 1)
assert.Equal(t, id, resumer.prompts[0].ID)
_, c = postAgentPrompt(h, id, `{"kind":"ask_user","response":{"text":"blue"}}`, owner)
assert.Equal(t, http.StatusBadRequest, appErrorCode(t, c), "a prompt is answered once")
}
+262
View File
@@ -0,0 +1,262 @@
package handler
import (
"net/http"
"strconv"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// AuditLogHandler exposes the per-tenant audit-log feed (PR 6, #1303).
// The route group lives under /tenants/:id/audit-log, gated by
// PathTenantMatch (URL :id == active tenant) plus an Admin role
// requirement — leaks of denied-action histories should not surface
// to ordinary members.
type AuditLogHandler struct {
auditService interfaces.AuditLogService
}
// NewAuditLogHandler constructs the handler.
func NewAuditLogHandler(auditService interfaces.AuditLogService) *AuditLogHandler {
return &AuditLogHandler{auditService: auditService}
}
// auditLogListResponse is the response envelope for ListTenantAuditLog. The
// cursor is the integer id of the last entry, or 0 if no more rows remain.
type auditLogListResponse struct {
Success bool `json:"success"`
Data []*types.AuditLog `json:"data"`
// NextCursor is the id of the last entry on this page, 0 when it is empty.
NextCursor uint64 `json:"next_cursor" extensions:"x-agent"`
}
// ListTenantAuditLog godoc
// @Summary 获取空间审计日志
// @Description 返回该空间最近的审计事件,按 id 倒序。游标分页:将上次响应的 next_cursor 作为下一次请求的 after_id。
// @Tags 审计日志
// @Produce json
// @Param id path string true "空间ID"
// @Param after_id query int false "游标:返回 id 小于此值的记录(默认从最新开始)"
// @Param limit query int false "页大小,1-100,默认 50"
// @Param action query string false "按 action 精确过滤(如 rbac.member_added / rbac.access_denied)"
// @Param outcome query string false "按 outcome 精确过滤(success / denied)"
// @Param actor query string false "按 actor_user_id 精确过滤"
// @Success 200 {object} auditLogListResponse
// @Failure 400 {object} errors.AppError
// @Security Bearer
// @Security ApiKeyAuth
// @Router /tenants/{id}/audit-log [get]
func (h *AuditLogHandler) ListTenantAuditLog(c *gin.Context) {
ctx := c.Request.Context()
tenantID, ok := parseTenantIDFromPath(c)
if !ok {
// parseTenantIDFromPath has already attached an error to gin.
return
}
// after_id cursor — invalid values are tolerated (treated as "from
// the top") so a misconfigured client doesn't see a hard 400 on
// the empty / first request. Tighter validation belongs at the
// frontend.
var afterID uint64
if raw := c.Query("after_id"); raw != "" {
if v, err := strconv.ParseUint(raw, 10, 64); err == nil {
afterID = v
}
}
limit := 0 // 0 lets the repository pick its default (50)
if raw := c.Query("limit"); raw != "" {
if v, err := strconv.Atoi(raw); err == nil && v > 0 {
limit = v
}
}
q := &interfaces.AuditLogQuery{
AfterID: afterID,
Limit: limit,
Action: types.AuditAction(c.Query("action")),
Outcome: types.AuditOutcome(c.Query("outcome")),
ActorUserID: c.Query("actor"),
UnscopedOnly: true,
}
entries, err := h.auditService.List(ctx, tenantID, q)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"tenant_id": tenantID})
c.Error(errors.NewInternalServerError(err.Error()))
return
}
// next_cursor is the smallest id in the page (since rows are sorted
// id DESC). Empty page ⇒ 0, telling the client there's nothing
// older to fetch.
var nextCursor uint64
if n := len(entries); n > 0 {
nextCursor = entries[n-1].ID
}
c.JSON(http.StatusOK, auditLogListResponse{
Success: true,
Data: entries,
NextCursor: nextCursor,
})
}
// ListKnowledgeBaseActivity returns the durable activity projection for one
// knowledge base. The route has already resolved KB access; this handler adds
// an owner-tenant check so organization-shared consumers cannot inspect source
// workspace actors or configuration history.
// @Summary 获取知识库活动记录
// @Description 返回知识库的重要变更与后台任务入口。仅知识库创建者或所属空间管理员可读,共享空间不可读。
// @Description 按 id 倒序;把 next_cursor 作为 after_id 取下一页,返回空列表表示没有更多。
// @Tags 知识库
// @Produce json
// @Param id path string true "知识库ID" extensions(x-agent=knowledge_base_id)
// @Param after_id query int false "游标:返回 id 小于此值的记录" extensions(x-agent=cursor)
// @Param limit query int false "页大小" minimum(1) maximum(100) default(50) extensions(x-agent,x-agent-maximum=50)
// @Param action query string false "按 action 精确过滤,如 knowledge.deleted" extensions(x-agent)
// @Param outcome query string false "结果过滤" Enums(success,accepted,partial,failed,denied,canceled) extensions(x-agent)
// @Param actor query string false "按 actor_user_id 精确过滤"
// @Success 200 {object} auditLogListResponse
// @Failure 403 {object} errors.AppError "非创建者或管理员,或知识库来自其他空间"
// @Failure 404 {object} errors.AppError "知识库不存在"
// @Security Bearer
// @x-agent {"id":"knowledge_base.list_activity","risk":"read","role":"contributor"}
// @x-agent-hint "Newest first; only the creator or a workspace admin may read it. Assistant actions carry via=agent."
// @Router /knowledge-bases/{id}/activity [get]
func (h *AuditLogHandler) ListKnowledgeBaseActivity(c *gin.Context) {
ctx := c.Request.Context()
kbID := c.Param("id")
access, ok := middleware.KBAccessFromContext(c)
if !ok || access == nil || access.KnowledgeBase == nil || access.KnowledgeBase.ID != kbID {
c.Error(errors.NewNotFoundError("knowledge base not found"))
return
}
callerTenantID := c.GetUint64(types.TenantIDContextKey.String())
if callerTenantID == 0 || access.KnowledgeBase.TenantID != callerTenantID {
c.Error(errors.NewForbiddenError("knowledge base activity is only available in the owner workspace"))
return
}
actorID, _ := types.UserIDFromContext(ctx)
role := types.TenantRoleFromContext(ctx)
if access.KnowledgeBase.CreatorID != actorID && !role.HasPermission(types.TenantRoleAdmin) {
c.Error(errors.NewForbiddenError("knowledge base activity requires creator or admin access"))
return
}
afterID, limit := parseAuditCursor(c)
q := &interfaces.AuditLogQuery{
AfterID: afterID,
Limit: limit,
Action: types.AuditAction(c.Query("action")),
Outcome: types.AuditOutcome(c.Query("outcome")),
ActorUserID: c.Query("actor"),
ScopeType: "knowledge_base",
ScopeID: kbID,
}
entries, err := h.auditService.List(ctx, access.KnowledgeBase.TenantID, q)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{"knowledge_base_id": kbID})
c.Error(errors.NewInternalServerError(err.Error()))
return
}
var nextCursor uint64
if n := len(entries); n > 0 {
nextCursor = entries[n-1].ID
}
c.JSON(http.StatusOK, auditLogListResponse{
Success: true, Data: entries, NextCursor: nextCursor,
})
}
func parseAuditCursor(c *gin.Context) (uint64, int) {
var afterID uint64
if raw := c.Query("after_id"); raw != "" {
if v, err := strconv.ParseUint(raw, 10, 64); err == nil {
afterID = v
}
}
limit := 0
if raw := c.Query("limit"); raw != "" {
if v, err := strconv.Atoi(raw); err == nil && v > 0 {
limit = v
}
}
return afterID, limit
}
// ListSystemAuditLog godoc
// @Summary 获取平台审计日志
// @Description 返回 system-scope(tenant_id=0)的审计事件,覆盖 system.setting_changed / system.admin_promoted / system.admin_revoked 等 SystemAdmin 操作。按 id 倒序的游标分页。
// @Tags 审计日志
// @Produce json
// @Param after_id query int false "游标:返回 id 小于此值的记录(默认从最新开始)"
// @Param limit query int false "页大小,1-100,默认 50"
// @Param action query string false "按 action 精确过滤(如 system.setting_changed)"
// @Param outcome query string false "按 outcome 精确过滤(success / denied)"
// @Param actor query string false "按 actor_user_id 精确过滤"
// @Success 200 {object} auditLogListResponse
// @Failure 500 {object} errors.AppError
// @Security Bearer
// @Security ApiKeyAuth
// @Router /system/admin/audit-log [get]
//
// Mounted on /api/v1/system/admin/audit-log under the SystemAdmin()
// guard. Unlike ListTenantAuditLog this route is *not* tenant-scoped:
// the system_settings table, admin promote/revoke, and the
// apply-default-storage-quota bulk write all emit audit rows with
// tenant_id=0 (see audit_log.go for the action constants). Those rows
// would never surface in any tenant's audit feed, so this endpoint
// fixes the "wrote audit, can't see it" gap.
func (h *AuditLogHandler) ListSystemAuditLog(c *gin.Context) {
ctx := c.Request.Context()
// Cursor / page-size parsing mirrors ListTenantAuditLog so the
// frontend can share the same call shape; tolerant of garbage
// because the empty / first request shouldn't bounce.
var afterID uint64
if raw := c.Query("after_id"); raw != "" {
if v, err := strconv.ParseUint(raw, 10, 64); err == nil {
afterID = v
}
}
limit := 0
if raw := c.Query("limit"); raw != "" {
if v, err := strconv.Atoi(raw); err == nil && v > 0 {
limit = v
}
}
q := &interfaces.AuditLogQuery{
AfterID: afterID,
Limit: limit,
Action: types.AuditAction(c.Query("action")),
Outcome: types.AuditOutcome(c.Query("outcome")),
ActorUserID: c.Query("actor"),
}
// tenant_id=0 is the system-scope convention; see
// AuditActionSystemSettingChanged comment in types/audit_log.go.
entries, err := h.auditService.List(ctx, 0, q)
if err != nil {
logger.Error(ctx, err)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
var nextCursor uint64
if n := len(entries); n > 0 {
nextCursor = entries[n-1].ID
}
c.JSON(http.StatusOK, auditLogListResponse{
Success: true,
Data: entries,
NextCursor: nextCursor,
})
}
+410
View File
@@ -0,0 +1,410 @@
package handler
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// stubAuditService implements just AuditLogService.List for the
// handler tests. Embeds the interface so any other call panics —
// surfaces a contract drift loudly instead of silently working.
type stubAuditService struct {
interfaces.AuditLogService
list func(ctx context.Context, tenantID uint64, q *interfaces.AuditLogQuery) ([]*types.AuditLog, error)
}
func (s *stubAuditService) List(
ctx context.Context, tenantID uint64, q *interfaces.AuditLogQuery,
) ([]*types.AuditLog, error) {
return s.list(ctx, tenantID, q)
}
// newAuditHandlerTestRouter mounts the handler with the production
// ErrorHandler so c.Error renders the canonical envelope. Path :id is
// resolved by parseTenantIDFromPath; tenant context is not required by
// the handler (PathTenantMatch is stripped from this layer because the
// tests focus on the handler's own surface).
func newAuditHandlerTestRouter(svc interfaces.AuditLogService) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
h := NewAuditLogHandler(svc)
r.GET("/tenants/:id/audit-log", h.ListTenantAuditLog)
return r
}
func TestAuditLogHandler_ReturnsEnvelopeAndCursor(t *testing.T) {
// Two rows: smallest id appears in the next_cursor field so the
// frontend can re-request older pages without re-parsing the body.
svc := &stubAuditService{
list: func(_ context.Context, tenantID uint64, q *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
if tenantID != 7 {
t.Fatalf("expected tenant 7, got %d", tenantID)
}
return []*types.AuditLog{
{ID: 102, TenantID: 7, Action: types.AuditActionMemberAdded},
{ID: 95, TenantID: 7, Action: types.AuditActionAccessDenied, Outcome: types.AuditOutcomeDenied},
}, nil
},
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/tenants/7/audit-log", nil)
newAuditHandlerTestRouter(svc).ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
}
var got auditLogListResponse
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if !got.Success {
t.Fatalf("expected success=true")
}
if len(got.Data) != 2 {
t.Fatalf("expected 2 entries, got %d", len(got.Data))
}
if got.NextCursor != 95 {
t.Fatalf("expected next_cursor to be the smallest id (95), got %d", got.NextCursor)
}
}
func TestAuditLogHandler_PassesQueryFiltersThrough(t *testing.T) {
// The handler must propagate after_id / limit / action / outcome /
// actor exactly as the service expects them. A regression here
// would silently drop a filter and over-return rows on the wire.
svc := &stubAuditService{
list: func(_ context.Context, _ uint64, q *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
if q.AfterID != 100 {
t.Fatalf("expected after_id=100, got %d", q.AfterID)
}
if q.Limit != 25 {
t.Fatalf("expected limit=25, got %d", q.Limit)
}
if q.Action != types.AuditActionAccessDenied {
t.Fatalf("expected action=access_denied, got %q", q.Action)
}
if q.Outcome != types.AuditOutcomeDenied {
t.Fatalf("expected outcome=denied, got %q", q.Outcome)
}
if q.ActorUserID != "u-probing" {
t.Fatalf("expected actor=u-probing, got %q", q.ActorUserID)
}
if !q.UnscopedOnly {
t.Fatalf("tenant audit feed must exclude resource-scoped activity rows")
}
return nil, nil
},
}
w := httptest.NewRecorder()
q := "after_id=100&limit=25&action=rbac.access_denied&outcome=denied&actor=u-probing"
req := httptest.NewRequest(http.MethodGet, "/tenants/7/audit-log?"+q, nil)
newAuditHandlerTestRouter(svc).ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
}
}
func TestAuditLogHandler_EmptyResultProducesZeroCursor(t *testing.T) {
// next_cursor=0 is the documented "no more rows" signal; the frontend
// stops paginating when it sees this, so a regression that returns
// the previous cursor on an empty page would loop forever.
svc := &stubAuditService{
list: func(_ context.Context, _ uint64, _ *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
return nil, nil
},
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/tenants/7/audit-log", nil)
newAuditHandlerTestRouter(svc).ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
}
var got auditLogListResponse
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if got.NextCursor != 0 {
t.Fatalf("expected next_cursor=0 on empty page, got %d", got.NextCursor)
}
}
func TestAuditLogHandler_InvalidTenantIDReturns400(t *testing.T) {
// parseTenantIDFromPath rejects non-numeric tenant ids with 400 so
// the handler never even calls the service. The harness still has
// to not crash on an empty service if it's reached — guard with a
// service that fails the test loudly.
svc := &stubAuditService{
list: func(_ context.Context, _ uint64, _ *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
return nil, fmt.Errorf("must not be called")
},
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/tenants/not-a-number/audit-log", nil)
newAuditHandlerTestRouter(svc).ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400 for non-numeric tenant id, got %d body=%s", w.Code, w.Body.String())
}
}
func newKBActivityHandlerTestRouter(
t *testing.T,
svc interfaces.AuditLogService,
callerTenantID uint64,
kb *types.KnowledgeBase,
userID string,
role types.TenantRole,
) *gin.Engine {
t.Helper()
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
r.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), callerTenantID)
c.Set(middleware.KBAccessContextKey, &middleware.KBAccess{KnowledgeBase: kb})
ctx := context.WithValue(c.Request.Context(), types.UserIDContextKey, userID)
ctx = context.WithValue(ctx, types.TenantRoleContextKey, role)
c.Request = c.Request.WithContext(ctx)
c.Next()
})
h := NewAuditLogHandler(svc)
r.GET("/knowledge-bases/:id/activity", h.ListKnowledgeBaseActivity)
return r
}
func TestKnowledgeBaseActivityHandler_UsesKBScope(t *testing.T) {
svc := &stubAuditService{list: func(_ context.Context, tenantID uint64, q *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
if tenantID != 7 || q.ScopeType != "knowledge_base" || q.ScopeID != "kb-1" {
t.Fatalf("unexpected scope: tenant=%d type=%q id=%q", tenantID, q.ScopeType, q.ScopeID)
}
if q.AfterID != 30 || q.Limit != 10 || q.Outcome != types.AuditOutcomePartial {
t.Fatalf("unexpected filters: %+v", q)
}
return []*types.AuditLog{{ID: 21, TenantID: 7, ScopeType: q.ScopeType, ScopeID: q.ScopeID}}, nil
}}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/activity?after_id=30&limit=10&outcome=partial", nil)
newKBActivityHandlerTestRouter(t, svc, 7,
&types.KnowledgeBase{ID: "kb-1", TenantID: 7, CreatorID: "creator"},
"creator", types.TenantRoleViewer).ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
}
}
func TestKnowledgeBaseActivityHandler_BlocksSharedWorkspace(t *testing.T) {
svc := &stubAuditService{list: func(_ context.Context, _ uint64, _ *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
t.Fatal("audit list must not be called for a shared workspace")
return nil, nil
}}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/activity", nil)
newKBActivityHandlerTestRouter(t, svc, 8,
&types.KnowledgeBase{ID: "kb-1", TenantID: 7, CreatorID: "creator"},
"creator", types.TenantRoleOwner).ServeHTTP(w, req)
if w.Code != http.StatusForbidden {
t.Fatalf("expected 403, got %d body=%s", w.Code, w.Body.String())
}
}
func TestKnowledgeBaseActivityHandler_RequiresCreatorOrAdmin(t *testing.T) {
svc := &stubAuditService{list: func(_ context.Context, _ uint64, _ *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
t.Fatal("audit list must not be called for ordinary members")
return nil, nil
}}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/activity", nil)
newKBActivityHandlerTestRouter(t, svc, 7,
&types.KnowledgeBase{ID: "kb-1", TenantID: 7, CreatorID: "creator"},
"other", types.TenantRoleContributor).ServeHTTP(w, req)
if w.Code != http.StatusForbidden {
t.Fatalf("expected 403, got %d body=%s", w.Code, w.Body.String())
}
}
// ---- ListSystemAuditLog (platform / system-scope feed) ----------------
//
// Mirrors the per-tenant suite above but covers the new
// GET /system/admin/audit-log endpoint. Key behavioural difference:
// the handler must always pass tenant_id=0 to the service (system-scope
// convention) regardless of any URL parameter. The route group is
// guarded by SystemAdmin() at the production wiring layer; the test
// mounts the handler directly so it focuses on the handler's own
// contract.
func newSystemAuditHandlerTestRouter(svc interfaces.AuditLogService) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
h := NewAuditLogHandler(svc)
r.GET("/system/admin/audit-log", h.ListSystemAuditLog)
return r
}
func TestSystemAuditLogHandler_AlwaysQueriesTenantZero(t *testing.T) {
// The defining contract of ListSystemAuditLog: the underlying
// service call is hard-pinned to tenant_id=0. A regression that
// reads a tenant_id from the URL / context / header would leak
// per-tenant rbac.* rows into the platform feed (and conversely,
// hide the platform's system.* rows from the SystemAdmin).
called := false
svc := &stubAuditService{
list: func(_ context.Context, tenantID uint64, _ *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
called = true
if tenantID != 0 {
t.Fatalf("system audit handler must call List with tenant_id=0, got %d", tenantID)
}
return []*types.AuditLog{
{ID: 50, TenantID: 0, Action: types.AuditActionSystemSettingChanged},
{ID: 42, TenantID: 0, Action: types.AuditActionSystemAdminPromoted},
}, nil
},
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/system/admin/audit-log", nil)
newSystemAuditHandlerTestRouter(svc).ServeHTTP(w, req)
if !called {
t.Fatalf("expected AuditLogService.List to be invoked")
}
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
}
var got auditLogListResponse
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if !got.Success {
t.Fatalf("expected success=true")
}
if len(got.Data) != 2 {
t.Fatalf("expected 2 entries, got %d", len(got.Data))
}
if got.NextCursor != 42 {
t.Fatalf("expected next_cursor to be the smallest id (42), got %d", got.NextCursor)
}
}
func TestSystemAuditLogHandler_PassesQueryFiltersThrough(t *testing.T) {
// Same propagation guarantee as the per-tenant variant. We exercise
// every filter the OpenAPI surface advertises so a typo in the
// query-key list (e.g. dropping "outcome") is caught.
svc := &stubAuditService{
list: func(_ context.Context, tenantID uint64, q *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
if tenantID != 0 {
t.Fatalf("expected tenant_id=0, got %d", tenantID)
}
if q.AfterID != 200 {
t.Fatalf("expected after_id=200, got %d", q.AfterID)
}
if q.Limit != 10 {
t.Fatalf("expected limit=10, got %d", q.Limit)
}
if q.Action != types.AuditActionSystemSettingChanged {
t.Fatalf("expected action=system.setting_changed, got %q", q.Action)
}
if q.Outcome != types.AuditOutcomeSuccess {
t.Fatalf("expected outcome=success, got %q", q.Outcome)
}
if q.ActorUserID != "u-admin-1" {
t.Fatalf("expected actor=u-admin-1, got %q", q.ActorUserID)
}
return nil, nil
},
}
w := httptest.NewRecorder()
q := "after_id=200&limit=10&action=system.setting_changed&outcome=success&actor=u-admin-1"
req := httptest.NewRequest(http.MethodGet, "/system/admin/audit-log?"+q, nil)
newSystemAuditHandlerTestRouter(svc).ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
}
}
func TestSystemAuditLogHandler_EmptyResultProducesZeroCursor(t *testing.T) {
// next_cursor=0 is the documented "no more rows" signal — the
// platform drawer's infinite-scroll watcher stops paginating on
// it. A regression returning the previous cursor on an empty page
// would loop forever and pin the CPU.
svc := &stubAuditService{
list: func(_ context.Context, _ uint64, _ *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
return nil, nil
},
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/system/admin/audit-log?after_id=10", nil)
newSystemAuditHandlerTestRouter(svc).ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
}
var got auditLogListResponse
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if got.NextCursor != 0 {
t.Fatalf("expected next_cursor=0 on empty page, got %d", got.NextCursor)
}
if len(got.Data) != 0 {
t.Fatalf("expected zero entries, got %d", len(got.Data))
}
}
func TestSystemAuditLogHandler_GarbageCursorAndLimitTolerated(t *testing.T) {
// Tolerant parsing matches ListTenantAuditLog so a misconfigured
// client doesn't hard-fail the first request. Garbage `after_id`
// or non-positive `limit` are treated as "use defaults" (0 / 0)
// rather than a 400 — the frontend would otherwise show a blank
// drawer the moment a stale param ends up in the URL.
var seenAfter uint64
var seenLimit int
svc := &stubAuditService{
list: func(_ context.Context, _ uint64, q *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
seenAfter = q.AfterID
seenLimit = q.Limit
return nil, nil
},
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/system/admin/audit-log?after_id=abc&limit=-1", nil)
newSystemAuditHandlerTestRouter(svc).ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200 (tolerant parse), got %d body=%s", w.Code, w.Body.String())
}
if seenAfter != 0 {
t.Fatalf("garbage after_id must collapse to 0, got %d", seenAfter)
}
if seenLimit != 0 {
t.Fatalf("non-positive limit must collapse to 0 (repo default), got %d", seenLimit)
}
}
func TestSystemAuditLogHandler_ServiceErrorReturns500(t *testing.T) {
// AuditLogService.List failures bubble through as 500 via
// errors.NewInternalServerError + middleware.ErrorHandler. The
// frontend surfaces the message verbatim in the drawer's error
// alert, so the body should still carry a non-empty string.
svc := &stubAuditService{
list: func(_ context.Context, _ uint64, _ *interfaces.AuditLogQuery) ([]*types.AuditLog, error) {
return nil, fmt.Errorf("db: connection refused")
},
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/system/admin/audit-log", nil)
newSystemAuditHandlerTestRouter(svc).ServeHTTP(w, req)
if w.Code != http.StatusInternalServerError {
t.Fatalf("expected 500, got %d body=%s", w.Code, w.Body.String())
}
if w.Body.Len() == 0 {
t.Fatalf("expected non-empty error body for drawer alert")
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,75 @@
package handler
import (
"context"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"academy/internal/config"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type browserPreferencesUserService struct {
interfaces.UserService
updatedUser string
patch types.UserPreferences
}
func (s *browserPreferencesUserService) GetCurrentUser(context.Context) (*types.User, error) {
return &types.User{ID: "current-user"}, nil
}
func (s *browserPreferencesUserService) BuildLoginMemberships(
context.Context, *types.User, *types.Tenant,
) []types.Membership {
return nil
}
func (s *browserPreferencesUserService) UpdateUserPreferences(
_ context.Context, id string, patch types.UserPreferences,
) (types.UserPreferences, error) {
s.updatedUser, s.patch = id, patch
return patch, nil
}
func TestBrowserPreferenceAPIExposesDefaultAndUpdatesCurrentUser(t *testing.T) {
users := &browserPreferencesUserService{}
h := &AuthHandler{userService: users, configInfo: &config.Config{Tenant: &config.TenantConfig{}}}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/auth/me", nil)
h.GetCurrentUser(c)
require.Equal(t, 200, w.Code)
var payload struct {
Data struct {
Defaults map[string]string `json:"preference_defaults"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &payload))
require.Equal(t, types.DefaultBrowserSearchInstructions, payload.Data.Defaults["browser_search_instructions"])
w = httptest.NewRecorder()
c, _ = gin.CreateTestContext(w)
c.Request = httptest.NewRequest("PUT", "/auth/me/preferences", strings.NewReader(
`{"user_id":"another-user","browser_search_instructions":"Use my engine"}`,
))
c.Request.Header.Set("Content-Type", "application/json")
h.UpdateMyPreferences(c)
require.Equal(t, 200, w.Code)
require.Equal(t, "current-user", users.updatedUser)
require.NotNil(t, users.patch.BrowserSearchInstructions)
require.Equal(t, "Use my engine", *users.patch.BrowserSearchInstructions)
users.updatedUser = ""
c, _ = gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest("PUT", "/auth/me/preferences", strings.NewReader(
`{"browser_search_instructions":"`+strings.Repeat("a", 4001)+`"}`,
))
c.Request.Header.Set("Content-Type", "application/json")
h.UpdateMyPreferences(c)
require.NotEmpty(t, c.Errors)
require.Empty(t, users.updatedUser, "invalid input must not reach the preference service")
}
@@ -0,0 +1,173 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"academy/internal/application/service"
apperrors "academy/internal/errors"
"academy/internal/types"
"academy/internal/types/interfaces"
)
type stubChangePasswordUserService struct {
interfaces.UserService
getCurrentUser func(ctx context.Context) (*types.User, error)
changePassword func(ctx context.Context, userID, oldPassword, newPassword string) error
}
func (s *stubChangePasswordUserService) GetCurrentUser(ctx context.Context) (*types.User, error) {
return s.getCurrentUser(ctx)
}
func (s *stubChangePasswordUserService) ChangePassword(
ctx context.Context,
userID, oldPassword, newPassword string,
) error {
return s.changePassword(ctx, userID, oldPassword, newPassword)
}
func changePasswordErrorCapture() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if len(c.Errors) == 0 {
return
}
err := c.Errors.Last().Err
if appErr, ok := err.(*apperrors.AppError); ok {
c.JSON(appErr.HTTPCode, gin.H{
"success": false,
"error": gin.H{
"code": appErr.Code,
"message": appErr.Message,
"details": appErr.Details,
},
})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
}
func newChangePasswordTestRouter(h *AuthHandler) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(changePasswordErrorCapture())
r.POST("/auth/change-password", h.ChangePassword)
return r
}
func doChangePassword(t *testing.T, r *gin.Engine, body any) *httptest.ResponseRecorder {
t.Helper()
buf, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPost, "/auth/change-password", bytes.NewReader(buf))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func TestChangePassword_MapsInvalidOldPasswordDetail(t *testing.T) {
h := &AuthHandler{
userService: &stubChangePasswordUserService{
getCurrentUser: func(ctx context.Context) (*types.User, error) {
return &types.User{ID: "user-1", Email: "alice@example.com"}, nil
},
changePassword: func(ctx context.Context, userID, oldPassword, newPassword string) error {
return service.ErrInvalidOldPassword
},
},
}
w := doChangePassword(t, newChangePasswordTestRouter(h), map[string]string{
"old_password": "wrong",
"new_password": "NewSecure9",
})
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusBadRequest, w.Body.String())
}
var resp struct {
Error struct {
Details string `json:"details"`
} `json:"error"`
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if resp.Error.Details != service.DetailInvalidOldPassword {
t.Fatalf("details = %q, want %q", resp.Error.Details, service.DetailInvalidOldPassword)
}
}
func TestChangePassword_MapsSamePasswordDetail(t *testing.T) {
h := &AuthHandler{
userService: &stubChangePasswordUserService{
getCurrentUser: func(ctx context.Context) (*types.User, error) {
return &types.User{ID: "user-1", Email: "alice@example.com"}, nil
},
changePassword: func(ctx context.Context, userID, oldPassword, newPassword string) error {
return service.ErrSamePassword
},
},
}
w := doChangePassword(t, newChangePasswordTestRouter(h), map[string]string{
"old_password": "OldSecure9",
"new_password": "OldSecure9",
})
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusBadRequest, w.Body.String())
}
var resp struct {
Error struct {
Details string `json:"details"`
} `json:"error"`
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if resp.Error.Details != service.DetailSamePassword {
t.Fatalf("details = %q, want %q", resp.Error.Details, service.DetailSamePassword)
}
}
func TestChangePassword_MapsPasswordPolicyDetail(t *testing.T) {
h := &AuthHandler{
userService: &stubChangePasswordUserService{
getCurrentUser: func(_ context.Context) (*types.User, error) {
return &types.User{ID: "user-1", Email: "alice@example.com"}, nil
},
changePassword: func(_ context.Context, _, _, _ string) error {
return service.ErrComplexPasswordPolicy
},
},
}
w := doChangePassword(t, newChangePasswordTestRouter(h), map[string]string{
"old_password": "OldSecure9",
"new_password": "NewSecure9",
})
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d body=%s", w.Code, http.StatusBadRequest, w.Body.String())
}
var resp struct {
Error struct {
Details string `json:"details"`
} `json:"error"`
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if resp.Error.Details != service.DetailPasswordPolicy {
t.Fatalf("details = %q, want %q", resp.Error.Details, service.DetailPasswordPolicy)
}
}
@@ -0,0 +1,62 @@
package handler
import (
"context"
"net/http/httptest"
"testing"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type desktopTestUsers struct {
interfaces.UserService
minted int
}
func (s *desktopTestUsers) GetUserByEmail(context.Context, string) (*types.User, error) {
return &types.User{ID: "test-user", TenantID: 1}, nil
}
func (s *desktopTestUsers) GenerateTokens(context.Context, *types.User) (string, string, error) {
s.minted++
return "test-access", "test-refresh", nil
}
type desktopTestTenants struct{ interfaces.TenantService }
func (s *desktopTestTenants) GetTenantByID(context.Context, uint64) (*types.Tenant, error) {
return &types.Tenant{ID: 1}, nil
}
func TestAutoSetupRequiresNativeCapability(t *testing.T) {
oldEdition, oldToken := Edition, liteSetupToken
t.Cleanup(func() { Edition = oldEdition; liteSetupToken = oldToken })
Edition = "lite"
SetLiteSetupToken("test-native-capability")
users := &desktopTestUsers{}
h := &AuthHandler{userService: users, tenantService: &desktopTestTenants{}}
for _, token := range []string{"", "wrong", "test-native-capability"} {
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest("POST", "/api/v1/auth/auto-setup", nil)
ctx.Request.Header.Set("X-Academy-Desktop-Token", token)
h.AutoSetup(ctx)
if token != "test-native-capability" {
require.NotEmpty(t, ctx.Errors)
require.Zero(t, users.minted)
} else {
require.Empty(t, ctx.Errors)
require.Equal(t, 1, users.minted)
}
}
SetLiteSetupToken("")
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest("POST", "/api/v1/auth/auto-setup", nil)
h.AutoSetup(ctx)
require.NotEmpty(t, ctx.Errors)
require.Equal(t, 1, users.minted)
}
+151
View File
@@ -0,0 +1,151 @@
package handler
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/application/service"
"academy/internal/config"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// stubOIDCPasswordUserService only implements LoginWithOIDCPassword; every
// other UserService call panics via the nil interface embedding. Keeps the
// test focused on the handler's error-code mapping.
type stubOIDCPasswordUserService struct {
interfaces.UserService
login func(ctx context.Context, username, password string, provisioning types.TenantProvisioningMode) (*types.OIDCCallbackResponse, error)
}
func (s *stubOIDCPasswordUserService) LoginWithOIDCPassword(ctx context.Context, username, password string, provisioning types.TenantProvisioningMode) (*types.OIDCCallbackResponse, error) {
return s.login(ctx, username, password, provisioning)
}
func newOIDCPasswordTestRouter(h *AuthHandler) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(errorCapture())
r.POST("/auth/oidc/password", h.LoginWithOIDCPassword)
return r
}
func postOIDCPassword(r *gin.Engine, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/auth/oidc/password", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
// 成功路径:200 + 与 OIDC 回调一致的会话摘要(token/user/tenant/memberships)。
func TestLoginWithOIDCPassword_Success(t *testing.T) {
us := &stubOIDCPasswordUserService{
login: func(context.Context, string, string, types.TenantProvisioningMode) (*types.OIDCCallbackResponse, error) {
return &types.OIDCCallbackResponse{
Success: true,
Token: "access-token",
User: &types.User{Username: "10001"},
}, nil
},
}
h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)
r := newOIDCPasswordTestRouter(h)
w := postOIDCPassword(r, `{"username":"10001","password":"pw"}`)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), `"token":"access-token"`) {
t.Fatalf("body missing token: %s", w.Body.String())
}
}
// 工号或密码错误:401。
func TestLoginWithOIDCPassword_InvalidCredentials(t *testing.T) {
us := &stubOIDCPasswordUserService{
login: func(context.Context, string, string, types.TenantProvisioningMode) (*types.OIDCCallbackResponse, error) {
return nil, service.ErrOIDCPasswordInvalidCredentials
},
}
h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)
r := newOIDCPasswordTestRouter(h)
w := postOIDCPassword(r, `{"username":"10001","password":"wrong"}`)
if w.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}
// 部署未开启 password 直登:404(前端能力开关应已隐藏入口,端点兜底 404)。
func TestLoginWithOIDCPassword_Disabled(t *testing.T) {
us := &stubOIDCPasswordUserService{
login: func(context.Context, string, string, types.TenantProvisioningMode) (*types.OIDCCallbackResponse, error) {
return nil, service.ErrOIDCPasswordLoginDisabled
},
}
h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)
r := newOIDCPasswordTestRouter(h)
w := postOIDCPassword(r, `{"username":"10001","password":"pw"}`)
if w.Code != http.StatusNotFound {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}
// Casdoor 应用 grantTypes 未勾 password:503(气泡图同款口径)。
func TestLoginWithOIDCPassword_GrantUnsupported(t *testing.T) {
us := &stubOIDCPasswordUserService{
login: func(context.Context, string, string, types.TenantProvisioningMode) (*types.OIDCCallbackResponse, error) {
return nil, service.ErrOIDCPasswordGrantUnsupported
},
}
h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)
r := newOIDCPasswordTestRouter(h)
w := postOIDCPassword(r, `{"username":"10001","password":"pw"}`)
if w.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}
// 业务性拒绝(停用账号):service 返回 Success=false,401 带原文 message。
func TestLoginWithOIDCPassword_AccountDisabled(t *testing.T) {
us := &stubOIDCPasswordUserService{
login: func(context.Context, string, string, types.TenantProvisioningMode) (*types.OIDCCallbackResponse, error) {
return &types.OIDCCallbackResponse{Success: false, Message: "Account is disabled"}, nil
},
}
h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)
r := newOIDCPasswordTestRouter(h)
w := postOIDCPassword(r, `{"username":"10001","password":"pw"}`)
if w.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), "Account is disabled") {
t.Fatalf("body missing disabled message: %s", w.Body.String())
}
}
// 参数校验:缺字段 400。
func TestLoginWithOIDCPassword_MissingFields(t *testing.T) {
us := &stubOIDCPasswordUserService{
login: func(context.Context, string, string, types.TenantProvisioningMode) (*types.OIDCCallbackResponse, error) {
t.Fatal("service must not be called on invalid payload")
return nil, errors.New("unreachable")
},
}
h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)
r := newOIDCPasswordTestRouter(h)
w := postOIDCPassword(r, `{"username":"10001"}`)
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
}
}
+123
View File
@@ -0,0 +1,123 @@
package handler
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/config"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// stubOIDCStartUserService only implements GetOIDCAuthorizationURL; every
// other UserService call panics via the nil interface embedding. Keeps the
// test focused on the OIDCStart handler's branching logic.
type stubOIDCStartUserService struct {
interfaces.UserService
getOIDCAuthorizationURL func(ctx context.Context, redirectURI string) (*types.OIDCAuthURLResponse, error)
}
func (s *stubOIDCStartUserService) GetOIDCAuthorizationURL(ctx context.Context, redirectURI string) (*types.OIDCAuthURLResponse, error) {
return s.getOIDCAuthorizationURL(ctx, redirectURI)
}
func newOIDCStartTestRouter(h *AuthHandler) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(errorCapture())
r.GET("/auth/oidc/start", h.OIDCStart)
return r
}
// TestOIDCStart_RedirectsToAuthProvider: on success the handler must 302
// to the IdP authorization URL and bind the nonce via cookie (CSRF/replay
// defence), exactly like /auth/oidc/url.
func TestOIDCStart_RedirectsToAuthProvider(t *testing.T) {
const authURL = "http://idp.example.com/authorize?client_id=academy"
us := &stubOIDCStartUserService{
getOIDCAuthorizationURL: func(context.Context, string) (*types.OIDCAuthURLResponse, error) {
return &types.OIDCAuthURLResponse{
Success: true,
AuthorizationURL: authURL,
State: "state123",
Nonce: "nonce456",
}, nil
},
}
h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)
r := newOIDCStartTestRouter(h)
req := httptest.NewRequest(http.MethodGet, "/auth/oidc/start", nil)
req.Host = "academy.example.com"
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusFound {
t.Fatalf("status = %d, want 302", w.Code)
}
if loc := w.Header().Get("Location"); loc != authURL {
t.Errorf("Location = %q, want %q", loc, authURL)
}
var hasNonce bool
for _, ck := range w.Result().Cookies() {
if ck.Name == oidcNonceCookieName && ck.Value == "nonce456" {
hasNonce = true
}
}
if !hasNonce {
t.Errorf("expected %s cookie to be set with the nonce", oidcNonceCookieName)
}
}
// TestOIDCStart_BuildsCallbackURLFromRequestOrigin: redirect_uri handed to
// the IdP is derived from the request's own origin (no caller-supplied
// value needed); X-Forwarded-Proto upgrades the scheme to https.
func TestOIDCStart_BuildsCallbackURLFromRequestOrigin(t *testing.T) {
var captured string
us := &stubOIDCStartUserService{
getOIDCAuthorizationURL: func(_ context.Context, redirectURI string) (*types.OIDCAuthURLResponse, error) {
captured = redirectURI
return &types.OIDCAuthURLResponse{Success: true, AuthorizationURL: "http://idp", Nonce: "n"}, nil
},
}
h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)
r := newOIDCStartTestRouter(h)
req := httptest.NewRequest(http.MethodGet, "/auth/oidc/start", nil)
req.Host = "academy.example.com"
req.Header.Set("X-Forwarded-Proto", "https")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
const want = "https://academy.example.com/api/v1/auth/oidc/callback"
if captured != want {
t.Errorf("callback URL passed to IdP = %q, want %q", captured, want)
}
if w.Code != http.StatusFound {
t.Fatalf("status = %d, want 302", w.Code)
}
}
// TestOIDCStart_ServiceErrorReturnsNonRedirect: if the IdP URL cannot be
// built, never 302 — surface the error the same way /auth/oidc/url does.
func TestOIDCStart_ServiceErrorReturnsNonRedirect(t *testing.T) {
us := &stubOIDCStartUserService{
getOIDCAuthorizationURL: func(context.Context, string) (*types.OIDCAuthURLResponse, error) {
return nil, fmt.Errorf("idp unavailable")
},
}
h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)
r := newOIDCStartTestRouter(h)
req := httptest.NewRequest(http.MethodGet, "/auth/oidc/start", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code == http.StatusFound {
t.Fatalf("status = 302, want non-redirect on service error")
}
}
+247
View File
@@ -0,0 +1,247 @@
package handler
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"academy/internal/application/service"
"academy/internal/config"
apperrors "academy/internal/errors"
"academy/internal/handler/dto"
"academy/internal/logger"
"academy/internal/types"
secutils "academy/internal/utils"
)
// registerByInviteRequest is the body for /auth/register-by-invite.
//
// Email is collected from the invitee themselves: share-link rows have
// no specific invitee, so we cannot pre-bind any address. The token
// IS the authorisation; the email is whatever account the invitee
// wants to register.
type registerByInviteRequest struct {
Token string `json:"token" binding:"required"`
Email string `json:"email" binding:"required,email"`
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required,min=6"`
}
// invitationLookupResponse is the public projection of a share-link
// row returned by /auth/invitations/lookup. Kept narrow on purpose:
// just enough for the registration page to render context ("X invited
// you to Y") without exposing inviter audit fields.
type invitationLookupResponse struct {
TenantID uint64 `json:"tenant_id"`
TenantName string `json:"tenant_name,omitempty"`
Role types.TenantRole `json:"role"`
ExpiresAt string `json:"expires_at"`
}
// invitationLookupRequest carries the token in the request body
// instead of the URL path: GET /auth/invitations/:token would have
// landed the plaintext token in access logs, browser history, and
// tracing spans. POST + body keeps the token out of those surfaces
// at the cost of "this endpoint reads, why is it POST" — worth it
// because the token is the sole authorisation for registration.
type invitationLookupRequest struct {
Token string `json:"token" binding:"required"`
}
// LookupInvitationByToken godoc
// @Summary 解析共享邀请链接 token
// @Description 根据邀请链接中的 token 返回邀请上下文(空间名 / 角色 / 过期时间),
// @Description 供注册页展示。无认证;token 无效或被撤销返回 410。
// @Description 使用 POST + body 而非 GET + path,避免 token 落入访问日志 / 浏览器历史 / tracing。
// @Tags 认证
// @Accept json
// @Produce json
// @Param request body invitationLookupRequest true "邀请 token"
// @Success 200 {object} invitationLookupResponse
// @Failure 410 {object} apperrors.AppError "链接无效或已撤销"
// @Router /auth/invitations/lookup [post]
func (h *AuthHandler) LookupInvitationByToken(c *gin.Context) {
ctx := c.Request.Context()
if h.invitationSvc == nil {
c.Error(apperrors.NewInternalServerError("invitation service unavailable"))
return
}
var req invitationLookupRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewValidationError("token is required").WithDetails(err.Error()))
return
}
token := strings.TrimSpace(req.Token)
if token == "" {
c.Error(apperrors.NewValidationError("token is required"))
return
}
inv, err := h.invitationSvc.LookupByToken(ctx, token)
if err != nil {
// Collapse "unknown / expired / revoked" into 410 to avoid
// leaking which slot a stolen token used to occupy.
c.Error(&apperrors.AppError{
Code: apperrors.ErrNotFound,
Message: "invitation link is invalid or has been revoked",
HTTPCode: http.StatusGone,
})
return
}
resp := invitationLookupResponse{
TenantID: inv.TenantID,
Role: inv.Role,
ExpiresAt: inv.ExpiresAt.UTC().Format("2006-01-02T15:04:05Z07:00"),
}
if tenant, terr := h.tenantService.GetTenantByID(ctx, inv.TenantID); terr == nil && tenant != nil {
resp.TenantName = tenant.Name
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": resp,
})
}
// RegisterByInvite godoc
// @Summary 使用共享链接注册
// @Description 通过共享邀请链接 token 完成注册,仅 self_serve / invite_register 模式允许。
// @Description 注册者自填邮箱(与 token 不绑定);注册成功后自动加入对应空间。
// @Tags 认证
// @Accept json
// @Produce json
// @Param request body registerByInviteRequest true "邀请注册请求"
// @Success 201 {object} types.LoginResponse
// @Failure 400 {object} apperrors.AppError "请求参数错误"
// @Failure 403 {object} apperrors.AppError "注册功能已禁用"
// @Failure 409 {object} apperrors.AppError "邮箱已注册"
// @Failure 410 {object} apperrors.AppError "链接无效或已撤销"
// @Router /auth/register-by-invite [post]
//
// RegisterByInvite requires both an enabled registration mode and a valid token.
func (h *AuthHandler) RegisterByInvite(c *gin.Context) {
ctx := c.Request.Context()
mode := h.resolveRegistrationMode(ctx)
if mode != config.AuthRegistrationModeSelfServe && mode != config.AuthRegistrationModeInviteRegister {
_ = c.Error(apperrors.NewForbiddenError("Registration is disabled"))
return
}
if h.invitationSvc == nil {
c.Error(apperrors.NewInternalServerError("invitation service unavailable"))
return
}
var req registerByInviteRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(apperrors.NewValidationError("Invalid registration parameters").WithDetails(err.Error()))
return
}
req.Token = strings.TrimSpace(req.Token)
req.Email = strings.TrimSpace(strings.ToLower(req.Email))
req.Username = strings.TrimSpace(req.Username)
// Password is intentionally NOT sanitized: SanitizeForLog strips
// \n, \r, \t and control chars to make a string safe to write into
// a log line — applying it to a real password would silently
// rewrite the stored credential and lock the user out. Passwords
// must never be logged, so they don't need that defence here.
if req.Token == "" || req.Email == "" || req.Username == "" || req.Password == "" {
c.Error(apperrors.NewValidationError("token, email, username and password are required"))
return
}
inv, err := h.invitationSvc.LookupByToken(ctx, req.Token)
if err != nil {
c.Error(&apperrors.AppError{
Code: apperrors.ErrNotFound,
Message: "invitation link is invalid or has been revoked",
HTTPCode: http.StatusGone,
})
return
}
// If the email already has an account we shouldn't quietly succeed
// here: register would fail with a duplicate-email error, but the
// share-link flow is "create new account + join tenant", not "join
// my existing account". Surface 409 so the SPA can prompt them to
// log in instead, and the invitation can be applied to their
// existing account via /me/invitations once we wire that path.
if existing, _ := h.userService.GetUserByEmail(ctx, req.Email); existing != nil {
c.Error(apperrors.NewConflictError(
"this email already has an account; please log in to join the workspace"))
return
}
if err := service.ValidatePasswordPolicy(req.Password, h.complexPasswordEnabled(ctx)); err != nil {
logger.Error(ctx, "Invalid password policy")
_ = c.Error(apperrors.NewValidationError(err.Error()))
return
}
user, err := h.userService.Register(ctx, &types.RegisterRequest{
Username: req.Username,
Email: req.Email,
Password: req.Password,
TenantProvisioning: types.TenantProvisioningTenantless,
})
if err != nil {
logger.Errorf(ctx, "register-by-invite: user create failed for %s: %v",
secutils.SanitizeForLog(req.Email), err)
c.Error(apperrors.NewBadRequestError(err.Error()))
return
}
// The invited tenant becomes the user's initial/default tenant. No
user.TenantID = inv.TenantID
if err := h.userService.UpdateUser(ctx, user); err != nil {
logger.Errorf(ctx, "register-by-invite: failed to set home tenant for user %s: %v", user.ID, err)
_ = h.userService.DeleteUser(ctx, user.ID)
c.Error(apperrors.NewInternalServerError("failed to finalise invited account").WithDetails(err.Error()))
return
}
if _, err := h.invitationSvc.AcceptByToken(ctx, req.Token, user.ID); err != nil {
// Race: link was revoked between Lookup and Accept. Keep the new
// account, but restore it to tenantless so it does not point at a
// tenant for which no membership was created. If even that repair
// fails, remove the half-provisioned identity.
logger.Errorf(ctx, "register-by-invite: accept failed for user %s: %v", user.ID, err)
user.TenantID = 0
if rollbackErr := h.userService.UpdateUser(ctx, user); rollbackErr != nil {
logger.Errorf(ctx, "register-by-invite: failed to restore tenantless user %s: %v", user.ID, rollbackErr)
_ = h.userService.DeleteUser(ctx, user.ID)
}
c.Error(&apperrors.AppError{
Code: apperrors.ErrNotFound,
Message: "invitation link is no longer valid; please log in to your new account",
HTTPCode: http.StatusGone,
})
return
}
accessToken, refreshToken, err := h.userService.GenerateTokens(ctx, user)
if err != nil {
logger.Errorf(ctx, "register-by-invite: token generation failed for user %s: %v", user.ID, err)
c.Error(apperrors.NewInternalServerError("token generation failed").WithDetails(err.Error()))
return
}
tenant, _ := h.tenantService.GetTenantByID(ctx, inv.TenantID)
c.JSON(http.StatusCreated, dto.NewAuthLoginResponse(&types.LoginResponse{
Success: true,
Message: "Registration successful",
User: user,
ActiveTenant: tenant,
Memberships: []types.Membership{{
TenantID: inv.TenantID,
TenantName: tenantNameOrEmpty(tenant),
Role: inv.Role,
}},
Token: accessToken,
RefreshToken: refreshToken,
}))
}
@@ -0,0 +1,200 @@
package handler
import (
"bytes"
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/config"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
type invitedRegistrationUserService struct {
interfaces.UserService
registeredMode types.TenantProvisioningMode
updatedTenant uint64
updateCalls []uint64
}
func (s *invitedRegistrationUserService) GetUserByEmail(context.Context, string) (*types.User, error) {
return nil, nil
}
func (s *invitedRegistrationUserService) Register(_ context.Context, req *types.RegisterRequest) (*types.User, error) {
s.registeredMode = req.TenantProvisioning
return &types.User{ID: "new-user", Username: req.Username, Email: req.Email, IsActive: true}, nil
}
func (s *invitedRegistrationUserService) UpdateUser(_ context.Context, user *types.User) error {
s.updatedTenant = user.TenantID
s.updateCalls = append(s.updateCalls, user.TenantID)
return nil
}
func (s *invitedRegistrationUserService) GenerateTokens(context.Context, *types.User) (string, string, error) {
return "access", "refresh", nil
}
type invitedRegistrationInvitationService struct {
interfaces.TenantInvitationService
acceptErr error
lookupErr error
}
func (s *invitedRegistrationInvitationService) LookupByToken(context.Context, string) (*types.TenantInvitation, error) {
if s.lookupErr != nil {
return nil, s.lookupErr
}
return &types.TenantInvitation{TenantID: 42, Role: types.TenantRoleViewer}, nil
}
func (s *invitedRegistrationInvitationService) AcceptByToken(context.Context, string, string) (*types.TenantMember, error) {
if s.acceptErr != nil {
return nil, s.acceptErr
}
return &types.TenantMember{TenantID: 42, Role: types.TenantRoleViewer}, nil
}
type invitedRegistrationTenantService struct {
interfaces.TenantService
}
func TestRegisterByInviteRestoresTenantlessAccountWhenInviteExpiresDuringRegistration(t *testing.T) {
gin.SetMode(gin.TestMode)
users := &invitedRegistrationUserService{}
h := &AuthHandler{
userService: users,
tenantService: &invitedRegistrationTenantService{},
invitationSvc: &invitedRegistrationInvitationService{acceptErr: errors.New("expired")},
}
r := gin.New()
r.Use(errorCapture())
r.POST("/auth/register-by-invite", h.RegisterByInvite)
body := []byte(`{"token":"invite-token","email":"alice@example.com","username":"alice","password":"supersecret1"}`)
req := httptest.NewRequest(http.MethodPost, "/auth/register-by-invite", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusGone {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if users.updatedTenant != 0 {
t.Fatalf("updated tenant=%d, want tenantless rollback", users.updatedTenant)
}
if len(users.updateCalls) != 2 || users.updateCalls[0] != 42 || users.updateCalls[1] != 0 {
t.Fatalf("update calls=%v, want [42 0]", users.updateCalls)
}
}
func (s *invitedRegistrationTenantService) GetTenantByID(context.Context, uint64) (*types.Tenant, error) {
return &types.Tenant{ID: 42, Name: "Invited Workspace"}, nil
}
func TestRegisterByInviteUsesInvitedTenantWithoutPersonalTenant(t *testing.T) {
gin.SetMode(gin.TestMode)
users := &invitedRegistrationUserService{}
h := &AuthHandler{
userService: users,
tenantService: &invitedRegistrationTenantService{},
invitationSvc: &invitedRegistrationInvitationService{},
}
r := gin.New()
r.Use(errorCapture())
r.POST("/auth/register-by-invite", h.RegisterByInvite)
body := []byte(`{"token":"invite-token","email":"alice@example.com","username":"alice","password":"supersecret1"}`)
req := httptest.NewRequest(http.MethodPost, "/auth/register-by-invite", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if users.registeredMode != types.TenantProvisioningTenantless {
t.Fatalf("register mode=%q, want tenantless", users.registeredMode)
}
if users.updatedTenant != 42 {
t.Fatalf("updated tenant=%d, want 42", users.updatedTenant)
}
}
func TestRegisterByInviteRejectsSimplePasswordWhenComplexEnabled(t *testing.T) {
gin.SetMode(gin.TestMode)
users := &invitedRegistrationUserService{}
h := &AuthHandler{
userService: users,
tenantService: &invitedRegistrationTenantService{},
invitationSvc: &invitedRegistrationInvitationService{},
systemSettingSvc: &tenantPolicySettingService{enabled: true},
}
r := gin.New()
r.Use(errorCapture())
r.POST("/auth/register-by-invite", h.RegisterByInvite)
body := []byte(`{"token":"invite-token","email":"alice@example.com","username":"alice","password":"supersecret1"}`)
req := httptest.NewRequest(http.MethodPost, "/auth/register-by-invite", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("status=%d body=%s, want 400", w.Code, w.Body.String())
}
if users.registeredMode != "" {
t.Fatalf("Register was called with mode=%q", users.registeredMode)
}
}
func TestRegisterByInviteRegistrationModes(t *testing.T) {
for _, tc := range []struct {
name string
mode string
lookupErr error
want int
}{
{"open", config.AuthRegistrationModeSelfServe, nil, http.StatusCreated},
{"invited", config.AuthRegistrationModeInviteRegister, nil, http.StatusCreated},
{"disabled", config.AuthRegistrationModeInviteOnly, nil, http.StatusForbidden},
{"unknown mode", "invalid", nil, http.StatusForbidden},
{"invalid invitation", config.AuthRegistrationModeInviteRegister, errors.New("invalid"), http.StatusGone},
{"expired invitation", config.AuthRegistrationModeInviteRegister, errors.New("expired"), http.StatusGone},
{"revoked invitation", config.AuthRegistrationModeInviteRegister, errors.New("revoked"), http.StatusGone},
} {
t.Run(tc.name, func(t *testing.T) {
users := &invitedRegistrationUserService{}
h := &AuthHandler{
configInfo: &config.Config{Auth: &config.AuthConfig{RegistrationMode: tc.mode}},
userService: users,
tenantService: &invitedRegistrationTenantService{},
invitationSvc: &invitedRegistrationInvitationService{lookupErr: tc.lookupErr},
}
r := gin.New()
r.Use(errorCapture())
r.POST("/auth/register-by-invite", h.RegisterByInvite)
req := httptest.NewRequest(http.MethodPost, "/auth/register-by-invite", bytes.NewBufferString(
`{"token":"invite-token","email":"alice@example.com","username":"alice","password":"supersecret1"}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != tc.want {
t.Fatalf("status=%d, want %d body=%s", w.Code, tc.want, w.Body.String())
}
if tc.want == http.StatusCreated {
if users.registeredMode != types.TenantProvisioningTenantless || users.updatedTenant != 42 {
t.Fatalf("expected account in invited tenant only: mode=%q tenant=%d",
users.registeredMode, users.updatedTenant)
}
} else if users.registeredMode != "" {
t.Fatal("rejected registration must not create an account")
}
})
}
}
@@ -0,0 +1,290 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/config"
apperrors "academy/internal/errors"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// stubRegisterUserService is a UserService whose ONLY useful method is
// Register; every other call panics. Using an interface embedding plus a
// targeted override keeps the test focused on the Register handler's
// branching logic without dragging in the entire user service surface.
type stubRegisterUserService struct {
interfaces.UserService
register func(ctx context.Context, req *types.RegisterRequest) (*types.User, error)
}
func (s *stubRegisterUserService) Register(ctx context.Context, req *types.RegisterRequest) (*types.User, error) {
return s.register(ctx, req)
}
// errorCapture mirrors gin's default ErrorHandler behaviour for tests:
// when a handler calls c.Error(), we surface it as an HTTP response so the
// recorder reflects the real client-visible status. The production
// middleware does the same thing in middleware/error_handler.go.
func errorCapture() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if len(c.Errors) == 0 {
return
}
err := c.Errors.Last().Err
if appErr, ok := err.(*apperrors.AppError); ok {
c.JSON(appErr.HTTPCode, gin.H{"error": appErr.Message})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
}
func newRegisterTestRouter(h *AuthHandler) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(errorCapture())
r.POST("/auth/register", h.Register)
return r
}
func doRegister(t *testing.T, r *gin.Engine, body any) *httptest.ResponseRecorder {
t.Helper()
buf, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPost, "/auth/register", bytes.NewReader(buf))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
// validRegisterBody returns a payload that passes parameter validation, so
// each test is exercising the gate logic and not the body parser.
func validRegisterBody() map[string]string {
return map[string]string{
"username": "alice",
"email": "alice@example.com",
"password": "supersecret1",
}
}
func TestRegister_InviteOnlyRejects(t *testing.T) {
// PR 3 (#1303): when auth.registration_mode=invite_only, Register
// must respond 403 BEFORE touching the user service. The frontend
// already hides the sign-up link via /auth/config; this is the
// server-side enforcement for direct API hits.
called := false
us := &stubRegisterUserService{
register: func(context.Context, *types.RegisterRequest) (*types.User, error) {
called = true
return &types.User{ID: "u1"}, nil
},
}
h := NewAuthHandler(&config.Config{
Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeInviteOnly},
}, us, nil, nil, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusForbidden {
t.Fatalf("invite_only must return 403, got %d body=%s", w.Code, w.Body.String())
}
if called {
t.Fatalf("UserService.Register must not be called when invite_only blocks the request")
}
}
func TestRegister_SelfServeAllowsRegistration(t *testing.T) {
// Default registration_mode keeps PR 1 behaviour intact: the gate
// is dormant and the request reaches the user service. We don't
// exercise the real service here — just confirm the gate let it
// through by observing the stub being invoked.
called := false
us := &stubRegisterUserService{
register: func(_ context.Context, req *types.RegisterRequest) (*types.User, error) {
called = true
if req.TenantProvisioning != types.TenantProvisioningCreatePersonal {
t.Fatalf("default provisioning = %q, want create_personal", req.TenantProvisioning)
}
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
},
}
h := NewAuthHandler(&config.Config{
Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeSelfServe},
}, us, nil, nil, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusCreated {
t.Fatalf("self_serve must allow registration, got %d body=%s", w.Code, w.Body.String())
}
if !called {
t.Fatalf("UserService.Register should have been invoked")
}
}
func TestRegister_TenantlessProvisioningFromConfig(t *testing.T) {
us := &stubRegisterUserService{
register: func(_ context.Context, req *types.RegisterRequest) (*types.User, error) {
if req.TenantProvisioning != types.TenantProvisioningTenantless {
t.Fatalf("provisioning = %q, want tenantless", req.TenantProvisioning)
}
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
},
}
h := NewAuthHandler(&config.Config{
Auth: &config.AuthConfig{
RegistrationMode: config.AuthRegistrationModeSelfServe,
DefaultTenantMode: config.AuthDefaultTenantModeTenantless,
},
}, us, nil, nil, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusCreated {
t.Fatalf("tenantless self-serve registration got %d body=%s", w.Code, w.Body.String())
}
}
func TestGetAuthConfigExposesComplexPassword(t *testing.T) {
gin.SetMode(gin.TestMode)
h := &AuthHandler{
configInfo: &config.Config{Auth: &config.AuthConfig{
RegistrationMode: config.AuthRegistrationModeSelfServe,
}},
systemSettingSvc: &tenantPolicySettingService{enabled: true},
}
r := gin.New()
r.GET("/auth/config", h.GetAuthConfig)
req := httptest.NewRequest(http.MethodGet, "/auth/config", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), `"complex_password_enabled":true`) {
t.Fatalf("body=%s, want complex_password_enabled true", w.Body.String())
}
}
func TestRegister_NilAuthConfigDoesNotPanic(t *testing.T) {
// Defensive: a nil Auth section means the operator hasn't set the
// registration mode at all, which must not crash and must keep the
// legacy "registration enabled" behaviour. Mirrors the nil guard in
// the handler so a config-loading bug doesn't take the server down.
us := &stubRegisterUserService{
register: func(_ context.Context, _ *types.RegisterRequest) (*types.User, error) {
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
},
}
h := NewAuthHandler(&config.Config{}, us, nil, nil, nil)
w := doRegister(t, newRegisterTestRouter(h), validRegisterBody())
if w.Code != http.StatusCreated {
t.Fatalf("nil Auth config must fall back to allow, got %d body=%s", w.Code, w.Body.String())
}
}
// TestRegister_PreservesPasswordBytes is the regression for #2521.
// SanitizeForLog is for log output only; applying it to credentials
// rewrites tabs/newlines/control chars before hashing, so a password
// that registers successfully cannot be used at login.
func TestRegister_PreservesPasswordBytes(t *testing.T) {
// Password contains a tab and a newline — both are rewritten by
// SanitizeForLog (tab → space, newline → space). The handler must
// pass the exact original string to UserService.Register.
const originalPassword = "abc\t123!\nX"
var gotPassword string
us := &stubRegisterUserService{
register: func(_ context.Context, req *types.RegisterRequest) (*types.User, error) {
gotPassword = req.Password
return &types.User{ID: "u1", Email: "alice@example.com"}, nil
},
}
h := NewAuthHandler(&config.Config{
Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeSelfServe},
}, us, nil, nil, nil)
body := validRegisterBody()
body["password"] = originalPassword
w := doRegister(t, newRegisterTestRouter(h), body)
if w.Code != http.StatusCreated {
t.Fatalf("registration with control chars in password must succeed, got %d body=%s",
w.Code, w.Body.String())
}
if gotPassword != originalPassword {
t.Fatalf("password mutated before UserService.Register:\n got %q\n want %q",
gotPassword, originalPassword)
}
}
// Settings are resolved on every request, for the UI and both registration APIs.
type registrationModeSettings struct {
interfaces.SystemSettingService
mode string
}
func (s *registrationModeSettings) GetString(_ context.Context, key, _, fallback string) string {
if key == "auth.registration_mode" {
return s.mode
}
return fallback
}
func (s *registrationModeSettings) GetBool(_ context.Context, _, _ string, fallback bool) bool {
return fallback
}
func TestRegistrationModeChangesApplyImmediately(t *testing.T) {
settings := &registrationModeSettings{}
h := &AuthHandler{
configInfo: &config.Config{
Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeInviteOnly},
},
systemSettingSvc: settings,
userService: &invitedRegistrationUserService{},
tenantService: &invitedRegistrationTenantService{},
invitationSvc: &invitedRegistrationInvitationService{},
}
r := newRegisterTestRouter(h)
r.POST("/auth/register-by-invite", h.RegisterByInvite)
r.GET("/auth/config", h.GetAuthConfig)
for _, mode := range []string{
config.AuthRegistrationModeInviteRegister,
config.AuthRegistrationModeSelfServe,
config.AuthRegistrationModeInviteOnly,
} {
settings.mode = mode
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/auth/config", nil))
var cfg struct {
RegistrationMode string `json:"registration_mode"`
}
if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil || cfg.RegistrationMode != mode {
t.Fatalf("config must expose live mode %q: %s", mode, w.Body.String())
}
for _, path := range []string{"/auth/register", "/auth/register-by-invite"} {
body := validRegisterBody()
body["token"] = "valid-token"
data, _ := json.Marshal(body)
req := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(data))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
want := http.StatusForbidden
if mode == config.AuthRegistrationModeSelfServe ||
(mode == config.AuthRegistrationModeInviteRegister && path == "/auth/register-by-invite") {
want = http.StatusCreated
}
if w.Code != want {
t.Fatalf("mode=%s path=%s status=%d want=%d body=%s", mode, path, w.Code, want, w.Body.String())
}
}
}
}
+498
View File
@@ -0,0 +1,498 @@
package handler
import (
stderrors "errors"
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"academy/internal/application/service"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
)
// AutomationHandler serves the caller's automations and notifications.
type AutomationHandler struct {
automations *service.AutomationService
notifications *service.NotificationService
}
// NewAutomationHandler builds the handler.
func NewAutomationHandler(
automations *service.AutomationService, notifications *service.NotificationService,
) *AutomationHandler {
return &AutomationHandler{automations: automations, notifications: notifications}
}
func (h *AutomationHandler) fail(c *gin.Context, err error) {
var appErr *errors.AppError
if stderrors.As(err, &appErr) {
_ = c.Error(appErr)
return
}
logger.ErrorWithFields(c.Request.Context(), err, nil)
_ = c.Error(errors.NewInternalServerError("automation request failed"))
}
// CreateAutomationRequest is the body of POST /automations; see
// types.AutomationPatch for the fields.
type CreateAutomationRequest struct {
// What the automation is called
Name string `json:"name" binding:"required" extensions:"x-agent"`
// What it is for
Description string `json:"description" extensions:"x-agent"`
// Optional chat model from model.list; empty follows the assistant default
ModelID string `json:"model_id" extensions:"x-agent"`
// The task, sent as the user message of each run. May name now,
// last_run_at, last_success_at, run_id or automation_name inside double
// curly braces to have it filled in
Instruction string `json:"instruction" binding:"required" extensions:"x-agent,x-agent-max-bytes=32000"`
// When it runs
Trigger types.AutomationTrigger `json:"trigger" binding:"required" extensions:"x-agent"`
// per_run (default) starts a new conversation each run; persistent keeps one
SessionMode string `json:"session_mode" enums:"per_run,persistent" extensions:"x-agent"`
// Whether each per_run conversation gets the last successful answer
CarryLastResult bool `json:"carry_last_result" extensions:"x-agent"`
// What happens to runs missed while the service was down; default skip
MisfirePolicy string `json:"misfire_policy" enums:"skip,run_once" extensions:"x-agent"`
// What happens when a run is due while the previous one is still going; default skip
OverlapPolicy string `json:"overlap_policy" enums:"skip,queue" extensions:"x-agent"`
// How far runs may change data without asking; default confirm
AccessLevel types.AssistantAccessLevel `json:"access_level" enums:"read_only,confirm,auto_write" extensions:"x-agent"`
// How long a run waits for an approval before it fails, in minutes; default 1440
ApprovalTimeoutMinutes int `json:"approval_timeout_minutes" extensions:"x-agent"`
Limits types.AutomationLimits `json:"limits"`
// Whether a successful run notifies the owner; failures always do
NotifyOnSuccess bool `json:"notify_on_success" extensions:"x-agent"`
}
func (r CreateAutomationRequest) patch() *types.AutomationPatch {
return &types.AutomationPatch{
Name: &r.Name, Description: &r.Description, ModelID: &r.ModelID, Instruction: &r.Instruction,
Trigger: &r.Trigger, SessionMode: &r.SessionMode, CarryLastResult: &r.CarryLastResult,
MisfirePolicy: &r.MisfirePolicy, OverlapPolicy: &r.OverlapPolicy, AccessLevel: &r.AccessLevel,
ApprovalTimeoutMinutes: &r.ApprovalTimeoutMinutes, Limits: &r.Limits, NotifyOnSuccess: &r.NotifyOnSuccess,
}
}
// ListAutomations godoc
// @Summary 列出我的自动化
// @Description 列出当前用户在本空间创建的自动化(定时任务),最新的在前
// @Tags 自动化
// @Produce json
// @Success 200 {object} handler.DataResponse{data=[]types.Automation} "自动化列表"
// @Security Bearer
// @x-agent {"id":"automation.list","risk":"read","max_items":100}
// @x-agent-hint "Lists the user's automations: scheduled tasks the Academy assistant runs on their behalf, with next and last run."
// @Router /automations [get]
func (h *AutomationHandler) ListAutomations(c *gin.Context) {
list, err := h.automations.List(c.Request.Context())
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": list})
}
// CreateAutomation godoc
// @Summary 创建自动化
// @Description 创建一个按计划由 Academy 助手以当前用户身份运行的任务
// @Tags 自动化
// @Accept json
// @Produce json
// @Param request body CreateAutomationRequest true "自动化"
// @Success 201 {object} handler.DataResponse{data=types.Automation} "创建的自动化"
// @Failure 400 {object} errors.AppError "参数不合法"
// @Security Bearer
// @x-agent {"id":"automation.create","role":"viewer","risk":"write","label_param":"name","always_confirm":true}
// @x-agent-hint "Creates an automation the Academy assistant runs as the user. If work requires other agents, name them and their assignments in the instruction so the assistant can delegate. Turn the user's wording into a cron expression (five fields, minute first) and an IANA timezone, and check it with automation.validate_trigger first, telling the user the next run times it returns. Runs are unattended: write the instruction as a complete task, since nobody can answer questions during a run. access_level defaults to confirm, where each change waits for the user's approval; only set auto_write when the user asks for it."
// @Router /automations [post]
func (h *AutomationHandler) CreateAutomation(c *gin.Context) {
var req CreateAutomationRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("invalid automation").WithDetails(err.Error()))
return
}
a, err := h.automations.Create(c.Request.Context(), req.patch())
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusCreated, gin.H{"success": true, "data": a})
}
// ValidateTriggerRequest is the body of POST /automations/validate-trigger.
type ValidateTriggerRequest struct {
// The trigger to check
Trigger types.AutomationTrigger `json:"trigger" binding:"required" extensions:"x-agent"`
}
// ValidateTriggerResult is the data of POST /automations/validate-trigger.
type ValidateTriggerResult struct {
// The next times the trigger fires, in UTC
NextRuns []time.Time `json:"next_runs" extensions:"x-agent"`
}
// ValidateTrigger godoc
// @Summary 校验触发器
// @Description 校验 cron 或一次性触发器,返回未来 3 次触发时间
// @Tags 自动化
// @Accept json
// @Produce json
// @Param request body ValidateTriggerRequest true "触发器"
// @Success 200 {object} handler.DataResponse{data=ValidateTriggerResult} "未来触发时间"
// @Failure 400 {object} errors.AppError "触发器不合法"
// @Security Bearer
// @x-agent {"id":"automation.validate_trigger","risk":"probe"}
// @x-agent-hint "Checks a trigger and returns its next three run times in UTC; convert them to the trigger's timezone for the user."
// @Router /automations/validate-trigger [post]
func (h *AutomationHandler) ValidateTrigger(c *gin.Context) {
var req ValidateTriggerRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("invalid trigger").WithDetails(err.Error()))
return
}
times, err := h.automations.ValidateTrigger(req.Trigger, 3)
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": ValidateTriggerResult{NextRuns: times}})
}
// GetAutomationBySession godoc
// @Summary 按会话查找自动化
// @Description 返回这次会话所属的自动化,供会话页跳回
// @Tags 自动化
// @Produce json
// @Param session_id path string true "会话 ID"
// @Success 200 {object} handler.DataResponse{data=types.Automation} "自动化"
// @Failure 404 {object} errors.AppError "不存在"
// @Security Bearer
// @Router /automations/by-session/{session_id} [get]
func (h *AutomationHandler) GetAutomationBySession(c *gin.Context) {
a, err := h.automations.FindBySession(c.Request.Context(), c.Param("session_id"))
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": a})
}
// GetAutomation godoc
// @Summary 获取自动化
// @Tags 自动化
// @Produce json
// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
// @Success 200 {object} handler.DataResponse{data=types.Automation} "自动化"
// @Failure 404 {object} errors.AppError "不存在"
// @Security Bearer
// @x-agent {"id":"automation.get","risk":"read"}
// @x-agent-hint "Returns one automation, including its instruction."
// @Router /automations/{id} [get]
func (h *AutomationHandler) GetAutomation(c *gin.Context) {
a, err := h.automations.Get(c.Request.Context(), c.Param("id"))
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": a})
}
// UpdateAutomation godoc
// @Summary 修改自动化
// @Description 只修改请求中出现的字段,其余保持不变
// @Tags 自动化
// @Accept json
// @Produce json
// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
// @Param request body types.AutomationPatch true "要修改的字段"
// @Success 200 {object} handler.DataResponse{data=types.Automation} "修改后的自动化"
// @Failure 400 {object} errors.AppError "参数不合法"
// @Security Bearer
// @x-agent {"id":"automation.update","role":"viewer","risk":"write","target":"automation.get","label":"name","always_confirm":true}
// @x-agent-hint "Changes the listed fields of an automation; a field left out is kept. Check a new trigger with automation.validate_trigger first. Use automation.pause and automation.resume to switch it off and on."
// @Router /automations/{id} [put]
func (h *AutomationHandler) UpdateAutomation(c *gin.Context) {
var req types.AutomationPatch
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("invalid automation").WithDetails(err.Error()))
return
}
a, err := h.automations.Update(c.Request.Context(), c.Param("id"), &req)
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": a})
}
// DeleteAutomation godoc
// @Summary 删除自动化
// @Description 停止进行中的运行,删除自动化及其运行记录、会话和长期授权
// @Tags 自动化
// @Produce json
// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
// @Success 200 {object} handler.SuccessResponse "删除成功"
// @Failure 404 {object} errors.AppError "不存在"
// @Security Bearer
// @x-agent {"id":"automation.delete","role":"viewer","risk":"destructive","target":"automation.get","label":"name"}
// @x-agent-hint "Deletes an automation with its run history and conversations. Cannot be undone; automation.pause keeps it."
// @Router /automations/{id} [delete]
func (h *AutomationHandler) DeleteAutomation(c *gin.Context) {
if err := h.automations.Delete(c.Request.Context(), c.Param("id")); err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// PauseAutomation godoc
// @Summary 暂停自动化
// @Description 停止按计划触发;进行中的运行不受影响
// @Tags 自动化
// @Produce json
// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
// @Success 200 {object} handler.DataResponse{data=types.Automation} "暂停后的自动化"
// @Security Bearer
// @x-agent {"id":"automation.pause","role":"viewer","risk":"write","target":"automation.get","label":"name"}
// @x-agent-hint "Stops an automation from running on schedule until automation.resume."
// @Router /automations/{id}/pause [post]
func (h *AutomationHandler) PauseAutomation(c *gin.Context) {
a, err := h.automations.Pause(c.Request.Context(), c.Param("id"))
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": a})
}
// ResumeAutomation godoc
// @Summary 恢复自动化
// @Description 从现在起重新按计划触发,并清零连续失败计数
// @Tags 自动化
// @Produce json
// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
// @Success 200 {object} handler.DataResponse{data=types.Automation} "恢复后的自动化"
// @Security Bearer
// @x-agent {"id":"automation.resume","role":"viewer","risk":"write","target":"automation.get","label":"name","always_confirm":true}
// @x-agent-hint "Schedules a paused automation again from now; missed runs are not caught up."
// @Router /automations/{id}/resume [post]
func (h *AutomationHandler) ResumeAutomation(c *gin.Context) {
a, err := h.automations.Resume(c.Request.Context(), c.Param("id"))
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": a})
}
// RunAutomation godoc
// @Summary 立即运行自动化
// @Description 排队一次手动运行;已有运行在排队或进行中时拒绝
// @Tags 自动化
// @Produce json
// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
// @Success 202 {object} handler.DataResponse{data=types.AutomationRun} "排队的运行"
// @Failure 409 {object} errors.AppError "已有运行"
// @Security Bearer
// @x-agent {"id":"automation.run_now","role":"viewer","risk":"write","target":"automation.get","label":"name","always_confirm":true}
// @x-agent-hint "Queues a run now, in the background; follow it with automation.list_runs."
// @Router /automations/{id}/run [post]
func (h *AutomationHandler) RunAutomation(c *gin.Context) {
run, err := h.automations.RunNow(c.Request.Context(), c.Param("id"))
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusAccepted, gin.H{"success": true, "data": run})
}
// ListAutomationRuns godoc
// @Summary 列出运行记录
// @Tags 自动化
// @Produce json
// @Param id path string true "自动化 ID" extensions(x-agent=automation_id)
// @Param page query int false "页码,从 1 开始" extensions(x-agent)
// @Param page_size query int false "每页条数,最多 100" extensions(x-agent,x-agent-maximum=20)
// @Success 200 {object} handler.PageResponse{data=[]types.AutomationRun} "运行记录"
// @Security Bearer
// @x-agent {"id":"automation.list_runs","risk":"read"}
// @x-agent-hint "Lists an automation's runs, newest first, with status, error and the start of the answer."
// @Router /automations/{id}/runs [get]
func (h *AutomationHandler) ListAutomationRuns(c *gin.Context) {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
size, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
page = max(page, 1)
if size <= 0 || size > 100 {
size = 20
}
runs, total, err := h.automations.ListRuns(c.Request.Context(), c.Param("id"), size, (page-1)*size)
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": runs, "total": total, "page": page, "page_size": size})
}
// GetAutomationRun godoc
// @Summary 获取运行记录
// @Tags 自动化
// @Produce json
// @Param id path string true "运行 ID"
// @Success 200 {object} handler.DataResponse{data=types.AutomationRun} "运行记录"
// @Security Bearer
// @Router /automation-runs/{id} [get]
func (h *AutomationHandler) GetAutomationRun(c *gin.Context) {
run, err := h.automations.GetRun(c.Request.Context(), c.Param("id"))
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": run})
}
// CancelAutomationRun godoc
// @Summary 停止运行
// @Description 排队或等待审批的运行立即结束;执行中的运行在下一次检查时停止
// @Tags 自动化
// @Produce json
// @Param id path string true "运行 ID"
// @Success 200 {object} handler.DataResponse{data=types.AutomationRun} "运行记录"
// @Security Bearer
// @Router /automation-runs/{id}/cancel [post]
func (h *AutomationHandler) CancelAutomationRun(c *gin.Context) {
run, err := h.automations.CancelRun(c.Request.Context(), c.Param("id"))
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": run})
}
// ListAutomationGrants godoc
// @Summary 列出自动化的长期授权
// @Description 列出以后的运行无需确认即可执行的调用,以及失效原因
// @Tags 自动化
// @Produce json
// @Param id path string true "自动化 ID"
// @Success 200 {object} map[string]interface{} "长期授权"
// @Security Bearer
// @Router /automations/{id}/grants [get]
func (h *AutomationHandler) ListAutomationGrants(c *gin.Context) {
grants, err := h.automations.Grants(c.Request.Context(), c.Param("id"))
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": grants})
}
// ListAutomationGrantCandidates godoc
// @Summary 列出可设为长期授权的调用
// @Description 列出本自动化的运行请求过审批、尚未长期授权的调用;需每次审批的调用不在其中
// @Tags 自动化
// @Produce json
// @Param id path string true "自动化 ID"
// @Success 200 {object} map[string]interface{} "候选调用"
// @Security Bearer
// @Router /automations/{id}/grant-candidates [get]
func (h *AutomationHandler) ListAutomationGrantCandidates(c *gin.Context) {
candidates, err := h.automations.GrantCandidates(c.Request.Context(), c.Param("id"))
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": candidates})
}
type addAutomationGrantRequest struct {
PromptID string `json:"prompt_id" binding:"required"`
}
// AddAutomationGrant godoc
// @Summary 添加长期授权
// @Description 让以后的运行无需确认即可执行某次运行请求过审批的调用;Agent 配置或所有者角色变化后失效
// @Tags 自动化
// @Accept json
// @Produce json
// @Param id path string true "自动化 ID"
// @Param request body object true "{prompt_id}"
// @Success 200 {object} map[string]interface{} "授权"
// @Security Bearer
// @Router /automations/{id}/grants [post]
func (h *AutomationHandler) AddAutomationGrant(c *gin.Context) {
var req addAutomationGrantRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("prompt_id is required"))
return
}
grant, err := h.automations.AddGrant(c.Request.Context(), c.Param("id"), req.PromptID)
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": grant})
}
// ListNotifications godoc
// @Summary 列出我的通知
// @Tags 通知
// @Produce json
// @Param limit query int false "条数,最多 100"
// @Param cursor query string false "上一页返回的 next_cursor"
// @Param unread query bool false "只看未读"
// @Success 200 {object} map[string]interface{} "{items, pending, unread, read_count, next_cursor}"
// @Security Bearer
// @Router /notifications [get]
func (h *AutomationHandler) ListNotifications(c *gin.Context) {
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
page, err := h.notifications.List(c.Request.Context(), limit, c.Query("unread") == "true", c.Query("cursor"))
if err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": page})
}
type markNotificationsReadRequest struct {
IDs []string `json:"ids"`
}
// MarkNotificationsRead godoc
// @Summary 标记通知已读
// @Description ids 为空时将全部通知记录标为已读,不改变待处理事项
// @Tags 通知
// @Accept json
// @Produce json
// @Param request body object false "{ids}"
// @Success 200 {object} map[string]interface{} "结果"
// @Security Bearer
// @Router /notifications/read [post]
func (h *AutomationHandler) MarkNotificationsRead(c *gin.Context) {
var req markNotificationsReadRequest
_ = c.ShouldBindJSON(&req)
if err := h.notifications.MarkRead(c.Request.Context(), req.IDs); err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// ClearReadNotifications removes read notification history without changing work.
// @Summary 清理已读通知
// @Tags 通知
// @Produce json
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /notifications/read [delete]
func (h *AutomationHandler) ClearReadNotifications(c *gin.Context) {
if err := h.notifications.ClearRead(c.Request.Context()); err != nil {
h.fail(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
+19
View File
@@ -0,0 +1,19 @@
package handler
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestCreateAutomationPreservesModelOverride(t *testing.T) {
var req CreateAutomationRequest
require.NoError(t, json.Unmarshal([]byte(`{
"name": "Digest", "instruction": "Summarize the news",
"model_id": "selected-model",
"trigger": {"type": "cron", "expr": "0 9 * * *"}
}`), &req))
require.NotNil(t, req.patch().ModelID)
require.Equal(t, "selected-model", *req.patch().ModelID)
}
+520
View File
@@ -0,0 +1,520 @@
package handler
import (
stderrors "errors"
"net/http"
"academy/internal/application/service"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
secutils "academy/internal/utils"
"github.com/gin-gonic/gin"
)
// ChunkHandler defines HTTP handlers for chunk operations.
//
// All KB-access checks (own / org-shared / via shared agent) are now
// performed by the route-level g.KBAccessRead*FromKnowledgeIDParam /
// g.KBAccessWrite*FromKnowledgeIDParam / g.KBAccess*FromChunkIDParam
// guards in router.go — the guard rewrites c.Request.Context() to
// carry the effective tenant ID, so the handler reads tenant from
// context the way it always did.
//
// kgService is retained because the route-level *creator-ownership*
// lookup KBCreatorLookupFromKnowledgeIDParam still walks
// knowledge_id -> kb_id to resolve creator_id (separate axis from
// access — that lookup answers "is the caller the creator of THIS
// resource", not "does the caller's tenant have access").
type ChunkHandler struct {
service interfaces.ChunkService
kgService interfaces.KnowledgeService
}
// NewChunkHandler creates a new chunk handler.
func NewChunkHandler(service interfaces.ChunkService, kgService interfaces.KnowledgeService) *ChunkHandler {
return &ChunkHandler{service: service, kgService: kgService}
}
// GetChunkByIDOnly godoc
// @Summary 通过ID获取分块
// @Description 仅通过分块ID获取分块详情(不需要knowledge_id);支持共享知识库下的分块访问
// @Tags 分块管理
// @Accept json
// @Produce json
// @Param id path string true "分块ID" extensions(x-agent=chunk_id)
// @Success 200 {object} handler.DataResponse{data=handler.AgentChunkDetail} "分块详情"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "分块不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @x-agent {"id":"chunk.get","risk":"read"}
// @x-agent-hint "Read a chunk before editing. knowledge_id identifies its parent document; content_revision is required as expected_revision for changes. If truncated, do not reconstruct missing content."
// @Router /chunks/by-id/{id} [get]
func (h *ChunkHandler) GetChunkByIDOnly(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start retrieving chunk by ID only")
chunkID := secutils.SanitizeForLog(c.Param("id"))
if chunkID == "" {
logger.Error(ctx, "Chunk ID is empty")
c.Error(errors.NewBadRequestError("Chunk ID cannot be empty"))
return
}
// Get chunk by ID without tenant filter (chunk may belong to shared
// KB; the route-level KB-access guard already verified read
// permission against the parent KB before we got here).
chunk, err := h.service.GetChunkByIDOnly(ctx, chunkID)
if err != nil {
if err == service.ErrChunkNotFound {
logger.Warnf(ctx, "Chunk not found, chunk ID: %s", chunkID)
c.Error(errors.NewNotFoundError("Chunk not found"))
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": chunk,
})
}
// ListKnowledgeChunks godoc
// @Summary 获取知识分块列表
// @Description 获取指定知识下的所有分块列表,支持分页。chunk_type 可重复,缺省 text
// @Description 取值 text, parent_text, image_ocr, image_caption, image_vector, summary, entity,
// @Description relationship, faq, web_search, table_summary, table_column, wiki_page
// @Tags 分块管理
// @Accept json
// @Produce json
// @Param knowledge_id path string true "知识ID" extensions(x-agent)
// @Param page query int false "页码" default(1) minimum(1) extensions(x-agent,x-agent-maximum=10000)
// @Param page_size query int false "每页数量" default(10) minimum(1) maximum(100) extensions(x-agent,x-agent-maximum=20)
// @Param chunk_type query []string false "分块类型,可重复,缺省 text" collectionFormat(multi) Enums(text,parent_text,image_ocr,image_caption,image_vector,summary,entity,relationship,faq,web_search,table_summary,table_column,wiki_page) extensions(x-agent)
// @Success 200 {object} handler.PageResponse{data=[]types.Chunk} "分块列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @x-agent {"id":"chunk.list","risk":"read"}
// @x-agent-hint "The chunks a document was split into, in order; use it to check how a document was parsed. meta.total counts every chunk."
// @Router /chunks/{knowledge_id} [get]
func (h *ChunkHandler) ListKnowledgeChunks(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start retrieving knowledge chunks list")
knowledgeID := secutils.SanitizeForLog(c.Param("knowledge_id"))
if knowledgeID == "" {
logger.Error(ctx, "Knowledge ID is empty")
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
// Parse pagination parameters
var pagination types.Pagination
if err := c.ShouldBindQuery(&pagination); err != nil {
logger.Errorf(ctx, "Failed to parse pagination parameters: %s", secutils.SanitizeForLog(err.Error()))
c.Error(errors.NewBadRequestError(err.Error()))
return
}
if pagination.Page < 1 {
pagination.Page = 1
}
if pagination.PageSize < 1 {
pagination.PageSize = 10
}
if pagination.PageSize > 100 {
pagination.PageSize = 100
}
// Default to text chunks; callers may override via ?chunk_type=image_caption etc.
chunkType := []types.ChunkType{types.ChunkTypeText}
if queryTypes := c.QueryArray("chunk_type"); len(queryTypes) > 0 {
chunkType = make([]types.ChunkType, 0, len(queryTypes))
for _, qt := range queryTypes {
chunkType = append(chunkType, types.ChunkType(qt))
}
}
// The route-level guard has rewritten the request's tenant context
// to the effective tenant for shared KBs.
result, err := h.service.ListPagedChunksByKnowledgeID(ctx, knowledgeID, &pagination, chunkType)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": result.Data,
"total": result.Total,
"page": result.Page,
"page_size": result.PageSize,
})
}
// UpdateChunkRequest defines the request structure for updating a chunk
type UpdateChunkRequest struct {
// Complete replacement content; omitted keeps the existing content.
Content *string `json:"content" extensions:"x-agent,x-agent-max-bytes=32000"`
// Whether this chunk participates in retrieval; omitted keeps its state.
IsEnabled *bool `json:"is_enabled" extensions:"x-agent"`
// Current content_revision from chunk.get; a stale value fails with HTTP 409.
ExpectedRevision *int `json:"expected_revision" minimum:"0" extensions:"x-agent,x-agent-required"`
}
// fetchChunkAndVerifyOwnership fetches a chunk by ID and verifies it
// belongs to the URL :knowledge_id (defence in depth: the route-level
// KB-access guard already ensured the caller has write access to the
// KB; this check stops a same-tenant attacker from passing one
// knowledge_id while addressing a chunk owned by a different
// knowledge in the same KB).
func (h *ChunkHandler) fetchChunkAndVerifyOwnership(c *gin.Context) (*types.Chunk, string, error) {
ctx := c.Request.Context()
knowledgeID := secutils.SanitizeForLog(c.Param("knowledge_id"))
if knowledgeID == "" {
logger.Error(ctx, "Knowledge ID is empty")
return nil, "", errors.NewBadRequestError("Knowledge ID cannot be empty")
}
id := secutils.SanitizeForLog(c.Param("id"))
if id == "" {
logger.Error(ctx, "Chunk ID is empty")
return nil, knowledgeID, errors.NewBadRequestError("Chunk ID cannot be empty")
}
chunk, err := h.service.GetChunkByID(ctx, id)
if err != nil {
if err == service.ErrChunkNotFound {
logger.Warnf(ctx, "Chunk not found, knowledge ID: %s, chunk ID: %s", knowledgeID, id)
return nil, knowledgeID, errors.NewNotFoundError("Chunk not found")
}
logger.ErrorWithFields(ctx, err, nil)
return nil, knowledgeID, errors.NewInternalServerError(err.Error())
}
if chunk.KnowledgeID != knowledgeID {
logger.Warnf(ctx, "Chunk does not belong to knowledge, knowledge ID: %s, chunk ID: %s", knowledgeID, id)
return nil, knowledgeID, errors.NewForbiddenError("No permission to access this chunk")
}
return chunk, knowledgeID, nil
}
// UpdateChunk godoc
// @Summary 更新分块
// @Description 更新指定分块的内容和属性
// @Tags 分块管理
// @Accept json
// @Produce json
// @Param knowledge_id path string true "知识ID" extensions(x-agent)
// @Param id path string true "分块ID" extensions(x-agent=chunk_id)
// @Param request body UpdateChunkRequest true "更新请求"
// @Success 200 {object} handler.UpdateChunkResponse "更新后的分块"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "分块不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @x-agent {"id":"chunk.update","risk":"write","target":"chunk.get","label":"chunk_id","require_complete_target":true}
// @x-agent-hint "Edit the complete content of a document chunk or set is_enabled; omitted fields stay unchanged. Read chunk.get first and pass its content_revision as expected_revision. Do not edit truncated content. A conflict requires rereading and reconciling edits. Reindexes affected content and preserves revision history; FAQ and wiki chunks use their own editors."
// @Router /chunks/{knowledge_id}/{id} [put]
func (h *ChunkHandler) UpdateChunk(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start updating knowledge chunk")
chunk, knowledgeID, err := h.fetchChunkAndVerifyOwnership(c)
if err != nil {
c.Error(err)
return
}
var req UpdateChunkRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Errorf(ctx, "Failed to parse request parameters: %s", secutils.SanitizeForLog(err.Error()))
c.Error(errors.NewBadRequestError(err.Error()))
return
}
chunk, err = h.service.UpdateDocumentChunk(ctx, chunk.ID, req.Content, req.IsEnabled, req.ExpectedRevision)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
if stderrors.Is(err, service.ErrChunkRevisionConflict) {
c.Error(errors.NewConflictError("Chunk was modified by another user; refresh and retry"))
return
}
var appErr *errors.AppError
if stderrors.As(err, &appErr) {
_ = c.Error(appErr)
} else {
_ = c.Error(errors.NewInternalServerError(err.Error()))
}
return
}
logger.Infof(ctx, "Knowledge chunk updated successfully, knowledge ID: %s, chunk ID: %s",
secutils.SanitizeForLog(knowledgeID), secutils.SanitizeForLog(chunk.ID))
knowledge, getErr := h.kgService.GetKnowledgeByID(ctx, knowledgeID)
if getErr != nil {
logger.Warnf(ctx, "Chunk updated but failed to reload summary status for %s: %v", knowledgeID, getErr)
}
response := gin.H{"success": true, "data": chunk}
if knowledge != nil {
response["summary_status"] = knowledge.SummaryStatus
response["description"] = knowledge.Description
}
c.JSON(http.StatusOK, response)
}
// ListChunkRevisions godoc
// @Summary 获取分块历史版本
// @Tags 分块管理
// @Accept json
// @Produce json
// @Param knowledge_id path string true "知识ID" extensions(x-agent)
// @Param id path string true "分块ID" extensions(x-agent=chunk_id)
// @Success 200 {object} handler.DataResponse{data=[]types.ChunkRevision}
// @Security Bearer
// @Security ApiKeyAuth
// @x-agent {"id":"chunk.list_revisions","risk":"read"}
// @x-agent-hint "Read saved earlier revisions of a document chunk. Current revision is returned by chunk.get."
// @Router /chunks/{knowledge_id}/{id}/revisions [get]
func (h *ChunkHandler) ListChunkRevisions(c *gin.Context) {
chunk, _, err := h.fetchChunkAndVerifyOwnership(c)
if err != nil {
c.Error(err)
return
}
items, err := h.service.ListChunkRevisions(c.Request.Context(), chunk.ID)
if err != nil {
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
}
type RevertChunkRequest struct {
// Historical revision number from chunk.list_revisions to restore.
Revision *int `json:"revision" binding:"required" minimum:"0" extensions:"x-agent"`
// Current content_revision from chunk.get; a stale value fails with HTTP 409.
ExpectedRevision *int `json:"expected_revision" minimum:"0" extensions:"x-agent,x-agent-required"`
}
// RevertChunk godoc
// @Summary 恢复分块历史版本
// @Tags 分块管理
// @Accept json
// @Produce json
// @Param knowledge_id path string true "知识ID" extensions(x-agent)
// @Param id path string true "分块ID" extensions(x-agent=chunk_id)
// @Param request body RevertChunkRequest true "恢复请求"
// @Success 200 {object} handler.DataResponse{data=types.Chunk}
// @Security Bearer
// @Security ApiKeyAuth
// @x-agent {"id":"chunk.revert","risk":"write","target":"chunk.get","label":"chunk_id"}
// @x-agent-hint "Restore content and enabled state from a saved revision, creating a new revision and reindexing. Get revision from chunk.list_revisions and expected_revision from chunk.get; on conflict reread before retrying."
// @Router /chunks/{knowledge_id}/{id}/revert [post]
func (h *ChunkHandler) RevertChunk(c *gin.Context) {
chunk, knowledgeID, err := h.fetchChunkAndVerifyOwnership(c)
if err != nil {
c.Error(err)
return
}
var req RevertChunkRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(errors.NewBadRequestError(err.Error()))
return
}
if req.Revision == nil || *req.Revision < 0 {
c.Error(errors.NewBadRequestError("revision must be a non-negative integer"))
return
}
updated, err := h.service.RevertDocumentChunk(c.Request.Context(), chunk.ID, *req.Revision, req.ExpectedRevision)
if stderrors.Is(err, service.ErrChunkRevisionConflict) {
c.Error(errors.NewConflictError("Chunk was modified by another user; refresh and retry"))
return
}
if err != nil {
var appErr *errors.AppError
if stderrors.As(err, &appErr) {
_ = c.Error(appErr)
} else {
_ = c.Error(errors.NewBadRequestError(err.Error()))
}
return
}
knowledge, getErr := h.kgService.GetKnowledgeByID(c.Request.Context(), knowledgeID)
if getErr != nil {
logger.Warnf(c.Request.Context(), "Chunk reverted but failed to reload summary status for %s: %v", knowledgeID, getErr)
}
response := gin.H{"success": true, "data": updated}
if knowledge != nil {
response["summary_status"] = knowledge.SummaryStatus
response["description"] = knowledge.Description
}
c.JSON(http.StatusOK, response)
}
type UpsertGeneratedQuestionRequest struct {
QuestionID string `json:"question_id"`
Question string `json:"question" binding:"required"`
}
func (h *ChunkHandler) UpsertGeneratedQuestion(c *gin.Context) {
chunkID := secutils.SanitizeForLog(c.Param("id"))
if chunkID == "" {
c.Error(errors.NewBadRequestError("Chunk ID is required"))
return
}
var req UpsertGeneratedQuestionRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(errors.NewBadRequestError(err.Error()))
return
}
item, err := h.service.UpsertGeneratedQuestion(c.Request.Context(), chunkID, req.QuestionID, req.Question)
if err != nil {
c.Error(errors.NewBadRequestError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": item})
}
func (h *ChunkHandler) RegenerateGeneratedQuestions(c *gin.Context) {
chunkID := secutils.SanitizeForLog(c.Param("id"))
if chunkID == "" {
c.Error(errors.NewBadRequestError("Chunk ID is required"))
return
}
items, err := h.kgService.RegenerateChunkQuestions(c.Request.Context(), chunkID)
if err != nil {
c.Error(errors.NewBadRequestError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": items})
}
// DeleteChunk godoc
// @Summary 删除分块
// @Description 删除指定的分块
// @Tags 分块管理
// @Accept json
// @Produce json
// @Param knowledge_id path string true "知识ID"
// @Param id path string true "分块ID"
// @Success 200 {object} handler.MessageResponse "删除成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "分块不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /chunks/{knowledge_id}/{id} [delete]
func (h *ChunkHandler) DeleteChunk(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start deleting knowledge chunk")
chunk, _, err := h.fetchChunkAndVerifyOwnership(c)
if err != nil {
c.Error(err)
return
}
if err := h.service.DeleteChunk(ctx, chunk.ID); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Chunk deleted",
})
}
// DeleteChunksByKnowledgeID godoc
// @Summary 删除知识下所有分块
// @Description 删除指定知识下的所有分块
// @Tags 分块管理
// @Accept json
// @Produce json
// @Param knowledge_id path string true "知识ID"
// @Success 200 {object} handler.MessageResponse "删除成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /chunks/{knowledge_id} [delete]
func (h *ChunkHandler) DeleteChunksByKnowledgeID(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start deleting all chunks under knowledge")
knowledgeID := secutils.SanitizeForLog(c.Param("knowledge_id"))
if knowledgeID == "" {
logger.Error(ctx, "Knowledge ID is empty")
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
return
}
if err := h.service.DeleteChunksByKnowledgeID(ctx, knowledgeID); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "All chunks under knowledge deleted",
})
}
// DeleteGeneratedQuestion godoc
// @Summary 删除生成的问题
// @Description 删除分块中生成的问题
// @Tags 分块管理
// @Accept json
// @Produce json
// @Param id path string true "分块ID"
// @Param request body object{question_id=string} true "问题ID"
// @Success 200 {object} handler.MessageResponse "删除成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "分块不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /chunks/by-id/{id}/questions [delete]
func (h *ChunkHandler) DeleteGeneratedQuestion(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start deleting generated question from chunk")
chunkID := secutils.SanitizeForLog(c.Param("id"))
if chunkID == "" {
logger.Error(ctx, "Chunk ID is empty")
c.Error(errors.NewBadRequestError("Chunk ID cannot be empty"))
return
}
var req struct {
QuestionID string `json:"question_id" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
logger.Errorf(ctx, "Failed to parse request parameters: %s", secutils.SanitizeForLog(err.Error()))
c.Error(errors.NewBadRequestError("Question ID is required"))
return
}
if err := h.service.DeleteGeneratedQuestion(ctx, chunkID, req.QuestionID); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewBadRequestError(err.Error()))
return
}
logger.Infof(ctx, "Generated question deleted successfully, chunk ID: %s, question ID: %s",
secutils.SanitizeForLog(chunkID), secutils.SanitizeForLog(req.QuestionID))
c.JSON(http.StatusOK, gin.H{
"success": true,
"message": "Generated question deleted",
})
}
// AgentChunkDetail describes the same chunk JSON with a larger detail projection.
// Lists keep their compact content preview; edits require a complete detail read.
type AgentChunkDetail struct {
types.Chunk
Content string `json:"content" extensions:"x-agent,x-agent-max-runes=8000"`
}
+294
View File
@@ -0,0 +1,294 @@
// Package handler — chunker_debug.go exposes a read-only preview endpoint
// that runs the adaptive chunker on supplied text without touching the DB
// or generating embeddings. Used by the KB editor's debug panel so users
// can experiment with chunking parameters before committing to a re-index.
package handler
import (
"context"
"math"
"net/http"
"strings"
"time"
"unicode/utf8"
"academy/internal/infrastructure/chunker"
"academy/internal/infrastructure/docparser"
"academy/internal/logger"
"github.com/gin-gonic/gin"
)
// previewMaxChars caps the input text size so a single preview request
// cannot tie up the splitter for long. Chosen to bound worst-case CPU
// well under the previewTimeout: at 64k runes even the heaviest tier
// chain finishes in well under a second on commodity hardware.
//
// SECURITY NOTE: the splitter is CPU-bound and does NOT accept a
// context.Context. When previewTimeout fires the handler returns to the
// caller, but the worker goroutine keeps running until the splitter
// finishes naturally. The 64k ceiling is the primary mitigation against
// goroutine pile-up under repeated authenticated requests. If the
// splitter ever gains context-awareness, the goroutine-wrapper in
// PreviewChunking should switch to it for true cancellation.
const previewMaxChars = 64 * 1024
// previewMaxChunks caps the number of chunks returned in a single preview
// response so the UI doesn't choke on pathological splits. Stats are
// computed over the full chunk set before truncation so the displayed
// avg/min/max/stddev stay representative.
const previewMaxChunks = 500
// previewTimeout caps how long the handler waits for the splitter
// goroutine before returning a 504. See note above on previewMaxChars.
const previewTimeout = 5 * time.Second
// PreviewChunkingRequest is the body shape accepted by /chunker/preview.
// Text is checked manually below so we can return a friendlier error than
// gin's default "Field validation for 'Text' failed on the 'required' tag".
type PreviewChunkingRequest struct {
Text string `json:"text"`
ChunkingConfig PreviewChunkingPayload `json:"chunking_config"`
}
// PreviewChunkingPayload mirrors the snake_case JSON the rest of the API
// uses for ChunkingConfig fields. We don't reuse types.ChunkingConfig
// directly because it carries unrelated parser rules and table-processing
// metadata that the preview path does not use.
type PreviewChunkingPayload struct {
ChunkSize int `json:"chunk_size"`
ChunkOverlap int `json:"chunk_overlap"`
Separators []string `json:"separators"`
EnableParentChild bool `json:"enable_parent_child"`
ParentChunkSize int `json:"parent_chunk_size"`
ChildChunkSize int `json:"child_chunk_size"`
Strategy string `json:"strategy"`
TokenLimit int `json:"token_limit"`
Languages []string `json:"languages"`
}
// PreviewChunkResult describes one chunk emitted during preview.
type PreviewChunkResult struct {
Seq int `json:"seq"`
Start int `json:"start"`
End int `json:"end"`
SizeChars int `json:"size_chars"`
SizeTokensApprox int `json:"size_tokens_approx"`
ContextHeader string `json:"context_header,omitempty"`
Content string `json:"content"`
}
// PreviewChunkingStats summarizes chunk-size distribution. Computed over
// the FULL chunk set, even when the response truncates to previewMaxChunks
// items, so avg/min/max/stddev reflect the real distribution, not just
// the first N.
type PreviewChunkingStats struct {
Count int `json:"count"`
AvgChars int `json:"avg_chars"`
MinChars int `json:"min_chars"`
MaxChars int `json:"max_chars"`
StddevChars int `json:"stddev_chars"`
// TruncatedTo, when set, is the original chunk count before the
// response was truncated to previewMaxChunks for transport.
TruncatedTo int `json:"truncated_to,omitempty"`
}
// PreviewChunkingResponse is the body returned by /chunker/preview.
type PreviewChunkingResponse struct {
SelectedTier chunker.StrategyTier `json:"selected_tier"`
TierChain []chunker.StrategyTier `json:"tier_chain"`
Rejected []chunker.TierRejection `json:"rejected"`
Profile *chunker.DocProfile `json:"profile"`
Chunks []PreviewChunkResult `json:"chunks"`
Stats PreviewChunkingStats `json:"stats"`
}
// PreviewChunking handles POST /chunker/preview. It runs the supplied text
// through the adaptive chunker and returns the chunks plus diagnostic
// information about which tier won. Read-only: no DB writes, no embedding
// calls, no logging of the supplied text.
//
// PreviewChunking godoc
// @Summary 预览分块结果
// @Description 对提交的文本运行自适应分块器并返回分块预览,不写入数据库不生成 embedding。文本最大 64k 字符
// @Tags 分块
// @Accept json
// @Produce json
// @Param request body handler.PreviewChunkingRequest true "{text, chunking_config}"
// @Success 200 {object} handler.PreviewChunkingResponse "分块结果"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 413 {object} map[string]interface{} "文本超过预览限制"
// @Failure 504 {object} map[string]interface{} "分块超时"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /chunker/preview [post]
func PreviewChunking(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), previewTimeout)
defer cancel()
var req PreviewChunkingRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "invalid request body: " + err.Error()})
return
}
if strings.TrimSpace(req.Text) == "" {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
"error": "text is empty — paste a sample to preview chunking",
})
return
}
if utf8.RuneCountInString(req.Text) > previewMaxChars {
c.JSON(http.StatusRequestEntityTooLarge, gin.H{
"success": false,
"error": "text exceeds preview limit",
"limit": previewMaxChars,
})
return
}
text := chunker.NormalizeLineEndings(req.Text)
text = docparser.NormalizeHTMLTables(text)
cfg := chunker.NormalizeSplitterConfig(chunker.SplitterConfig{
ChunkSize: req.ChunkingConfig.ChunkSize,
ChunkOverlap: req.ChunkingConfig.ChunkOverlap,
Separators: req.ChunkingConfig.Separators,
Strategy: req.ChunkingConfig.Strategy,
TokenLimit: req.ChunkingConfig.TokenLimit,
Languages: req.ChunkingConfig.Languages,
})
// Run the splitter on a goroutine so we can honor the request timeout.
// The splitter is CPU-bound and doesn't accept a context — wrapping
// here is the cheapest cancellation we can offer.
type splitResult struct {
chunks []chunker.Chunk
diag *chunker.Diagnostics
}
resCh := make(chan splitResult, 1)
go func() {
var chunks []chunker.Chunk
var diag *chunker.Diagnostics
if req.ChunkingConfig.EnableParentChild {
parentCfg, childCfg := chunker.DeriveParentChildConfigs(
cfg,
req.ChunkingConfig.ParentChunkSize,
req.ChunkingConfig.ChildChunkSize,
)
result, parentDiag := chunker.SplitParentChildWithDiagnostics(text, parentCfg, childCfg)
chunks = make([]chunker.Chunk, len(result.Children))
for i, child := range result.Children {
chunks[i] = child.Chunk
}
diag = parentDiag
} else {
chunks, diag = chunker.SplitWithDiagnostics(text, cfg)
}
resCh <- splitResult{chunks: chunks, diag: diag}
}()
var sr splitResult
select {
case sr = <-resCh:
case <-ctx.Done():
c.JSON(http.StatusGatewayTimeout, gin.H{
"success": false,
"error": "chunker preview timed out",
})
return
}
chunks, diag := sr.chunks, sr.diag
// Diagnostics carries the profile when auto-strategy ran; for explicit
// strategies the profile is nil and we materialize it here so the UI
// can still show document stats. Avoids the previous double-pass.
profile := diag.Profile
if profile == nil {
profile = chunker.ProfileDocument(text)
}
logger.Debugf(ctx, "chunker preview: tier=%s chunks=%d", diag.SelectedTier, len(chunks))
lang := chunker.LangMixed
if len(profile.DetectedLangs) > 0 {
lang = profile.DetectedLangs[0]
}
// Compute rune lengths once per chunk; reused for stats and result
// payload below. Avoids the previous triple-pass over each chunk's
// content (stats + result + ApproxTokenCount each rune-counted).
runeLens := make([]int, len(chunks))
for i, ch := range chunks {
runeLens[i] = utf8.RuneCountInString(ch.Content)
}
// Compute stats over the FULL chunk set first so the metrics stay
// representative even when we trim the response to previewMaxChunks.
totalCount := len(chunks)
stats := computeChunkSizeStats(runeLens)
if totalCount > previewMaxChunks {
stats.TruncatedTo = totalCount
chunks = chunks[:previewMaxChunks]
runeLens = runeLens[:previewMaxChunks]
}
results := make([]PreviewChunkResult, 0, len(chunks))
for i, ch := range chunks {
results = append(results, PreviewChunkResult{
Seq: ch.Seq,
Start: ch.Start,
End: ch.End,
SizeChars: runeLens[i],
SizeTokensApprox: chunker.ApproxTokenCountFromRuneLen(runeLens[i], lang),
ContextHeader: ch.ContextHeader,
Content: ch.Content,
})
}
resp := PreviewChunkingResponse{
SelectedTier: diag.SelectedTier,
TierChain: diag.TierChain,
Rejected: diag.Rejected,
Profile: profile,
Chunks: results,
Stats: stats,
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": resp})
}
// computeChunkSizeStats summarizes count / avg / min / max / stddev from
// a pre-computed rune-length slice. Decoupling from chunker.Chunk lets
// the caller compute rune lengths once and reuse them for the response
// payload (avoids a second []rune allocation per chunk).
func computeChunkSizeStats(runeLens []int) PreviewChunkingStats {
stats := PreviewChunkingStats{Count: len(runeLens)}
if len(runeLens) == 0 {
return stats
}
var sum, sumSq float64
minLen, maxLen := math.MaxInt32, 0
for _, l := range runeLens {
sum += float64(l)
sumSq += float64(l) * float64(l)
if l < minLen {
minLen = l
}
if l > maxLen {
maxLen = l
}
}
avg := sum / float64(len(runeLens))
variance := sumSq/float64(len(runeLens)) - avg*avg
if variance < 0 {
// Float precision can push the variance slightly below zero on
// near-uniform inputs; clamp so sqrt doesn't return NaN.
variance = 0
}
stats.AvgChars = int(avg + 0.5)
stats.MinChars = minLen
stats.MaxChars = maxLen
stats.StddevChars = int(math.Sqrt(variance) + 0.5)
return stats
}
+342
View File
@@ -0,0 +1,342 @@
package handler
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/infrastructure/chunker"
"github.com/gin-gonic/gin"
)
func init() {
gin.SetMode(gin.TestMode)
}
func TestComputeChunkSizeStats_Empty(t *testing.T) {
stats := computeChunkSizeStats(nil)
if stats.Count != 0 || stats.AvgChars != 0 || stats.MaxChars != 0 {
t.Errorf("empty input should yield zero stats, got %+v", stats)
}
}
func TestComputeChunkSizeStats_SingleChunk(t *testing.T) {
stats := computeChunkSizeStats([]int{500})
if stats.Count != 1 {
t.Errorf("count: got %d want 1", stats.Count)
}
if stats.AvgChars != 500 || stats.MinChars != 500 || stats.MaxChars != 500 {
t.Errorf("single-chunk stats should all equal 500, got %+v", stats)
}
if stats.StddevChars != 0 {
t.Errorf("stddev for one element should be 0, got %d", stats.StddevChars)
}
}
func TestComputeChunkSizeStats_VaryingSizes(t *testing.T) {
// 100, 200, 300, 400, 500 → avg 300, stddev ≈ 141
stats := computeChunkSizeStats([]int{100, 200, 300, 400, 500})
if stats.Count != 5 {
t.Errorf("count: got %d want 5", stats.Count)
}
if stats.AvgChars != 300 {
t.Errorf("avg: got %d want 300", stats.AvgChars)
}
if stats.MinChars != 100 || stats.MaxChars != 500 {
t.Errorf("min/max: got %d/%d want 100/500", stats.MinChars, stats.MaxChars)
}
if stats.StddevChars < 130 || stats.StddevChars > 150 {
t.Errorf("stddev: got %d, want ~141", stats.StddevChars)
}
}
func TestComputeChunkSizeStats_NoVarianceUnderflow(t *testing.T) {
// All identical — variance must clamp to 0 not flip negative on
// float-precision rounding.
stats := computeChunkSizeStats([]int{1234, 1234, 1234, 1234})
if stats.StddevChars != 0 {
t.Errorf("identical values must yield stddev=0, got %d", stats.StddevChars)
}
}
// --- PreviewChunking httptest -------------------------------------------------
func newPreviewRouter() *gin.Engine {
r := gin.New()
r.POST("/chunker/preview", PreviewChunking)
return r
}
func postPreview(t *testing.T, body any) (*httptest.ResponseRecorder, map[string]any) {
t.Helper()
r := newPreviewRouter()
buf := &bytes.Buffer{}
if err := json.NewEncoder(buf).Encode(body); err != nil {
t.Fatalf("encode body: %v", err)
}
req := httptest.NewRequest(http.MethodPost, "/chunker/preview", buf)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
var parsed map[string]any
if w.Body.Len() > 0 {
_ = json.Unmarshal(w.Body.Bytes(), &parsed)
}
return w, parsed
}
func TestPreviewChunking_HappyPath_AutoStrategy(t *testing.T) {
body := PreviewChunkingRequest{
Text: "# Top\nintro paragraph here.\n\n## Section A\nbody A.\n\n## Section B\nbody B.",
ChunkingConfig: PreviewChunkingPayload{
ChunkSize: 200,
ChunkOverlap: 20,
Separators: []string{"\n\n", "\n"},
Strategy: "auto",
},
}
w, parsed := postPreview(t, body)
if w.Code != http.StatusOK {
t.Fatalf("status: got %d want 200; body=%s", w.Code, w.Body.String())
}
if parsed["success"] != true {
t.Fatalf("success flag missing or false: %v", parsed)
}
data, ok := parsed["data"].(map[string]any)
if !ok {
t.Fatalf("data missing: %v", parsed)
}
if data["selected_tier"] == "" {
t.Errorf("selected_tier must be set, got %v", data["selected_tier"])
}
if _, ok := data["chunks"].([]any); !ok {
t.Errorf("chunks must be an array, got %T", data["chunks"])
}
stats, ok := data["stats"].(map[string]any)
if !ok {
t.Fatalf("stats must be an object, got %T", data["stats"])
}
if c, _ := stats["count"].(float64); c <= 0 {
t.Errorf("stats.count should be > 0, got %v", stats["count"])
}
}
func TestPreviewChunking_RejectsEmptyText(t *testing.T) {
w, parsed := postPreview(t, PreviewChunkingRequest{Text: " \n\t "})
if w.Code != http.StatusBadRequest {
t.Errorf("status: got %d want 400", w.Code)
}
if errStr, _ := parsed["error"].(string); !strings.Contains(errStr, "empty") {
t.Errorf("error should mention 'empty', got %q", errStr)
}
}
func TestPreviewChunking_RejectsOversizedText(t *testing.T) {
body := PreviewChunkingRequest{Text: strings.Repeat("a", previewMaxChars+1)}
w, parsed := postPreview(t, body)
if w.Code != http.StatusRequestEntityTooLarge {
t.Errorf("status: got %d want 413", w.Code)
}
if parsed["limit"] == nil {
t.Errorf("response should include limit hint, got %v", parsed)
}
}
func TestPreviewChunking_LegacyStrategy_NoProfile(t *testing.T) {
// Auto-strategy is the only path that produces a profile inside
// SplitWithDiagnostics. For explicit strategies the handler
// materializes one itself so the UI always sees stats.
body := PreviewChunkingRequest{
Text: "para one.\n\npara two.\n\npara three.\n\npara four.",
ChunkingConfig: PreviewChunkingPayload{
ChunkSize: 100,
ChunkOverlap: 10,
Separators: []string{"\n\n"},
Strategy: "legacy",
},
}
w, parsed := postPreview(t, body)
if w.Code != http.StatusOK {
t.Fatalf("status %d body=%s", w.Code, w.Body.String())
}
data := parsed["data"].(map[string]any)
if data["profile"] == nil {
t.Error("profile should be materialized for explicit strategy too")
}
if string(chunker.StrategyTier(data["selected_tier"].(string))) != string(chunker.TierLegacy) {
t.Errorf("selected_tier: got %v want %s", data["selected_tier"], chunker.TierLegacy)
}
}
func TestPreviewChunking_ChunkTruncation(t *testing.T) {
// Build text that produces > previewMaxChunks chunks.
body := PreviewChunkingRequest{
Text: strings.Repeat("x.\n\n", previewMaxChunks+50),
ChunkingConfig: PreviewChunkingPayload{
ChunkSize: 3,
ChunkOverlap: 0,
Separators: []string{"\n\n"},
Strategy: "legacy",
},
}
w, parsed := postPreview(t, body)
if w.Code != http.StatusOK {
t.Fatalf("status %d", w.Code)
}
data := parsed["data"].(map[string]any)
chunks := data["chunks"].([]any)
if len(chunks) > previewMaxChunks {
t.Errorf("chunks should be truncated to ≤%d, got %d", previewMaxChunks, len(chunks))
}
stats := data["stats"].(map[string]any)
if truncated, _ := stats["truncated_to"].(float64); int(truncated) <= previewMaxChunks {
t.Errorf("stats.truncated_to should reflect ORIGINAL count > %d, got %v", previewMaxChunks, truncated)
}
}
func TestPreviewChunking_ParentChildMatchesIngestion(t *testing.T) {
text := strings.Repeat("## Record\n"+strings.Repeat("A sufficiently long entry body. ", 10)+"\n\n", 12)
payload := PreviewChunkingPayload{
ChunkSize: 300,
ChunkOverlap: 30,
Separators: []string{"\n\n", "\n"},
EnableParentChild: true,
ParentChunkSize: 300,
ChildChunkSize: 100,
Strategy: chunker.StrategyHeading,
}
w, parsed := postPreview(t, PreviewChunkingRequest{Text: text, ChunkingConfig: payload})
if w.Code != http.StatusOK {
t.Fatalf("status %d body=%s", w.Code, w.Body.String())
}
base := chunker.NormalizeSplitterConfig(chunker.SplitterConfig{
ChunkSize: payload.ChunkSize,
ChunkOverlap: payload.ChunkOverlap,
Separators: payload.Separators,
Strategy: payload.Strategy,
})
parentCfg, childCfg := chunker.DeriveParentChildConfigs(base, payload.ParentChunkSize, payload.ChildChunkSize)
want := chunker.SplitParentChild(text, parentCfg, childCfg)
data := parsed["data"].(map[string]any)
got := data["chunks"].([]any)
if len(got) != len(want.Children) {
t.Fatalf("chunk count: got %d want %d", len(got), len(want.Children))
}
for i, child := range want.Children {
previewChunk := got[i].(map[string]any)
if previewChunk["content"] != child.Content {
t.Errorf("chunk %d content differs", i)
}
if int(previewChunk["start"].(float64)) != child.Start || int(previewChunk["end"].(float64)) != child.End {
t.Errorf("chunk %d span: got %v-%v want %d-%d", i, previewChunk["start"], previewChunk["end"], child.Start, child.End)
}
gotHeader, _ := previewChunk["context_header"].(string)
if gotHeader != child.ContextHeader {
t.Errorf("chunk %d context_header: got %q want %q", i, gotHeader, child.ContextHeader)
}
}
}
func TestPreviewChunking_SingleLevelUnchanged(t *testing.T) {
text := strings.Repeat("Paragraph one.\n\nParagraph two.\n\n", 20)
payload := PreviewChunkingPayload{
ChunkSize: 200,
ChunkOverlap: 20,
Separators: []string{"\n\n", "\n"},
Strategy: chunker.StrategyLegacy,
}
w, parsed := postPreview(t, PreviewChunkingRequest{Text: text, ChunkingConfig: payload})
if w.Code != http.StatusOK {
t.Fatalf("status %d body=%s", w.Code, w.Body.String())
}
want, _ := chunker.SplitWithDiagnostics(text, chunker.NormalizeSplitterConfig(chunker.SplitterConfig{
ChunkSize: payload.ChunkSize,
ChunkOverlap: payload.ChunkOverlap,
Separators: payload.Separators,
Strategy: payload.Strategy,
}))
data := parsed["data"].(map[string]any)
got := data["chunks"].([]any)
if len(got) != len(want) {
t.Fatalf("chunk count: got %d want %d", len(got), len(want))
}
}
func TestPreviewChunking_ParentChildDefaultSizes(t *testing.T) {
text := strings.Repeat("## Record\n"+strings.Repeat("A sufficiently long entry body. ", 10)+"\n\n", 12)
payload := PreviewChunkingPayload{
ChunkSize: 300,
ChunkOverlap: 30,
Separators: []string{"\n\n", "\n"},
EnableParentChild: true,
Strategy: chunker.StrategyHeading,
}
w, parsed := postPreview(t, PreviewChunkingRequest{Text: text, ChunkingConfig: payload})
if w.Code != http.StatusOK {
t.Fatalf("status %d body=%s", w.Code, w.Body.String())
}
base := chunker.NormalizeSplitterConfig(chunker.SplitterConfig{
ChunkSize: payload.ChunkSize,
ChunkOverlap: payload.ChunkOverlap,
Separators: payload.Separators,
Strategy: payload.Strategy,
})
parentCfg, childCfg := chunker.DeriveParentChildConfigs(base, 0, 0)
want := chunker.SplitParentChild(text, parentCfg, childCfg)
data := parsed["data"].(map[string]any)
got := data["chunks"].([]any)
if len(got) != len(want.Children) {
t.Fatalf("chunk count: got %d want %d", len(got), len(want.Children))
}
}
func TestPreviewChunking_LineEndingsMatchUpload(t *testing.T) {
uploaded := strings.Repeat("## Record\r\n"+strings.Repeat("A sufficiently long entry body. ", 10)+"\r\n\r\n", 12)
pasted := strings.ReplaceAll(uploaded, "\r\n", "\n") // HTML textarea normalization
payload := PreviewChunkingPayload{
ChunkSize: 500,
ChunkOverlap: 20,
Separators: []string{"\n\n", "\n", "。", "!", "?", ";", ";"},
Strategy: chunker.StrategyHeading,
}
actual := chunker.Split(chunker.NormalizeLineEndings(uploaded), chunker.NormalizeSplitterConfig(chunker.SplitterConfig{
ChunkSize: payload.ChunkSize,
ChunkOverlap: payload.ChunkOverlap,
Separators: payload.Separators,
Strategy: payload.Strategy,
}))
for name, text := range map[string]string{
"uploaded CRLF": uploaded,
"pasted LF": pasted,
} {
t.Run(name, func(t *testing.T) {
w, parsed := postPreview(t, PreviewChunkingRequest{Text: text, ChunkingConfig: payload})
if w.Code != http.StatusOK {
t.Fatalf("status %d body=%s", w.Code, w.Body.String())
}
data := parsed["data"].(map[string]any)
preview := data["chunks"].([]any)
if len(preview) != len(actual) {
t.Fatalf("chunk count: got %d want %d", len(preview), len(actual))
}
for i, chunk := range actual {
previewChunk := preview[i].(map[string]any)
if previewChunk["content"] != chunk.Content {
t.Errorf("chunk %d content differs", i)
}
if int(previewChunk["start"].(float64)) != chunk.Start || int(previewChunk["end"].(float64)) != chunk.End {
t.Errorf("chunk %d span: got %v-%v want %d-%d", i, previewChunk["start"], previewChunk["end"], chunk.Start, chunk.End)
}
}
})
}
}
@@ -0,0 +1,74 @@
package handler
import (
"context"
"net/http/httptest"
"testing"
"time"
"academy/internal/agent/hitl"
"academy/internal/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type collaborationPromptResumer struct {
delegated bool
calls int
}
func (r *collaborationPromptResumer) ResumeSuspendedRun(*gin.Context, *types.AgentPrompt, bool, *time.Time) {
r.calls++
}
func (r *collaborationPromptResumer) HandlesDelegatedPrompt(context.Context, *types.AgentPrompt) bool {
return r.delegated
}
func TestDelegatedPromptAnswerDoesNotBypassDurableScheduler(t *testing.T) {
for _, delegated := range []bool{true, false} {
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest("POST", "/agent/prompts/p", nil)
resumer := &collaborationPromptResumer{delegated: delegated}
handler := &MCPServiceHandler{runResumer: resumer}
handler.finishResolve(ctx, "p", hitl.Resolution{Prompt: &types.AgentPrompt{ID: "p"}, Resume: true}, nil)
require.Equal(t, 200, recorder.Code)
if delegated {
require.Zero(t, resumer.calls)
require.Contains(t, recorder.Body.String(), `"resumed":false`)
} else {
require.Equal(t, 1, resumer.calls)
require.Contains(t, recorder.Body.String(), `"resumed":true`)
}
}
}
func TestScheduledPromptAnswerReattachesWithoutStartingChatRun(t *testing.T) {
for _, suspended := range []bool{true, false} {
t.Run(map[bool]string{true: "suspended", false: "still_running"}[suspended], func(t *testing.T) {
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest("POST", "/agent/prompts/p", nil)
resumer := &collaborationPromptResumer{delegated: true}
handler := &MCPServiceHandler{runResumer: resumer}
queued := 0
handler.SetScheduledPromptRouter(func(_ context.Context, prompt *types.AgentPrompt) bool {
require.Equal(t, "p", prompt.ID)
queued++
return true
})
handler.finishResolve(ctx, "p", hitl.Resolution{
Prompt: &types.AgentPrompt{ID: "p"}, Resume: suspended,
}, nil)
require.Equal(t, 200, recorder.Code)
require.Equal(t, 1, queued)
require.Zero(t, resumer.calls, "the scheduler must retain ownership of automation runs")
if suspended {
require.JSONEq(t, `{"success":true,"resumed":true}`, recorder.Body.String())
} else {
require.JSONEq(t, `{"success":true,"resumed":false}`, recorder.Body.String())
}
})
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,94 @@
package handler
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"testing"
apperrors "academy/internal/errors"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type suggestedQuestionsAgentService struct {
interfaces.CustomAgentService
err error
tagScopes []types.TagScope
}
func (s *suggestedQuestionsAgentService) GetSuggestedQuestions(
_ context.Context,
_ string,
_ []string,
_ []string,
tagScopes []types.TagScope,
_ int,
) ([]types.SuggestedQuestion, error) {
s.tagScopes = tagScopes
return nil, s.err
}
func TestGetSuggestedQuestionsPreservesAppErrorStatus(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
h := &CustomAgentHandler{service: &suggestedQuestionsAgentService{
err: apperrors.NewForbiddenError("API key scope does not allow one or more knowledge bases"),
}}
r.GET("/agents/:id/suggested-questions", h.GetSuggestedQuestions)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/agents/agent-1/suggested-questions?knowledge_base_ids=kb-blocked", nil)
r.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("status = %d, want %d, body=%s", rec.Code, http.StatusForbidden, rec.Body.String())
}
}
func TestGetSuggestedQuestionsParsesScopedTags(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
service := &suggestedQuestionsAgentService{}
h := &CustomAgentHandler{service: service}
r.GET("/agents/:id/suggested-questions", h.GetSuggestedQuestions)
rawScopes := `[{"knowledge_base_id":"kb-1","tag_ids":["tag-1","tag-2"]}]`
rec := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodGet,
"/agents/agent-1/suggested-questions?tag_scopes="+url.QueryEscape(rawScopes),
nil,
)
r.ServeHTTP(rec, req)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Equal(t, []types.TagScope{{KnowledgeBaseID: "kb-1", TagIDs: []string{"tag-1", "tag-2"}}}, service.tagScopes)
}
func TestGetSuggestedQuestionsRejectsInvalidScopedTags(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
h := &CustomAgentHandler{service: &suggestedQuestionsAgentService{}}
r.GET("/agents/:id/suggested-questions", h.GetSuggestedQuestions)
rec := httptest.NewRecorder()
req := httptest.NewRequest(
http.MethodGet,
"/agents/agent-1/suggested-questions?tag_scopes="+url.QueryEscape("not-json"),
nil,
)
r.ServeHTTP(rec, req)
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
}
@@ -0,0 +1,103 @@
package handler
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/application/service"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type agentAvatarRepository struct {
interfaces.CustomAgentRepository
agent *types.CustomAgent
err error
writes int
}
func (r *agentAvatarRepository) GetAgentByID(context.Context, string, uint64) (*types.CustomAgent, error) {
return r.agent, r.err
}
func (r *agentAvatarRepository) UpdateAgent(_ context.Context, a *types.CustomAgent) error {
r.writes++
r.agent = a
return r.err
}
func (r *agentAvatarRepository) CreateAgent(_ context.Context, a *types.CustomAgent) error {
r.writes++
r.agent = a
return r.err
}
func TestCustomAgentAvatarAndErrorResponses(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
name, method, body, want string
status, writes int
repoErr error
}{
{"omitted", "PUT", `{"name":"updated","config":{}}`, "🤖", 200, 1, nil},
{"null", "PUT", `{"name":"updated","avatar":null}`, "🤖", 200, 1, nil},
{"clear", "PUT", `{"name":"updated","avatar":""}`, "", 200, 1, nil},
{"replace", "PUT", `{"name":"updated","avatar":"🐱"}`, "🐱", 200, 1, nil},
{
name: "64 unicode", method: "PUT",
body: `{"name":"updated","avatar":"` + strings.Repeat("🤖", 64) + `"}`,
want: strings.Repeat("🤖", 64), status: 200, writes: 1,
},
{"65 unicode update", "PUT", `{"name":"updated","avatar":"` + strings.Repeat("🤖", 65) + `"}`, "", 400, 0, nil},
{"65 unicode create", "POST", `{"name":"updated","avatar":"` + strings.Repeat("🤖", 65) + `"}`, "", 400, 0, nil},
{"config only still requires name", "PUT", `{"config":{}}`, "", 400, 0, nil},
{"update hides database error", "PUT", `{"name":"updated"}`, "", 500, 0, errors.New("SQLSTATE secret_schema")},
{"create hides database error", "POST", `{"name":"updated"}`, "", 500, 1, errors.New("SQLSTATE secret_schema")},
{"get hides database error", "GET", ``, "", 500, 0, errors.New("SQLSTATE secret_schema")},
} {
t.Run(tc.name, func(t *testing.T) {
repo := &agentAvatarRepository{
agent: &types.CustomAgent{ID: "custom-1", Name: "old", Avatar: "🤖", TenantID: 1},
err: tc.repoErr,
}
svc := service.NewCustomAgentService(repo, nil, nil, nil, nil, nil, nil, nil)
h := &CustomAgentHandler{service: svc}
router := gin.New()
router.Use(middleware.ErrorHandler())
router.PUT("/agents/:id", h.UpdateAgent)
router.POST("/agents", h.CreateAgent)
router.GET("/agents/:id", h.GetAgent)
path := "/agents/custom-1"
if tc.method == http.MethodPost {
path = "/agents"
}
req := httptest.NewRequest(tc.method, path, strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
req = req.WithContext(context.WithValue(req.Context(), types.TenantIDContextKey, uint64(1)))
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, tc.status, rec.Code, rec.Body.String())
require.Equal(t, tc.writes, repo.writes)
if tc.status == http.StatusOK {
var response struct {
Data types.CustomAgent `json:"data"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &response))
require.Equal(t, tc.want, response.Data.Avatar)
require.Equal(t, tc.want, repo.agent.Avatar)
}
if tc.repoErr != nil {
require.NotContains(t, rec.Body.String(), "SQLSTATE")
require.NotContains(t, rec.Body.String(), "secret_schema")
}
})
}
}
+277
View File
@@ -0,0 +1,277 @@
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/application/service"
"academy/internal/middleware"
"academy/internal/sandbox"
"academy/internal/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func patchTestAgent() *types.CustomAgent {
return &types.CustomAgent{
ID: "custom-1", Name: "Support", Description: "Answers tickets", Avatar: "🤖", TenantID: 1,
Config: types.CustomAgentConfig{
AgentMode: types.AgentModeQuickAnswer,
SystemPrompt: "Be brief.",
ModelID: "model-1",
KBSelectionMode: "selected",
KnowledgeBases: []string{"kb-1"},
MCPSelectionMode: "none",
Temperature: 0.3,
WebSearchEnabled: true,
},
}
}
func servePatch(t *testing.T, repo *agentAvatarRepository, body string) *httptest.ResponseRecorder {
t.Helper()
return servePatchWithSkills(t, repo, body, nil)
}
func servePatchWithSkills(
t *testing.T, repo *agentAvatarRepository, body string, skills usableSkillLister,
) *httptest.ResponseRecorder {
t.Helper()
return servePatchWith(t, repo, body, &CustomAgentHandler{usableSkills: skills})
}
func servePatchWith(
t *testing.T, repo *agentAvatarRepository, body string, h *CustomAgentHandler,
) *httptest.ResponseRecorder {
t.Helper()
gin.SetMode(gin.TestMode)
h.service = service.NewCustomAgentService(repo, nil, nil, nil, nil, nil, nil, nil)
router := gin.New()
router.Use(middleware.ErrorHandler())
router.PATCH("/agents/:id", h.PatchAgent)
req := httptest.NewRequest(http.MethodPatch, "/agents/custom-1", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req = req.WithContext(context.WithValue(req.Context(), types.TenantIDContextKey, uint64(1)))
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
return rec
}
func TestPatchAgentKeepsFieldsItDoesNotCarry(t *testing.T) {
repo := &agentAvatarRepository{agent: patchTestAgent()}
rec := servePatch(t, repo, `{"name":"Helpdesk","model_id":"model-2"}`)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Equal(t, 1, repo.writes)
got := repo.agent
assert.Equal(t, "Helpdesk", got.Name)
assert.Equal(t, "model-2", got.Config.ModelID)
assert.Equal(t, "Answers tickets", got.Description)
assert.Equal(t, "🤖", got.Avatar)
assert.Equal(t, "Be brief.", got.Config.SystemPrompt)
assert.Equal(t, []string{"kb-1"}, got.Config.KnowledgeBases)
assert.Equal(t, 0.3, got.Config.Temperature)
assert.True(t, got.Config.WebSearchEnabled)
assert.Equal(t, types.AgentModeQuickAnswer, got.Config.AgentMode)
}
func TestPatchAgentSelectionLists(t *testing.T) {
repo := &agentAvatarRepository{agent: patchTestAgent()}
repo.agent.Config.KBSelectionMode = "all"
rec := servePatch(t, repo,
`{"knowledge_bases":["kb-2","kb-3"],"mcp_services":["mcp-1"],"web_search_enabled":false}`)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
cfg := repo.agent.Config
assert.Equal(t, "selected", cfg.KBSelectionMode, "a list alone switches the scope to selected")
assert.Equal(t, []string{"kb-2", "kb-3"}, cfg.KnowledgeBases)
assert.Equal(t, "selected", cfg.MCPSelectionMode)
assert.Equal(t, []string{"mcp-1"}, cfg.MCPServices)
assert.False(t, cfg.WebSearchEnabled)
rec = servePatch(t, repo, `{"knowledge_bases":[],"kb_selection_mode":"none"}`)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
assert.Equal(t, "none", repo.agent.Config.KBSelectionMode, "an explicit mode wins")
assert.Empty(t, repo.agent.Config.KnowledgeBases)
}
func TestPatchAgentRejectsBadInput(t *testing.T) {
for name, body := range map[string]string{
"unknown mode": `{"kb_selection_mode":"some"}`,
"unknown agent": `{"agent_mode":"agent"}`,
"blank name": `{"name":" "}`,
"not json": `{`,
} {
t.Run(name, func(t *testing.T) {
repo := &agentAvatarRepository{agent: patchTestAgent()}
rec := servePatch(t, repo, body)
assert.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
assert.Zero(t, repo.writes)
})
}
}
func TestPatchAgentMode(t *testing.T) {
repo := &agentAvatarRepository{agent: patchTestAgent()}
rec := servePatch(t, repo, `{"agent_mode":" smart-reasoning "}`)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
assert.Equal(t, types.AgentModeSmartReasoning, repo.agent.Config.AgentMode)
assert.True(t, repo.agent.Config.MultiTurnEnabled, "smart-reasoning keeps earlier turns")
assert.Equal(t, "Be brief.", repo.agent.Config.SystemPrompt)
assert.Equal(t, "Support", repo.agent.Name)
rec = servePatch(t, repo, `{"agent_mode":"quick-answer"}`)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
assert.Equal(t, types.AgentModeQuickAnswer, repo.agent.Config.AgentMode)
assert.True(t, repo.agent.Config.MultiTurnEnabled, "leaving smart-reasoning does not turn multi-turn off")
}
func TestPatchAgentNotFound(t *testing.T) {
repo := &agentAvatarRepository{err: service.ErrAgentNotFound}
rec := servePatch(t, repo, `{"name":"x"}`)
assert.Equal(t, http.StatusNotFound, rec.Code, rec.Body.String())
}
func TestPatchAgentSkills(t *testing.T) {
for _, tc := range []struct {
name, body, mode string
skills []string
}{
{"names alone", `{"selected_skills":["ppt-generator"]}`, "selected", []string{"ppt-generator"}},
{"explicit selected", `{"skills_selection_mode":"selected"}`, "selected", []string{"ppt-generator"}},
{"empty selection", `{"selected_skills":[]}`, "selected", []string{}},
{"all clears names", `{"skills_selection_mode":"all"}`, "all", []string{}},
{"none clears names", `{"skills_selection_mode":"none"}`, "none", []string{}},
{"explicit all wins", `{"skills_selection_mode":"all","selected_skills":["unknown"]}`, "all", []string{}},
{"explicit none wins", `{"skills_selection_mode":"none","selected_skills":["unknown"]}`, "none", []string{}},
} {
t.Run(tc.name, func(t *testing.T) {
agent := patchTestAgent()
agent.Config.SandboxConfigID = "cfg-1"
agent.Config.SkillsSelectionMode = "none"
agent.Config.SelectedSkills = []string{"ppt-generator"}
agent.EnsureDefaults()
want := agent.Config
want.SkillsSelectionMode, want.SelectedSkills = tc.mode, tc.skills
repo := &agentAvatarRepository{agent: agent}
lister := &fakeUsableSkillLister{skills: []*types.TenantSkillEntity{nil, {Name: "ppt-generator"}}}
rec := servePatchWithSkills(t, repo, tc.body, lister)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Equal(t, 1, repo.writes)
assert.Equal(t, want, repo.agent.Config, "unmentioned config fields must be kept")
assert.Equal(t, "Support", repo.agent.Name)
assert.Equal(t, "Answers tickets", repo.agent.Description)
assert.Equal(t, "🤖", repo.agent.Avatar)
if tc.mode == "selected" && len(tc.skills) > 0 {
assert.Equal(t, uint64(1), lister.tenantID)
assert.Equal(t, "cfg-1", lister.configID)
} else {
assert.Empty(t, lister.configID)
}
})
}
}
func TestPatchAgentRejectsUnavailableSkills(t *testing.T) {
for _, body := range []string{
`{"selected_skills":["ppt-generator","unknown","PPT-generator"]}`,
`{"skills_selection_mode":"selected"}`,
} {
t.Run(body, func(t *testing.T) {
agent := patchTestAgent()
agent.Config.SandboxConfigID = "cfg-1"
agent.Config.SkillsSelectionMode = "selected"
agent.Config.SelectedSkills = []string{"unknown", "PPT-generator"}
repo := &agentAvatarRepository{agent: agent}
lister := &fakeUsableSkillLister{skills: []*types.TenantSkillEntity{{Name: "ppt-generator"}}}
rec := servePatchWithSkills(t, repo, body, lister)
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
assert.Contains(t, rec.Body.String(), "Unknown or unavailable skills: unknown, PPT-generator")
assert.Zero(t, repo.writes)
assert.Equal(t, "Support", repo.agent.Name)
assert.Equal(t, []string{"unknown", "PPT-generator"}, repo.agent.Config.SelectedSkills)
})
}
}
func TestPatchAgentKeepsSavedSkillsOnUnrelatedChange(t *testing.T) {
agent := patchTestAgent()
agent.Config.SandboxConfigID = "cfg-1"
agent.Config.SkillsSelectionMode = "selected"
agent.Config.SelectedSkills = []string{"uninstalled"}
repo := &agentAvatarRepository{agent: agent}
lister := &fakeUsableSkillLister{}
rec := servePatchWithSkills(t, repo, `{"name":"Renamed"}`, lister)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
assert.Equal(t, "Renamed", repo.agent.Name)
assert.Equal(t, []string{"uninstalled"}, repo.agent.Config.SelectedSkills)
assert.Zero(t, lister.tenantID, "saved skills are not re-checked")
}
func TestPatchAgentSkillsOnLiteUseHostTarget(t *testing.T) {
repo := &agentAvatarRepository{agent: patchTestAgent()}
lister := &fakeUsableSkillLister{skills: []*types.TenantSkillEntity{{Name: "ppt-generator"}}}
h := &CustomAgentHandler{usableSkills: lister, desktop: true}
rec := servePatchWith(t, repo, `{"selected_skills":["ppt-generator"]}`, h)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
assert.Equal(t, sandbox.HostSkillTargetID, lister.configID)
assert.Empty(t, repo.agent.Config.SandboxConfigID)
assert.Equal(t, []string{"ppt-generator"}, repo.agent.Config.SelectedSkills)
}
func TestPatchAgentSkillsRequireSandbox(t *testing.T) {
for _, body := range []string{
`{"skills_selection_mode":"all"}`,
`{"skills_selection_mode":"selected"}`,
`{"selected_skills":["ppt-generator"]}`,
`{"selected_skills":[]}`,
} {
t.Run(body, func(t *testing.T) {
repo := &agentAvatarRepository{agent: patchTestAgent()}
lister := &fakeUsableSkillLister{}
rec := servePatchWithSkills(t, repo, body, lister)
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
assert.Contains(t, rec.Body.String(), "Choose a sandbox in the agent editor")
assert.Zero(t, repo.writes)
assert.Zero(t, lister.tenantID)
})
}
for _, body := range []string{`{"skills_selection_mode":"none"}`, `{"name":"Renamed"}`} {
repo := &agentAvatarRepository{agent: patchTestAgent()}
repo.agent.Config.SkillsSelectionMode = "all"
rec := servePatch(t, repo, body)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
}
}
func TestPatchAgentRejectsInvalidSkillsInput(t *testing.T) {
tooMany, err := json.Marshal(map[string]any{"selected_skills": make([]string, 51)})
require.NoError(t, err)
for _, body := range []string{
`{"skills_selection_mode":"some"}`, `{"skills_selection_mode":""}`,
`{"selected_skills":"ppt-generator"}`, string(tooMany),
} {
t.Run(body, func(t *testing.T) {
repo := &agentAvatarRepository{agent: patchTestAgent()}
repo.agent.Config.SandboxConfigID = "cfg-1"
rec := servePatch(t, repo, body)
assert.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
assert.Zero(t, repo.writes)
})
}
}
func TestPatchAgentSkillsFailClosedWithoutLister(t *testing.T) {
repo := &agentAvatarRepository{agent: patchTestAgent()}
repo.agent.Config.SandboxConfigID = "cfg-1"
rec := servePatch(t, repo, `{"selected_skills":["ppt-generator"]}`)
assert.Equal(t, http.StatusInternalServerError, rec.Code, rec.Body.String())
assert.Zero(t, repo.writes)
}
@@ -0,0 +1,52 @@
package handler
import (
"testing"
"academy/internal/types"
)
// TestNormalizeAgentReasoningEffortRejectsUnknownLevel pins the create/update
// guard. An unvalidated level does not degrade to "off": ReasoningEffort wins
// over the legacy boolean and every non-empty value other than "off" counts as
// thinking-on, so a typo used to enable thinking and hand the vendor a level
// it never documented.
func TestNormalizeAgentReasoningEffortRejectsUnknownLevel(t *testing.T) {
cfg := types.CustomAgentConfig{ReasoningEffort: "hgih"}
if err := normalizeAgentReasoningEffort(&cfg); err == nil {
t.Fatal("expected an error for an unknown reasoning_effort")
}
}
// TestNormalizeAgentReasoningEffortCanonicalizes checks the accepted aliases
// are rewritten, so EnsureDefaults and the editor only ever see canonical
// values.
func TestNormalizeAgentReasoningEffortCanonicalizes(t *testing.T) {
cases := map[string]string{
"": "",
"high": "high",
"off": "off",
"none": "off",
"false": "off",
"true": "auto",
"on": "auto",
}
for in, want := range cases {
cfg := types.CustomAgentConfig{ReasoningEffort: in}
if err := normalizeAgentReasoningEffort(&cfg); err != nil {
t.Errorf("normalize(%q): unexpected error %v", in, err)
continue
}
if cfg.ReasoningEffort != want {
t.Errorf("normalize(%q) = %q, want %q", in, cfg.ReasoningEffort, want)
}
}
}
// TestNormalizeAgentReasoningEffortNilConfig keeps the helper safe for the
// zero-value paths.
func TestNormalizeAgentReasoningEffortNilConfig(t *testing.T) {
if err := normalizeAgentReasoningEffort(nil); err != nil {
t.Fatalf("nil config should be a no-op, got %v", err)
}
}
@@ -0,0 +1,117 @@
package handler
import (
"context"
"encoding/json"
stderrors "errors"
"net/http"
"testing"
"github.com/stretchr/testify/require"
apperrors "academy/internal/errors"
"academy/internal/types"
)
// stubSandboxConfigLookup answers the existence check without a database.
type stubSandboxConfigLookup struct {
entity *types.TenantSandboxConfigEntity
err error
lookups []string
}
func (s *stubSandboxConfigLookup) Get(
_ context.Context, _ uint64, id string,
) (*types.TenantSandboxConfigEntity, error) {
s.lookups = append(s.lookups, id)
return s.entity, s.err
}
func agentTenantContext() context.Context {
return context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
}
// The field must round-trip through the agent's JSON config column, since that
// is where it is persisted (no dedicated column).
func TestAgentConfigCarriesSandboxConfigID(t *testing.T) {
cfg := types.CustomAgentConfig{
AgentMode: "smart-reasoning",
SandboxConfigID: "cfg-a",
}
raw, err := json.Marshal(cfg)
require.NoError(t, err)
require.Contains(t, string(raw), `"sandbox_config_id":"cfg-a"`)
var back types.CustomAgentConfig
require.NoError(t, json.Unmarshal(raw, &back))
require.Equal(t, "cfg-a", back.SandboxConfigID)
}
// Empty must be omitted so existing agents keep an unchanged config payload.
func TestAgentConfigOmitsEmptySandboxConfigID(t *testing.T) {
raw, err := json.Marshal(types.CustomAgentConfig{AgentMode: "quick-answer"})
require.NoError(t, err)
require.NotContains(t, string(raw), "sandbox_config_id")
}
// Saving a dangling reference must fail here with a readable message. Deferring
// it means the agent looks fine until its first skill execution, which then dies
// on an opaque resolver error mid-conversation.
func TestAgentSandboxConfigValidationRejectsUnknownID(t *testing.T) {
lookup := &stubSandboxConfigLookup{}
h := &CustomAgentHandler{sandboxConfigs: lookup}
err := h.validateAgentSandboxConfig(agentTenantContext(),
types.CustomAgentConfig{SandboxConfigID: "cfg-gone"})
var appErr *apperrors.AppError
require.ErrorAs(t, err, &appErr)
require.Equal(t, http.StatusBadRequest, appErr.HTTPCode)
require.Equal(t, []string{"cfg-gone"}, lookup.lookups)
}
func TestAgentSandboxConfigValidationAcceptsExistingID(t *testing.T) {
lookup := &stubSandboxConfigLookup{
entity: &types.TenantSandboxConfigEntity{ID: "cfg-a", TenantID: 7},
}
h := &CustomAgentHandler{sandboxConfigs: lookup}
require.NoError(t, h.validateAgentSandboxConfig(agentTenantContext(),
types.CustomAgentConfig{SandboxConfigID: "cfg-a"}))
}
// Most agents run on the deployment default, so the common path must not pay for
// a lookup - and must never be rejected for leaving the field blank.
func TestAgentSandboxConfigValidationSkipsEmptyID(t *testing.T) {
lookup := &stubSandboxConfigLookup{}
h := &CustomAgentHandler{sandboxConfigs: lookup}
require.NoError(t, h.validateAgentSandboxConfig(agentTenantContext(),
types.CustomAgentConfig{SandboxConfigID: " "}))
require.Empty(t, lookup.lookups)
}
// A lookup failure is not the admin's fault; it must not read as "you picked a
// config that does not exist".
func TestAgentSandboxConfigValidationSurfacesLookupFailure(t *testing.T) {
lookup := &stubSandboxConfigLookup{err: stderrors.New("database is on fire")}
h := &CustomAgentHandler{sandboxConfigs: lookup}
err := h.validateAgentSandboxConfig(agentTenantContext(),
types.CustomAgentConfig{SandboxConfigID: "cfg-a"})
var appErr *apperrors.AppError
require.ErrorAs(t, err, &appErr)
require.Equal(t, http.StatusInternalServerError, appErr.HTTPCode)
}
// Partially-wired handlers appear in tests and in deployments without the
// config service; they must not reject every agent that selects a backend.
func TestAgentSandboxConfigValidationSkipsWhenServiceMissing(t *testing.T) {
h := &CustomAgentHandler{}
require.NoError(t, h.validateAgentSandboxConfig(agentTenantContext(),
types.CustomAgentConfig{SandboxConfigID: "cfg-a"}))
}
+69
View File
@@ -0,0 +1,69 @@
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"academy/internal/agent/tools"
"academy/internal/types"
)
func TestValidateAgentSandboxConfigRejectsAnyConfigOnLite(t *testing.T) {
h := &CustomAgentHandler{desktop: true}
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
err := h.validateAgentSandboxConfig(ctx, types.CustomAgentConfig{SandboxConfigID: "cfg-1"})
require.Error(t, err)
require.NoError(t, h.validateAgentSandboxConfig(ctx, types.CustomAgentConfig{}))
}
func TestGetAgentToolsServesTheToolCatalog(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodGet, "/api/v1/agents/tools", nil)
(&CustomAgentHandler{}).GetAgentTools(c)
require.Equal(t, http.StatusOK, recorder.Code)
var body struct {
Success bool `json:"success"`
Data struct {
Tools []struct {
Name string `json:"name"`
Group string `json:"group"`
Danger bool `json:"danger"`
Requirement struct {
AnyOf []string `json:"any_of"`
AllOf []string `json:"all_of"`
} `json:"requirement"`
} `json:"tools"`
DefaultTools []string `json:"default_tools"`
SwitchManagedTools []string `json:"switch_managed_tools"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &body))
require.True(t, body.Success)
byName := make(map[string]int, len(body.Data.Tools))
for i, tool := range body.Data.Tools {
byName[tool.Name] = i
}
for _, name := range []string{
tools.ToolSearchConversations, tools.ToolSearchKnowledge, tools.ToolWikiDeletePage, tools.ToolWikiSearch,
} {
require.Contains(t, byName, name)
}
search := body.Data.Tools[byName[tools.ToolSearchKnowledge]]
require.Equal(t, tools.ToolGroupRAG, search.Group)
require.ElementsMatch(t, []string{"vector", "keyword"}, search.Requirement.AnyOf)
require.True(t, body.Data.Tools[byName[tools.ToolWikiDeletePage]].Danger)
require.Equal(t, []string{"wiki"}, body.Data.Tools[byName[tools.ToolWikiSearch]].Requirement.AllOf)
require.Equal(t, tools.DefaultAllowedTools(), body.Data.DefaultTools)
require.Equal(t, tools.SwitchManagedTools(), body.Data.SwitchManagedTools)
}
+39
View File
@@ -0,0 +1,39 @@
package handler
import (
"fmt"
"strings"
"academy/internal/agent/tools"
"academy/internal/errors"
"academy/internal/types"
)
// allowedToolsWarnings tells the caller what saving did to an allowed_tools
// list without rejecting it.
type allowedToolsWarnings struct {
// KeptUnknown are stored names no built-in tool answers to. They stay so
// the agent can still be saved, but the agent cannot call them.
KeptUnknown []string `json:"kept_unknown,omitempty"`
// Dropped are tools other agent settings decide on; listing them had no
// effect, so they are not stored.
Dropped []string `json:"dropped,omitempty"`
}
// checkAgentAllowedTools validates config.AllowedTools before an agent is
// saved and rewrites it to the list that will be stored. stored is the
// agent's current list, nil for a new agent. Names a request adds that no
// built-in tool answers to are rejected, so a typo cannot silently leave an
// agent without the tool it was meant to get.
func checkAgentAllowedTools(stored []string, config *types.CustomAgentConfig) (*allowedToolsWarnings, error) {
check := tools.CheckAllowedTools(stored, config.AllowedTools)
if len(check.Rejected) > 0 {
return nil, errors.NewBadRequestError(fmt.Sprintf(
"allowed_tools contains unknown tools: %s", strings.Join(check.Rejected, ", ")))
}
config.AllowedTools = check.Tools
if len(check.KeptUnknown) == 0 && len(check.Dropped) == 0 {
return nil, nil
}
return &allowedToolsWarnings{KeptUnknown: check.KeptUnknown, Dropped: check.Dropped}, nil
}
+127
View File
@@ -0,0 +1,127 @@
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/agent/tools"
"academy/internal/application/service"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
// savingAgentService stores what the handler hands it, so a test can read
// the allowed_tools list that would reach the database.
type savingAgentService struct {
interfaces.CustomAgentService
stored *types.CustomAgent
lookupErr error
saved *types.CustomAgent
}
func (s *savingAgentService) GetAgentByID(context.Context, string) (*types.CustomAgent, error) {
return s.stored, s.lookupErr
}
func (s *savingAgentService) CreateAgent(_ context.Context, agent *types.CustomAgent) (*types.CustomAgent, error) {
s.saved = agent
return agent, nil
}
func (s *savingAgentService) UpdateAgent(
_ context.Context, agent *types.CustomAgent, _ *string,
) (*types.CustomAgent, error) {
s.saved = agent
return agent, nil
}
func sendAgent(t *testing.T, svc *savingAgentService, method, allowedTools string) *httptest.ResponseRecorder {
t.Helper()
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
h := &CustomAgentHandler{service: svc}
r.POST("/agents", h.CreateAgent)
r.PUT("/agents/:id", h.UpdateAgent)
path := "/agents"
if method == http.MethodPut {
path = "/agents/agent-1"
}
body := `{"name":"agent","config":{"agent_mode":"smart-reasoning","allowed_tools":` + allowedTools + `}}`
rec := httptest.NewRecorder()
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(rec, req)
return rec
}
func TestSavingAnAgentChecksItsToolList(t *testing.T) {
t.Run("create rejects names no tool answers to", func(t *testing.T) {
svc := &savingAgentService{}
rec := sendAgent(t, svc, http.MethodPost, `["thinking","serch_knowledge"]`)
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
require.Contains(t, rec.Body.String(), "serch_knowledge")
require.Nil(t, svc.saved)
})
t.Run("create rewrites retired names and drops switch-managed tools", func(t *testing.T) {
svc := &savingAgentService{}
rec := sendAgent(t, svc, http.MethodPost, `["knowledge_search","web_search"]`)
require.Equal(t, http.StatusCreated, rec.Code, rec.Body.String())
require.Equal(t, []string{tools.ToolSearchKnowledge}, svc.saved.Config.AllowedTools)
var body struct {
Warnings allowedToolsWarnings `json:"allowed_tools_warnings"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
require.Equal(t, []string{tools.ToolWebSearch}, body.Warnings.Dropped)
})
t.Run("create keeps an empty list empty and an unset list unset", func(t *testing.T) {
svc := &savingAgentService{}
require.Equal(t, http.StatusCreated, sendAgent(t, svc, http.MethodPost, `[]`).Code)
require.NotNil(t, svc.saved.Config.AllowedTools)
require.Empty(t, svc.saved.Config.AllowedTools)
svc = &savingAgentService{}
require.Equal(t, http.StatusCreated, sendAgent(t, svc, http.MethodPost, `null`).Code)
require.Nil(t, svc.saved.Config.AllowedTools)
})
t.Run("update keeps unknown names that were already stored", func(t *testing.T) {
svc := &savingAgentService{stored: &types.CustomAgent{
ID: "agent-1", Config: types.CustomAgentConfig{AllowedTools: []string{"thinking", "none"}},
}}
rec := sendAgent(t, svc, http.MethodPut, `["thinking","none"]`)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
require.Equal(t, []string{"thinking", "none"}, svc.saved.Config.AllowedTools)
var body struct {
Warnings allowedToolsWarnings `json:"allowed_tools_warnings"`
}
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
require.Equal(t, []string{"none"}, body.Warnings.KeptUnknown)
})
t.Run("update rejects unknown names it adds", func(t *testing.T) {
svc := &savingAgentService{stored: &types.CustomAgent{
ID: "agent-1", Config: types.CustomAgentConfig{AllowedTools: []string{"none"}},
}}
rec := sendAgent(t, svc, http.MethodPut, `["none","nothing"]`)
require.Equal(t, http.StatusBadRequest, rec.Code, rec.Body.String())
require.Contains(t, rec.Body.String(), "nothing")
require.Nil(t, svc.saved)
})
t.Run("update of a missing agent answers 404 before checking tools", func(t *testing.T) {
svc := &savingAgentService{lookupErr: service.ErrAgentNotFound}
rec := sendAgent(t, svc, http.MethodPut, `["nothing"]`)
require.Equal(t, http.StatusNotFound, rec.Code, rec.Body.String())
require.Nil(t, svc.saved)
})
}
+640
View File
@@ -0,0 +1,640 @@
package handler
import (
"context"
"net/http"
"strconv"
"academy/internal/datasource"
"academy/internal/handler/dto"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// DataSourceHandler handles HTTP requests for data source management
type DataSourceHandler struct {
service interfaces.DataSourceService
kbService interfaces.KnowledgeBaseService
}
// NewDataSourceHandler creates a new data source handler
func NewDataSourceHandler(
service interfaces.DataSourceService,
kbService interfaces.KnowledgeBaseService,
) *DataSourceHandler {
return &DataSourceHandler{
service: service,
kbService: kbService,
}
}
// getTenantID safely extracts and validates tenant ID from context
// Returns 0 if tenant ID is not found (caller should return 401)
func (h *DataSourceHandler) getTenantID(c *gin.Context) uint64 {
tenantID := c.GetUint64(types.TenantIDContextKey.String())
return tenantID
}
// Data source settings contain connector credentials, so only the owning tenant can access them.
func (h *DataSourceHandler) getOwnedKnowledgeBase(
ctx context.Context,
tenantID uint64,
kbID string,
) (*types.KnowledgeBase, int, string) {
if kbID == "" {
return nil, http.StatusBadRequest, "kb_id is required"
}
kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID)
if err != nil || kb == nil {
return nil, http.StatusNotFound, "knowledge base not found"
}
if kb.TenantID != tenantID {
return nil, http.StatusForbidden, "access denied"
}
if err := types.AuthorizeTenantAPIKeyKnowledgeBases(ctx, kbID); err != nil {
return nil, http.StatusForbidden, err.Error()
}
return kb, http.StatusOK, ""
}
func (h *DataSourceHandler) getOwnedDataSource(
ctx context.Context,
tenantID uint64,
id string,
) (*types.DataSource, int, string) {
ds, err := h.service.GetDataSource(ctx, id)
if err != nil {
return nil, http.StatusNotFound, "data source not found"
}
if _, status, msg := h.getOwnedKnowledgeBase(ctx, tenantID, ds.KnowledgeBaseID); status != http.StatusOK {
return nil, status, msg
}
return ds, http.StatusOK, ""
}
// CreateDataSource godoc
// @Summary Create a new data source
// @Description Create a new data source configuration for a knowledge base
// @Tags DataSource
// @Accept json
// @Produce json
// @Param request body types.DataSource true "Data source configuration"
// @Success 201 {object} types.DataSource
// @Failure 400 {object} map[string]string
// @Router /datasource [post]
func (h *DataSourceHandler) CreateDataSource(c *gin.Context) {
ctx := c.Request.Context()
// Extract tenant ID from context (set by auth middleware)
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: workspace context missing"})
return
}
var req types.DataSource
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
return
}
if _, status, msg := h.getOwnedKnowledgeBase(ctx, tenantID, req.KnowledgeBaseID); status != http.StatusOK {
c.JSON(status, gin.H{"error": msg})
return
}
// Enforce tenant isolation
req.TenantID = tenantID
ds, err := h.service.CreateDataSource(ctx, &req)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, dto.NewDataSourceResponse(ds))
}
// GetDataSource godoc
// @Summary 获取数据源详情
// @Description Retrieve a data source configuration by ID
// @Tags DataSource
// @Produce json
// @Param id path string true "Data source ID" extensions(x-agent=data_source_id)
// @Success 200 {object} dto.DataSourceResponse
// @Failure 404 {object} map[string]string
// @x-agent {"id":"data_source.get","risk":"read"}
// @x-agent-hint "Read a configured data source and its sync state; credentials, connector settings and raw upstream errors are omitted. For detailed failures use the data source settings page."
// @Router /datasource/{id} [get]
func (h *DataSourceHandler) GetDataSource(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
id := c.Param("id")
ds, status, msg := h.getOwnedDataSource(ctx, tenantID, id)
if status != http.StatusOK {
c.JSON(status, gin.H{"error": msg})
return
}
c.JSON(http.StatusOK, dto.NewDataSourceResponse(ds))
}
// ListDataSources godoc
// @Summary 获取数据源列表
// @Description List all data sources for a specific knowledge base
// @Tags DataSource
// @Produce json
// @Param kb_id query string true "Knowledge base ID" extensions(x-agent=knowledge_base_id)
// @Success 200 {array} dto.DataSourceResponse
// @Failure 400 {object} map[string]string
// @x-agent {"id":"data_source.list","risk":"read"}
// @x-agent-hint "List configured data sources for a knowledge base; use the returned data_source_id for sync control."
// @Router /datasource [get]
func (h *DataSourceHandler) ListDataSources(c *gin.Context) {
ctx := c.Request.Context()
// Extract tenant ID from context
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized: workspace context missing"})
return
}
kbID := c.Query("kb_id")
if _, status, msg := h.getOwnedKnowledgeBase(ctx, tenantID, kbID); status != http.StatusOK {
c.JSON(status, gin.H{"error": msg})
return
}
dataSources, err := h.service.ListDataSources(ctx, kbID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list data sources"})
return
}
if dataSources == nil {
dataSources = make([]*types.DataSource, 0)
}
c.JSON(http.StatusOK, dto.NewDataSourceResponses(dataSources))
}
// UpdateDataSource godoc
// @Summary Update a data source
// @Description Update an existing data source configuration
// @Tags DataSource
// @Accept json
// @Produce json
// @Param id path string true "Data source ID"
// @Param request body types.DataSource true "Updated configuration"
// @Success 200 {object} types.DataSource
// @Failure 400 {object} map[string]string
// @Router /datasource/{id} [put]
func (h *DataSourceHandler) UpdateDataSource(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
id := c.Param("id")
var req types.DataSource
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
return
}
existing, status, msg := h.getOwnedDataSource(ctx, tenantID, id)
if status != http.StatusOK {
c.JSON(status, gin.H{"error": msg})
return
}
req.ID = id
req.TenantID = existing.TenantID
req.KnowledgeBaseID = existing.KnowledgeBaseID
ds, err := h.service.UpdateDataSource(ctx, &req)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, dto.NewDataSourceResponse(ds))
}
// DeleteDataSource godoc
// @Summary Delete a data source
// @Description Delete a data source (soft delete)
// @Tags DataSource
// @Param id path string true "Data source ID"
// @Success 204
// @Failure 404 {object} map[string]string
// @Router /datasource/{id} [delete]
func (h *DataSourceHandler) DeleteDataSource(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
id := c.Param("id")
if _, status, msg := h.getOwnedDataSource(ctx, tenantID, id); status != http.StatusOK {
c.JSON(status, gin.H{"error": msg})
return
}
if err := h.service.DeleteDataSource(ctx, id); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete data source"})
return
}
c.Status(http.StatusNoContent)
}
// DataSourceStatusResponse is the status returned by connection and sync controls.
type DataSourceStatusResponse struct {
Status string `json:"status" extensions:"x-agent"`
}
// ValidateConnection godoc
// @Summary 测试数据源连接
// @Description Validate the connection to an external data source
// @Tags DataSource
// @Param id path string true "Data source ID" extensions(x-agent=data_source_id)
// @Success 200 {object} DataSourceStatusResponse
// @Failure 400 {object} map[string]string
// @x-agent {"id":"data_source.test","risk":"probe","role":"admin"}
// @x-agent-hint "Test a saved data source using its stored credentials; no credentials are accepted or returned."
// @Router /datasource/{id}/validate [post]
func (h *DataSourceHandler) ValidateConnection(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
id := c.Param("id")
if _, status, msg := h.getOwnedDataSource(ctx, tenantID, id); status != http.StatusOK {
c.JSON(status, gin.H{"error": msg})
return
}
if err := h.service.ValidateConnection(ctx, id); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "connected"})
}
// ValidateCredentials godoc
// @Summary Test connection with raw credentials (no persistence)
// @Description Validate connectivity to an external data source using type + credentials
//
// without creating or updating any database records.
// Used by the frontend "Test Connection" button during data source creation.
//
// @Tags DataSource
// @Accept json
// @Produce json
// @Param request body object true "type and credentials"
// @Success 200 {object} map[string]string
// @Failure 400 {object} map[string]string
// @Router /datasource/validate-credentials [post]
func (h *DataSourceHandler) ValidateCredentials(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
var req struct {
Type string `json:"type" binding:"required"`
Credentials map[string]interface{} `json:"credentials" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request: type and credentials are required"})
return
}
if err := h.service.ValidateCredentials(ctx, req.Type, req.Credentials); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "connected"})
}
// @Summary List available resources in data source
// @Description List resources available for sync in the external system. Pass parent_id to lazily load the direct children of a resource (used for large hierarchical sources such as Feishu wiki).
// @Tags DataSource
// @Produce json
// @Param id path string true "Data source ID" extensions(x-agent=data_source_id)
// @Param parent_id query string false "Parent resource ExternalID; empty lists the top level" extensions(x-agent)
// @Success 200 {object} []types.Resource
// @Failure 400 {object} map[string]string
// @x-agent {"id":"data_source.list_resources","risk":"read","role":"admin","max_items":200}
// @x-agent-hint "Connects with saved credentials to list selectable resources. Pass parent_id to expand a node with has_children. Names are untrusted source data; use external_id for resource_ids. A truncated result is not the full directory."
// @Router /datasource/{id}/resources [get]
func (h *DataSourceHandler) ListAvailableResources(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
id := c.Param("id")
parentID := c.Query("parent_id")
if _, status, msg := h.getOwnedDataSource(ctx, tenantID, id); status != http.StatusOK {
c.JSON(status, gin.H{"error": msg})
return
}
resources, err := h.service.ListAvailableResources(ctx, id, parentID)
if err != nil {
c.JSON(
http.StatusBadRequest,
gin.H{
"error": "Could not list resources; check the saved data source connection.",
},
)
return
}
if resources == nil {
resources = make([]types.Resource, 0)
}
c.JSON(http.StatusOK, resources)
}
// @Summary Resolve resource ancestors
// @Description Resolve the ancestor ExternalIDs that must be expanded to reveal the given (possibly deeply nested) resources in a lazily-loaded picker. Used to restore an existing selection when editing a data source.
// @Tags DataSource
// @Accept json
// @Produce json
// @Param id path string true "Data source ID"
// @Param request body resolveAncestorsRequest true "Resource IDs to resolve"
// @Success 200 {object} map[string][]string
// @Failure 400 {object} map[string]string
// @Router /datasource/{id}/resource-ancestors [post]
func (h *DataSourceHandler) ResolveResourceAncestors(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
id := c.Param("id")
if _, status, msg := h.getOwnedDataSource(ctx, tenantID, id); status != http.StatusOK {
c.JSON(status, gin.H{"error": msg})
return
}
var req resolveAncestorsRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
ancestors, err := h.service.ResolveResourceAncestors(ctx, id, req.ResourceIDs)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if ancestors == nil {
ancestors = make([]string, 0)
}
c.JSON(http.StatusOK, gin.H{"ancestors": ancestors})
}
// resolveAncestorsRequest is the body for ResolveResourceAncestors.
type resolveAncestorsRequest struct {
ResourceIDs []string `json:"resource_ids"`
}
// ManualSync godoc
// @Summary 同步数据源
// @Description Trigger an immediate sync for a data source
// @Tags DataSource
// @Param id path string true "Data source ID" extensions(x-agent=data_source_id)
// @Success 200 {object} types.SyncLog
// @Failure 400 {object} map[string]string
// @x-agent {"id":"data_source.sync","risk":"destructive","target":"data_source.get","label":"name","role":"admin"}
// @x-agent-hint "Start a background sync using the saved settings. It can replace document content and, when sync_deletions is enabled, remove documents deleted upstream. Always asks for confirmation. Follow with data_source.get_sync_log using sync_log_id."
// @Router /datasource/{id}/sync [post]
func (h *DataSourceHandler) ManualSync(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
id := c.Param("id")
if _, status, msg := h.getOwnedDataSource(ctx, tenantID, id); status != http.StatusOK {
c.JSON(status, gin.H{"error": msg})
return
}
syncLog, err := h.service.ManualSync(ctx, id)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, syncLog)
}
// PauseDataSource godoc
// @Summary 暂停数据源同步
// @Description Pause a data source's scheduled syncs
// @Tags DataSource
// @Param id path string true "Data source ID" extensions(x-agent=data_source_id)
// @Success 200 {object} DataSourceStatusResponse
// @Failure 400 {object} map[string]string
// @x-agent {"id":"data_source.pause","risk":"write","target":"data_source.get","label":"name","role":"admin"}
// @x-agent-hint "Pause scheduled syncs. Does not cancel a sync that is already running."
// @Router /datasource/{id}/pause [post]
func (h *DataSourceHandler) PauseDataSource(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
id := c.Param("id")
if _, status, msg := h.getOwnedDataSource(ctx, tenantID, id); status != http.StatusOK {
c.JSON(status, gin.H{"error": msg})
return
}
if err := h.service.PauseDataSource(ctx, id); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "paused"})
}
// ResumeDataSource godoc
// @Summary 恢复数据源同步
// @Description Resume a paused data source
// @Tags DataSource
// @Param id path string true "Data source ID" extensions(x-agent=data_source_id)
// @Success 200 {object} DataSourceStatusResponse
// @Failure 400 {object} map[string]string
// @x-agent {"id":"data_source.resume","risk":"write","target":"data_source.get","label":"name","role":"admin"}
// @x-agent-hint "Resume scheduled syncs using the saved schedule and deletion policy."
// @Router /datasource/{id}/resume [post]
func (h *DataSourceHandler) ResumeDataSource(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
id := c.Param("id")
if _, status, msg := h.getOwnedDataSource(ctx, tenantID, id); status != http.StatusOK {
c.JSON(status, gin.H{"error": msg})
return
}
if err := h.service.ResumeDataSource(ctx, id); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "active"})
}
// GetSyncLogs godoc
// @Summary 获取数据源同步记录
// @Description Retrieve sync history for a data source
// @Tags DataSource
// @Produce json
// @Param id path string true "Data source ID" extensions(x-agent=data_source_id)
// @Param limit query int false "Limit (default: 10)" minimum(1) maximum(100) extensions(x-agent,x-agent-maximum=50)
// @Param offset query int false "Offset (default: 0)" minimum(0) extensions(x-agent,x-agent-maximum=10000)
// @Success 200 {array} types.SyncLog
// @Failure 400 {object} map[string]string
// @x-agent {"id":"data_source.list_sync_logs","risk":"read"}
// @x-agent-hint "Read recent sync status and counts. Use limit and offset for older records. Raw upstream errors are omitted; detailed failures remain on the data source settings page."
// @Router /datasource/{id}/logs [get]
func (h *DataSourceHandler) GetSyncLogs(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
id := c.Param("id")
if _, status, msg := h.getOwnedDataSource(ctx, tenantID, id); status != http.StatusOK {
c.JSON(status, gin.H{"error": msg})
return
}
limit := 10
offset := 0
if l := c.Query("limit"); l != "" {
v, err := strconv.Atoi(l)
if err != nil || v <= 0 || v > maxListPageSize {
c.JSON(http.StatusBadRequest, gin.H{"error": "limit must be between 1 and " + strconv.Itoa(maxListPageSize)})
return
}
limit = v
}
if o := c.Query("offset"); o != "" {
if v, err := strconv.Atoi(o); err == nil && v >= 0 {
offset = v
}
}
logs, err := h.service.GetSyncLogs(ctx, id, limit, offset)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if logs == nil {
logs = make([]*types.SyncLog, 0)
}
c.JSON(http.StatusOK, logs)
}
// GetSyncLog godoc
// @Summary 获取数据源同步进度
// @Description Retrieve a specific sync log entry
// @Tags DataSource
// @Produce json
// @Param log_id path string true "Sync log ID" extensions(x-agent=sync_log_id)
// @Success 200 {object} types.SyncLog
// @Failure 404 {object} map[string]string
// @x-agent {"id":"data_source.get_sync_log","risk":"read"}
// @x-agent-hint "Read the current status and counts of a sync_log_id returned by data_source.sync or data_source.list_sync_logs. A started job is not a completed sync. Raw upstream errors are omitted; detailed failures remain on the data source settings page."
// @Router /datasource/logs/{log_id} [get]
func (h *DataSourceHandler) GetSyncLog(c *gin.Context) {
ctx := c.Request.Context()
tenantID := h.getTenantID(c)
if tenantID == 0 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
logID := c.Param("log_id")
log, err := h.service.GetSyncLog(ctx, logID)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "sync log not found"})
return
}
if _, status, msg := h.getOwnedDataSource(ctx, tenantID, log.DataSourceID); status != http.StatusOK {
c.JSON(status, gin.H{"error": msg})
return
}
c.JSON(http.StatusOK, log)
}
// GetAvailableConnectors godoc
// @Summary Get available connectors
// @Description Get list of available data source connectors
// @Tags DataSource
// @Produce json
// @Success 200 {object} []datasource.ConnectorMetadata
// @Router /datasource/types [get]
func (h *DataSourceHandler) GetAvailableConnectors(c *gin.Context) {
connectors := datasource.ListAvailableConnectors()
c.JSON(http.StatusOK, connectors)
}
+115
View File
@@ -0,0 +1,115 @@
package handler
import (
"net/http"
"academy/internal/errors"
"academy/internal/handler/dto"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
secutils "academy/internal/utils"
"github.com/gin-gonic/gin"
)
// DataSourceCredentialsHandler handles credentials for data source
// connectors via the dedicated /credentials subresource.
//
// Unlike the other three resources (MCP / Model / WebSearch), DataSource
// credentials are a per-connector atomic map — there's no individual-field
// PUT or DELETE because half-configured connector auth doesn't work. So we
// expose a single logical field "credentials": GET returns whether anything
// is stored, PUT replaces the whole map, DELETE wipes it.
type DataSourceCredentialsHandler struct {
service interfaces.DataSourceService
kbService interfaces.KnowledgeBaseService
}
func NewDataSourceCredentialsHandler(
service interfaces.DataSourceService,
kbService interfaces.KnowledgeBaseService,
) *DataSourceCredentialsHandler {
return &DataSourceCredentialsHandler{service: service, kbService: kbService}
}
// ownDataSource is the same tenant-isolation check used in datasource.go,
// duplicated here to avoid coupling the two handlers via internal helpers.
func (h *DataSourceCredentialsHandler) ownDataSource(c *gin.Context) (*types.DataSource, bool) {
ctx := c.Request.Context()
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if tenantID == 0 {
c.Error(errors.NewBadRequestError("Workspace ID cannot be empty"))
return nil, false
}
id := c.Param("id")
ds, err := h.service.GetDataSource(ctx, id)
if err != nil || ds == nil {
c.Error(errors.NewNotFoundError("data source not found"))
return nil, false
}
kb, err := h.kbService.GetKnowledgeBaseByID(ctx, ds.KnowledgeBaseID)
if err != nil || kb == nil || kb.TenantID != tenantID {
c.Error(errors.NewNotFoundError("data source not found"))
return nil, false
}
return ds, true
}
type dataSourceCredentialsPutRequest struct {
Credentials map[string]interface{} `json:"credentials" binding:"required"`
}
func (h *DataSourceCredentialsHandler) Put(c *gin.Context) {
ds, ok := h.ownDataSource(c)
if !ok {
return
}
var req dataSourceCredentialsPutRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.Error(errors.NewBadRequestError(err.Error()))
return
}
if len(req.Credentials) == 0 {
c.Error(errors.NewBadRequestError(
"credentials map must be non-empty; to remove credentials use DELETE /credentials/credentials"))
return
}
updated, err := h.service.UpdateDataSourceCredentials(c.Request.Context(), ds.ID, req.Credentials)
if err != nil {
logger.ErrorWithFields(c.Request.Context(), err, map[string]interface{}{
"data_source_id": secutils.SanitizeForLog(ds.ID),
})
c.Error(errors.NewBadRequestError("failed to update credentials: " + err.Error()))
return
}
configured := false
if parsed, err := updated.ParseConfig(); err == nil && parsed != nil {
configured = parsed.HasConfiguredCredentials(updated.Type)
}
resp := dto.CredentialsResponse{
Fields: map[string]dto.CredentialFieldMetadata{
"credentials": {Configured: configured},
},
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": resp})
}
func (h *DataSourceCredentialsHandler) DeleteField(c *gin.Context) {
ds, ok := h.ownDataSource(c)
if !ok {
return
}
field := c.Param("field")
if field != "credentials" {
c.Error(errors.NewBadRequestError("unknown credential field: " + secutils.SanitizeForLog(field)))
return
}
if err := h.service.ClearDataSourceCredentials(c.Request.Context(), ds.ID); err != nil {
logger.ErrorWithFields(c.Request.Context(), err, map[string]interface{}{
"data_source_id": secutils.SanitizeForLog(ds.ID),
})
c.Error(errors.NewInternalServerError("failed to clear credentials: " + err.Error()))
return
}
c.Status(http.StatusNoContent)
}
@@ -0,0 +1,80 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"academy/internal/application/repository"
"academy/internal/application/service"
"academy/internal/datasource"
"academy/internal/types"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func TestDataSourceScheduleAPIRejectsInvalidCron(t *testing.T) {
for _, operation := range []string{"create", "update", "resume"} {
t.Run(operation, func(t *testing.T) {
db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "schedule.db")), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&types.DataSource{}))
repo := repository.NewDataSourceRepository(db)
scheduler := datasource.NewScheduler(repo, nil, nil)
kbSvc := &stubKBServiceForDS{getByID: func(context.Context, string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "kb-schedule", TenantID: 1}, nil
}}
svc := service.NewDataSourceService(repo, nil, nil, kbSvc, nil, nil, scheduler, nil, nil, nil)
ds := &types.DataSource{
ID: "ds-schedule", KnowledgeBaseID: "kb-schedule", TenantID: 1,
Type: types.ConnectorTypeRSS, Status: types.DataSourceStatusActive,
SyncSchedule: "0 0 * * * *",
}
if operation == "resume" {
ds.Status = types.DataSourceStatusPaused
ds.SyncSchedule = "invalid"
}
if operation != "create" {
require.NoError(t, repo.Create(context.Background(), ds))
require.NoError(t, scheduler.AddOrUpdate(ds))
}
entries := scheduler.EntryCount()
h := NewDataSourceHandler(svc, kbSvc)
router := newDataSourceTestRouter(h)
router.POST("/datasource", h.CreateDataSource)
router.PUT("/datasource/:id", h.UpdateDataSource)
router.POST("/datasource/:id/resume", h.ResumeDataSource)
body := *ds
body.SyncSchedule = "invalid"
payload, err := json.Marshal(body)
require.NoError(t, err)
method, url := http.MethodPost, "/datasource"
switch operation {
case "update":
method, url = http.MethodPut, "/datasource/"+ds.ID
case "resume":
url = "/datasource/" + ds.ID + "/resume"
}
req := withDSCtx(httptest.NewRequest(method, url, bytes.NewReader(payload)), 1)
req.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, req)
require.Equal(t, http.StatusBadRequest, response.Code, response.Body.String())
require.Contains(t, response.Body.String(), "invalid cron expression")
require.Equal(t, entries, scheduler.EntryCount())
saved, err := svc.GetDataSource(context.Background(), ds.ID)
if operation == "create" {
require.Error(t, err)
} else {
require.NoError(t, err)
require.Equal(t, ds.Status, saved.Status)
require.Equal(t, ds.SyncSchedule, saved.SyncSchedule)
}
})
}
}
+256
View File
@@ -0,0 +1,256 @@
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
type stubDataSourceService struct {
interfaces.DataSourceService
getSyncLogs func(ctx context.Context, dsID string, limit int, offset int) ([]*types.SyncLog, error)
getDataSource func(ctx context.Context, id string) (*types.DataSource, error)
}
func (s *stubDataSourceService) GetSyncLogs(ctx context.Context, dsID string, limit int, offset int) ([]*types.SyncLog, error) {
if s.getSyncLogs != nil {
return s.getSyncLogs(ctx, dsID, limit, offset)
}
return nil, nil
}
func (s *stubDataSourceService) GetDataSource(ctx context.Context, id string) (*types.DataSource, error) {
if s.getDataSource != nil {
return s.getDataSource(ctx, id)
}
return nil, nil
}
type stubKBServiceForDS struct {
interfaces.KnowledgeBaseService
getByID func(ctx context.Context, id string) (*types.KnowledgeBase, error)
}
func (s *stubKBServiceForDS) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) {
if s.getByID != nil {
return s.getByID(ctx, id)
}
return nil, nil
}
func newDataSourceTestRouter(h *DataSourceHandler) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(errorCapture())
r.Use(func(c *gin.Context) {
if tenantID, ok := c.Request.Context().Value(types.TenantIDContextKey).(uint64); ok {
c.Set(types.TenantIDContextKey.String(), tenantID)
}
c.Next()
})
r.GET("/datasource/:id/logs", h.GetSyncLogs)
return r
}
func withDSCtx(req *http.Request, tenantID uint64) *http.Request {
ctx := req.Context()
ctx = context.WithValue(ctx, types.TenantIDContextKey, tenantID)
return req.WithContext(ctx)
}
func TestDataSource_GetSyncLogs_ValidLimitWithinBounds(t *testing.T) {
var capturedLimit, capturedOffset int
dsSvc := &stubDataSourceService{
getDataSource: func(_ context.Context, id string) (*types.DataSource, error) {
return &types.DataSource{ID: id, KnowledgeBaseID: "kb1"}, nil
},
getSyncLogs: func(_ context.Context, _ string, limit int, offset int) ([]*types.SyncLog, error) {
capturedLimit = limit
capturedOffset = offset
return []*types.SyncLog{
{ID: "log1", DataSourceID: "ds1"},
}, nil
},
}
kbSvc := &stubKBServiceForDS{
getByID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "kb1", TenantID: 1}, nil
},
}
h := NewDataSourceHandler(dsSvc, kbSvc)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/datasource/ds1/logs?limit=50&offset=25", nil)
req = withDSCtx(req, 1)
newDataSourceTestRouter(h).ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
}
if capturedLimit != 50 {
t.Fatalf("expected limit=50, got %d", capturedLimit)
}
if capturedOffset != 25 {
t.Fatalf("expected offset=25, got %d", capturedOffset)
}
}
func TestDataSource_GetSyncLogs_LimitExceedingMaximum(t *testing.T) {
dsSvc := &stubDataSourceService{
getDataSource: func(_ context.Context, id string) (*types.DataSource, error) {
return &types.DataSource{ID: id, KnowledgeBaseID: "kb1"}, nil
},
getSyncLogs: func(_ context.Context, _ string, _ int, _ int) ([]*types.SyncLog, error) {
t.Fatalf("service must not be called when limit exceeds maximum")
return nil, nil
},
}
kbSvc := &stubKBServiceForDS{
getByID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "kb1", TenantID: 1}, nil
},
}
h := NewDataSourceHandler(dsSvc, kbSvc)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/datasource/ds1/logs?limit=999", nil)
req = withDSCtx(req, 1)
newDataSourceTestRouter(h).ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400 for limit > 100, got %d body=%s", w.Code, w.Body.String())
}
var resp map[string]interface{}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
errMsg, ok := resp["error"].(string)
if !ok || errMsg == "" {
t.Fatalf("expected error message in response")
}
if errMsg != "limit must be between 1 and 100" {
t.Fatalf("expected specific error message, got %q", errMsg)
}
}
func TestDataSource_GetSyncLogs_MissingLimitDefaultsCorrectly(t *testing.T) {
var capturedLimit, capturedOffset int
dsSvc := &stubDataSourceService{
getDataSource: func(_ context.Context, id string) (*types.DataSource, error) {
return &types.DataSource{ID: id, KnowledgeBaseID: "kb1"}, nil
},
getSyncLogs: func(_ context.Context, _ string, limit int, offset int) ([]*types.SyncLog, error) {
capturedLimit = limit
capturedOffset = offset
return []*types.SyncLog{}, nil
},
}
kbSvc := &stubKBServiceForDS{
getByID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "kb1", TenantID: 1}, nil
},
}
h := NewDataSourceHandler(dsSvc, kbSvc)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/datasource/ds1/logs", nil)
req = withDSCtx(req, 1)
newDataSourceTestRouter(h).ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
}
if capturedLimit != 10 {
t.Fatalf("expected default limit=10, got %d", capturedLimit)
}
if capturedOffset != 0 {
t.Fatalf("expected default offset=0 (page 1), got %d", capturedOffset)
}
}
func TestDataSource_GetSyncLogs_NonNumericLimitRejected(t *testing.T) {
dsSvc := &stubDataSourceService{
getDataSource: func(_ context.Context, id string) (*types.DataSource, error) {
return &types.DataSource{ID: id, KnowledgeBaseID: "kb1"}, nil
},
getSyncLogs: func(_ context.Context, _ string, _ int, _ int) ([]*types.SyncLog, error) {
t.Fatalf("service must not be called with non-numeric limit")
return nil, nil
},
}
kbSvc := &stubKBServiceForDS{
getByID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "kb1", TenantID: 1}, nil
},
}
h := NewDataSourceHandler(dsSvc, kbSvc)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/datasource/ds1/logs?limit=abc", nil)
req = withDSCtx(req, 1)
newDataSourceTestRouter(h).ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400 for non-numeric limit, got %d body=%s", w.Code, w.Body.String())
}
}
func TestDataSource_GetSyncLogs_ZeroLimitRejected(t *testing.T) {
dsSvc := &stubDataSourceService{
getDataSource: func(_ context.Context, id string) (*types.DataSource, error) {
return &types.DataSource{ID: id, KnowledgeBaseID: "kb1"}, nil
},
getSyncLogs: func(_ context.Context, _ string, _ int, _ int) ([]*types.SyncLog, error) {
t.Fatalf("service must not be called with limit=0")
return nil, nil
},
}
kbSvc := &stubKBServiceForDS{
getByID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "kb1", TenantID: 1}, nil
},
}
h := NewDataSourceHandler(dsSvc, kbSvc)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/datasource/ds1/logs?limit=0", nil)
req = withDSCtx(req, 1)
newDataSourceTestRouter(h).ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400 for limit=0, got %d body=%s", w.Code, w.Body.String())
}
}
func TestDataSource_GetSyncLogs_NegativeLimitRejected(t *testing.T) {
dsSvc := &stubDataSourceService{
getDataSource: func(_ context.Context, id string) (*types.DataSource, error) {
return &types.DataSource{ID: id, KnowledgeBaseID: "kb1"}, nil
},
getSyncLogs: func(_ context.Context, _ string, _ int, _ int) ([]*types.SyncLog, error) {
t.Fatalf("service must not be called with negative limit")
return nil, nil
},
}
kbSvc := &stubKBServiceForDS{
getByID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "kb1", TenantID: 1}, nil
},
}
h := NewDataSourceHandler(dsSvc, kbSvc)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/datasource/ds1/logs?limit=-5", nil)
req = withDSCtx(req, 1)
newDataSourceTestRouter(h).ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400 for negative limit, got %d body=%s", w.Code, w.Body.String())
}
}
+178
View File
@@ -0,0 +1,178 @@
package handler
import (
"net/http"
"strings"
"academy/internal/sandbox"
"github.com/gin-gonic/gin"
)
// DeploymentCapabilityKeys is the canonical capability key list shared with
// frontend/src/config/deploymentCapabilities.ts — keep both in sync.
var DeploymentCapabilityKeys = []string{
"organizations",
"agents",
"integrations.im",
"integrations.embed",
"integrations.api",
"integrations.mcpserver",
"settings.mcp",
"settings.websearch",
"settings.vectorstore",
"settings.storage",
"settings.sandbox",
"settings.sandbox.docker",
"settings.sandbox.host",
"settings.sandbox.remote",
"settings.sandbox.user_allocation",
}
// DeploymentCapability describes whether a deployment exposes a feature route.
type DeploymentCapability struct {
Supported bool `json:"supported"`
Reason string `json:"reason,omitempty"`
}
// DeploymentCapabilitiesData is returned by GET /system/capabilities.
type DeploymentCapabilitiesData struct {
Edition string `json:"edition"`
Capabilities map[string]DeploymentCapability `json:"capabilities"`
}
// DeploymentFeatureAvailability mirrors injected backend handlers/services.
type DeploymentFeatureAvailability struct {
Organizations bool
Agents bool
IM bool
Embed bool
API bool
MCPServer bool
MCP bool
WebSearch bool
VectorStore bool
Storage bool
Sandbox bool
SandboxDocker bool
SandboxHost bool
SandboxRemote bool
SandboxUserAllocation bool
}
func supportedDeploymentCapability(supported bool) DeploymentCapability {
if supported {
return DeploymentCapability{Supported: true}
}
return DeploymentCapability{Supported: false, Reason: "route_not_registered"}
}
// BuildDeploymentCapabilities derives the deployment capability snapshot.
func BuildDeploymentCapabilities(
edition string,
available DeploymentFeatureAvailability,
) DeploymentCapabilitiesData {
isLite := strings.EqualFold(strings.TrimSpace(edition), "lite")
organizations := supportedDeploymentCapability(available.Organizations && !isLite)
if isLite {
organizations.Reason = "not_supported_in_lite"
}
sandboxDocker := DeploymentCapability{
Supported: available.Sandbox && available.SandboxDocker,
}
if available.Sandbox && !available.SandboxDocker {
sandboxDocker.Reason = "docker_backend_disabled"
} else if !available.Sandbox {
sandboxDocker.Reason = "route_not_registered"
}
sandboxHost := DeploymentCapability{
Supported: available.Sandbox && available.SandboxHost,
}
if available.Sandbox && !available.SandboxHost {
// The platform has no OS-enforced backend (Windows/Linux today).
sandboxHost.Reason = "platform_unsupported"
} else if !available.Sandbox {
sandboxHost.Reason = "route_not_registered"
}
sandboxRemote := DeploymentCapability{Supported: available.Sandbox && available.SandboxRemote}
if available.Sandbox && !available.SandboxRemote {
sandboxRemote.Reason = "not_supported_in_lite"
} else if !available.Sandbox {
sandboxRemote.Reason = "route_not_registered"
}
sandboxUserAllocation := DeploymentCapability{
Supported: sandboxRemote.Supported && available.SandboxUserAllocation,
}
if !sandboxUserAllocation.Supported {
sandboxUserAllocation.Reason = "deployment_gate_off"
if !sandboxRemote.Supported {
sandboxUserAllocation.Reason = sandboxRemote.Reason
}
}
return DeploymentCapabilitiesData{
Edition: edition,
Capabilities: map[string]DeploymentCapability{
"organizations": organizations,
"agents": supportedDeploymentCapability(available.Agents),
"integrations.im": supportedDeploymentCapability(available.IM),
"integrations.embed": supportedDeploymentCapability(available.Embed),
"integrations.api": supportedDeploymentCapability(available.API),
"integrations.mcpserver": supportedDeploymentCapability(available.MCPServer),
"settings.mcp": supportedDeploymentCapability(available.MCP),
"settings.websearch": supportedDeploymentCapability(available.WebSearch),
"settings.vectorstore": supportedDeploymentCapability(available.VectorStore),
"settings.storage": supportedDeploymentCapability(available.Storage),
"settings.sandbox": supportedDeploymentCapability(available.Sandbox),
"settings.sandbox.docker": sandboxDocker,
"settings.sandbox.host": sandboxHost,
"settings.sandbox.remote": sandboxRemote,
"settings.sandbox.user_allocation": sandboxUserAllocation,
},
}
}
// BindDeploymentCapabilities stores the startup snapshot used by GetDeploymentCapabilities.
func (h *SystemHandler) BindDeploymentCapabilities(data DeploymentCapabilitiesData) {
h.deploymentCapabilities = data
}
// GetDeploymentCapabilities godoc
// @Summary 获取部署能力清单
// @Description 返回当前部署版本及实际注册的后端路由所对应的功能能力;仅 supported=false 表示入口应隐藏
// @Tags 系统
// @Produce json
// @Success 200 {object} handler.GetDeploymentCapabilitiesResponse
// @Router /system/capabilities [get]
func (h *SystemHandler) GetDeploymentCapabilities(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "success",
"data": overlayLiveDockerSandboxCapability(h.deploymentCapabilities),
})
}
// overlayLiveDockerSandboxCapability replaces the startup snapshot's Docker
// flag with the live 3-tier value so a System Settings toggle is visible
// without restarting the process.
func overlayLiveDockerSandboxCapability(data DeploymentCapabilitiesData) DeploymentCapabilitiesData {
caps := make(map[string]DeploymentCapability, len(data.Capabilities))
for key, capability := range data.Capabilities {
caps[key] = capability
}
sandboxCap := caps["settings.sandbox"]
docker := DeploymentCapability{
Supported: sandboxCap.Supported && sandbox.DockerBackendEnabled(),
}
if sandboxCap.Supported && !docker.Supported {
docker.Reason = "docker_backend_disabled"
} else if !sandboxCap.Supported {
docker.Reason = "route_not_registered"
}
caps["settings.sandbox.docker"] = docker
data.Capabilities = caps
return data
}
@@ -0,0 +1,141 @@
package handler
import (
"os"
"path/filepath"
"regexp"
"runtime"
"slices"
"strings"
"testing"
"academy/internal/sandbox"
"github.com/stretchr/testify/require"
)
func TestDeploymentCapabilityKeysMatchFrontend(t *testing.T) {
frontendKeys, err := readFrontendDeploymentCapabilityKeys()
if err != nil {
t.Fatalf("read frontend capability keys: %v", err)
}
if !slices.Equal(DeploymentCapabilityKeys, frontendKeys) {
t.Fatalf("backend keys = %#v, frontend keys = %#v", DeploymentCapabilityKeys, frontendKeys)
}
}
func TestBuildDeploymentCapabilitiesIncludesAllKeys(t *testing.T) {
result := BuildDeploymentCapabilities("standard", DeploymentFeatureAvailability{
Organizations: true,
Agents: true,
IM: true,
Embed: true,
API: true,
MCP: true,
WebSearch: true,
VectorStore: true,
Storage: true,
Sandbox: true,
})
for _, key := range DeploymentCapabilityKeys {
if _, ok := result.Capabilities[key]; !ok {
t.Fatalf("missing capability key %q", key)
}
}
}
func TestOverlayLiveDockerSandboxCapabilityIgnoresStartupSnapshot(t *testing.T) {
sandbox.ClearDockerBackendEnabledOverride()
t.Cleanup(sandbox.ClearDockerBackendEnabledOverride)
t.Setenv(sandbox.DockerBackendEnabledEnv, "")
snapshot := BuildDeploymentCapabilities("standard", DeploymentFeatureAvailability{
Sandbox: true,
SandboxDocker: true,
})
live := overlayLiveDockerSandboxCapability(snapshot)
docker := live.Capabilities["settings.sandbox.docker"]
if docker.Supported {
t.Fatal("live env off must hide docker even if the startup snapshot was on")
}
if docker.Reason != "docker_backend_disabled" {
t.Fatalf("reason = %q, want docker_backend_disabled", docker.Reason)
}
t.Setenv(sandbox.DockerBackendEnabledEnv, "true")
enabled := overlayLiveDockerSandboxCapability(snapshot)
if !enabled.Capabilities["settings.sandbox.docker"].Supported {
t.Fatal("live env true must expose docker")
}
}
func readFrontendDeploymentCapabilityKeys() ([]string, error) {
_, thisFile, _, ok := runtime.Caller(0)
if !ok {
return nil, os.ErrInvalid
}
repoRoot := filepath.Clean(filepath.Join(filepath.Dir(thisFile), "..", ".."))
frontendPath := filepath.Join(repoRoot, "frontend", "src", "config", "deploymentCapabilities.ts")
content, err := os.ReadFile(frontendPath)
if err != nil {
return nil, err
}
re := regexp.MustCompile(`(?s)export const DEPLOYMENT_CAPABILITY_KEYS = \[(.*?)\]`)
match := re.FindSubmatch(content)
if len(match) < 2 {
return nil, os.ErrInvalid
}
var keys []string
for _, line := range strings.Split(string(match[1]), "\n") {
line = strings.TrimSpace(strings.TrimRight(line, ","))
if line == "" {
continue
}
line = strings.Trim(line, `'`)
keys = append(keys, line)
}
return keys, nil
}
func TestHostSandboxCapabilityFollowsAvailability(t *testing.T) {
data := BuildDeploymentCapabilities("lite", DeploymentFeatureAvailability{
Sandbox: true,
SandboxHost: true,
})
require.True(t, data.Capabilities["settings.sandbox.host"].Supported)
off := BuildDeploymentCapabilities("lite", DeploymentFeatureAvailability{
Sandbox: true,
})
require.False(t, off.Capabilities["settings.sandbox.host"].Supported)
require.Equal(t, "platform_unsupported",
off.Capabilities["settings.sandbox.host"].Reason)
}
func TestRemoteSandboxCapabilityIsOffOnLiteDesktop(t *testing.T) {
on := BuildDeploymentCapabilities("standard", DeploymentFeatureAvailability{Sandbox: true, SandboxRemote: true})
require.True(t, on.Capabilities["settings.sandbox.remote"].Supported)
off := BuildDeploymentCapabilities("lite", DeploymentFeatureAvailability{
Sandbox: true, SandboxRemote: false, SandboxHost: true,
})
require.False(t, off.Capabilities["settings.sandbox.remote"].Supported)
require.Equal(t, "not_supported_in_lite", off.Capabilities["settings.sandbox.remote"].Reason)
none := BuildDeploymentCapabilities("standard", DeploymentFeatureAvailability{})
require.Equal(t, "route_not_registered", none.Capabilities["settings.sandbox.remote"].Reason)
}
func TestBuildDeploymentCapabilitiesUserAllocation(t *testing.T) {
off := BuildDeploymentCapabilities("standard", DeploymentFeatureAvailability{Sandbox: true, SandboxRemote: true})
require.False(t, off.Capabilities["settings.sandbox.user_allocation"].Supported)
require.Equal(t, "deployment_gate_off", off.Capabilities["settings.sandbox.user_allocation"].Reason)
on := BuildDeploymentCapabilities("standard", DeploymentFeatureAvailability{
Sandbox: true, SandboxRemote: true, SandboxUserAllocation: true,
})
require.True(t, on.Capabilities["settings.sandbox.user_allocation"].Supported)
}
@@ -0,0 +1,99 @@
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/application/access"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/hibiken/asynq"
"github.com/stretchr/testify/require"
)
type documentWriteHandlerKnowledge struct {
interfaces.KnowledgeService
called bool
}
func (*documentWriteHandlerKnowledge) GetKnowledgeByIDOnly(context.Context, string) (*types.Knowledge, error) {
return &types.Knowledge{ID: "doc", TenantID: 7, KnowledgeBaseID: "kb"}, nil
}
func (s *documentWriteHandlerKnowledge) UpdateKnowledgeTagBatch(
ctx context.Context,
kb string,
_ map[string][]string,
) error {
if err := access.RequireKBWrite(ctx, &types.KnowledgeBase{ID: kb, TenantID: 7}); err != nil {
return err
}
s.called = true
return nil
}
type documentDeleteEnqueuer struct{ task *asynq.Task }
func (q *documentDeleteEnqueuer) Enqueue(task *asynq.Task, _ ...asynq.Option) (*asynq.TaskInfo, error) {
q.task = task
return &asynq.TaskInfo{ID: "delete-task"}, nil
}
func documentHandlerRouter() *gin.Engine {
r := gin.New()
r.Use(middleware.ErrorHandler(), func(c *gin.Context) {
ctx := types.WithCaller(
c.Request.Context(),
types.Caller{TenantID: 7, UserID: "user", Role: types.TenantRoleAdmin},
)
ctx = types.WithExecutionTenant(ctx, 7)
c.Set(types.TenantIDContextKey.String(), uint64(7))
c.Request = c.Request.WithContext(ctx)
c.Next()
})
return r
}
func TestDocumentTagBodyRouteIssuesWriteGrant(t *testing.T) {
for _, body := range []string{`{"kb_id":"kb","updates":{"doc":["tag"]}}`, `{"updates":{"doc":["tag"]}}`} {
t.Run(body, func(t *testing.T) {
kg := &documentWriteHandlerKnowledge{}
h := &KnowledgeHandler{
kgService: kg,
kbService: &stubKBService{get: func(context.Context, string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "kb", TenantID: 7}, nil
}},
}
r := documentHandlerRouter()
r.PUT("/tags", h.UpdateKnowledgeTagBatch)
req := httptest.NewRequest(http.MethodPut, "/tags", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, 200, w.Code, w.Body.String())
require.True(t, kg.called)
})
}
}
func TestSingleDocumentDeletePersistsAuthorizedKBInTask(t *testing.T) {
q := &documentDeleteEnqueuer{}
h := &KnowledgeHandler{kgService: &documentWriteHandlerKnowledge{}, asynqClient: q}
r := documentHandlerRouter()
r.DELETE("/:id", h.DeleteKnowledge)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodDelete, "/doc", nil))
require.Equal(t, 200, w.Code, w.Body.String())
require.NotNil(t, q.task)
var payload types.KnowledgeListDeletePayload
require.NoError(t, json.Unmarshal(q.task.Payload(), &payload))
require.Equal(t, uint64(7), payload.TenantID)
require.Equal(t, "kb", payload.KnowledgeBaseID)
require.Equal(t, []string{"doc"}, payload.KnowledgeIDs)
}
+76
View File
@@ -0,0 +1,76 @@
package dto
import "academy/internal/types"
// AuthLoginResponse is the HTTP-safe login / switch-tenant response shape.
type AuthLoginResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
User *types.User `json:"user,omitempty"`
ActiveTenant *TenantResponse `json:"active_tenant,omitempty"`
Memberships []types.Membership `json:"memberships"`
Token string `json:"token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
}
// AuthOIDCCallbackResponse is the HTTP-safe OIDC callback payload shape.
type AuthOIDCCallbackResponse struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
User *types.User `json:"user,omitempty"`
Tenant *TenantResponse `json:"tenant,omitempty"`
Memberships []types.Membership `json:"memberships"`
Token string `json:"token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
IsNewUser bool `json:"is_new_user,omitempty"`
}
// NewAuthLoginResponse converts a service-layer login response for HTTP output.
func NewAuthLoginResponse(resp *types.LoginResponse) *AuthLoginResponse {
if resp == nil {
return nil
}
var role types.TenantRole
if resp.ActiveTenant != nil {
role = membershipRoleForTenant(resp.Memberships, resp.ActiveTenant.ID)
}
return &AuthLoginResponse{
Success: resp.Success,
Message: resp.Message,
User: resp.User,
ActiveTenant: NewTenantResponseWithRole(resp.ActiveTenant, role),
Memberships: resp.Memberships,
Token: resp.Token,
RefreshToken: resp.RefreshToken,
}
}
// NewAuthOIDCCallbackResponse converts an OIDC callback response for HTTP output.
func NewAuthOIDCCallbackResponse(resp *types.OIDCCallbackResponse) *AuthOIDCCallbackResponse {
if resp == nil {
return nil
}
var role types.TenantRole
if resp.Tenant != nil {
role = membershipRoleForTenant(resp.Memberships, resp.Tenant.ID)
}
return &AuthOIDCCallbackResponse{
Success: resp.Success,
Message: resp.Message,
User: resp.User,
Tenant: NewTenantResponseWithRole(resp.Tenant, role),
Memberships: resp.Memberships,
Token: resp.Token,
RefreshToken: resp.RefreshToken,
IsNewUser: resp.IsNewUser,
}
}
func membershipRoleForTenant(memberships []types.Membership, tenantID uint64) types.TenantRole {
for _, m := range memberships {
if m.TenantID == tenantID && m.Role.IsValid() {
return m.Role
}
}
return ""
}
+60
View File
@@ -0,0 +1,60 @@
package dto
import (
"encoding/json"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAuthLoginResponse_ViewerOmitsActiveTenantSecrets(t *testing.T) {
tenant := sampleSecretTenant()
resp := NewAuthLoginResponse(&types.LoginResponse{
Success: true,
ActiveTenant: tenant,
Memberships: []types.Membership{{
TenantID: tenant.ID,
Role: types.TenantRoleViewer,
}},
})
body, err := json.Marshal(resp)
require.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "tenant-api-key-123")
assert.NotContains(t, s, "parser-secret-123")
}
func TestAuthLoginResponse_OwnerOmitsLegacyTenantAPIKey(t *testing.T) {
tenant := sampleSecretTenant()
resp := NewAuthLoginResponse(&types.LoginResponse{
Success: true,
ActiveTenant: tenant,
Memberships: []types.Membership{{
TenantID: tenant.ID,
Role: types.TenantRoleOwner,
}},
})
body, err := json.Marshal(resp)
require.NoError(t, err)
s := string(body)
assert.NotContains(t, s, `"api_key"`)
assert.NotContains(t, s, "legacy-search-secret-999")
assert.Contains(t, s, "web_search_config")
}
func TestAuthOIDCCallbackResponse_ViewerOmitsTenantSecrets(t *testing.T) {
tenant := sampleSecretTenant()
resp := NewAuthOIDCCallbackResponse(&types.OIDCCallbackResponse{
Success: true,
Tenant: tenant,
Memberships: []types.Membership{{
TenantID: tenant.ID,
Role: types.TenantRoleViewer,
}},
})
body, err := json.Marshal(resp)
require.NoError(t, err)
assert.NotContains(t, string(body), "tenant-api-key-123")
}
+140
View File
@@ -0,0 +1,140 @@
package dto
import (
"encoding/json"
"strings"
"time"
"academy/internal/types"
)
// DataSourceResponse mirrors types.DataSource for response bodies, with the
// connector Credentials map stripped from the Config jsonb. Credential
// presence is exposed via the dedicated /credentials subresource.
//
// Unlike MCP / Model / WebSearch (which have a flat set of named credential
// fields), DataSource credentials are a per-connector atomic map — an OAuth
// token pair, a Confluence email+token bundle, etc. Splitting them at the
// field level would leave half-configured states that can't actually
// authenticate. The subresource therefore exposes only one logical field,
// "credentials", with PUT replacing the whole map and DELETE wiping it.
type DataSourceResponse struct {
ID string `json:"id" extensions:"x-agent=data_source_id"`
TenantID uint64 `json:"tenant_id"`
KnowledgeBaseID string `json:"knowledge_base_id" extensions:"x-agent"`
Name string `json:"name" extensions:"x-agent"`
Type string `json:"type" extensions:"x-agent"`
Config *DataSourceConfigDTO `json:"config,omitempty" extensions:"x-agent"`
SyncSchedule string `json:"sync_schedule" extensions:"x-agent"`
SyncMode string `json:"sync_mode" extensions:"x-agent"`
Status string `json:"status" extensions:"x-agent"`
ConflictStrategy string `json:"conflict_strategy" extensions:"x-agent"`
SyncDeletions bool `json:"sync_deletions" extensions:"x-agent"`
LastSyncAt *time.Time `json:"last_sync_at" extensions:"x-agent"`
LastSyncCursor json.RawMessage `json:"last_sync_cursor,omitempty"`
LastSyncResult json.RawMessage `json:"last_sync_result,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
SyncLogRetentionDays int `json:"sync_log_retention_days"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
TotalItemsSynced int64 `json:"total_items_synced" extensions:"x-agent"`
LatestSyncLog *types.SyncLog `json:"latest_sync_log,omitempty"`
// Single logical credential field — DataSource credentials are a
// per-connector atomic map, so "configured?" applies to the whole set.
Credentials map[string]CredentialFieldMetadata `json:"credentials,omitempty"`
}
// DataSourceConfigDTO is types.DataSourceConfig with the Credentials map
// removed by construction. Type, ResourceIDs and Settings remain visible.
type DataSourceConfigDTO struct {
Type string `json:"type"`
ResourceIDs []string `json:"resource_ids,omitempty" extensions:"x-agent"`
Settings map[string]interface{} `json:"settings,omitempty"`
}
// NewDataSourceResponse converts a stored entity into its response shape.
// Returns nil for nil input.
func NewDataSourceResponse(ds *types.DataSource) *DataSourceResponse {
if ds == nil {
return nil
}
var cfgDTO *DataSourceConfigDTO
configured := false
if parsed, err := ds.ParseConfig(); err == nil && parsed != nil {
cfgDTO = &DataSourceConfigDTO{
Type: parsed.Type,
ResourceIDs: parsed.ResourceIDs,
Settings: parsed.Settings,
}
enrichRSSFeedURLsInSettings(ds.Type, parsed, cfgDTO)
configured = parsed.HasConfiguredCredentials(ds.Type)
}
return &DataSourceResponse{
ID: ds.ID,
TenantID: ds.TenantID,
KnowledgeBaseID: ds.KnowledgeBaseID,
Name: ds.Name,
Type: ds.Type,
Config: cfgDTO,
SyncSchedule: ds.SyncSchedule,
SyncMode: ds.SyncMode,
Status: ds.Status,
ConflictStrategy: ds.ConflictStrategy,
SyncDeletions: ds.SyncDeletions,
LastSyncAt: ds.LastSyncAt,
LastSyncCursor: json.RawMessage(ds.LastSyncCursor),
LastSyncResult: json.RawMessage(ds.LastSyncResult),
ErrorMessage: ds.ErrorMessage,
SyncLogRetentionDays: ds.SyncLogRetentionDays,
CreatedAt: ds.CreatedAt,
UpdatedAt: ds.UpdatedAt,
TotalItemsSynced: ds.TotalItemsSynced,
LatestSyncLog: ds.LatestSyncLog,
Credentials: map[string]CredentialFieldMetadata{
"credentials": {Configured: configured},
},
}
}
// enrichRSSFeedURLsInSettings copies feed_urls from credentials into settings
// for API responses. Feed URLs are not secrets but may still live in the
// encrypted credentials blob on rows created before they moved to settings.
func enrichRSSFeedURLsInSettings(dsType string, parsed *types.DataSourceConfig, cfgDTO *DataSourceConfigDTO) {
if dsType != types.ConnectorTypeRSS || parsed == nil || cfgDTO == nil {
return
}
if cfgDTO.Settings != nil {
if v, ok := cfgDTO.Settings["feed_urls"].(string); ok && strings.TrimSpace(v) != "" {
return
}
}
raw, ok := parsed.Credentials["feed_urls"]
if !ok {
return
}
feedURLs, ok := raw.(string)
if !ok || strings.TrimSpace(feedURLs) == "" {
return
}
if cfgDTO.Settings == nil {
cfgDTO.Settings = make(map[string]interface{})
}
cfgDTO.Settings["feed_urls"] = feedURLs
}
// NewDataSourceResponses converts a list of entities for the list endpoint.
// The sync cursor is stripped from every element: the settings page polls
// the list every few seconds during a sync, cursors can grow to megabytes,
// and no list consumer reads them. Detail, create and update responses
// still carry the cursor through NewDataSourceResponse.
func NewDataSourceResponses(dss []*types.DataSource) []*DataSourceResponse {
out := make([]*DataSourceResponse, 0, len(dss))
for _, d := range dss {
resp := NewDataSourceResponse(d)
if resp != nil {
resp.LastSyncCursor = nil
}
out = append(out, resp)
}
return out
}
+139
View File
@@ -0,0 +1,139 @@
package dto
import (
"encoding/json"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
)
func TestDataSourceResponse_OmitsCredentials(t *testing.T) {
cfg := types.DataSourceConfig{
Type: "github",
Credentials: map[string]interface{}{
"token": "ghp-secret-do-not-leak",
},
ResourceIDs: []string{"repo-1"},
Settings: map[string]interface{}{"branch": "main"},
}
blob, _ := cfg.ToJSON()
ds := &types.DataSource{
ID: "ds-1",
Name: "github-prod",
Type: "github",
Config: blob,
}
body, err := json.Marshal(NewDataSourceResponse(ds))
assert.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "ghp-secret-do-not-leak")
// The inner config object must not carry the credentials map (the
// DataSourceConfigDTO type omits it structurally).
var raw map[string]json.RawMessage
assert.NoError(t, json.Unmarshal(body, &raw))
if cfgRaw, ok := raw["config"]; ok {
var inner map[string]json.RawMessage
assert.NoError(t, json.Unmarshal(cfgRaw, &inner))
_, hasCredsInConfig := inner["credentials"]
assert.False(t, hasCredsInConfig,
"credentials map must not appear inside the config DTO")
}
// Top-level credentials map is just the "configured?" indicator,
// replaces the removed GET /credentials endpoint.
assert.Contains(t, s, `"credentials":{"credentials":{"configured":true}}`)
// Non-secret config fields pass through.
assert.Contains(t, s, "repo-1")
assert.Contains(t, s, "branch")
assert.Contains(t, s, "main")
}
func TestDataSourceResponses_OmitsLastSyncCursor(t *testing.T) {
ds := &types.DataSource{
ID: "ds-1",
Name: "github-prod",
Type: "github",
LastSyncCursor: types.JSON(`{"page":42}`),
LastSyncResult: types.JSON(`{"total":10}`),
}
list := NewDataSourceResponses([]*types.DataSource{ds})
assert.Len(t, list, 1)
got := list[0]
assert.Empty(t, got.LastSyncCursor)
body, err := json.Marshal(got)
assert.NoError(t, err)
var raw map[string]json.RawMessage
assert.NoError(t, json.Unmarshal(body, &raw))
assert.NotContains(t, raw, "last_sync_cursor")
// Every other field must match the single-entity conversion.
want := NewDataSourceResponse(ds)
assert.Equal(t, json.RawMessage(`{"page":42}`), want.LastSyncCursor)
want.LastSyncCursor = nil
assert.Equal(t, want, got)
}
func TestDataSourceResponse_NilSafe(t *testing.T) {
assert.Nil(t, NewDataSourceResponse(nil))
assert.Equal(t, []*DataSourceResponse{}, NewDataSourceResponses(nil))
}
func TestDataSourceResponse_RSSFeedURLsFromCredentials(t *testing.T) {
cfg := types.DataSourceConfig{
Type: types.ConnectorTypeRSS,
Credentials: map[string]interface{}{
"feed_urls": "https://example.com/a.xml\nhttps://example.com/b.xml",
},
ResourceIDs: []string{"https://example.com/a.xml"},
}
blob, _ := cfg.ToJSON()
ds := &types.DataSource{
ID: "ds-rss",
Name: "my-rss",
Type: types.ConnectorTypeRSS,
Config: blob,
}
resp := NewDataSourceResponse(ds)
assert.NotNil(t, resp.Config)
assert.Equal(t, "https://example.com/a.xml\nhttps://example.com/b.xml", resp.Config.Settings["feed_urls"])
assert.False(t, resp.Credentials["credentials"].Configured)
body, err := json.Marshal(resp)
assert.NoError(t, err)
s := string(body)
assert.Contains(t, s, "https://example.com/a.xml")
assert.NotContains(t, s, "Bearer secret")
}
func TestDataSourceResponse_RSSAuthHeadersConfigured(t *testing.T) {
cfg := types.DataSourceConfig{
Type: types.ConnectorTypeRSS,
Credentials: map[string]interface{}{
"auth_headers": "Authorization: Bearer secret",
},
Settings: map[string]interface{}{
"feed_urls": "https://example.com/feed.xml",
},
}
blob, _ := cfg.ToJSON()
ds := &types.DataSource{
ID: "ds-rss-auth",
Name: "my-rss",
Type: types.ConnectorTypeRSS,
Config: blob,
}
resp := NewDataSourceResponse(ds)
assert.True(t, resp.Credentials["credentials"].Configured)
body, err := json.Marshal(resp)
assert.NoError(t, err)
assert.NotContains(t, string(body), "Bearer secret")
}
func TestDataSourceResponse_NoConfig(t *testing.T) {
ds := &types.DataSource{ID: "x", Name: "x"}
body, err := json.Marshal(NewDataSourceResponse(ds))
assert.NoError(t, err)
// No config jsonb stored → no config object in the response.
assert.NotContains(t, string(body), `"config":`)
}
+216
View File
@@ -0,0 +1,216 @@
// Package dto holds response shapes for handler responses that need to differ
// from the persisted GORM model — most notably, response types that must NOT
// carry secret fields.
//
// Why a separate package: response DTOs are deliberately distinct from the
// internal model so the "no secret in responses" guarantee is a compile-time
// invariant rather than a runtime redaction step. If a future contributor
// wants to expose a credential in a response, they must add it to the DTO
// explicitly, which makes the leak surface review-able in a single diff.
package dto
import (
"context"
"time"
"academy/internal/types"
)
// MCPServiceResponse mirrors types.MCPService for response bodies, omitting
// every secret field (api_key, token). Credential presence/absence is exposed
// separately via the /credentials subresource endpoint; this shape carries
// only a boolean per credential field so the frontend can render a
// "configured / not configured" badge without an additional round-trip.
type MCPServiceResponse struct {
UsageInstructions string `json:"usage_instructions"`
ID string `json:"id" extensions:"x-agent=mcp_service_id"`
TenantID uint64 `json:"tenant_id"`
Name string `json:"name" extensions:"x-agent"`
Description string `json:"description" extensions:"x-agent"`
Enabled bool `json:"enabled" extensions:"x-agent"`
TransportType types.MCPTransportType `json:"transport_type" extensions:"x-agent"`
URL *string `json:"url,omitempty"`
Headers types.MCPHeaders `json:"headers,omitempty"`
AuthConfig *MCPAuthConfigResponse `json:"auth_config,omitempty" extensions:"x-agent"`
AdvancedConfig *types.MCPAdvancedConfig `json:"advanced_config,omitempty"`
StdioConfig *types.MCPStdioConfig `json:"stdio_config,omitempty"`
EnvVars types.MCPEnvVars `json:"env_vars,omitempty"`
IsBuiltin bool `json:"is_builtin" extensions:"x-agent"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Credentials is the per-field "configured?" map. Embedded on the main
// response so the credential UI doesn't need a follow-up GET. The
// frontend never sees the actual secret value — only whether one is
// stored. Omitted entirely for builtin services (they can't have
// per-tenant credentials).
Credentials map[string]CredentialFieldMetadata `json:"credentials,omitempty"`
// Catalog is the persisted tool-directory summary for list cards.
// Omitted when this principal has never synchronized the service.
Catalog *MCPCatalogSummary `json:"catalog,omitempty"`
}
// MCPCatalogSummary is the list-card view of a saved MCP directory.
type MCPCatalogSummary struct {
ToolCount int `json:"tool_count"`
Stale bool `json:"stale"`
SyncedAt time.Time `json:"synced_at"`
}
// MCPAuthConfigResponse intentionally has no APIKey, Token or ClientSecret
// fields. Their presence is signalled via MCPServiceResponse.Credentials.
// AuthType, Scopes, AuthServerMetadataURL and ClientID are non-secret OAuth
// configuration and are safe to echo back so the UI can render the current
// strategy.
type MCPAuthConfigResponse struct {
AuthType types.MCPAuthType `json:"auth_type,omitempty" extensions:"x-agent"`
APIKeyHeader string `json:"api_key_header,omitempty"`
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
Scopes []string `json:"scopes,omitempty"`
AuthServerMetadataURL string `json:"auth_server_metadata_url,omitempty"`
ClientID string `json:"client_id,omitempty"`
}
// CredentialFieldMetadata reports whether a credential field has a value
// stored server-side, without exposing the value itself.
type CredentialFieldMetadata struct {
Configured bool `json:"configured"`
}
// NewMCPServiceResponse converts a stored MCPService into its response shape.
//
// Builtin MCP services have their tenant-specific transport details (URL,
// Headers, EnvVars, StdioConfig) stripped — these reveal how the tenant
// configured an upstream provider and must not be visible to other tenants
// that see the same builtin row via the cross-tenant list.
func NewMCPServiceResponse(ctx context.Context, svc *types.MCPService) *MCPServiceResponse {
if svc == nil {
return nil
}
includeDetail := CanViewIntegrationSecrets(ctx)
resp := &MCPServiceResponse{
ID: svc.ID,
TenantID: svc.TenantID,
Name: svc.Name,
Description: svc.Description,
UsageInstructions: svc.UsageInstructions,
Enabled: svc.Enabled,
TransportType: svc.TransportType,
URL: svc.URL,
Headers: svc.Headers,
AdvancedConfig: svc.AdvancedConfig,
StdioConfig: svc.StdioConfig,
EnvVars: svc.EnvVars,
IsBuiltin: svc.IsBuiltin,
CreatedAt: svc.CreatedAt,
UpdatedAt: svc.UpdatedAt,
}
if !includeDetail {
resp.Headers = nil
resp.EnvVars = nil
resp.URL = nil
resp.StdioConfig = nil
resp.AdvancedConfig = nil
}
if svc.AuthConfig != nil {
auth := &MCPAuthConfigResponse{
AuthType: svc.AuthConfig.AuthType,
APIKeyHeader: svc.AuthConfig.APIKeyHeader,
CustomHeaders: svc.AuthConfig.CustomHeaders,
Scopes: svc.AuthConfig.Scopes,
AuthServerMetadataURL: svc.AuthConfig.AuthServerMetadataURL,
ClientID: svc.AuthConfig.ClientID,
}
if !includeDetail {
auth.CustomHeaders = nil
}
resp.AuthConfig = auth
}
if svc.IsBuiltin {
// Builtin services are shared across tenants — strip everything that
// could leak how this tenant configured the underlying provider.
resp.URL = nil
resp.Headers = nil
resp.EnvVars = nil
resp.StdioConfig = nil
resp.AuthConfig = nil
} else {
resp.Credentials = map[string]CredentialFieldMetadata{
"api_key": {Configured: svc.AuthConfig != nil && svc.AuthConfig.APIKey != ""},
"token": {Configured: svc.AuthConfig != nil && svc.AuthConfig.Token != ""},
"client_secret": {Configured: svc.AuthConfig != nil && svc.AuthConfig.ClientSecret != ""},
}
}
return resp
}
// NewMCPServiceResponses is the slice convenience wrapper used by ListMCPServices.
func NewMCPServiceResponses(ctx context.Context, svcs []*types.MCPService) []*MCPServiceResponse {
out := make([]*MCPServiceResponse, 0, len(svcs))
for _, s := range svcs {
out = append(out, NewMCPServiceResponse(ctx, s))
}
return out
}
// NewSharedAgentMCPServiceResponses is the cross-workspace list shape: the
// @MCP picker of a borrowed agent needs a service's identity and how many
// tools it offers, and nothing else.
//
// It fills the fields explicitly instead of reusing NewMCPServiceResponse and
// blanking the rest, so a field added to MCPServiceResponse later is absent
// here until someone decides it may cross a workspace boundary. Endpoint URLs,
// headers, env vars, stdio commands, auth config and credential metadata all
// describe how the OWNER wired the service up; the borrower never configures
// it and must not see it.
func NewSharedAgentMCPServiceResponses(svcs []*types.MCPService) []*MCPServiceResponse {
out := make([]*MCPServiceResponse, 0, len(svcs))
for _, s := range svcs {
if s == nil {
continue
}
out = append(out, &MCPServiceResponse{
ID: s.ID,
TenantID: s.TenantID,
Name: s.Name,
Description: s.Description,
UsageInstructions: s.UsageInstructions,
Enabled: s.Enabled,
TransportType: s.TransportType,
IsBuiltin: s.IsBuiltin,
})
}
return out
}
// AttachMCPCatalogs copies persisted directory counts onto list/detail responses.
func AttachMCPCatalogs(
resp []*MCPServiceResponse,
services []*types.MCPService,
summaries map[string]*types.MCPMetadataSummary,
) {
if len(resp) != len(services) || summaries == nil {
return
}
for i, service := range services {
if resp[i] == nil || service == nil {
continue
}
summary := summaries[service.ID]
if summary == nil {
continue
}
resp[i].Catalog = &MCPCatalogSummary{
ToolCount: summary.ToolCount,
Stale: summary.ConfigFingerprint != types.MCPConfigFingerprint(service),
SyncedAt: summary.SyncedAt,
}
}
}
// CredentialsResponse is the shared shape returned by PUT
// /{resource}/{id}/credentials. Keyed by field name (e.g. "api_key",
// "token"). The frontend uses this to update its in-memory metadata after a
// successful save without needing to re-fetch the whole resource.
type CredentialsResponse struct {
Fields map[string]CredentialFieldMetadata `json:"fields"`
}
+139
View File
@@ -0,0 +1,139 @@
package dto
import (
"encoding/json"
"strings"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
)
// The most important guarantee of the DTO layer is structural: the serialized
// response body must NEVER contain api_key or token under any condition,
// regardless of the underlying entity's state. We assert this via the
// serialized JSON (not just struct shape) because reflection-based
// custom-marshalers anywhere downstream could otherwise reintroduce a leak.
func TestMCPServiceResponse_OmitsSecrets(t *testing.T) {
svc := &types.MCPService{
ID: "svc-1",
Name: "svc",
AuthConfig: &types.MCPAuthConfig{
APIKey: "sk-real-api-key-do-not-leak",
Token: "tok-real-bearer-token-do-not-leak",
CustomHeaders: map[string]string{"X-Trace": "abc"},
},
}
body, err := json.Marshal(NewMCPServiceResponse(adminContext(), svc))
assert.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "sk-real-api-key-do-not-leak",
"raw api_key must never appear in MCPServiceResponse")
assert.NotContains(t, s, "tok-real-bearer-token-do-not-leak",
"raw token must never appear in MCPServiceResponse")
// auth_config no longer has api_key/token fields (only custom_headers
// survived). Verify the auth_config sub-object contains no secret keys.
var raw map[string]json.RawMessage
assert.NoError(t, json.Unmarshal(body, &raw))
if ac, ok := raw["auth_config"]; ok {
acStr := string(ac)
assert.NotContains(t, acStr, `"api_key"`)
assert.NotContains(t, acStr, `"token"`)
}
// The new credentials map exposes "configured?" booleans by design
// (replaces the standalone GET /credentials endpoint). Verify the
// values are booleans, not strings.
assert.Contains(t, s, `"credentials"`)
assert.Contains(t, s, `"api_key":{"configured":true}`)
assert.Contains(t, s, `"token":{"configured":true}`)
// CustomHeaders is structural metadata and SHOULD pass through.
assert.Contains(t, s, `"custom_headers"`)
assert.Contains(t, s, `"X-Trace"`)
}
func TestMCPServiceResponse_BuiltinStripsTenantConfig(t *testing.T) {
url := "https://tenant-private.example.com"
svc := &types.MCPService{
ID: "builtin-1",
IsBuiltin: true,
URL: &url,
Headers: types.MCPHeaders{"X-Tenant-Secret": "shhh"},
AuthConfig: &types.MCPAuthConfig{
APIKey: "should-not-leak-via-builtin",
},
}
resp := NewMCPServiceResponse(adminContext(), svc)
assert.Nil(t, resp.URL, "builtin must not leak per-tenant URL")
assert.Nil(t, resp.Headers, "builtin must not leak per-tenant headers")
assert.Nil(t, resp.AuthConfig, "builtin must not leak auth config")
body, _ := json.Marshal(resp)
assert.False(t, strings.Contains(string(body), "should-not-leak-via-builtin"))
assert.False(t, strings.Contains(string(body), "X-Tenant-Secret"))
}
func TestMCPServiceResponse_ViewerStripsIntegrationDetail(t *testing.T) {
url := "https://tenant-private.example.com"
svc := &types.MCPService{
ID: "svc-2",
URL: &url,
Headers: types.MCPHeaders{"Authorization": "Bearer secret"},
EnvVars: types.MCPEnvVars{"TOKEN": "secret"},
StdioConfig: &types.MCPStdioConfig{
Command: "npx",
Args: []string{"-y", "mcp-server"},
},
AdvancedConfig: &types.MCPAdvancedConfig{},
AuthConfig: &types.MCPAuthConfig{
CustomHeaders: map[string]string{"X-Auth": "secret"},
},
}
resp := NewMCPServiceResponse(viewerContext(), svc)
assert.Nil(t, resp.URL)
assert.Nil(t, resp.Headers)
assert.Nil(t, resp.EnvVars)
assert.Nil(t, resp.StdioConfig)
assert.Nil(t, resp.AdvancedConfig)
assert.NotNil(t, resp.AuthConfig)
assert.Nil(t, resp.AuthConfig.CustomHeaders)
}
func TestMCPServiceResponse_NilSafe(t *testing.T) {
assert.Nil(t, NewMCPServiceResponse(adminContext(), nil))
assert.Equal(t, []*MCPServiceResponse{}, NewMCPServiceResponses(adminContext(), nil))
}
func TestAttachMCPCatalogs_MarksStaleWithoutCopyingTools(t *testing.T) {
svc := &types.MCPService{ID: "svc-1", TransportType: types.MCPTransportSSE}
resp := NewMCPServiceResponses(adminContext(), []*types.MCPService{svc})
AttachMCPCatalogs(resp, []*types.MCPService{svc}, map[string]*types.MCPMetadataSummary{
"svc-1": {ServiceID: "svc-1", ToolCount: 3, ConfigFingerprint: "old"},
})
require := assert.New(t)
require.NotNil(resp[0].Catalog)
require.Equal(3, resp[0].Catalog.ToolCount)
require.True(resp[0].Catalog.Stale)
body, err := json.Marshal(resp[0])
require.NoError(err)
require.NotContains(string(body), `"tools"`)
require.Contains(string(body), `"tool_count":3`)
}
func TestMCPServiceResponse_EchoesClientIDButNotItsSecret(t *testing.T) {
svc := &types.MCPService{
ID: "svc-1",
Name: "svc",
AuthConfig: &types.MCPAuthConfig{
AuthType: types.MCPAuthOAuth,
ClientID: "pre-registered",
ClientSecret: "client-secret-do-not-leak",
},
}
body, err := json.Marshal(NewMCPServiceResponse(adminContext(), svc))
assert.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "client-secret-do-not-leak")
assert.Contains(t, s, `"client_id":"pre-registered"`)
assert.Contains(t, s, `"client_secret":{"configured":true}`)
}
+350
View File
@@ -0,0 +1,350 @@
package dto
import (
"context"
"strings"
"time"
modelruntime "academy/internal/models/runtime"
"academy/internal/types"
)
// VendorRef identifies the vendor a set of model parameters belongs to.
// BaseURL covers legacy rows saved before provider was stored; the vendor is
// then detected from the endpoint.
type VendorRef struct {
Provider string
BaseURL string
}
// vendorID resolves the ref to a comparable vendor id. An id that matches no
// registered vendor is returned as typed, so two rows pinned to the same
// hand-written provider still compare equal.
func (r VendorRef) vendorID() string {
id := strings.ToLower(strings.TrimSpace(r.Provider))
if id == "" {
id = modelruntime.DetectByURL(r.BaseURL)
}
return id
}
// names reports whether the ref identifies a vendor at all. A PUT body that
// carries neither provider nor base URL names none, and must not be read as
// "the user moved this row to another vendor".
func (r VendorRef) names() bool {
return strings.TrimSpace(r.Provider) != "" || strings.TrimSpace(r.BaseURL) != ""
}
func secretKeysOf(v *modelruntime.Provider, into map[string]bool) map[string]bool {
for _, f := range v.ExtraFields {
if !f.Secret && f.Type != "password" {
continue
}
if into == nil {
into = map[string]bool{}
}
into[f.Key] = true
}
return into
}
// SecretExtraConfigKeys returns the extra_config keys the vendor declares as
// secret (providers.ExtraField.Secret, or a password input). These are real
// credentials — LKEAP and Volcengine rerank keep an IAM/CAM secret key there
// — so they get the same treatment as api_key / app_secret: never echoed,
// only reported as present.
//
// The field's ModelTypes restriction is deliberately ignored: a key that is
// secret for any model type of the vendor is redacted for every row of that
// vendor.
func SecretExtraConfigKeys(provider, baseURL string) map[string]bool {
v, ok := modelruntime.Get(VendorRef{Provider: provider, BaseURL: baseURL}.vendorID())
if !ok {
return nil
}
return secretKeysOf(v, nil)
}
// AllSecretExtraConfigKeys returns every extra_config key any registered
// vendor declares secret.
//
// Redaction must not depend on the row's own provider being the one that
// declared the key: a row whose provider was switched, hand-edited or never
// stored would otherwise echo a credential in plaintext simply because its
// current vendor declares no secret field. Treating a name that is secret
// somewhere as secret everywhere is the safe direction — the worst case is
// withholding a value that happened to reuse the name.
func AllSecretExtraConfigKeys() map[string]bool {
var keys map[string]bool
for _, v := range modelruntime.List() {
keys = secretKeysOf(v, keys)
}
return keys
}
// redactedSecretPlaceholder reports whether an incoming extra_config value
// carries no new secret: empty, or a mask the UI shows for a value it never
// received (GET omits the key entirely, but forms happily render bullets).
func redactedSecretPlaceholder(v string) bool {
t := strings.TrimSpace(v)
return t == "" || strings.Trim(t, "*•·●") == ""
}
// PreserveStoredSecretExtras merges the stored secret extra_config values
// into an incoming map.
//
// PUT /models/{id} replaces extra_config wholesale and the frontend always
// sends the map for remote rows, but GET redacts the vendor's secret fields,
// so a plain edit-and-save round-trip carries no value for them. Without this
// merge the first save after any unrelated edit would erase the stored secret
// key and break rerank for that row. An incoming value that is absent, empty
// or a mask means "unchanged"; anything else replaces the stored secret.
//
// storedVendor identifies the vendor the stored values belong to; edited is
// the vendor the incoming values are for. They differ when the user moves the
// row to another vendor, and then the stored credential must be dropped
// rather than carried over: it belongs to the previous integration's account,
// the editor no longer renders a field for it, and the new vendor may not
// declare it secret at all — which is how it ended up echoed in plaintext.
//
// incoming is filled in place and returned.
func PreserveStoredSecretExtras(
stored, incoming map[string]string, storedVendor, edited VendorRef,
) map[string]string {
keys := SecretExtraConfigKeys(storedVendor.Provider, storedVendor.BaseURL)
// A request that names no vendor at all changed none: keep the old
// contract, which rerank rows rely on for their redacted secret.
switched := edited.names() && edited.vendorID() != storedVendor.vendorID()
if incoming == nil {
if !switched || len(keys) == 0 || len(stored) == 0 {
return stored
}
// extra_config omitted entirely still keeps the rest of the stored
// map, but not the previous vendor's credential.
out := make(map[string]string, len(stored))
for k, v := range stored {
if !keys[k] {
out[k] = v
}
}
return out
}
if len(keys) == 0 {
return incoming
}
if switched {
// Only a value the user actually typed survives a vendor switch; an
// absent or masked one would otherwise resurrect the old secret when
// the new vendor happens to reuse the key name.
for key := range keys {
if redactedSecretPlaceholder(incoming[key]) {
delete(incoming, key)
}
}
return incoming
}
for key := range keys {
storedValue := stored[key]
if storedValue == "" {
continue
}
if redactedSecretPlaceholder(incoming[key]) {
incoming[key] = storedValue
}
}
return incoming
}
// HasAllSecretExtras reports whether extra already carries a usable value for
// every secret extra field the vendor declares. Callers that would otherwise
// skip a lookup of the stored row use it to notice that the request is
// missing a redacted secret.
func HasAllSecretExtras(provider, baseURL string, extra map[string]string) bool {
for key := range SecretExtraConfigKeys(provider, baseURL) {
if redactedSecretPlaceholder(extra[key]) {
return false
}
}
return true
}
// ModelResponse mirrors types.Model for response bodies, with all secret
// fields (APIKey, AppSecret) removed by construction. Credential presence
// metadata lives behind the /credentials subresource, not inlined here.
//
// BaseURL is preserved for tenant-owned models (the frontend needs it to
// render which endpoint a custom model points at). For builtin models it is
// stripped along with every other field that could leak how a particular
// tenant configured the upstream provider.
type ModelResponse struct {
ID string `json:"id" extensions:"x-agent=model_id"`
TenantID uint64 `json:"tenant_id"`
Name string `json:"name" extensions:"x-agent"`
DisplayName string `json:"display_name" extensions:"x-agent"`
Type types.ModelType `json:"type" extensions:"x-agent"`
Source types.ModelSource `json:"source" extensions:"x-agent"`
Description string `json:"description" extensions:"x-agent"`
Parameters ModelParametersDTO `json:"parameters" extensions:"x-agent"`
IsDefault bool `json:"is_default" extensions:"x-agent"`
IsBuiltin bool `json:"is_builtin" extensions:"x-agent"`
Status types.ModelStatus `json:"status" extensions:"x-agent"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Per-field "configured?" map. Omitted for builtin models unless the
// caller is a system administrator. See MCPServiceResponse.Credentials.
Credentials map[string]CredentialFieldMetadata `json:"credentials,omitempty"`
// Capabilities is the catalog view of the model. Chat models get the
// protocol, thinking levels and context window; embedding and rerank
// models get input modalities, including support for image input.
Capabilities *modelruntime.Capabilities `json:"capabilities,omitempty" extensions:"x-agent,x-agent-detail"`
}
// ModelParametersDTO carries every parameter field EXCEPT the two secret
// ones (APIKey, AppSecret). AppID is non-secret and stays — it's an account
// identifier the Academy Cloud frontend renders. CustomHeaders is also kept
// (structural metadata, not a credential).
type ModelParametersDTO struct {
// BaseURL is empty for callers who may not view integration detail, and
// for builtin models; see NewModelResponse.
BaseURL string `json:"base_url" extensions:"x-agent"`
InterfaceType string `json:"interface_type"`
EmbeddingParameters types.EmbeddingParameters `json:"embedding_parameters"`
ParameterSize string `json:"parameter_size"`
Provider string `json:"provider" extensions:"x-agent"`
ExtraConfig map[string]string `json:"extra_config,omitempty" extensions:"x-agent,x-agent-detail,x-agent-keys=remote_model_name"`
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
SupportsVision bool `json:"supports_vision"`
ContextWindow int `json:"context_window,omitempty"`
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
MaxConcurrency int `json:"max_concurrency,omitempty"`
AppID string `json:"app_id,omitempty"`
Spec *types.ModelSpecOverride `json:"spec,omitempty"`
}
// NewModelResponse converts a stored Model into its response shape.
//
// Builtin models are shared across tenants — strip BaseURL (which can leak
// the tenant's private endpoint) and any non-shared parameters.
func NewModelResponse(ctx context.Context, m *types.Model) *ModelResponse {
if m == nil {
return nil
}
params := ModelParametersDTO{
BaseURL: m.Parameters.BaseURL,
InterfaceType: m.Parameters.InterfaceType,
EmbeddingParameters: m.Parameters.EmbeddingParameters,
ParameterSize: m.Parameters.ParameterSize,
Provider: m.Parameters.Provider,
ExtraConfig: m.Parameters.ExtraConfig,
CustomHeaders: m.Parameters.CustomHeaders,
SupportsVision: m.Parameters.SupportsVision,
ContextWindow: m.Parameters.ContextWindow,
MaxOutputTokens: m.Parameters.MaxOutputTokens,
MaxConcurrency: m.Parameters.MaxConcurrency,
AppID: m.Parameters.AppID,
Spec: m.Parameters.Spec,
}
canManageBuiltin := m.IsBuiltin && types.IsSystemAdminFromContext(ctx)
if !CanViewIntegrationSecrets(ctx) && !canManageBuiltin {
params.ExtraConfig = nil
params.CustomHeaders = nil
params.BaseURL = ""
// Spec is deployment configuration of the same kind: it pins the
// protocol and carries the compat overlay, whose extra_body is
// merged verbatim into every request. It belongs with ExtraConfig,
// not with the capability fields kept below.
params.Spec = nil
}
if m.IsBuiltin && !canManageBuiltin {
// Builtin: strip everything that could reveal per-tenant config.
// EmbeddingParameters and ParameterSize / Provider / InterfaceType /
// SupportsVision / ContextWindow / MaxOutputTokens are intentionally
// preserved (they describe the capability surface, not the configured
// endpoint).
params.BaseURL = ""
params.ExtraConfig = nil
params.CustomHeaders = nil
params.AppID = ""
params.Spec = nil
}
// Vendor-declared secret extra fields are credentials that happen to be
// stored in extra_config. Drop them from the echoed map — even for
// callers allowed to see integration detail, exactly as api_key is
// withheld from an admin — and report presence instead. The stored map is
// never mutated: params.ExtraConfig still aliases it here.
//
// Redaction spans every registered vendor, not just this row's: a row
// whose provider was switched or hand-edited must not leak a leftover
// credential just because its current vendor declares no secret field.
secretKeys := SecretExtraConfigKeys(m.Parameters.Provider, m.Parameters.BaseURL)
redactKeys := AllSecretExtraConfigKeys()
if len(redactKeys) > 0 && len(params.ExtraConfig) > 0 {
sanitized := make(map[string]string, len(params.ExtraConfig))
for k, v := range params.ExtraConfig {
if !redactKeys[k] {
sanitized[k] = v
}
}
params.ExtraConfig = sanitized
}
var creds map[string]CredentialFieldMetadata
if !m.IsBuiltin || canManageBuiltin {
creds = map[string]CredentialFieldMetadata{
"api_key": {Configured: m.Parameters.APIKey != ""},
"app_secret": {Configured: m.Parameters.AppSecret != ""},
}
for key := range secretKeys {
creds[key] = CredentialFieldMetadata{
Configured: strings.TrimSpace(m.Parameters.ExtraConfig[key]) != "",
}
}
// A key this row's vendor does not declare was still withheld above,
// so say it is there — otherwise the value silently vanishes from the
// editor with nothing to explain why.
for key := range redactKeys {
if _, reported := creds[key]; reported {
continue
}
if strings.TrimSpace(m.Parameters.ExtraConfig[key]) != "" {
creds[key] = CredentialFieldMetadata{Configured: true}
}
}
}
var caps *modelruntime.Capabilities
switch m.Type {
case types.ModelTypeKnowledgeQA, types.ModelTypeVLLM, types.ModelTypeEmbedding, types.ModelTypeRerank:
if resolved, err := modelruntime.Resolve(modelruntime.Ref{
Provider: m.Parameters.Provider, Model: m.Name, BaseURL: m.Parameters.BaseURL,
ModelType: m.Type, Extra: m.Parameters.ExtraConfig, Override: m.Parameters.Spec,
}); err == nil && m.Source == types.ModelSourceRemote {
c := resolved.Capabilities()
caps = &c
}
}
return &ModelResponse{
ID: m.ID,
TenantID: m.TenantID,
Name: m.Name,
DisplayName: m.DisplayName,
Type: m.Type,
Source: m.Source,
Description: m.Description,
Parameters: params,
IsDefault: m.IsDefault,
IsBuiltin: m.IsBuiltin,
Status: m.Status,
CreatedAt: m.CreatedAt,
UpdatedAt: m.UpdatedAt,
Credentials: creds,
Capabilities: caps,
}
}
// NewModelResponses is the slice convenience wrapper.
func NewModelResponses(ctx context.Context, models []*types.Model) []*ModelResponse {
out := make([]*ModelResponse, 0, len(models))
for _, m := range models {
out = append(out, NewModelResponse(ctx, m))
}
return out
}
+377
View File
@@ -0,0 +1,377 @@
package dto
import (
"context"
"encoding/json"
"slices"
"strings"
"testing"
"academy/internal/models/providers"
modelruntime "academy/internal/models/runtime"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestModelResponse_OmitsSecrets(t *testing.T) {
m := &types.Model{
ID: "m-1",
Name: "gpt-x",
DisplayName: "Support QA",
Parameters: types.ModelParameters{
APIKey: "sk-real-api-key-do-not-leak",
AppSecret: "app-real-secret-do-not-leak",
AppID: "appid-public-ok-to-show",
BaseURL: "https://api.example.com",
Provider: "openai",
},
}
body, err := json.Marshal(NewModelResponse(adminContext(), m))
assert.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "sk-real-api-key-do-not-leak")
assert.NotContains(t, s, "app-real-secret-do-not-leak")
// Parameters sub-object must contain no secret keys.
var raw map[string]json.RawMessage
assert.NoError(t, json.Unmarshal(body, &raw))
params := string(raw["parameters"])
assert.NotContains(t, params, `"api_key"`)
assert.NotContains(t, params, `"app_secret"`)
// Credential metadata map exposes booleans only.
assert.Contains(t, s, `"credentials"`)
assert.Contains(t, s, `"api_key":{"configured":true}`)
assert.Contains(t, s, `"app_secret":{"configured":true}`)
// Non-secret fields pass through.
assert.Contains(t, s, "appid-public-ok-to-show")
assert.Contains(t, s, "api.example.com")
assert.Contains(t, s, `"display_name":"Support QA"`)
}
func TestModelResponse_BuiltinStripsTenantConfig(t *testing.T) {
m := &types.Model{
ID: "builtin-1",
IsBuiltin: true,
Parameters: types.ModelParameters{
BaseURL: "https://tenant-private.example.com",
APIKey: "should-not-leak",
AppID: "tenant-app-id",
SupportsVision: true,
ExtraConfig: map[string]string{"region": "cn-hangzhou"},
},
}
resp := NewModelResponse(adminContext(), m)
assert.Empty(t, resp.Parameters.BaseURL,
"builtin must not leak per-tenant base URL")
assert.Empty(t, resp.Parameters.AppID,
"builtin must not leak per-tenant app_id")
assert.Nil(t, resp.Parameters.ExtraConfig,
"builtin must not leak per-tenant extra_config")
assert.True(t, resp.Parameters.SupportsVision,
"capability metadata must survive (not per-tenant)")
body, _ := json.Marshal(resp)
assert.False(t, strings.Contains(string(body), "should-not-leak"))
assert.False(t, strings.Contains(string(body), "tenant-private.example.com"))
}
func TestModelResponse_SystemAdminCanManageBuiltinConfig(t *testing.T) {
ctx := context.WithValue(viewerContext(), types.SystemAdminContextKey, true)
m := &types.Model{
ID: "builtin-1",
IsBuiltin: true,
Parameters: types.ModelParameters{
BaseURL: "https://global-provider.example.com",
APIKey: "should-never-be-returned",
AppSecret: "also-never-returned",
AppID: "global-app-id",
ExtraConfig: map[string]string{"region": "ap-guangzhou"},
CustomHeaders: map[string]string{"X-Route": "global"},
},
}
resp := NewModelResponse(ctx, m)
assert.Equal(t, "https://global-provider.example.com", resp.Parameters.BaseURL)
assert.Equal(t, "global-app-id", resp.Parameters.AppID)
assert.Equal(t, map[string]string{"region": "ap-guangzhou"}, resp.Parameters.ExtraConfig)
assert.Equal(t, map[string]string{"X-Route": "global"}, resp.Parameters.CustomHeaders)
assert.True(t, resp.Credentials["api_key"].Configured)
assert.True(t, resp.Credentials["app_secret"].Configured)
body, err := json.Marshal(resp)
require.NoError(t, err)
assert.NotContains(t, string(body), "should-never-be-returned")
assert.NotContains(t, string(body), "also-never-returned")
}
func TestModelResponse_ViewerStripsIntegrationDetail(t *testing.T) {
m := &types.Model{
ID: "m-2",
Parameters: types.ModelParameters{
BaseURL: "https://tenant-private.example.com",
CustomHeaders: map[string]string{"Authorization": "Bearer secret"},
ExtraConfig: map[string]string{"region": "cn-hangzhou"},
},
}
resp := NewModelResponse(viewerContext(), m)
assert.Empty(t, resp.Parameters.BaseURL)
assert.Nil(t, resp.Parameters.CustomHeaders)
assert.Nil(t, resp.Parameters.ExtraConfig)
}
// registerSecretExtraVendor adds a vendor whose extra_config carries a real
// credential, the way LKEAP / Volcengine rerank declare secret_key.
func registerSecretExtraVendor(t *testing.T) string {
t.Helper()
id := "dto-secret-extra-vendor"
modelruntime.Register(&providers.Definition{
ID: id,
Name: "Secret Extra Vendor",
ModelTypes: []types.ModelType{types.ModelTypeRerank},
URLPatterns: []string{"secret-extra-vendor.example.com"},
ExtraFields: []providers.ExtraField{
{Key: "secret_key", Label: "Secret Key", Type: "password", Secret: true},
{Key: "region", Label: "Region", Type: "string"},
},
})
return id
}
// A vendor-declared secret extra field is a credential that happens to live
// in extra_config: GET must report its presence, never its value — even to a
// caller allowed to see integration detail, exactly like api_key.
func TestModelResponse_RedactsVendorSecretExtraConfig(t *testing.T) {
provider := registerSecretExtraVendor(t)
m := &types.Model{
ID: "m-rerank",
Type: types.ModelTypeRerank,
Parameters: types.ModelParameters{
Provider: provider,
BaseURL: "https://secret-extra-vendor.example.com",
APIKey: "AKID-public-id",
ExtraConfig: map[string]string{
"secret_key": "cam-secret-do-not-leak",
"region": "ap-guangzhou",
},
},
}
resp := NewModelResponse(adminContext(), m)
assert.NotContains(t, resp.Parameters.ExtraConfig, "secret_key")
assert.Equal(t, "ap-guangzhou", resp.Parameters.ExtraConfig["region"],
"non-secret extra fields still round-trip")
assert.True(t, resp.Credentials["secret_key"].Configured,
"presence is reported in the same shape as api_key")
body, err := json.Marshal(resp)
require.NoError(t, err)
assert.NotContains(t, string(body), "cam-secret-do-not-leak")
assert.Equal(t, "cam-secret-do-not-leak", m.Parameters.ExtraConfig["secret_key"],
"the stored model must not be mutated by rendering a response")
}
func TestModelResponse_SecretExtraConfigReportsAbsence(t *testing.T) {
provider := registerSecretExtraVendor(t)
m := &types.Model{
ID: "m-rerank",
Type: types.ModelTypeRerank,
Parameters: types.ModelParameters{Provider: provider, ExtraConfig: map[string]string{"region": "ap-beijing"}},
}
resp := NewModelResponse(adminContext(), m)
assert.False(t, resp.Credentials["secret_key"].Configured)
assert.Equal(t, "ap-beijing", resp.Parameters.ExtraConfig["region"])
}
// Legacy rows saved before provider was stored are matched by endpoint.
func TestModelResponse_RedactsSecretExtraConfigForLegacyRowWithoutProvider(t *testing.T) {
registerSecretExtraVendor(t)
m := &types.Model{
ID: "m-legacy",
Type: types.ModelTypeRerank,
Parameters: types.ModelParameters{
BaseURL: "https://secret-extra-vendor.example.com/v1",
ExtraConfig: map[string]string{"secret_key": "cam-secret-do-not-leak"},
},
}
resp := NewModelResponse(adminContext(), m)
assert.NotContains(t, resp.Parameters.ExtraConfig, "secret_key")
assert.True(t, resp.Credentials["secret_key"].Configured)
}
// PUT replaces extra_config wholesale and GET redacts the secret, so the
// save that follows an unrelated edit must not erase the stored key.
func TestPreserveStoredSecretExtras(t *testing.T) {
provider := registerSecretExtraVendor(t)
stored := map[string]string{"secret_key": "cam-secret-stored", "region": "ap-guangzhou"}
sameVendor := VendorRef{Provider: provider}
t.Run("incoming omits the key", func(t *testing.T) {
got := PreserveStoredSecretExtras(
stored, map[string]string{"region": "ap-beijing"}, sameVendor, sameVendor)
assert.Equal(t, "cam-secret-stored", got["secret_key"])
assert.Equal(t, "ap-beijing", got["region"], "non-secret edits still apply")
})
t.Run("incoming carries an empty or masked value", func(t *testing.T) {
for _, masked := range []string{"", " ", "******", "••••"} {
got := PreserveStoredSecretExtras(
stored, map[string]string{"secret_key": masked}, sameVendor, sameVendor)
assert.Equal(t, "cam-secret-stored", got["secret_key"], "masked value %q means unchanged", masked)
}
})
t.Run("incoming carries a new value", func(t *testing.T) {
got := PreserveStoredSecretExtras(
stored, map[string]string{"secret_key": "cam-secret-rotated"}, sameVendor, sameVendor)
assert.Equal(t, "cam-secret-rotated", got["secret_key"])
})
t.Run("nil incoming keeps the whole stored map", func(t *testing.T) {
assert.Equal(t, stored, PreserveStoredSecretExtras(stored, nil, sameVendor, sameVendor))
})
t.Run("unknown stored provider passes the map through", func(t *testing.T) {
in := map[string]string{"secret_key": ""}
assert.Equal(t, in,
PreserveStoredSecretExtras(stored, in, VendorRef{Provider: "no-such-vendor"}, sameVendor))
})
t.Run("a request naming no vendor is not a vendor change", func(t *testing.T) {
got := PreserveStoredSecretExtras(stored, map[string]string{}, sameVendor, VendorRef{})
assert.Equal(t, "cam-secret-stored", got["secret_key"])
})
// Switching the row to another vendor leaves the credential behind: it
// authenticates the account of the integration being replaced.
t.Run("vendor change drops the stored secret", func(t *testing.T) {
other := VendorRef{Provider: "openai"}
got := PreserveStoredSecretExtras(stored, map[string]string{"api": "openai_completions"}, sameVendor, other)
assert.NotContains(t, got, "secret_key")
assert.Equal(t, "openai_completions", got["api"])
})
t.Run("vendor change drops a masked secret instead of refilling it", func(t *testing.T) {
other := VendorRef{Provider: "openai"}
got := PreserveStoredSecretExtras(stored, map[string]string{"secret_key": "****"}, sameVendor, other)
assert.NotContains(t, got, "secret_key")
})
t.Run("vendor change keeps a value the user typed", func(t *testing.T) {
other := VendorRef{Provider: "openai"}
got := PreserveStoredSecretExtras(stored, map[string]string{"secret_key": "typed-now"}, sameVendor, other)
assert.Equal(t, "typed-now", got["secret_key"])
})
t.Run("vendor change with no extra_config at all", func(t *testing.T) {
got := PreserveStoredSecretExtras(stored, nil, sameVendor, VendorRef{Provider: "openai"})
assert.NotContains(t, got, "secret_key")
assert.Equal(t, "ap-guangzhou", got["region"], "non-secret settings are not credentials")
assert.Equal(t, "cam-secret-stored", stored["secret_key"], "the stored map is not mutated")
})
t.Run("a legacy row is matched by endpoint, not treated as a switch", func(t *testing.T) {
legacy := VendorRef{BaseURL: "https://secret-extra-vendor.example.com/v1"}
got := PreserveStoredSecretExtras(stored, map[string]string{}, legacy, legacy)
assert.Equal(t, "cam-secret-stored", got["secret_key"])
})
}
// Redaction may not depend on the row's provider being the one that declared
// the key: a hand-edited or emptied provider would otherwise echo a stored
// credential in plaintext.
func TestModelResponse_RedactsSecretExtraDeclaredByAnotherVendor(t *testing.T) {
registerSecretExtraVendor(t)
for _, provider := range []string{"openai", ""} {
m := &types.Model{
ID: "m-switched",
Type: types.ModelTypeRerank,
Parameters: types.ModelParameters{
Provider: provider,
ExtraConfig: map[string]string{"secret_key": "cam-secret-do-not-leak", "region": "ap-beijing"},
},
}
resp := NewModelResponse(adminContext(), m)
body, err := json.Marshal(resp)
require.NoError(t, err)
assert.NotContains(t, string(body), "cam-secret-do-not-leak", "provider %q", provider)
assert.Equal(t, "ap-beijing", resp.Parameters.ExtraConfig["region"])
assert.True(t, resp.Credentials["secret_key"].Configured,
"a withheld value is still reported as present")
}
}
func TestHasAllSecretExtras(t *testing.T) {
provider := registerSecretExtraVendor(t)
assert.True(t, HasAllSecretExtras(provider, "", map[string]string{"secret_key": "cam-secret"}))
assert.False(t, HasAllSecretExtras(provider, "", map[string]string{"region": "ap-guangzhou"}))
assert.False(t, HasAllSecretExtras(provider, "", map[string]string{"secret_key": "****"}))
assert.True(t, HasAllSecretExtras("no-such-vendor", "", nil), "a vendor with no secret extras is complete")
}
func TestModelResponse_NilSafe(t *testing.T) {
assert.Nil(t, NewModelResponse(adminContext(), nil))
assert.Equal(t, []*ModelResponse{}, NewModelResponses(adminContext(), nil))
}
func TestNewModelResponseStripsSpecFromNonAdmins(t *testing.T) {
// Spec pins the protocol and carries the compat overlay, whose
// extra_body is merged verbatim into every request. It is deployment
// configuration, like base_url and extra_config beside it, not part of
// the capability surface a viewer is shown.
spec := &types.ModelSpecOverride{
API: "anthropic-messages",
Compat: map[string]any{"extra_body": map[string]any{"internal_route": "eu-gateway"}},
}
model := &types.Model{
ID: "m1", Name: "claude-sonnet-4-5", Type: types.ModelTypeKnowledgeQA,
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
Provider: "anthropic", BaseURL: "https://gateway.internal/v1", Spec: spec,
},
}
admin := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleAdmin)
if got := NewModelResponse(admin, model).Parameters.Spec; got == nil {
t.Fatalf("an admin configures this; it must still be returned")
}
viewer := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleViewer)
params := NewModelResponse(viewer, model).Parameters
if params.Spec != nil {
t.Errorf("viewer should not see the protocol override, got %+v", params.Spec)
}
if params.BaseURL != "" || params.ExtraConfig != nil {
t.Errorf("the neighbouring fields should still be stripped")
}
// The stored model is shared; stripping must not mutate it.
if model.Parameters.Spec == nil {
t.Errorf("NewModelResponse must not clear the stored spec")
}
}
func TestNewModelResponseReportsEmbeddingInputModalities(t *testing.T) {
// Whether an embedding model maps images into the same space as text is
// what decides if a knowledge base can store image vectors. The catalog
// knows it for listed models; a row can declare it through spec.input.
declare := func(input ...string) *types.ModelSpecOverride { return &types.ModelSpecOverride{Input: input} }
embedding := func(provider, name string, spec *types.ModelSpecOverride) *types.Model {
return &types.Model{
ID: "e1", Name: name, Type: types.ModelTypeEmbedding, Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{Provider: provider, Spec: spec},
}
}
viewer := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleViewer)
cases := []struct {
name string
model *types.Model
image bool
}{
{"catalog multimodal", embedding("volcengine", "doubao-embedding-vision-251215", nil), true},
{"catalog pattern", embedding("aliyun", "qwen3-vl-embedding", nil), true},
{"catalog text only", embedding("openai", "text-embedding-3-small", nil), false},
{"row declares image", embedding("openai", "my-clip", declare("text", "image")), true},
{"row narrows catalog", embedding("jina", "jina-embeddings-v4", declare("text")), false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// A viewer never sees spec, but the capability it implies is
// not configuration and stays visible.
caps := NewModelResponse(viewer, tc.model).Capabilities
require.NotNil(t, caps)
assert.Equal(t, tc.image, slices.Contains(caps.Input, "image"), "input=%v", caps.Input)
assert.Empty(t, caps.ThinkingLevels, "an embedding model does not think")
})
}
}
+42
View File
@@ -0,0 +1,42 @@
package dto
import (
"context"
"academy/internal/types"
)
// RoleFromContext returns the caller's tenant role from ctx.
func RoleFromContext(ctx context.Context) types.TenantRole {
return types.TenantRoleFromContext(ctx)
}
// CanViewIntegrationSecrets is true for Admin+ tenant members and for API keys
// with full tenant access or the manage_tenant_settings capability.
func CanViewIntegrationSecrets(ctx context.Context) bool {
if RoleFromContext(ctx).HasPermission(types.TenantRoleAdmin) {
return true
}
return apiKeyCanManageIntegrationSecrets(ctx)
}
func apiKeyCanManageIntegrationSecrets(ctx context.Context) bool {
scope, ok := types.TenantAPIKeyScopeFromContext(ctx)
if !ok {
return false
}
if scope.FullAccess {
return true
}
return scope.HasCapability(types.APIKeyCapabilityManageTenantSettings)
}
// RoleCanViewTenantAPIKey is true for Owner+ only.
func RoleCanViewTenantAPIKey(role types.TenantRole) bool {
return role.HasPermission(types.TenantRoleOwner)
}
// CanViewTenantAPIKey is true for Owner+ only.
func CanViewTenantAPIKey(ctx context.Context) bool {
return RoleCanViewTenantAPIKey(RoleFromContext(ctx))
}
+42
View File
@@ -0,0 +1,42 @@
package dto
import (
"context"
"testing"
"academy/internal/types"
)
func TestCanViewIntegrationSecretsAdminRole(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleAdmin)
if !CanViewIntegrationSecrets(ctx) {
t.Fatal("admin should view integration secrets")
}
}
func TestCanViewIntegrationSecretsViewerDenied(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleViewer)
if CanViewIntegrationSecrets(ctx) {
t.Fatal("viewer should not view integration secrets")
}
}
func TestCanViewIntegrationSecretsScopedAPIKeyWithManageTenantSettings(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Capabilities: types.StringArray{string(types.APIKeyCapabilityManageTenantSettings)},
})
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
if !CanViewIntegrationSecrets(ctx) {
t.Fatal("manage_tenant_settings API key should view integration secrets")
}
}
func TestCanViewIntegrationSecretsScopedAPIKeyWithoutCapabilityDenied(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
Capabilities: types.StringArray{string(types.APIKeyCapabilityChat)},
})
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
if CanViewIntegrationSecrets(ctx) {
t.Fatal("chat-only API key should not view integration secrets")
}
}
+93
View File
@@ -0,0 +1,93 @@
package dto
import (
"context"
"time"
"academy/internal/types"
"gorm.io/gorm"
)
// TenantResponse is the viewer-safe tenant profile shape. Secret-bearing
// columns are omitted or redacted unless the caller has Admin+.
type TenantResponse struct {
ID uint64 `json:"id" extensions:"x-agent=workspace_id"`
Name string `json:"name" extensions:"x-agent"`
Description string `json:"description" extensions:"x-agent"`
Status string `json:"status" extensions:"x-agent"`
RetrieverEngines types.RetrieverEngines `json:"retriever_engines"`
Business string `json:"business"`
StorageQuota int64 `json:"storage_quota" extensions:"x-agent"`
StorageUsed int64 `json:"storage_used" extensions:"x-agent"`
ContextConfig *types.ContextConfig `json:"context_config,omitempty"`
WebSearchConfig *types.WebSearchConfig `json:"web_search_config,omitempty"`
ParserEngineConfig *types.ParserEngineConfig `json:"parser_engine_config,omitempty"`
Credentials *types.CredentialsConfig `json:"credentials,omitempty"`
StorageEngineConfig *types.StorageEngineConfig `json:"storage_engine_config,omitempty"`
ChatHistoryConfig *types.ChatHistoryConfig `json:"chat_history_config,omitempty"`
RetrievalConfig *types.RetrievalConfig `json:"retrieval_config,omitempty"`
MemoryConfig *types.MemoryConfig `json:"memory_config,omitempty"`
AssistantConfig *types.AssistantConfig `json:"assistant_config,omitempty"`
CreatedAt time.Time `json:"created_at" extensions:"x-agent"`
UpdatedAt time.Time `json:"updated_at" extensions:"x-agent"`
DeletedAt gorm.DeletedAt `json:"deleted_at"`
}
// NewTenantResponse converts a stored tenant into its HTTP response shape.
func NewTenantResponse(ctx context.Context, tenant *types.Tenant) *TenantResponse {
return NewTenantResponseWithRole(tenant, RoleFromContext(ctx))
}
// NewTenantResponseWithRole converts a stored tenant using an explicit role
// (for auth flows where tenant role is not yet in request context).
func NewTenantResponseWithRole(tenant *types.Tenant, role types.TenantRole) *TenantResponse {
if tenant == nil {
return nil
}
includeSecrets := role.HasPermission(types.TenantRoleAdmin)
resp := &TenantResponse{
ID: tenant.ID,
Name: tenant.Name,
Description: tenant.Description,
Status: tenant.Status,
RetrieverEngines: tenant.RetrieverEngines,
Business: tenant.Business,
StorageQuota: tenant.StorageQuota,
StorageUsed: tenant.StorageUsed,
ContextConfig: tenant.ContextConfig,
ChatHistoryConfig: tenant.ChatHistoryConfig,
RetrievalConfig: tenant.RetrievalConfig,
MemoryConfig: tenant.MemoryConfig,
AssistantConfig: tenant.AssistantConfig,
CreatedAt: tenant.CreatedAt,
UpdatedAt: tenant.UpdatedAt,
DeletedAt: tenant.DeletedAt,
}
if includeSecrets {
resp.WebSearchConfig = types.WebSearchConfigForResponse(tenant.WebSearchConfig, true)
resp.ParserEngineConfig = types.ParserEngineConfigForResponse(tenant.ParserEngineConfig, true)
resp.Credentials = types.CredentialsConfigForResponse(tenant.Credentials, true)
resp.StorageEngineConfig = types.StorageEngineConfigForResponse(tenant.StorageEngineConfig, true)
}
return resp
}
// NewTenantResponses is the slice convenience wrapper.
func NewTenantResponses(ctx context.Context, tenants []*types.Tenant) []*TenantResponse {
out := make([]*TenantResponse, 0, len(tenants))
for _, t := range tenants {
out = append(out, NewTenantResponse(ctx, t))
}
return out
}
// NewTenantResponsesCrossTenant redacts every tenant as Viewer regardless of
// the caller's active-tenant role. Used by cross-tenant list/search endpoints
// where the caller's home-tenant role must not unlock other tenants' secrets.
func NewTenantResponsesCrossTenant(tenants []*types.Tenant) []*TenantResponse {
out := make([]*TenantResponse, 0, len(tenants))
for _, t := range tenants {
out = append(out, NewTenantResponseWithRole(t, types.TenantRoleViewer))
}
return out
}
+86
View File
@@ -0,0 +1,86 @@
package dto
import (
"encoding/json"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTenantResponse_ViewerOmitsSecrets(t *testing.T) {
tenant := sampleSecretTenant()
body, err := json.Marshal(NewTenantResponse(viewerContext(), tenant))
require.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "tenant-api-key-123")
assert.NotContains(t, s, "legacy-search-secret-999")
assert.NotContains(t, s, "wk-app-secret-def")
assert.NotContains(t, s, "parser-secret-123")
assert.NotContains(t, s, "minio-secret-789")
assert.NotContains(t, s, "web_search_config")
assert.NotContains(t, s, "parser_engine_config")
assert.NotContains(t, s, "storage_engine_config")
assert.NotContains(t, s, "credentials")
}
func TestTenantResponse_OwnerOmitsLegacyTenantAPIKey(t *testing.T) {
tenant := sampleSecretTenant()
body, err := json.Marshal(NewTenantResponse(ownerContext(), tenant))
require.NoError(t, err)
s := string(body)
assert.NotContains(t, s, `"api_key"`)
assert.NotContains(t, s, "legacy-search-secret-999")
assert.NotContains(t, s, "parser-secret-123")
assert.Contains(t, s, "web_search_config")
}
func TestTenantResponse_AdminGetsRedactedIntegrationConfigs(t *testing.T) {
tenant := sampleSecretTenant()
resp := NewTenantResponse(adminContext(), tenant)
require.NotNil(t, resp.WebSearchConfig)
assert.Equal(t, types.RedactedSecretPlaceholder, resp.WebSearchConfig.ProxyURL)
assert.Empty(t, resp.WebSearchConfig.APIKey)
require.NotNil(t, resp.ParserEngineConfig)
assert.Equal(t, types.RedactedSecretPlaceholder, resp.ParserEngineConfig.MinerUAPIKey)
require.NotNil(t, resp.StorageEngineConfig.MinIO)
assert.Equal(t, types.RedactedSecretPlaceholder, resp.StorageEngineConfig.MinIO.SecretAccessKey)
}
func TestTenantResponsesCrossTenant_RedactsEvenForOwnerContext(t *testing.T) {
tenant := sampleSecretTenant()
body, err := json.Marshal(NewTenantResponsesCrossTenant([]*types.Tenant{tenant}))
require.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "tenant-api-key-123")
assert.NotContains(t, s, "parser-secret-123")
}
func sampleSecretTenant() *types.Tenant {
return &types.Tenant{
ID: 42,
Name: "tenant",
WebSearchConfig: &types.WebSearchConfig{
APIKey: "legacy-search-secret-999",
ProxyURL: "http://proxy.internal:8080",
},
Credentials: &types.CredentialsConfig{
AcademyCloud: &types.AcademyCloudCredentials{
AppID: "wk-app-id-abc",
AppSecret: "wk-app-secret-def",
},
},
ParserEngineConfig: &types.ParserEngineConfig{
MinerUAPIKey: "parser-secret-123",
PaddleOCRVLCloudToken: "paddle-secret-456",
},
StorageEngineConfig: &types.StorageEngineConfig{
DefaultProvider: "minio",
MinIO: &types.MinIOEngineConfig{
AccessKeyID: "minio-access-id",
SecretAccessKey: "minio-secret-789",
},
},
}
}
+22
View File
@@ -0,0 +1,22 @@
package dto
import (
"context"
"academy/internal/types"
)
func adminContext() context.Context {
ctx := context.Background()
return context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleAdmin)
}
func viewerContext() context.Context {
ctx := context.Background()
return context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
}
func ownerContext() context.Context {
ctx := context.Background()
return context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleOwner)
}
@@ -0,0 +1,74 @@
package dto
import (
"context"
"time"
"academy/internal/types"
)
// WebSearchProviderResponse mirrors types.WebSearchProviderEntity for
// response bodies, with the APIKey field removed by construction. Credential
// presence is exposed via the /credentials subresource.
type WebSearchProviderResponse struct {
ID string `json:"id" extensions:"x-agent=web_search_provider_id"`
TenantID uint64 `json:"tenant_id"`
Name string `json:"name" extensions:"x-agent"`
Provider types.WebSearchProviderType `json:"provider" extensions:"x-agent"`
Description string `json:"description" extensions:"x-agent"`
Parameters WebSearchProviderParametersDTO `json:"parameters"`
IsDefault bool `json:"is_default" extensions:"x-agent"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Per-field "configured?" map. See MCPServiceResponse.Credentials.
Credentials map[string]CredentialFieldMetadata `json:"credentials,omitempty"`
}
// WebSearchProviderParametersDTO holds every parameter field except APIKey.
// EngineID, BaseURL, ProxyURL and ExtraConfig are not secrets (they describe
// where to send the request, not how to authenticate) and remain visible.
type WebSearchProviderParametersDTO struct {
EngineID string `json:"engine_id,omitempty"`
BaseURL string `json:"base_url,omitempty"`
ProxyURL string `json:"proxy_url,omitempty"`
ExtraConfig map[string]string `json:"extra_config,omitempty"`
}
// NewWebSearchProviderResponse converts a stored entity into its response shape.
func NewWebSearchProviderResponse(ctx context.Context, e *types.WebSearchProviderEntity) *WebSearchProviderResponse {
if e == nil {
return nil
}
params := WebSearchProviderParametersDTO{
EngineID: e.Parameters.EngineID,
BaseURL: e.Parameters.BaseURL,
ProxyURL: e.Parameters.ProxyURL,
ExtraConfig: e.Parameters.ExtraConfig,
}
if !CanViewIntegrationSecrets(ctx) {
params.ProxyURL = ""
params.ExtraConfig = nil
}
return &WebSearchProviderResponse{
ID: e.ID,
TenantID: e.TenantID,
Name: e.Name,
Provider: e.Provider,
Description: e.Description,
Parameters: params,
IsDefault: e.IsDefault,
CreatedAt: e.CreatedAt,
UpdatedAt: e.UpdatedAt,
Credentials: map[string]CredentialFieldMetadata{
"api_key": {Configured: e.Parameters.APIKey != ""},
},
}
}
func NewWebSearchProviderResponses(ctx context.Context, es []*types.WebSearchProviderEntity) []*WebSearchProviderResponse {
out := make([]*WebSearchProviderResponse, 0, len(es))
for _, e := range es {
out = append(out, NewWebSearchProviderResponse(ctx, e))
}
return out
}
@@ -0,0 +1,54 @@
package dto
import (
"encoding/json"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
)
func TestWebSearchProviderResponse_OmitsSecrets(t *testing.T) {
e := &types.WebSearchProviderEntity{
ID: "wsp-1",
Name: "bing prod",
Provider: types.WebSearchProviderTypeBing,
Parameters: types.WebSearchProviderParameters{
APIKey: "bing-secret-do-not-leak",
EngineID: "engine-public-id",
BaseURL: "https://example.com",
},
}
body, err := json.Marshal(NewWebSearchProviderResponse(adminContext(), e))
assert.NoError(t, err)
s := string(body)
assert.NotContains(t, s, "bing-secret-do-not-leak")
// Parameters sub-object must contain no secret keys.
var raw map[string]json.RawMessage
assert.NoError(t, json.Unmarshal(body, &raw))
assert.NotContains(t, string(raw["parameters"]), `"api_key"`)
// Credential metadata map exposes booleans only.
assert.Contains(t, s, `"credentials"`)
assert.Contains(t, s, `"api_key":{"configured":true}`)
// Non-secret fields pass through.
assert.Contains(t, s, "engine-public-id")
assert.Contains(t, s, "example.com")
}
func TestWebSearchProviderResponse_ViewerStripsIntegrationDetail(t *testing.T) {
e := &types.WebSearchProviderEntity{
ID: "wsp-2",
Parameters: types.WebSearchProviderParameters{
ProxyURL: "http://proxy:8080",
ExtraConfig: map[string]string{"token": "secret"},
},
}
resp := NewWebSearchProviderResponse(viewerContext(), e)
assert.Empty(t, resp.Parameters.ProxyURL)
assert.Nil(t, resp.Parameters.ExtraConfig)
}
func TestWebSearchProviderResponse_NilSafe(t *testing.T) {
assert.Nil(t, NewWebSearchProviderResponse(adminContext(), nil))
assert.Equal(t, []*WebSearchProviderResponse{}, NewWebSearchProviderResponses(adminContext(), nil))
}
@@ -0,0 +1,30 @@
package handler
import "testing"
func TestValidateEmbedAllowedOrigins(t *testing.T) {
t.Setenv("GIN_MODE", "release")
for _, tc := range []struct {
origins []string
valid bool
}{
{nil, false},
{[]string{" "}, false},
{[]string{"*"}, false},
{[]string{"https://a.example"}, true},
{[]string{"https://a.example/"}, true},
{[]string{"*.example.com:8443"}, true},
{[]string{"https://a.example/path"}, false},
{[]string{"https://a.example?"}, false},
{[]string{"https://user@a.example"}, false},
{[]string{"https://a.example; frame-ancestors *"}, false},
} {
if err := validateAllowedOrigins(tc.origins); (err == nil) != tc.valid {
t.Errorf("%v: %v", tc.origins, err)
}
}
t.Setenv("GIN_MODE", "debug")
if err := validateAllowedOrigins([]string{"*"}); err != nil {
t.Fatal(err)
}
}
+851
View File
@@ -0,0 +1,851 @@
package handler
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"academy/internal/application/service"
"academy/internal/embedpolicy"
apperrors "academy/internal/errors"
"academy/internal/handler/session"
"academy/internal/logger"
"academy/internal/middleware"
"academy/internal/storageurl"
"academy/internal/types"
"academy/internal/types/interfaces"
secutils "academy/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: set SYSTEM_SIGNING_KEY on the server",
})
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
created.OwnerAuthSource = types.AuthSourceForBoundOwnerID(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)
}
// EmbedResolveAgentPrompt answers a prompt raised in the visitor's session.
func (h *EmbedChannelHandler) EmbedResolveAgentPrompt(c *gin.Context) {
if err := h.ensureEmbedSession(c); err != nil {
return
}
if h.mcpServiceHandler == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "agent prompt handler unavailable"})
return
}
h.mcpServiceHandler.ResolveAgentPrompt(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)
}
c.Set(types.PrincipalContextKey.String(), 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.WithPrincipalAuthSource(
types.WithPrincipal(ctx, principal), types.AuthSourceEmbed,
))
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
// 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{}
// 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")
delete(payload, "page_context")
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"})
}
}
@@ -0,0 +1,151 @@
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/application/service"
"academy/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, *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(), types.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(), types.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(), types.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)
}
}
+379
View File
@@ -0,0 +1,379 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/application/service"
"academy/internal/middleware"
"academy/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, *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) 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) GetAcademyCloudCredentials(context.Context) *types.AcademyCloudCredentials {
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","agent_source_tenant_id":84,"web_search_enabled":true,` +
`"knowledge_ids":["doc-x"],"tag_ids":["tag-x"],"mentioned_items":[{"id":"kb-x","type":"kb"}],` +
`"skill_names":["s"],"summary_model_id":"model-x","question_origin":{"knowledge_base_id":"kb-x"},` +
`"page_context":{"knowledge_base_id":"kb-x"}}`
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 _, ok := payload[types.AgentSourceTenantIDParam]; ok {
t.Fatalf("agent_source_tenant_id = %v, want dropped so the channel agent stays local",
payload[types.AgentSourceTenantIDParam])
}
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"])
}
// Explicit targets and a model override would reach any KB or model of
// the channel workspace by ID.
for _, key := range []string{"knowledge_ids", "tag_ids", "mentioned_items", "skill_names"} {
if values, ok := payload[key].([]any); !ok || len(values) != 0 {
t.Fatalf("%s = %v, want empty", key, payload[key])
}
}
for _, key := range []string{"summary_model_id", "question_origin", "page_context"} {
if _, ok := payload[key]; ok {
t.Fatalf("%s = %v, want dropped", key, payload[key])
}
}
}
func TestPatchEmbedChatPayloadWebSearchRequiresClientOptIn(t *testing.T) {
ch := &types.EmbedChannel{AgentID: "agent-1", AllowWebSearch: true}
body := `{"query":"hello","web_search_enabled":false}`
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"])
}
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 TestPatchEmbedChatPayloadStripsAttachmentsWhenUploadDisabled(t *testing.T) {
ch := &types.EmbedChannel{AgentID: "agent-1", AllowFileUpload: false}
body := `{"query":"hello","images":[{"data":"x"}],"attachment_uploads":[{"file_name":"a.pdf"}],"attachment_ids":["doc-1"]}`
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)
}
for _, key := range []string{"images", "attachment_uploads", "attachment_ids"} {
if _, ok := payload[key]; ok {
t.Fatalf("%s should be stripped when allow_file_upload is false, got %v", key, payload[key])
}
}
}
func TestPatchEmbedChatPayloadKeepsAttachmentIDsWhenUploadAllowed(t *testing.T) {
ch := &types.EmbedChannel{AgentID: "agent-1", AllowFileUpload: true}
body := `{"query":"hello","attachment_ids":["doc-1","doc-2"]}`
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)
}
ids, ok := payload["attachment_ids"].([]any)
if !ok || len(ids) != 2 {
t.Fatalf("attachment_ids = %v, want preserved when upload allowed", payload["attachment_ids"])
}
}
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 }
func (f *flowTenantSvc) UpdateTenantProfile(context.Context, uint64, *string, *string) (*types.Tenant, error) {
panic("unexpected UpdateTenantProfile call")
}
@@ -0,0 +1,87 @@
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"
"academy/internal/application/service"
"academy/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(), types.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) {
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("SYSTEM_AES_KEY", "test-embed-signing-key-32-bytes!!!")
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("SYSTEM_SIGNING_KEY", "")
t.Setenv("SYSTEM_AES_KEY", "test-embed-signing-key-32-bytes!!!")
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")
}
+419
View File
@@ -0,0 +1,419 @@
package handler
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/application/service"
"academy/internal/handler/session"
"academy/internal/types"
"academy/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) GetSessionByID(_ context.Context, tenantID uint64, id string) (*types.Session, error) {
sess, ok := s.sessions[id]
if !ok || sess.TenantID != tenantID {
return nil, errors.New("session not found")
}
return sess, nil
}
func (s *stubSessionServiceForEmbed) SetSessionOwnerID(_ context.Context, tenantID uint64, sessionID, ownerID string) error {
sess, ok := s.sessions[sessionID]
if !ok || sess.TenantID != tenantID {
return errors.New("session not found")
}
sess.UserID = ownerID
sess.OwnerAuthSource = types.AuthSourceForBoundOwnerID(ownerID)
return 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, *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(), types.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
return c, w
}
func TestEnsureEmbedSessionValid(t *testing.T) {
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("SYSTEM_AES_KEY", "test-embed-signing-key-32-bytes!!!")
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) {
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("SYSTEM_AES_KEY", "test-embed-signing-key-32-bytes!!!")
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.StatusNotFound {
t.Fatalf("status = %d, want %d, body = %s", w.Code, http.StatusNotFound, w.Body.String())
}
}
func TestEnsureEmbedSessionWrongDescription(t *testing.T) {
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("SYSTEM_AES_KEY", "test-embed-signing-key-32-bytes!!!")
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) {
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("SYSTEM_AES_KEY", "test-embed-signing-key-32-bytes!!!")
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) {
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("SYSTEM_AES_KEY", "test-embed-signing-key-32-bytes!!!")
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) {
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("SYSTEM_AES_KEY", "test-embed-signing-key-32-bytes!!!")
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(), types.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) {
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("SYSTEM_AES_KEY", "test-embed-signing-key-32-bytes!!!")
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(), types.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) {
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("SYSTEM_AES_KEY", "test-embed-signing-key-32-bytes!!!")
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(), types.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(), types.EmbedChannelContextKey, ch)
c.Request = c.Request.WithContext(ctx)
return c, w
}
func TestEmbedStopSessionInvalidSig(t *testing.T) {
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("SYSTEM_AES_KEY", "test-embed-signing-key-32-bytes!!!")
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) {
t.Setenv("SYSTEM_SIGNING_KEY", "")
t.Setenv("SYSTEM_AES_KEY", "test-embed-signing-key-32-bytes!!!")
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())
}
}
+131
View File
@@ -0,0 +1,131 @@
package handler
import (
"net/http"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
secutils "academy/internal/utils"
"github.com/gin-gonic/gin"
)
// EvaluationHandler handles evaluation related HTTP requests
type EvaluationHandler struct {
evaluationService interfaces.EvaluationService // Service for evaluation operations
}
// NewEvaluationHandler creates a new EvaluationHandler instance
func NewEvaluationHandler(evaluationService interfaces.EvaluationService) *EvaluationHandler {
return &EvaluationHandler{evaluationService: evaluationService}
}
// EvaluationRequest contains parameters for evaluation request
type EvaluationRequest struct {
DatasetID string `json:"dataset_id"` // ID of dataset to evaluate
KnowledgeBaseID string `json:"knowledge_base_id"` // ID of knowledge base to use
ChatModelID string `json:"chat_id"` // ID of chat model to use
RerankModelID string `json:"rerank_id"` // ID of rerank model to use
}
// Evaluation godoc
// @Summary 执行评估
// @Description 对知识库进行评估测试
// @Tags 评估
// @Accept json
// @Produce json
// @Param request body EvaluationRequest true "评估请求参数"
// @Success 200 {object} handler.DataResponse{data=types.EvaluationDetail} "评估任务"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /evaluation/ [post]
func (e *EvaluationHandler) Evaluation(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start processing evaluation request")
var request EvaluationRequest
if err := c.ShouldBind(&request); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
return
}
tenantID, exists := c.Get(string(types.TenantIDContextKey))
if !exists {
logger.Error(ctx, "Failed to get tenant ID")
c.Error(errors.NewUnauthorizedError("Unauthorized"))
return
}
logger.Infof(ctx, "Executing evaluation, tenant: %v, dataset: %s, knowledge_base: %s, chat: %s, rerank: %s",
tenantID,
secutils.SanitizeForLog(request.DatasetID),
secutils.SanitizeForLog(request.KnowledgeBaseID),
secutils.SanitizeForLog(request.ChatModelID),
secutils.SanitizeForLog(request.RerankModelID),
)
task, err := e.evaluationService.Evaluation(ctx,
secutils.SanitizeForLog(request.DatasetID),
secutils.SanitizeForLog(request.KnowledgeBaseID),
secutils.SanitizeForLog(request.ChatModelID),
secutils.SanitizeForLog(request.RerankModelID),
)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Infof(ctx, "Evaluation task created successfully")
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": task,
})
}
// GetEvaluationRequest contains parameters for getting evaluation result
type GetEvaluationRequest struct {
TaskID string `form:"task_id" binding:"required"` // ID of evaluation task
}
// GetEvaluationResult godoc
// @Summary 获取评估结果
// @Description 根据任务ID获取评估结果
// @Tags 评估
// @Accept json
// @Produce json
// @Param task_id query string true "评估任务ID"
// @Success 200 {object} handler.DataResponse{data=types.EvaluationDetail} "评估结果"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /evaluation/ [get]
func (e *EvaluationHandler) GetEvaluationResult(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start retrieving evaluation result")
var request GetEvaluationRequest
if err := c.ShouldBind(&request); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewBadRequestError("Invalid request parameters").WithDetails(err.Error()))
return
}
result, err := e.evaluationService.EvaluationResult(ctx, secutils.SanitizeForLog(request.TaskID))
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
logger.Info(ctx, "Retrieved evaluation result successfully")
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": result,
})
}
+620
View File
@@ -0,0 +1,620 @@
package handler
import (
"net/http"
"strconv"
"strings"
"github.com/gin-gonic/gin"
"academy/internal/errors"
"academy/internal/logger"
"academy/internal/types"
"academy/internal/types/interfaces"
secutils "academy/internal/utils"
)
// FAQHandler handles FAQ knowledge base operations.
//
// All KB-access checks (own / org-shared / via shared agent) are now
// performed by the route-level g.KBAccessRead / g.KBAccessWrite
// guards in router.go — the guard rewrites c.Request.Context() to
// carry the effective tenant ID for the duration of the handler, so
// the handler reads tenant from context the way it always did.
type FAQHandler struct {
knowledgeService interfaces.KnowledgeService
kbService interfaces.KnowledgeBaseService
}
// NewFAQHandler creates a new FAQ handler.
func NewFAQHandler(
knowledgeService interfaces.KnowledgeService,
kbService interfaces.KnowledgeBaseService,
) *FAQHandler {
return &FAQHandler{
knowledgeService: knowledgeService,
kbService: kbService,
}
}
// faqDeleteRequest is a request for deleting FAQ entries in batch
type faqDeleteRequest struct {
// Entries to delete (entry_id).
IDs []int64 `json:"ids" binding:"required,min=1" extensions:"x-agent=entry_ids,x-agent-maximum=20"`
}
// faqEntryTagBatchRequest is a request for updating tags for FAQ entries in batch
// key: entry seq_id, value: tag seq_id (nil to remove tag)
type faqEntryTagBatchRequest struct {
Updates map[int64]*int64 `json:"updates" binding:"required,min=1"`
}
// addSimilarQuestionsRequest is a request for adding similar questions to a FAQ entry
type addSimilarQuestionsRequest struct {
// Phrasings to add to the entry.
SimilarQuestions []string `json:"similar_questions" binding:"required,min=1" extensions:"x-agent"`
}
// updateLastFAQImportResultDisplayStatusRequest is the request payload for UpdateLastImportResultDisplayStatus
type updateLastFAQImportResultDisplayStatusRequest struct {
DisplayStatus string `json:"display_status" binding:"required,oneof=open close"`
}
// ListEntries godoc
// @Summary 获取FAQ条目列表
// @Description 获取知识库下的FAQ条目列表,支持分页和筛选
// @Tags FAQ管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID" extensions(x-agent=knowledge_base_id)
// @Param page query int false "页码" minimum(1) extensions(x-agent,x-agent-maximum=10000)
// @Param page_size query int false "每页数量" minimum(1) maximum(1000) extensions(x-agent,x-agent-maximum=50)
// @Param tag_id query int false "标签ID筛选(seq_id),兼容旧版单标签"
// @Param tag_ids query string false "标签UUID筛选,逗号分隔(OR语义)" extensions(x-agent)
// @Param keyword query string false "关键词搜索" extensions(x-agent)
// @Param search_field query string false "搜索字段,默认搜索全部" Enums(standard_question,similar_questions,answers) extensions(x-agent)
// @Param sort_order query string false "排序方式: asc(按更新时间正序), 默认按更新时间倒序" Enums(asc) extensions(x-agent)
// @Param is_enabled query bool false "启用状态筛选;不传时返回全部" extensions(x-agent)
// @Success 200 {object} handler.DataResponse{data=handler.FAQEntryPage} "FAQ列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @x-agent {"id":"faq.list_entries","risk":"read","root":"data.data"}
// @x-agent-hint "FAQ entries of an FAQ knowledge base, newest first; keyword searches questions and answers."
// @Router /knowledge-bases/{id}/faq/entries [get]
func (h *FAQHandler) ListEntries(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
var page types.Pagination
if err := c.ShouldBindQuery(&page); err != nil {
logger.Error(ctx, "Failed to bind pagination query", err)
c.Error(errors.NewBadRequestError("分页参数不合法").WithDetails(err.Error()))
return
}
tagUUIDs := parseCommaSeparatedTagIDs(c.Query("tag_ids"))
var legacyTagSeqID int64
tagIDStr := c.Query("tag_id")
if tagIDStr != "" {
var err error
legacyTagSeqID, err = strconv.ParseInt(tagIDStr, 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("tag_id 必须是整数"))
return
}
}
keyword := secutils.SanitizeForLog(c.Query("keyword"))
searchField := secutils.SanitizeForLog(c.Query("search_field"))
sortOrder := secutils.SanitizeForLog(c.Query("sort_order"))
isEnabled, err := parseOptionalFAQEnabled(c)
if err != nil {
c.Error(err)
return
}
result, err := h.knowledgeService.ListFAQEntries(ctx, kbID, &page, tagUUIDs, legacyTagSeqID, keyword, searchField, sortOrder, isEnabled)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": result,
})
}
// parseOptionalFAQEnabled preserves the distinction between an omitted filter
// and an explicit false value so the management endpoint remains backward compatible.
func parseOptionalFAQEnabled(c *gin.Context) (*bool, error) {
raw, exists := c.GetQuery("is_enabled")
if !exists {
return nil, nil
}
var value bool
switch strings.ToLower(strings.TrimSpace(raw)) {
case "true":
value = true
case "false":
value = false
default:
return nil, errors.NewBadRequestError("is_enabled must be true or false")
}
return &value, nil
}
// UpsertEntries godoc
// @Summary 批量更新/插入FAQ条目
// @Description 异步批量更新或插入FAQ条目。支持 dry_run 模式(设置 dry_run=true),异步验证不实际导入。
// @Description dry_run 模式是异步操作,返回 task_id,通过 /faq/import/progress/{task_id} 查询进度和结果。
// @Description 验证内容包括:1) 条目基本格式 2) 重复问题(批次内和知识库已有) 3) 内容安全检查。
// @Tags FAQ管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Param request body types.FAQBatchUpsertPayload true "批量操作请求"
// @Success 200 {object} handler.DataResponse{data=handler.TaskIDData} "任务ID"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/faq/entries [post]
func (h *FAQHandler) UpsertEntries(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
var req types.FAQBatchUpsertPayload
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ upsert payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
taskID, err := h.knowledgeService.UpsertFAQEntries(ctx, kbID, &req)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"task_id": taskID,
},
})
}
// CreateEntry godoc
// @Summary 创建单个FAQ条目
// @Description 同步创建单个FAQ条目
// @Tags FAQ管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID" extensions(x-agent=knowledge_base_id)
// @Param request body types.FAQEntryPayload true "FAQ条目"
// @Success 200 {object} handler.DataResponse{data=types.FAQEntry} "创建的FAQ条目"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @x-agent {"id":"faq.create_entry","risk":"write","target":"knowledge_base.get","label":"name"}
// @x-agent-hint "Adds one FAQ entry. Questions already used by another entry are refused."
// @Router /knowledge-bases/{id}/faq/entry [post]
func (h *FAQHandler) CreateEntry(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
var req types.FAQEntryPayload
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ entry payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
entry, err := h.knowledgeService.CreateFAQEntry(ctx, kbID, &req)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": entry,
})
}
// UpdateEntry godoc
// @Summary 更新FAQ条目
// @Description 更新指定的FAQ条目
// @Tags FAQ管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID" extensions(x-agent=knowledge_base_id)
// @Param entry_id path int true "FAQ条目ID(seq_id)" extensions(x-agent)
// @Param request body types.FAQEntryPayload true "FAQ条目"
// @Success 200 {object} handler.DataResponse{data=types.FAQEntry} "更新成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @x-agent {"id":"faq.update_entry","risk":"write","require_complete_target":true,"target":"faq.get_entry","label":"standard_question"}
// @x-agent-hint "Replaces the whole entry. Read it with faq.get_entry first and send every field, changed or not, or the rest is lost. Updates are refused if the current entry is truncated; use the FAQ editor for entries beyond the complete-read limits. To only add phrasings, use faq.add_similar_questions."
// @Router /knowledge-bases/{id}/faq/entries/{entry_id} [put]
func (h *FAQHandler) UpdateEntry(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
var req types.FAQEntryPayload
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ entry payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
entrySeqID, err := strconv.ParseInt(c.Param("entry_id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("entry_id 必须是整数"))
return
}
entry, err := h.knowledgeService.UpdateFAQEntry(ctx, kbID, entrySeqID, &req)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": entry,
})
}
// UpdateEntryTagBatch godoc
// @Summary 批量更新FAQ标签
// @Description 批量更新FAQ条目的标签
// @Tags FAQ管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Param request body object true "标签更新请求"
// @Success 200 {object} handler.SuccessResponse "更新成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/faq/entries/tags [put]
func (h *FAQHandler) UpdateEntryTagBatch(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
var req faqEntryTagBatchRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ entry tag batch payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if err := h.knowledgeService.UpdateFAQEntryTagBatch(ctx, kbID, req.Updates); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
})
}
// UpdateEntryFieldsBatch godoc
// @Summary 批量更新FAQ字段
// @Description 批量更新FAQ条目的多个字段(is_enabled, is_recommended, tag_id)
// @Tags FAQ管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Param request body types.FAQEntryFieldsBatchUpdate true "字段更新请求"
// @Success 200 {object} handler.SuccessResponse "更新成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/faq/entries/fields [put]
func (h *FAQHandler) UpdateEntryFieldsBatch(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
var req types.FAQEntryFieldsBatchUpdate
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ entry fields batch payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if err := h.knowledgeService.UpdateFAQEntryFieldsBatch(ctx, kbID, &req); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
})
}
// DeleteEntries godoc
// @Summary 批量删除FAQ条目
// @Description 批量删除指定的FAQ条目
// @Tags FAQ管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID" extensions(x-agent=knowledge_base_id)
// @Param request body faqDeleteRequest true "要删除的FAQ ID列表(seq_id)"
// @Success 200 {object} handler.SuccessResponse "删除成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @x-agent {"id":"faq.delete_entries","risk":"destructive","target":"knowledge_base.get","label":"name","items":{"param":"entry_ids","target":"faq.get_entry","as":"entry_id","label":"standard_question"}}
// @x-agent-hint "Removes up to 20 FAQ entries. Cannot be undone; the confirmation lists every question."
// @Router /knowledge-bases/{id}/faq/entries [delete]
func (h *FAQHandler) DeleteEntries(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
var req faqDeleteRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Errorf(ctx, "Failed to bind FAQ delete payload: %s", secutils.SanitizeForLog(err.Error()))
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if err := h.knowledgeService.DeleteFAQEntries(ctx, kbID, req.IDs); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
})
}
// SearchFAQ godoc
// @Summary 搜索FAQ
// @Description 使用混合搜索在FAQ中搜索,支持两级优先级标签召回:first_priority_tag_ids优先级最高,second_priority_tag_ids次之
// @Tags FAQ管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Param request body types.FAQSearchRequest true "搜索请求"
// @Success 200 {object} handler.DataResponse{data=[]types.FAQEntry} "搜索结果"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/faq/search [post]
func (h *FAQHandler) SearchFAQ(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
var req types.FAQSearchRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind FAQ search payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
req.QueryText = secutils.SanitizeForLog(req.QueryText)
if req.MatchCount <= 0 {
req.MatchCount = 10
}
if req.MatchCount > 200 {
req.MatchCount = 200
}
entries, err := h.knowledgeService.SearchFAQEntries(ctx, kbID, &req)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": entries,
})
}
// ExportEntries godoc
// @Summary 导出FAQ条目
// @Description 将所有FAQ条目导出为 CSV(默认)或 JSON。?format=json 返回与 FAQEntryPayload 结构兼容的数组。
// @Tags FAQ管理
// @Accept json
// @Produce text/csv
// @Produce application/json
// @Param id path string true "知识库ID"
// @Param format query string false "导出格式:csv(默认)或 json"
// @Success 200 {file} file "导出文件"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/faq/entries/export [get]
func (h *FAQHandler) ExportEntries(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
format := strings.ToLower(strings.TrimSpace(c.Query("format")))
if format == "json" {
jsonData, err := h.knowledgeService.ExportFAQEntriesJSON(ctx, kbID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.Header("Content-Type", "application/json; charset=utf-8")
c.Header("Content-Disposition", "attachment; filename=faq_export.json")
c.Data(http.StatusOK, "application/json; charset=utf-8", jsonData)
return
}
csvData, err := h.knowledgeService.ExportFAQEntries(ctx, kbID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
// Set response headers for CSV download
c.Header("Content-Type", "text/csv; charset=utf-8")
c.Header("Content-Disposition", "attachment; filename=faq_export.csv")
// Add BOM for Excel compatibility with UTF-8
bom := []byte{0xEF, 0xBB, 0xBF}
c.Data(http.StatusOK, "text/csv; charset=utf-8", append(bom, csvData...))
}
// GetEntry godoc
// @Summary 获取FAQ条目详情
// @Description 根据ID获取单个FAQ条目的详情
// @Tags FAQ管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID" extensions(x-agent=knowledge_base_id)
// @Param entry_id path int true "FAQ条目ID(seq_id)" extensions(x-agent)
// @Success 200 {object} handler.DataResponse{data=types.FAQEntry} "FAQ条目详情"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "条目不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @x-agent {"id":"faq.get_entry","risk":"read"}
// @Router /knowledge-bases/{id}/faq/entries/{entry_id} [get]
func (h *FAQHandler) GetEntry(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
entrySeqID, err := strconv.ParseInt(c.Param("entry_id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("entry_id 必须是整数"))
return
}
entry, err := h.knowledgeService.GetFAQEntry(ctx, kbID, entrySeqID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": entry,
})
}
// GetImportProgress godoc
// @Summary 获取FAQ导入进度
// @Description 获取FAQ导入任务的进度
// @Tags FAQ管理
// @Accept json
// @Produce json
// @Param task_id path string true "任务ID"
// @Success 200 {object} handler.DataResponse{data=types.FAQImportProgress} "导入进度"
// @Failure 404 {object} errors.AppError "任务不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /faq/import/progress/{task_id} [get]
func (h *FAQHandler) GetImportProgress(c *gin.Context) {
ctx := c.Request.Context()
taskID := secutils.SanitizeForLog(c.Param("task_id"))
if err := requireTaskProgressTenant(ctx, taskID); err != nil {
c.Error(err)
return
}
progress, err := h.knowledgeService.GetFAQImportProgress(ctx, taskID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": progress,
})
}
// UpdateLastImportResultDisplayStatus godoc
// @Summary 更新FAQ最后一次导入结果显示状态
// @Description 更新FAQ知识库导入结果统计卡片的显示或隐藏状态
// @Tags FAQ管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Param request body updateLastFAQImportResultDisplayStatusRequest true "状态更新请求"
// @Success 200 {object} handler.SuccessResponse "更新成功"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "知识库不存在或无导入记录"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/faq/import/last-result/display [put]
func (h *FAQHandler) UpdateLastImportResultDisplayStatus(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
var req updateLastFAQImportResultDisplayStatusRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind display status update payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
if err := h.knowledgeService.UpdateLastFAQImportResultDisplayStatus(ctx, kbID, req.DisplayStatus); err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
})
}
// AddSimilarQuestions godoc
// @Summary 添加相似问
// @Description 向指定的FAQ条目添加相似问题
// @Tags FAQ管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID" extensions(x-agent=knowledge_base_id)
// @Param entry_id path int true "FAQ条目ID(seq_id)" extensions(x-agent)
// @Param request body addSimilarQuestionsRequest true "相似问列表"
// @Success 200 {object} handler.DataResponse{data=types.FAQEntry} "更新后的FAQ条目"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 404 {object} errors.AppError "条目不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @x-agent {"id":"faq.add_similar_questions","risk":"write","target":"faq.get_entry","label":"standard_question"}
// @x-agent-hint "Adds phrasings to an entry and keeps everything else."
// @Router /knowledge-bases/{id}/faq/entries/{entry_id}/similar-questions [post]
func (h *FAQHandler) AddSimilarQuestions(c *gin.Context) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("id"))
entrySeqID, err := strconv.ParseInt(c.Param("entry_id"), 10, 64)
if err != nil {
c.Error(errors.NewBadRequestError("entry_id 必须是整数"))
return
}
var req addSimilarQuestionsRequest
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to bind add similar questions payload", err)
c.Error(errors.NewBadRequestError("请求参数不合法").WithDetails(err.Error()))
return
}
entry, err := h.knowledgeService.AddSimilarQuestions(ctx, kbID, entrySeqID, req.SimilarQuestions)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": entry,
})
}
+82
View File
@@ -0,0 +1,82 @@
package handler
import (
"net/http"
"academy/internal/errors"
"academy/internal/types"
"github.com/gin-gonic/gin"
)
// FAQBatchPatchRequest applies the same partial change to a bounded list of entries.
// Unlike the legacy map-based endpoint, this shape also fits the operation catalog.
type FAQBatchPatchRequest struct {
// Explicit FAQ entry seq_ids from faq.list_entries. At most 20 per call.
EntryIDs []int64 `json:"entry_ids" binding:"required,min=1,max=20" extensions:"x-agent,x-agent-maximum=20"`
// Whether these entries can be retrieved; omitted keeps the current state.
IsEnabled *bool `json:"is_enabled,omitempty" extensions:"x-agent"`
// Whether these entries are recommended; omitted keeps the current state.
IsRecommended *bool `json:"is_recommended,omitempty" extensions:"x-agent"`
// Tag seq_id from knowledge_base.list_tags; 0 clears tags, omitted keeps them.
TagID *int64 `json:"tag_id,omitempty" extensions:"x-agent=tag_seq_id" minimum:"0"`
}
func (req FAQBatchPatchRequest) updatePlan() (*types.FAQEntryFieldsBatchUpdate, error) {
if len(req.EntryIDs) == 0 || len(req.EntryIDs) > 20 {
return nil, errors.NewBadRequestError("entry_ids must contain 1-20 entries")
}
if req.IsEnabled == nil && req.IsRecommended == nil && req.TagID == nil {
return nil, errors.NewBadRequestError("at least one field must be provided")
}
if req.TagID != nil && *req.TagID < 0 {
return nil, errors.NewBadRequestError("tag_id must be non-negative; use 0 to clear tags")
}
plan := &types.FAQEntryFieldsBatchUpdate{ByID: make(map[int64]types.FAQEntryFieldsUpdate, len(req.EntryIDs))}
for _, id := range req.EntryIDs {
if id <= 0 {
return nil, errors.NewBadRequestError("entry_ids must be positive seq_ids")
}
if _, ok := plan.ByID[id]; ok {
return nil, errors.NewBadRequestError("entry_ids must not contain duplicates")
}
plan.ByID[id] = types.FAQEntryFieldsUpdate{
IsEnabled: req.IsEnabled,
IsRecommended: req.IsRecommended,
TagID: req.TagID,
}
}
return plan, nil
}
// PatchEntriesBatch godoc
// @Summary 批量修改 FAQ 状态和标签
// @Description 对明确指定的 FAQ 条目应用相同的部分更新,保留问题、答案及未指定字段
// @Tags FAQ管理
// @Accept json
// @Produce json
// @Param id path string true "知识库ID" extensions(x-agent=knowledge_base_id)
// @Param request body FAQBatchPatchRequest true "批量修改请求"
// @Success 200 {object} handler.SuccessResponse
// @Failure 400 {object} errors.AppError
// @Security Bearer
// @Security ApiKeyAuth
// @x-agent {"id":"faq.batch_update","risk":"write","target":"knowledge_base.get","label":"name","items":{"param":"entry_ids","target":"faq.get_entry","as":"entry_id","label":"standard_question"}}
// @x-agent-hint "Set is_enabled, is_recommended or tag_seq_id for 1-20 explicit FAQ entry seq_ids; at least one field is required. Omitted fields and all questions/answers stay unchanged. tag_seq_id comes from knowledge_base.list_tags (tag_seq_id); 0 removes the tag. Select entries with faq.list_entries first; for a whole tag or knowledge base paginate the list and process batches of up to 20. Confirmation lists every question."
// @Router /knowledge-bases/{id}/faq/entries [patch]
func (h *FAQHandler) PatchEntriesBatch(c *gin.Context) {
var req FAQBatchPatchRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("Invalid FAQ batch patch").WithDetails(err.Error()))
return
}
plan, err := req.updatePlan()
if err != nil {
_ = c.Error(err)
return
}
if err := h.knowledgeService.UpdateFAQEntryFieldsBatch(c.Request.Context(), c.Param("id"), plan); err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
+99
View File
@@ -0,0 +1,99 @@
package handler
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/errors"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type faqBatchService struct {
interfaces.KnowledgeService
kbID string
plan *types.FAQEntryFieldsBatchUpdate
err error
}
func (s *faqBatchService) UpdateFAQEntryFieldsBatch(
_ context.Context,
kb string,
p *types.FAQEntryFieldsBatchUpdate,
) error {
s.kbID = kb
s.plan = p
return s.err
}
func runFAQBatchPatch(body string, s *faqBatchService) (*gin.Context, *httptest.ResponseRecorder) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPatch, "/knowledge-bases/kb1/faq/entries", strings.NewReader(body))
c.Request.Header.Set("Content-Type", "application/json")
c.Params = gin.Params{{Key: "id", Value: "kb1"}}
(&FAQHandler{knowledgeService: s}).PatchEntriesBatch(c)
return c, w
}
func TestFAQBatchPatchPreservesOmittedFieldsAndExplicitFalse(t *testing.T) {
for _, body := range []string{
`{"entry_ids":[1,2],"is_enabled":false}`,
`{"entry_ids":[1,2],"is_recommended":false,"tag_id":0}`,
} {
s := &faqBatchService{}
c, w := runFAQBatchPatch(body, s)
require.Empty(t, c.Errors)
assert.Equal(t, 200, w.Code)
assert.Equal(t, "kb1", s.kbID)
require.Len(t, s.plan.ByID, 2)
assert.Empty(t, s.plan.ByTag)
for _, p := range s.plan.ByID {
if strings.Contains(body, "is_enabled") {
require.NotNil(t, p.IsEnabled)
assert.False(t, *p.IsEnabled)
assert.Nil(t, p.IsRecommended)
assert.Nil(t, p.TagID)
} else {
assert.Nil(t, p.IsEnabled)
require.NotNil(t, p.IsRecommended)
assert.False(t, *p.IsRecommended)
require.NotNil(t, p.TagID)
assert.Zero(t, *p.TagID)
}
}
}
}
func TestFAQBatchPatchRejectsInvalidSelectionWithoutDispatch(t *testing.T) {
ids := make([]string, 21)
for i := range ids {
ids[i] = fmt.Sprint(i + 1)
}
for _, body := range []string{
`{"entry_ids":[],"is_enabled":false}`, `{"entry_ids":[1]}`, `{"entry_ids":[1],"is_enabled":null}`,
`{"entry_ids":[0],"is_enabled":false}`, `{"entry_ids":[1,1],"is_enabled":false}`,
`{"entry_ids":[1],"tag_id":-1}`, `{"entry_ids":[` + strings.Join(ids, ",") + `],"is_enabled":false}`,
} {
s := &faqBatchService{}
c, _ := runFAQBatchPatch(body, s)
require.NotEmpty(t, c.Errors, body)
assert.Nil(t, s.plan, body)
}
}
func TestFAQBatchPatchPropagatesAccessFailure(t *testing.T) {
s := &faqBatchService{err: errors.NewForbiddenError("entry belongs to another knowledge base")}
c, w := runFAQBatchPatch(`{"entry_ids":[1],"is_enabled":false}`, s)
require.NotEmpty(t, c.Errors)
assert.NotContains(t, w.Body.String(), `"success":true`)
assert.Contains(t, c.Errors.Last().Error(), "another knowledge base")
}
+137
View File
@@ -0,0 +1,137 @@
package handler
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
type faqListKnowledgeServiceStub struct {
interfaces.KnowledgeService
callCount int
isEnabled *bool
}
func (s *faqListKnowledgeServiceStub) ListFAQEntries(
_ context.Context,
_ string,
page *types.Pagination,
_ []string,
_ int64,
_ string,
_ string,
_ string,
isEnabled *bool,
) (*types.PageResult, error) {
s.callCount++
s.isEnabled = isEnabled
return types.NewPageResult(0, page, []*types.FAQEntry{}), nil
}
func TestParseOptionalFAQEnabled(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name string
query string
want bool
wantValue bool
wantError bool
}{
{name: "omitted"},
{name: "enabled", query: "?is_enabled=true", want: true, wantValue: true},
{name: "disabled", query: "?is_enabled=false", want: true},
{name: "case insensitive", query: "?is_enabled=TRUE", want: true, wantValue: true},
{name: "invalid", query: "?is_enabled=invalid", wantError: true},
{name: "numeric", query: "?is_enabled=1", wantError: true},
{name: "empty", query: "?is_enabled=", wantError: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
context, _ := gin.CreateTestContext(httptest.NewRecorder())
context.Request = httptest.NewRequest("GET", "/faq/entries"+tt.query, nil)
value, err := parseOptionalFAQEnabled(context)
if (err != nil) != tt.wantError {
t.Fatalf("error = %v, wantError %v", err, tt.wantError)
}
if tt.wantError {
return
}
if (value != nil) != tt.want {
t.Fatalf("value presence = %v, want %v", value != nil, tt.want)
}
if value != nil && *value != tt.wantValue {
t.Fatalf("value = %v, want %v", *value, tt.wantValue)
}
})
}
}
func TestFAQListEntriesPassesEnabledFilter(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name string
query string
want bool
wantValue bool
}{
{name: "all entries"},
{name: "enabled entries", query: "?is_enabled=true", want: true, wantValue: true},
{name: "disabled entries", query: "?is_enabled=false", want: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
service := &faqListKnowledgeServiceStub{}
handler := &FAQHandler{knowledgeService: service}
context, _ := gin.CreateTestContext(httptest.NewRecorder())
context.Params = gin.Params{{Key: "id", Value: "kb-1"}}
context.Request = httptest.NewRequest("GET", "/faq/entries"+tt.query, nil)
handler.ListEntries(context)
if len(context.Errors) != 0 {
t.Fatalf("unexpected errors: %v", context.Errors)
}
if service.callCount != 1 {
t.Fatalf("service call count = %d, want 1", service.callCount)
}
if (service.isEnabled != nil) != tt.want {
t.Fatalf("filter presence = %v, want %v", service.isEnabled != nil, tt.want)
}
if service.isEnabled != nil && *service.isEnabled != tt.wantValue {
t.Fatalf("filter = %v, want %v", *service.isEnabled, tt.wantValue)
}
})
}
}
func TestFAQListEntriesRejectsInvalidEnabledFilter(t *testing.T) {
gin.SetMode(gin.TestMode)
service := &faqListKnowledgeServiceStub{}
handler := &FAQHandler{knowledgeService: service}
router := gin.New()
router.Use(middleware.ErrorHandler())
router.GET("/knowledge-bases/:id/faq/entries", handler.ListEntries)
recorder := httptest.NewRecorder()
request := httptest.NewRequest("GET", "/knowledge-bases/kb-1/faq/entries?is_enabled=invalid", nil)
router.ServeHTTP(recorder, request)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", recorder.Code, http.StatusBadRequest)
}
if service.callCount != 0 {
t.Fatalf("service call count = %d, want 0", service.callCount)
}
}
+75
View File
@@ -0,0 +1,75 @@
package handler
import (
"encoding/json"
"io"
"net/http"
apperrors "academy/internal/errors"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// GraphSearchHandler exposes a read-only JSON view of one authorized KB graph.
type GraphSearchHandler struct {
kbHandler *KnowledgeBaseHandler
service interfaces.GraphSearchService
}
// NewGraphSearchHandler reuses the standard KB access resolver.
func NewGraphSearchHandler(kbHandler *KnowledgeBaseHandler, service interfaces.GraphSearchService) *GraphSearchHandler {
return &GraphSearchHandler{kbHandler: kbHandler, service: service}
}
// Search godoc
// @Summary 查询知识图谱
// @Description 对单个授权知识库按实体名进行区分大小写的子串查询,返回实体、定向关系及仍然有效的来源分块。不调用模型,不影响默认检索。0 表示使用默认上限。
// @Tags 知识库
// @Accept json
// @Produce json
// @Param id path string true "知识库ID"
// @Param agent_id query string false "共享智能体 ID"
// @Param agent_source_tenant_id query integer false "共享智能体来源空间"
// @Param request body types.GraphSearchRequest true "查询及结果上限"
// @Success 200 {object} handler.DataResponse{data=types.GraphSearchResult}
// @Failure 400 {object} apperrors.AppError "参数错误"
// @Failure 401 {object} apperrors.AppError "未登录"
// @Failure 403 {object} apperrors.AppError "无权访问知识库"
// @Failure 404 {object} apperrors.AppError "知识库不存在"
// @Failure 409 {object} apperrors.AppError "知识图谱未启用"
// @Failure 500 {object} apperrors.AppError "来源校验失败"
// @Failure 503 {object} apperrors.AppError "图谱服务不可用"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/graph-search [post]
func (h *GraphSearchHandler) Search(c *gin.Context) {
kb, _, _, _, err := h.kbHandler.validateAndGetKnowledgeBase(c)
if err != nil {
_ = c.Error(err)
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 8<<10)
decoder := json.NewDecoder(c.Request.Body)
decoder.DisallowUnknownFields()
var req types.GraphSearchRequest
if err := decoder.Decode(&req); err != nil {
_ = c.Error(apperrors.NewBadRequestError("Invalid graph query request"))
return
}
// Reject trailing JSON rather than silently executing only the first query.
if err := decoder.Decode(new(any)); err != io.EOF {
_ = c.Error(apperrors.NewBadRequestError("Expected one graph query object"))
return
}
if err := req.Normalize(); err != nil {
_ = c.Error(apperrors.NewBadRequestError(err.Error()))
return
}
result, err := h.service.Search(c.Request.Context(), kb, req)
if err != nil {
_ = c.Error(err)
return
}
c.JSON(http.StatusOK, gin.H{"success": true, "data": result})
}
+198
View File
@@ -0,0 +1,198 @@
package handler
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/application/access"
"academy/internal/application/repository"
apperrors "academy/internal/errors"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type graphSearchHandlerServiceStub struct {
calls int
req types.GraphSearchRequest
kb *types.KnowledgeBase
grant bool
err error
}
func (s *graphSearchHandlerServiceStub) Search(
ctx context.Context, kb *types.KnowledgeBase, req types.GraphSearchRequest,
) (*types.GraphSearchResult, error) {
s.calls++
s.req, s.kb = req, kb
s.grant = access.HasKBGrant(ctx, kb.ID, kb.TenantID, types.OrgRoleViewer)
return &types.GraphSearchResult{
KnowledgeBaseID: kb.ID, Query: req.Query,
Entities: []types.GraphSearchEntity{}, Relationships: []types.GraphSearchRelation{},
SourceChunks: []types.GraphSearchSourceChunk{},
}, s.err
}
func graphSearchHandlerRouter(
kbService interfaces.KnowledgeBaseService, shares interfaces.KBShareService,
svc interfaces.GraphSearchService, caller uint64, scope *types.TenantAPIKeyScope,
agents ...interfaces.AgentShareService,
) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler(), func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), caller)
c.Set(types.UserIDContextKey.String(), "reader")
if scope != nil {
c.Request = c.Request.WithContext(types.WithTenantAPIKeyScope(c.Request.Context(), *scope))
}
c.Next()
})
kbHandler := &KnowledgeBaseHandler{service: kbService, kbShareService: shares}
if len(agents) > 0 {
kbHandler.agentShareService = agents[0]
}
h := NewGraphSearchHandler(kbHandler, svc)
r.POST("/knowledge-bases/:id/graph-search", h.Search)
return r
}
func graphSearchHandlerKB(owner uint64) *stubKBOnlyService {
return &stubKBOnlyService{getByID: func(_ context.Context, id string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: id, TenantID: owner}, nil
}}
}
func TestGraphSearchHandlerValidation(t *testing.T) {
for name, body := range map[string]string{
"empty": "",
"missing query": `{}`,
"null root": `null`,
"query whitespace": `{"query":" "}`,
"wrong query type": `{"query":1}`,
"unknown field": `{"query":"Acme","tenant_id":7}`,
"trailing object": `{"query":"Acme"} {}`,
"fractional limit": `{"query":"Acme","max_nodes":1.5}`,
"negative limit": `{"query":"Acme","max_source_chunks":-1}`,
"excessive limit": `{"query":"Acme","max_relations":201}`,
"long query": `{"query":"` + strings.Repeat("中", 513) + `"}`,
"large body": `{"query":"Acme"}` + strings.Repeat(" ", 8192),
} {
t.Run(name, func(t *testing.T) {
svc := &graphSearchHandlerServiceStub{}
w := httptest.NewRecorder()
graphSearchHandlerRouter(graphSearchHandlerKB(1), nil, svc, 1, nil).
ServeHTTP(w, httptest.NewRequest(http.MethodPost,
"/knowledge-bases/kb/graph-search", strings.NewReader(body)))
require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String())
require.Zero(t, svc.calls)
require.Contains(t, w.Body.String(), `"code":1000`)
})
}
}
func TestGraphSearchHandlerSharedAccessAndErrors(t *testing.T) {
shares := &handlerKBShareStub{}
svc := &graphSearchHandlerServiceStub{}
r := graphSearchHandlerRouter(graphSearchHandlerKB(7), shares, svc, 1, nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/knowledge-bases/kb/graph-search",
strings.NewReader(`{"query":" Acme "}`)))
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
require.True(t, svc.grant, "the service receives the exact KB read grant")
require.Equal(t, uint64(7), svc.kb.TenantID)
require.Equal(t, uint64(1), shares.caller)
require.Equal(t, "Acme", svc.req.Query)
require.Equal(t, 50, svc.req.MaxNodes)
svc.err = apperrors.NewServiceUnavailableError("graph unavailable")
w = httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/knowledge-bases/kb/graph-search",
strings.NewReader(`{"query":"Acme"}`)))
require.Equal(t, http.StatusServiceUnavailable, w.Code)
require.NotContains(t, w.Body.String(), `"entities"`, "errors never expose partial results")
}
func TestGraphSearchHandlerDeniesBeforeQuery(t *testing.T) {
for _, tt := range []struct {
name string
caller uint64
scope *types.TenantAPIKeyScope
kbService interfaces.KnowledgeBaseService
status int
}{
{name: "unauthenticated", caller: 0, kbService: graphSearchHandlerKB(1), status: 401},
{name: "unshared KB", caller: 1, kbService: graphSearchHandlerKB(7), status: 403},
{
name: "key outside allow list", caller: 1, kbService: graphSearchHandlerKB(1), status: 403,
scope: &types.TenantAPIKeyScope{KnowledgeBaseIDs: types.StringArray{"other"}},
},
{
name: "missing KB", caller: 1, status: 404,
kbService: &stubKBOnlyService{getByID: func(context.Context, string) (*types.KnowledgeBase, error) {
return nil, repository.ErrKnowledgeBaseNotFound
}},
},
} {
t.Run(tt.name, func(t *testing.T) {
svc := &graphSearchHandlerServiceStub{}
r := graphSearchHandlerRouter(tt.kbService, nil, svc, tt.caller, tt.scope)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/knowledge-bases/kb/graph-search",
strings.NewReader(`{"query":"Acme"}`)))
require.Equal(t, tt.status, w.Code, w.Body.String())
require.Zero(t, svc.calls)
})
}
}
type graphSearchAgentStub struct {
interfaces.AgentShareService
config types.CustomAgentConfig
owner uint64
}
func (s *graphSearchAgentStub) GetSharedAgentForTenant(
context.Context, uint64, types.TenantRole, string, ...uint64,
) (*types.CustomAgent, error) {
return &types.CustomAgent{ID: "shared", TenantID: s.owner, Config: s.config}, nil
}
func TestGraphSearchHandlerSharedAgentScope(t *testing.T) {
for _, tt := range []struct {
name, mode string
kbs []string
owner uint64
status int
}{
{"selected KB", "selected", []string{"kb"}, 7, 200},
{"none is not all", "none", nil, 7, 403},
{"empty selected is not all", "selected", nil, 7, 403},
{"another selection", "selected", []string{"other"}, 7, 403},
{"all in another owner", "all", nil, 8, 403},
} {
t.Run(tt.name, func(t *testing.T) {
svc := &graphSearchHandlerServiceStub{}
agent := &graphSearchAgentStub{
owner: tt.owner,
config: types.CustomAgentConfig{KBSelectionMode: tt.mode, KnowledgeBases: tt.kbs},
}
r := graphSearchHandlerRouter(graphSearchHandlerKB(7), nil, svc, 1, nil, agent)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodPost,
"/knowledge-bases/kb/graph-search?agent_id=shared", strings.NewReader(`{"query":"Acme"}`)))
require.Equal(t, tt.status, w.Code, w.Body.String())
if tt.status == http.StatusOK {
require.Equal(t, 1, svc.calls)
require.True(t, svc.grant)
} else {
require.Zero(t, svc.calls)
}
})
}
}
+55
View File
@@ -0,0 +1,55 @@
package handler
import (
"net/http"
"sync"
"github.com/gin-gonic/gin"
)
// hostProjectPicker opens the native folder dialog on Lite desktop.
// Nil on every other deployment: the route then 404s.
var (
hostProjectPickerMu sync.RWMutex
hostProjectPicker func() (string, error)
)
// SetHostProjectPicker is called by cmd/desktop. Standard servers leave it nil.
func SetHostProjectPicker(fn func() (string, error)) {
hostProjectPickerMu.Lock()
hostProjectPicker = fn
hostProjectPickerMu.Unlock()
}
func currentHostProjectPicker() func() (string, error) {
hostProjectPickerMu.RLock()
defer hostProjectPickerMu.RUnlock()
return hostProjectPicker
}
// PickHostProjectDir opens the system folder picker. The SPA talks HTTP to
// this process; Wails JS bindings are not injected through the
// reverse-proxied frontend, so this is the working authorization path.
func (*SystemHandler) PickHostProjectDir(c *gin.Context) {
picker := currentHostProjectPicker()
if picker == nil {
c.JSON(http.StatusNotFound, gin.H{
"success": false,
"error": gin.H{"message": "host project picker is not available"},
})
return
}
dir, err := picker()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"success": false,
"error": gin.H{"message": err.Error()},
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "success",
"data": gin.H{"dir": dir},
})
}
@@ -0,0 +1,65 @@
package handler
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestPickHostProjectDirUnavailableWithoutDesktop(t *testing.T) {
gin.SetMode(gin.TestMode)
SetHostProjectPicker(nil)
t.Cleanup(func() { SetHostProjectPicker(nil) })
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/system/host-project-dir", nil)
(&SystemHandler{}).PickHostProjectDir(c)
require.Equal(t, http.StatusNotFound, w.Code)
}
func TestPickHostProjectDirReturnsPickedPath(t *testing.T) {
gin.SetMode(gin.TestMode)
SetHostProjectPicker(func() (string, error) {
return "/Users/dev/My Project", nil
})
t.Cleanup(func() { SetHostProjectPicker(nil) })
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/system/host-project-dir", nil)
(&SystemHandler{}).PickHostProjectDir(c)
require.Equal(t, http.StatusOK, w.Code)
var body struct {
Data struct {
Dir string `json:"dir"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.Equal(t, "/Users/dev/My Project", body.Data.Dir)
}
func TestPickHostProjectDirCancelReturnsEmptyDir(t *testing.T) {
gin.SetMode(gin.TestMode)
SetHostProjectPicker(func() (string, error) { return "", nil })
t.Cleanup(func() { SetHostProjectPicker(nil) })
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/system/host-project-dir", nil)
(&SystemHandler{}).PickHostProjectDir(c)
require.Equal(t, http.StatusOK, w.Code)
var body struct {
Data struct {
Dir string `json:"dir"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.Empty(t, body.Data.Dir)
}
+490
View File
@@ -0,0 +1,490 @@
package handler
import (
"context"
"errors"
"net/http"
"sort"
"strings"
"academy/internal/im"
"academy/internal/logger"
"academy/internal/types"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// validIMPlatforms is the set of supported IM platforms.
var validIMPlatforms = map[string]bool{
"wecom": true, "feishu": true, "lark": true, "slack": true, "telegram": true, "dingtalk": true,
"mattermost": true, "wechat": true, "qqbot": true, "yunzhijia": true,
}
// invalidIMPlatformError is the 400 message listing the accepted platforms. It
// is derived from validIMPlatforms so the two cannot drift apart as platforms
// are added.
var invalidIMPlatformError = func() string {
names := make([]string, 0, len(validIMPlatforms))
for p := range validIMPlatforms {
names = append(names, "'"+p+"'")
}
sort.Strings(names)
return "platform must be one of: " + strings.Join(names, ", ")
}()
// IMHandler handles IM platform callback requests and channel CRUD.
type IMHandler struct {
imService *im.Service
}
// NewIMHandler creates a new IM handler.
func NewIMHandler(imService *im.Service) *IMHandler {
return &IMHandler{
imService: imService,
}
}
// ── Channel CRUD handlers ──
// CreateIMChannel creates a new IM channel for an agent.
func (h *IMHandler) CreateIMChannel(c *gin.Context) {
agentID := c.Param("id")
if agentID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "agent_id is required"})
return
}
tenantID, ok := c.Request.Context().Value(types.TenantIDContextKey).(uint64)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
var req struct {
Platform string `json:"platform" binding:"required"`
Name string `json:"name"`
Mode string `json:"mode"`
OutputMode string `json:"output_mode"`
Locale string `json:"locale"`
SessionMode string `json:"session_mode"`
KnowledgeBaseID string `json:"knowledge_base_id"`
Credentials types.JSON `json:"credentials"`
Enabled *bool `json:"enabled"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if !validIMPlatforms[req.Platform] {
c.JSON(http.StatusBadRequest, gin.H{"error": invalidIMPlatformError})
return
}
locale, err := normalizeIMLocale(req.Locale)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
channel := &im.IMChannel{
TenantID: tenantID,
AgentID: agentID,
Platform: req.Platform,
Name: req.Name,
Mode: req.Mode,
OutputMode: req.OutputMode,
Locale: locale,
SessionMode: req.SessionMode,
Credentials: req.Credentials,
Enabled: true,
}
// The route guard passes an agent it cannot find in this workspace; both
// the agent and the file-saving KB must belong to the channel's workspace.
if err := h.imService.SetChannelAgentID(c.Request.Context(), channel, agentID); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "agent not found"})
return
}
if err := h.imService.SetChannelKnowledgeBaseID(c.Request.Context(), channel, req.KnowledgeBaseID); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "knowledge base not found"})
return
}
if req.Enabled != nil {
channel.Enabled = *req.Enabled
}
// WeChat uses long-polling mode and full output only
if req.Platform == "wechat" {
channel.Mode = "longpoll"
channel.OutputMode = "full"
} else {
if channel.Mode == "" {
if channel.Platform == "mattermost" || channel.Platform == "yunzhijia" {
channel.Mode = "webhook"
} else {
channel.Mode = "websocket"
}
}
if channel.OutputMode == "" {
channel.OutputMode = "stream"
}
}
if channel.Credentials == nil {
channel.Credentials = types.JSON("{}")
}
if err := h.imService.CreateChannel(channel); err != nil {
logger.Errorf(c.Request.Context(), "[IM] Create channel failed: %v", err)
if strings.HasPrefix(err.Error(), "duplicate_bot:") {
c.JSON(http.StatusConflict, gin.H{"error": strings.TrimPrefix(err.Error(), "duplicate_bot: ")})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create channel"})
return
}
c.JSON(http.StatusOK, gin.H{"data": channel})
}
// ListIMChannels lists all IM channels for an agent.
func (h *IMHandler) ListIMChannels(c *gin.Context) {
agentID := c.Param("id")
if agentID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "agent_id is required"})
return
}
tenantID, ok := c.Request.Context().Value(types.TenantIDContextKey).(uint64)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
channels, err := h.imService.ListChannelsByAgent(agentID, tenantID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list channels"})
return
}
c.JSON(http.StatusOK, gin.H{"data": im.SummarizeIMChannels(channels)})
}
// ListAllIMChannels lists every IM channel in the current tenant, across
// agents, for the cross-agent overview page. Credentials are intentionally
// NOT included in the response.
func (h *IMHandler) ListAllIMChannels(c *gin.Context) {
tenantID, ok := c.Request.Context().Value(types.TenantIDContextKey).(uint64)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
channels, err := h.imService.ListChannelsByTenant(c.Request.Context(), tenantID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list channels"})
return
}
c.JSON(http.StatusOK, gin.H{"data": channels})
}
// UpdateIMChannel updates an IM channel.
//
// UpdateIMChannel godoc
// @Summary 更新 IM 渠道
// @Description 更新指定 IM 渠道的名称、模式、回复语言、知识库、凭证或启用状态
// @Tags IM 渠道
// @Accept json
// @Produce json
// @Param id path string true "渠道 ID"
// @Param request body map[string]interface{} true "更新字段(含 locale)"
// @Success 200 {object} handler.UpdateIMChannelResponse "更新后的渠道"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 404 {object} map[string]interface{} "渠道不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /im-channels/{id} [put]
func (h *IMHandler) UpdateIMChannel(c *gin.Context) {
channelID := c.Param("id")
if channelID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "channel id is required"})
return
}
tenantID, ok := c.Request.Context().Value(types.TenantIDContextKey).(uint64)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
channel, err := h.imService.GetChannelByIDAndTenant(channelID, tenantID)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})
return
}
var req struct {
Name *string `json:"name"`
Mode *string `json:"mode"`
OutputMode *string `json:"output_mode"`
Locale *string `json:"locale"`
SessionMode *string `json:"session_mode"`
KnowledgeBaseID *string `json:"knowledge_base_id"`
Credentials types.JSON `json:"credentials"`
Enabled *bool `json:"enabled"`
AgentID *string `json:"agent_id"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if req.Name != nil {
channel.Name = *req.Name
}
if req.Mode != nil {
channel.Mode = *req.Mode
}
if req.OutputMode != nil {
channel.OutputMode = *req.OutputMode
}
if req.Locale != nil {
locale, err := normalizeIMLocale(*req.Locale)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
channel.Locale = locale
}
if req.SessionMode != nil {
channel.SessionMode = *req.SessionMode
}
if req.KnowledgeBaseID != nil {
ctx := c.Request.Context()
if err := h.imService.SetChannelKnowledgeBaseID(ctx, channel, *req.KnowledgeBaseID); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "knowledge base not found"})
return
}
}
if req.Credentials != nil {
channel.Credentials = req.Credentials
}
if req.Enabled != nil {
channel.Enabled = *req.Enabled
}
if req.AgentID != nil {
newAgentID := strings.TrimSpace(*req.AgentID)
if newAgentID != "" && newAgentID != channel.AgentID {
if err := h.imService.SetChannelAgentID(c.Request.Context(), channel, newAgentID); err != nil {
logger.Errorf(c.Request.Context(), "[IM] Update channel agent failed: %v", err)
c.JSON(http.StatusBadRequest, gin.H{"error": "agent not found"})
return
}
}
}
if err := h.imService.UpdateChannel(channel); err != nil {
logger.Errorf(c.Request.Context(), "[IM] Update channel failed: %v", err)
if strings.HasPrefix(err.Error(), "duplicate_bot:") {
c.JSON(http.StatusConflict, gin.H{"error": strings.TrimPrefix(err.Error(), "duplicate_bot: ")})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update channel"})
return
}
c.JSON(http.StatusOK, gin.H{"data": channel})
}
func normalizeIMLocale(locale string) (string, error) {
locale = strings.TrimSpace(locale)
if locale == "" {
return "", nil
}
if normalized := types.NormalizeSupportedLocale(locale); normalized != "" {
return normalized, nil
}
return "", errors.New("locale must be one of: 'en-US', 'ja-JP', 'ko-KR', 'ru-RU', 'zh-CN', 'zh-TW'")
}
// DeleteIMChannel deletes an IM channel.
//
// DeleteIMChannel godoc
// @Summary 删除 IM 渠道
// @Description 删除指定 IM 渠道
// @Tags IM 渠道
// @Produce json
// @Param id path string true "渠道 ID"
// @Success 200 {object} handler.SuccessResponse "success: true"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 404 {object} map[string]interface{} "渠道不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /im-channels/{id} [delete]
func (h *IMHandler) DeleteIMChannel(c *gin.Context) {
channelID := c.Param("id")
if channelID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "channel id is required"})
return
}
tenantID, ok := c.Request.Context().Value(types.TenantIDContextKey).(uint64)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
if err := h.imService.DeleteChannel(channelID, tenantID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete channel"})
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// ToggleIMChannel toggles the enabled state of an IM channel.
//
// ToggleIMChannel godoc
// @Summary 启用/停用 IM 渠道
// @Description 切换指定 IM 渠道的启用状态
// @Tags IM 渠道
// @Produce json
// @Param id path string true "渠道 ID"
// @Success 200 {object} handler.UpdateIMChannelResponse "更新后的渠道"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 404 {object} map[string]interface{} "渠道不存在"
// @Security Bearer
// @Security ApiKeyAuth
// @Router /im-channels/{id}/toggle [post]
func (h *IMHandler) ToggleIMChannel(c *gin.Context) {
channelID := c.Param("id")
if channelID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "channel id is required"})
return
}
tenantID, ok := c.Request.Context().Value(types.TenantIDContextKey).(uint64)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
channel, err := h.imService.ToggleChannel(channelID, tenantID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to toggle channel"})
return
}
c.JSON(http.StatusOK, gin.H{"data": channel})
}
func writeIMCallbackACK(c *gin.Context, platform string) {
if platform == "yunzhijia" {
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"type": 2,
"content": "",
},
})
return
}
c.JSON(http.StatusOK, gin.H{"success": true})
}
// ── Callback handlers ──
// IMCallback handles IM platform callback requests for a specific channel.
// Route: POST /api/v1/im/callback/:channel_id
//
// IMCallback godoc
// @Summary IM 平台回调
// @Description 接收各 IM 平台的事件回调;走平台自身签名校验,不使用 API Key
// @Tags IM 回调
// @Accept json
// @Produce json
// @Param channel_id path string true "渠道 ID"
// @Success 200 {object} map[string]interface{} "处理结果"
// @Failure 400 {object} map[string]interface{} "请求参数错误"
// @Failure 401 {object} map[string]interface{} "签名校验失败"
// @Router /im/callback/{channel_id} [get]
// @Router /im/callback/{channel_id} [post]
func (h *IMHandler) IMCallback(c *gin.Context) {
ctx := c.Request.Context()
channelID := c.Param("channel_id")
// Always validate the durable row before using a cached webhook adapter.
// This is the correctness fallback when a replica missed Redis invalidation
// while disconnected, and prevents stale credentials/config from being used.
adapter, channel, err := h.imService.EnsureChannelAdapter(channelID)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
logger.Errorf(ctx, "[IM] Channel not found for callback: %s", channelID)
c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"})
return
}
if errors.Is(err, im.ErrChannelDisabled) {
logger.Errorf(ctx, "[IM] Channel disabled for callback: %s", channelID)
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "channel is disabled"})
return
}
logger.Errorf(ctx, "[IM] Channel unavailable for callback %s: %v", channelID, err)
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "channel not available"})
return
}
defaultMode := "websocket"
if channel.Platform == "mattermost" || channel.Platform == "yunzhijia" {
defaultMode = "webhook"
}
if im.ResolveMode(channel, defaultMode) != "webhook" ||
channel.Platform == "qqbot" || channel.Platform == "wechat" || channel.Platform == "dingtalk" {
c.JSON(http.StatusForbidden, gin.H{"error": "HTTP callbacks are disabled for this channel"})
return
}
logger.Infof(ctx, "[IM] Callback received platform=%s path_channel_id=%s", channel.Platform, channelID)
// Handle URL verification
if adapter.HandleURLVerification(c) {
return
}
// Verify callback signature
if err := adapter.VerifyCallback(c); err != nil {
logger.Errorf(ctx, "[IM] Callback verification failed for channel %s: %v", channelID, err)
c.JSON(http.StatusForbidden, gin.H{"error": "verification failed"})
return
}
// Parse the callback message
msg, err := adapter.ParseCallback(c)
if err != nil {
logger.Errorf(ctx, "[IM] Parse callback failed for channel %s: %v", channelID, err)
c.JSON(http.StatusBadRequest, gin.H{"error": "parse failed"})
return
}
// If nil, it's a non-message event - just acknowledge
if msg == nil {
if channel.Platform == "mattermost" {
logger.Infof(ctx, "[IM] Mattermost callback ignored (no message): path_channel_id=%s — check: (1) trigger word must be the *first word* of the post; (2) if channel+trigger are both set, post must be in that channel; (3) bot_user_id must not match the sender", channelID)
} else {
logger.Infof(ctx, "[IM] Callback parsed no message to process platform=%s path_channel_id=%s", channel.Platform, channelID)
}
writeIMCallbackACK(c, channel.Platform)
return
}
// Respond immediately to avoid platform timeout
writeIMCallbackACK(c, channel.Platform)
// Detach from gin request context
asyncCtx := context.WithoutCancel(ctx)
// Process message asynchronously
go func() {
if err := h.imService.HandleMessage(asyncCtx, msg, channelID); err != nil {
logger.Errorf(asyncCtx, "[IM] Handle message error for channel %s: %v", channelID, err)
}
}()
}
+61
View File
@@ -0,0 +1,61 @@
package handler
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/types"
"github.com/gin-gonic/gin"
)
func TestNormalizeIMLocale(t *testing.T) {
for _, tt := range []struct {
name string
locale string
want string
wantErr bool
}{
{name: "empty", locale: "", want: ""},
{name: "supported", locale: "en-US", want: "en-US"},
{name: "trimmed", locale: " zh-CN ", want: "zh-CN"},
{name: "unsupported", locale: "fr-FR", wantErr: true},
} {
t.Run(tt.name, func(t *testing.T) {
got, err := normalizeIMLocale(tt.locale)
if (err != nil) != tt.wantErr {
t.Fatalf("normalizeIMLocale(%q) error = %v, wantErr %v", tt.locale, err, tt.wantErr)
}
if got != tt.want {
t.Fatalf("normalizeIMLocale(%q) = %q, want %q", tt.locale, got, tt.want)
}
})
}
}
func TestCreateIMChannelRejectsUnsupportedLocale(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
handler := NewIMHandler(nil)
router.POST("/agents/:id/im-channels", handler.CreateIMChannel)
req := httptest.NewRequest(
http.MethodPost,
"/agents/agent-1/im-channels",
strings.NewReader(`{"platform":"feishu","locale":"fr-FR"}`),
)
req.Header.Set("Content-Type", "application/json")
req = req.WithContext(context.WithValue(req.Context(), types.TenantIDContextKey, uint64(42)))
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
if recorder.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d; body=%s", recorder.Code, http.StatusBadRequest, recorder.Body.String())
}
if !strings.Contains(recorder.Body.String(), "locale must be one of") {
t.Fatalf("body = %s, want locale validation error", recorder.Body.String())
}
}
+33
View File
@@ -0,0 +1,33 @@
package handler
import (
"strings"
"testing"
)
// The channel-creation endpoint rejects any platform without a registered
// adapter factory, so this set must track the factories wired in the container.
func TestValidIMPlatforms_CoversLark(t *testing.T) {
want := []string{
"wecom", "feishu", "lark", "slack", "telegram",
"dingtalk", "mattermost", "wechat", "qqbot",
}
for _, platform := range want {
if !validIMPlatforms[platform] {
t.Errorf("platform %q is not accepted", platform)
}
}
if validIMPlatforms["nonsense"] {
t.Error("unknown platform is accepted")
}
}
// The 400 message is derived from validIMPlatforms; it must not drift as
// platforms are added.
func TestInvalidIMPlatformError_ListsEveryPlatform(t *testing.T) {
for platform := range validIMPlatforms {
if !strings.Contains(invalidIMPlatformError, "'"+platform+"'") {
t.Errorf("error message omits %q: %s", platform, invalidIMPlatformError)
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,92 @@
package handler
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/types"
"academy/internal/utils"
"github.com/stretchr/testify/require"
)
// fakeChatGateway answers every chat completion with the given status and body.
func fakeChatGateway(t *testing.T, status int, body string) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = w.Write([]byte(body))
}))
t.Cleanup(srv.Close)
// The test server is a bare loopback IP; let the SSRF guard through.
utils.SetSSRFWhitelistFromRaw("127.0.0.1")
t.Cleanup(func() { utils.SetSSRFWhitelistFromRaw("") })
return srv
}
func remoteChatModel(baseURL string) *types.Model {
return &types.Model{
Name: "gpt-5.6-luna",
Type: types.ModelTypeKnowledgeQA,
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
BaseURL: baseURL,
APIKey: "sk-test",
},
}
}
// A reasoning model behind LiteLLM cannot finish within the 1-token probe and
// the gateway answers 400. The endpoint is reachable and the key accepted, so
// the check must pass, as it did before the HTTP client changed its wording.
func TestCheckChatModelConnectionTreats400AsReachable(t *testing.T) {
srv := fakeChatGateway(t, http.StatusBadRequest,
`{"error":{"message":"litellm.BadRequestError: OpenAIException - Could not finish the message `+
`because max_tokens or model output limit was reached.","type":"invalid_request_error","code":"400"}}`)
h := &InitializationHandler{}
available, message := h.checkChatModelConnection(context.Background(), remoteChatModel(srv.URL), "", "")
require.True(t, available, "message: %s", message)
}
func TestCheckChatModelConnectionReportsAuthFailure(t *testing.T) {
srv := fakeChatGateway(t, http.StatusUnauthorized,
`{"error":{"message":"Invalid API key","type":"invalid_request_error","code":"401"}}`)
h := &InitializationHandler{}
available, message := h.checkChatModelConnection(context.Background(), remoteChatModel(srv.URL), "", "")
require.False(t, available)
require.Contains(t, message, "认证失败")
}
// Gemini's native API reports an invalid key as 400 INVALID_ARGUMENT /
// API_KEY_INVALID. That 400 is an auth failure, not "reachable".
func TestCheckChatModelConnectionReportsGeminiInvalidKey(t *testing.T) {
var gotPath string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":{"code":400,"message":"API key not valid. Please pass a valid API key.",` +
`"status":"INVALID_ARGUMENT","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo",` +
`"reason":"API_KEY_INVALID","domain":"googleapis.com"}]}}`))
}))
t.Cleanup(srv.Close)
utils.SetSSRFWhitelistFromRaw("127.0.0.1")
t.Cleanup(func() { utils.SetSSRFWhitelistFromRaw("") })
model := remoteChatModel(srv.URL)
model.Name = "gemini-2.5-flash"
model.Parameters.Provider = "gemini"
h := &InitializationHandler{}
available, message := h.checkChatModelConnection(context.Background(), model, "", "")
require.Contains(t, gotPath, ":generateContent", "probe should use the native Gemini API")
require.False(t, available, "message: %s", message)
require.Contains(t, message, "认证失败")
}
@@ -0,0 +1,90 @@
package handler
import (
"context"
"encoding/json"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBuildConfigResponse_ViewerOmitsModelBaseURL(t *testing.T) {
h := &InitializationHandler{}
ctx := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleViewer)
models := []*types.Model{{
Type: types.ModelTypeKnowledgeQA,
Name: "custom-llm",
Parameters: types.ModelParameters{
BaseURL: "https://tenant-private.example.com",
APIKey: "sk-secret-do-not-leak",
},
}}
kb := &types.KnowledgeBase{}
config := h.buildConfigResponse(ctx, models, kb, false)
llm, ok := config["llm"].(map[string]interface{})
require.True(t, ok)
assert.Empty(t, llm["baseUrl"])
body, err := json.Marshal(config)
require.NoError(t, err)
assert.NotContains(t, string(body), "tenant-private.example.com")
assert.NotContains(t, string(body), "sk-secret-do-not-leak")
}
func TestBuildConfigResponse_AdminKeepsModelBaseURL(t *testing.T) {
h := &InitializationHandler{}
ctx := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleAdmin)
ctx = types.WithCaller(ctx, types.Caller{TenantID: 42, UserID: "u", Role: types.TenantRoleAdmin})
models := []*types.Model{{
Type: types.ModelTypeKnowledgeQA,
Name: "custom-llm",
Parameters: types.ModelParameters{
BaseURL: "https://tenant-private.example.com",
APIKey: "sk-secret-do-not-leak",
},
}}
kb := &types.KnowledgeBase{TenantID: 42}
config := h.buildConfigResponse(ctx, models, kb, false)
llm, ok := config["llm"].(map[string]interface{})
require.True(t, ok)
assert.Equal(t, "https://tenant-private.example.com", llm["baseUrl"])
body, err := json.Marshal(config)
require.NoError(t, err)
assert.NotContains(t, string(body), "sk-secret-do-not-leak")
}
// A share receiver's admin is an admin of its own workspace, not of the KB's:
// it sees whether credentials exist, never the owner's endpoints or buckets.
func TestBuildConfigResponse_ShareReceiverAdminSeesPresenceOnly(t *testing.T) {
h := &InitializationHandler{}
ctx := context.WithValue(context.Background(), types.TenantRoleContextKey, types.TenantRoleAdmin)
ctx = types.WithCaller(ctx, types.Caller{TenantID: 42, UserID: "u", Role: types.TenantRoleAdmin})
ctx = types.WithExecutionTenant(ctx, 7)
models := []*types.Model{{
Type: types.ModelTypeKnowledgeQA,
Name: "owner-llm",
Parameters: types.ModelParameters{BaseURL: "https://owner-private.example.com"},
}}
kb := &types.KnowledgeBase{TenantID: 7}
legacy := &kb.StorageConfig //nolint:staticcheck // old KBs still carry the legacy COS config
legacy.Provider = "cos"
legacy.BucketName = "owner-bucket"
legacy.Region = "ap-owner"
legacy.AppID = "owner-app"
legacy.SecretID = "id"
legacy.SecretKey = "key"
config := h.buildConfigResponse(ctx, models, kb, false)
body, err := json.Marshal(config)
require.NoError(t, err)
for _, detail := range []string{"owner-private.example.com", "owner-bucket", "ap-owner", "owner-app"} {
assert.NotContains(t, string(body), detail)
}
cos := config["multimodal"].(map[string]interface{})["cos"].(map[string]interface{})
assert.Equal(t, map[string]bool{"secretId": true, "secretKey": true}, cos["credentials"])
}
@@ -0,0 +1,40 @@
package handler
import (
"context"
"errors"
"testing"
"academy/internal/config"
"academy/internal/models/chat"
"academy/internal/types"
)
type proseReplyChat struct{}
func (proseReplyChat) Chat(context.Context, []chat.Message, *chat.ChatOptions) (*types.ChatResponse, error) {
return &types.ChatResponse{Content: "抱歉,这段文本没有可抽取的实体和关系。", FinishReason: "stop"}, nil
}
func (proseReplyChat) ChatStream(
context.Context, []chat.Message, *chat.ChatOptions,
) (<-chan types.StreamResponse, error) {
return nil, errors.New("not implemented")
}
func (proseReplyChat) GetModelName() string { return "prose" }
func (proseReplyChat) GetModelID() string { return "prose" }
// The graph-settings "try extract" button must report a prose refusal as a
// failure. Returning an empty graph would make the UI clear the user's
// few-shot nodes/relations and show "success" (#3606 review).
func TestExtractRelationsFromTextReportsModelRefusal(t *testing.T) {
h := &InitializationHandler{config: &config.Config{
ExtractManager: &config.ExtractManagerConfig{
ExtractGraph: &types.PromptTemplateStructured{Description: "extract"},
},
}}
res, err := h.extractRelationsFromText(context.Background(), "目录", nil, proseReplyChat{})
if err == nil {
t.Fatalf("expected an error for a prose refusal, got %+v", res)
}
}
@@ -0,0 +1,146 @@
package handler
import (
"context"
"errors"
"testing"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// stubFillSecretsModelService only implements GetModelByID; every other
// ModelService call panics via the nil interface embedding. Keeps the test
// focused on fillSecretsFromStoredModel's branching logic.
type stubFillSecretsModelService struct {
interfaces.ModelService
getModelByID func(ctx context.Context, id string) (*types.Model, error)
}
func (s *stubFillSecretsModelService) GetModelByID(ctx context.Context, id string) (*types.Model, error) {
return s.getModelByID(ctx, id)
}
func TestFillSecretsFromStoredModel_FillsExtraConfig(t *testing.T) {
stored := &types.Model{
Parameters: types.ModelParameters{
APIKey: "sk-stored",
AppSecret: "app-secret-stored",
ExtraConfig: map[string]string{
"thinking_control": "none",
"api_version": "2024-10-21",
},
},
}
h := &InitializationHandler{
modelService: &stubFillSecretsModelService{
getModelByID: func(context.Context, string) (*types.Model, error) { return stored, nil },
},
}
req := &ModelTestRequest{ModelID: "m-1"}
h.fillSecretsFromStoredModel(context.Background(), req)
if req.APIKey != "sk-stored" || req.AppSecret != "app-secret-stored" {
t.Fatalf("secrets not filled from stored model: apiKey=%q appSecret=%q", req.APIKey, req.AppSecret)
}
if req.ExtraConfig == nil {
t.Fatalf("ExtraConfig not filled from stored model: got nil, want thinking_control/api_version")
}
if req.ExtraConfig["thinking_control"] != "none" || req.ExtraConfig["api_version"] != "2024-10-21" {
t.Fatalf("ExtraConfig contents wrong: %v", req.ExtraConfig)
}
}
// TestFillSecretsFromStoredModel_RequestExtraConfigWins: when the caller
// actively sends an extraConfig payload (user editing the form), the stored
// one must not overwrite it — same precedence as the secret fields.
func TestFillSecretsFromStoredModel_RequestExtraConfigWins(t *testing.T) {
stored := &types.Model{
Parameters: types.ModelParameters{
ExtraConfig: map[string]string{"thinking_control": "none"},
},
}
h := &InitializationHandler{
modelService: &stubFillSecretsModelService{
getModelByID: func(context.Context, string) (*types.Model, error) { return stored, nil },
},
}
req := &ModelTestRequest{
ModelID: "m-1",
APIKey: "sk-typed",
AppSecret: "app-typed",
ExtraConfig: map[string]string{"thinking_control": "enabled"},
}
h.fillSecretsFromStoredModel(context.Background(), req)
if req.ExtraConfig["thinking_control"] != "enabled" {
t.Fatalf("request ExtraConfig overwritten: %v", req.ExtraConfig)
}
if req.APIKey != "sk-typed" || req.AppSecret != "app-typed" {
t.Fatalf("request secrets overwritten: %q %q", req.APIKey, req.AppSecret)
}
}
// TestFillSecretsFromStoredModel_SecretsStillFilledWithoutExtraConfig:
// regression guard for the early-return — a request that already carries
// both secrets but no extraConfig must still pick up the stored
// extraConfig (this is the exact #3057 scenario: the frontend "test"
// button only sends modelId).
func TestFillSecretsFromStoredModel_SecretsStillFilledWithoutExtraConfig(t *testing.T) {
stored := &types.Model{
Parameters: types.ModelParameters{
APIKey: "sk-stored",
AppSecret: "app-secret-stored",
ExtraConfig: map[string]string{"remote_model_name": "gpt-x"},
},
}
h := &InitializationHandler{
modelService: &stubFillSecretsModelService{
getModelByID: func(context.Context, string) (*types.Model, error) { return stored, nil },
},
}
req := &ModelTestRequest{ModelID: "m-1", APIKey: "sk-typed", AppSecret: "app-typed"}
h.fillSecretsFromStoredModel(context.Background(), req)
if req.ExtraConfig == nil || req.ExtraConfig["remote_model_name"] != "gpt-x" {
t.Fatalf("ExtraConfig not filled when secrets were provided: %v", req.ExtraConfig)
}
}
func TestFillSecretsFromStoredModel_NoModelIDNoop(t *testing.T) {
h := &InitializationHandler{
modelService: &stubFillSecretsModelService{
getModelByID: func(context.Context, string) (*types.Model, error) {
t.Fatal("GetModelByID must not be called without a model id")
return nil, nil
},
},
}
req := &ModelTestRequest{}
h.fillSecretsFromStoredModel(context.Background(), req)
if req.ExtraConfig != nil {
t.Fatalf("ExtraConfig changed without model id: %v", req.ExtraConfig)
}
}
func TestFillSecretsFromStoredModel_ModelNotFoundNoop(t *testing.T) {
h := &InitializationHandler{
modelService: &stubFillSecretsModelService{
getModelByID: func(context.Context, string) (*types.Model, error) {
return nil, errors.New("not found")
},
},
}
req := &ModelTestRequest{ModelID: "missing"}
h.fillSecretsFromStoredModel(context.Background(), req)
if req.ExtraConfig != nil {
t.Fatalf("ExtraConfig changed on model lookup failure: %v", req.ExtraConfig)
}
}
@@ -0,0 +1,215 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/types"
"academy/internal/types/interfaces"
secutils "academy/internal/utils"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Re-initializing a KB used to assign the wizard's four fields over the whole
// parameter struct of the stored row, erasing everything the model editor
// owns (provider, extra_config, custom headers, spec, concurrency, context
// window) and blanking the API key whenever the payload carried none.
func storedEditorConfiguredModel() *types.Model {
return &types.Model{
ID: "m-llm", Type: types.ModelTypeKnowledgeQA, Name: "gpt-4o",
TenantID: 10042, Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
Provider: "azure",
BaseURL: "https://old.example.com/v1",
APIKey: "stored-key",
ExtraConfig: map[string]string{
"api_version": "2024-06-01",
"secret_key": "cam-secret-stored",
},
CustomHeaders: map[string]string{"X-Team": "rag"},
MaxConcurrency: 4,
ContextWindow: 128000,
Spec: &types.ModelSpecOverride{API: "openai-completions"},
},
}
}
// initExistingLLM runs processInitializationModels against a KB whose LLM
// slot already points at stored, and returns the row it persisted.
func initExistingLLM(t *testing.T, stored *types.Model, mutate func(*InitializationRequest)) *types.Model {
t.Helper()
svc := &stubTenantStampModelService{}
svc.getModelByID = func(_ context.Context, id string) (*types.Model, error) {
if id == stored.ID {
return stored, nil
}
return nil, nil
}
h := &InitializationHandler{modelService: svc}
kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 10042, SummaryModelID: stored.ID}
req := newTenantStampRequest()
if mutate != nil {
mutate(req)
}
_, err := h.processInitializationModels(context.Background(), kb, "kb-1", req)
require.NoError(t, err)
require.NotEmpty(t, svc.updated, "the existing model was not updated")
return svc.updated[0]
}
func TestProcessInitializationModelsKeepsEditorOwnedParameters(t *testing.T) {
stored := storedEditorConfiguredModel()
updated := initExistingLLM(t, stored, func(req *InitializationRequest) {
req.LLM.APIKey = "" // the wizard re-submits without re-typing the key
req.LLM.BaseURL = "https://new.example.com/v1"
})
p := updated.Parameters
assert.Equal(t, "https://new.example.com/v1", p.BaseURL, "the endpoint edit must still land")
assert.Equal(t, "stored-key", p.APIKey, "an omitted key means unchanged, not cleared")
assert.Equal(t, "azure", p.Provider)
assert.Equal(t, "2024-06-01", p.ExtraConfig["api_version"])
assert.Equal(t, "cam-secret-stored", p.ExtraConfig["secret_key"])
assert.Equal(t, map[string]string{"X-Team": "rag"}, p.CustomHeaders)
assert.Equal(t, 4, p.MaxConcurrency)
assert.Equal(t, 128000, p.ContextWindow)
assert.NotNil(t, p.Spec)
}
// Initialization's own purpose still works: endpoint and key are writable.
func TestProcessInitializationModelsStillAppliesSubmittedFields(t *testing.T) {
stored := storedEditorConfiguredModel()
updated := initExistingLLM(t, stored, func(req *InitializationRequest) {
req.LLM.APIKey = "rotated-key"
req.LLM.BaseURL = "https://new.example.com/v1"
})
assert.Equal(t, "rotated-key", updated.Parameters.APIKey)
assert.Equal(t, "https://new.example.com/v1", updated.Parameters.BaseURL)
}
// The embedding slot carries a dimension, and changing it is the one reason
// an operator re-runs initialization against an existing embedding row.
func TestProcessInitializationModelsAppliesEmbeddingDimension(t *testing.T) {
stored := &types.Model{
ID: "m-embed", Type: types.ModelTypeEmbedding, Name: "bge-m3", TenantID: 10042,
Source: types.ModelSourceRemote,
Parameters: types.ModelParameters{
Provider: "siliconflow",
BaseURL: "https://old.example.com/v1",
APIKey: "stored-key",
ExtraConfig: map[string]string{"remote_model_name": "BAAI/bge-m3"},
EmbeddingParameters: types.EmbeddingParameters{Dimension: 768, TruncatePromptTokens: 512},
},
}
svc := &stubTenantStampModelService{}
svc.getModelByID = func(_ context.Context, id string) (*types.Model, error) {
if id == "m-embed" {
return stored, nil
}
return nil, nil
}
h := &InitializationHandler{modelService: svc}
kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 10042, EmbeddingModelID: "m-embed"}
req := newTenantStampRequest()
req.Embedding.Dimension = 1024
req.Embedding.APIKey = ""
_, err := h.processInitializationModels(context.Background(), kb, "kb-1", req)
require.NoError(t, err)
require.NotEmpty(t, svc.updated)
p := svc.updated[0].Parameters
assert.Equal(t, 1024, p.EmbeddingParameters.Dimension, "the dimension edit must still land")
assert.Equal(t, 512, p.EmbeddingParameters.TruncatePromptTokens,
"the rest of the embedding parameters is not part of the payload")
assert.Equal(t, "BAAI/bge-m3", p.ExtraConfig["remote_model_name"])
assert.Equal(t, "stored-key", p.APIKey)
}
type stubInitKBService struct {
interfaces.KnowledgeBaseService
kb *types.KnowledgeBase
}
func (s *stubInitKBService) GetKnowledgeBaseByID(context.Context, string) (*types.KnowledgeBase, error) {
return s.kb, nil
}
type stubInitKBRepository struct {
interfaces.KnowledgeBaseRepository
}
func (s *stubInitKBRepository) UpdateKnowledgeBase(context.Context, *types.KnowledgeBase) error {
return nil
}
// POST /initialization/initialize/{kbId} used to marshal the raw model rows,
// and types.Model carries api_key in plaintext. Now that the reuse path keeps
// the stored credential rather than overwriting it with the payload's, that
// body would hand back a key the caller never submitted.
func TestInitializeByKB_ResponseDoesNotEchoStoredAPIKey(t *testing.T) {
gin.SetMode(gin.TestMode)
stored := storedEditorConfiguredModel()
svc := &stubTenantStampModelService{}
svc.getModelByID = func(_ context.Context, id string) (*types.Model, error) {
if id == stored.ID {
return stored, nil
}
return nil, nil
}
kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 10042, SummaryModelID: stored.ID}
h := &InitializationHandler{
modelService: svc,
kbService: &stubInitKBService{kb: kb},
kbRepository: &stubInitKBRepository{},
}
req := newTenantStampRequest()
req.LLM.APIKey = ""
// The full handler runs SSRF validation, which would otherwise resolve
// the host over the network. Whitelist one name of our own and clear it
// again, so no other test in this package sees a relaxed check.
secutils.SetSSRFWhitelistFromRaw("init-merge-test.example.com")
t.Cleanup(func() { secutils.SetSSRFWhitelistFromRaw("") })
req.LLM.BaseURL = "https://init-merge-test.example.com/v1"
req.Embedding.BaseURL = "https://init-merge-test.example.com/v1"
req.DocumentSplitting.ChunkSize = 512
req.DocumentSplitting.ChunkOverlap = 64
req.DocumentSplitting.Separators = []string{"\n"}
body, err := json.Marshal(req)
require.NoError(t, err)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/initialization/initialize/kb-1", bytes.NewReader(body))
c.Request.Header.Set("Content-Type", "application/json")
c.Request = c.Request.WithContext(types.WithCaller(c.Request.Context(), types.Caller{
TenantID: 10042, UserID: "u-1", Role: types.TenantRoleAdmin,
}))
c.Params = gin.Params{{Key: "kbId", Value: "kb-1"}}
h.InitializeByKB(c)
require.Empty(t, c.Errors.Errors())
require.Equal(t, http.StatusOK, w.Code)
assert.NotContains(t, w.Body.String(), "stored-key")
assert.NotContains(t, w.Body.String(), "cam-secret-stored")
assert.Contains(t, w.Body.String(), stored.ID, "the model ids the caller needs are still returned")
}
// A rerank row is never reached by this path at all: the KB has no rerank
// slot, so findExistingModelID has nothing to return and every run creates a
// fresh row. Pinning it keeps the reasoning above honest if a slot is added.
func TestFindExistingModelIDHasNoRerankSlot(t *testing.T) {
h := &InitializationHandler{}
kb := &types.KnowledgeBase{SummaryModelID: "m-llm", EmbeddingModelID: "m-embed"}
assert.Empty(t, h.findExistingModelID(kb, types.ModelTypeRerank))
assert.Equal(t, "m-llm", h.findExistingModelID(kb, types.ModelTypeKnowledgeQA))
}
@@ -0,0 +1,115 @@
package handler
import (
"context"
"testing"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// The initialization endpoint's model creation used to insert rows without a
// tenant: toModel() carries no TenantID, so models landed at tenant_id = 0
// where the (tenant_id = ? OR is_builtin) read filter made them invisible to
// every tenant — including the one that just configured the KB — leaving the
// KB bound to unreadable model IDs (issue #3333).
type stubTenantStampModelService struct {
interfaces.ModelService
created []*types.Model
updated []*types.Model
getModelByID func(ctx context.Context, id string) (*types.Model, error)
}
func (s *stubTenantStampModelService) GetModelByID(ctx context.Context, id string) (*types.Model, error) {
if s.getModelByID != nil {
return s.getModelByID(ctx, id)
}
return nil, nil // default: force the create path
}
func (s *stubTenantStampModelService) CreateModel(ctx context.Context, model *types.Model) error {
m := *model
s.created = append(s.created, &m)
return nil
}
func (s *stubTenantStampModelService) UpdateModel(ctx context.Context, model *types.Model) error {
m := *model
s.updated = append(s.updated, &m)
return nil
}
func newTenantStampRequest() *InitializationRequest {
req := &InitializationRequest{}
req.LLM.Source = "remote"
req.LLM.ModelName = "qwen2.5"
req.LLM.BaseURL = "http://ollama.internal/v1"
req.LLM.APIKey = "ollama"
req.Embedding.Source = "remote"
req.Embedding.ModelName = "bge-m3"
req.Embedding.BaseURL = "http://ollama.internal/v1"
req.Embedding.APIKey = "ollama"
return req
}
func TestProcessInitializationModelsStampsKBTenantOnCreatedModels(t *testing.T) {
stub := &stubTenantStampModelService{}
h := &InitializationHandler{modelService: stub}
kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 10042}
models, err := h.processInitializationModels(context.Background(), kb, "kb-1", newTenantStampRequest())
if err != nil {
t.Fatalf("processInitializationModels: %v", err)
}
if len(models) != 2 || len(stub.created) != 2 {
t.Fatalf("created = %d models (returned %d), want 2", len(stub.created), len(models))
}
for _, m := range stub.created {
if m.TenantID != 10042 {
t.Fatalf("created model %q has tenant_id = %d, want 10042 (the KB's tenant)", m.Name, m.TenantID)
}
}
}
func TestProcessInitializationModelsKeepsExistingModelTenant(t *testing.T) {
// The reuse path (update of an already-stored model) must not rewrite the
// stored row's tenant: only freshly created rows get stamped.
stored := &types.Model{
ID: "m-existing", Type: types.ModelTypeKnowledgeQA, Name: "old-name",
TenantID: 10042, Source: types.ModelSourceRemote,
}
svc := &stubTenantStampModelService{}
svc.getModelByID = func(ctx context.Context, id string) (*types.Model, error) {
if id == "m-existing" {
return stored, nil
}
return nil, nil
}
h := &InitializationHandler{modelService: svc}
kb := &types.KnowledgeBase{
ID: "kb-1",
TenantID: 10042,
SummaryModelID: "m-existing", // LLM slot reuses; embedding slot creates
}
models, err := h.processInitializationModels(context.Background(), kb, "kb-1", newTenantStampRequest())
if err != nil {
t.Fatalf("processInitializationModels: %v", err)
}
if len(svc.created) != 1 {
t.Fatalf("created = %d models, want exactly 1 (embedding only)", len(svc.created))
}
if svc.created[0].Type != types.ModelTypeEmbedding || svc.created[0].TenantID != 10042 {
t.Fatalf("unexpected created model: type=%v tenant=%d", svc.created[0].Type, svc.created[0].TenantID)
}
foundReuse := false
for _, m := range models {
if m.ID == "m-existing" {
foundReuse = true
}
}
if !foundReuse {
t.Fatal("existing model not returned by the reuse path")
}
}
@@ -0,0 +1,189 @@
package handler
import (
"context"
stderrors "errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/application/access"
"academy/internal/config"
apperrors "academy/internal/errors"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type stubInitializationKBService struct {
interfaces.KnowledgeBaseService
kb *types.KnowledgeBase
}
func (s *stubInitializationKBService) GetKnowledgeBaseByID(context.Context, string) (*types.KnowledgeBase, error) {
return s.kb, nil
}
func requireForbidden(t *testing.T, err error) {
t.Helper()
var appErr *apperrors.AppError
if !stderrors.As(err, &appErr) || appErr.HTTPCode != http.StatusForbidden {
t.Fatalf("err = %v, want 403", err)
}
}
// A shared-KB editor reaches the handler with execution moved into the owner
// workspace; the KB must still be refused because the caller does not own it.
func TestInitializationRejectsKBOfAnotherWorkspace(t *testing.T) {
h := &InitializationHandler{kbService: &stubInitializationKBService{
kb: &types.KnowledgeBase{ID: "kb-1", TenantID: 7},
}}
ctx := types.WithCaller(context.Background(), types.Caller{TenantID: 42, UserID: "u", Role: types.TenantRoleOwner})
ctx = types.WithExecutionTenant(ctx, 7)
_, err := h.getKnowledgeBaseForInitialization(ctx, "kb-1")
requireForbidden(t, err)
}
func TestInitializationAllowsOwnKB(t *testing.T) {
h := &InitializationHandler{kbService: &stubInitializationKBService{
kb: &types.KnowledgeBase{ID: "kb-1", TenantID: 42},
}}
ctx := types.WithCaller(context.Background(),
types.Caller{TenantID: 42, UserID: "u", Role: types.TenantRoleContributor})
if _, err := h.getKnowledgeBaseForInitialization(ctx, "kb-1"); err != nil {
t.Fatalf("own KB rejected: %v", err)
}
}
// Rewriting an already-stored model needs the same authority as PUT
// /models/:id; creating the KB's first models does not.
func TestInitializationExistingModelUpdateRequiresModelAuthority(t *testing.T) {
enforced := true
stored := &types.Model{ID: "m-existing", Type: types.ModelTypeKnowledgeQA, TenantID: 42}
kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 42, SummaryModelID: "m-existing"}
caller := func(role types.TenantRole) context.Context {
return types.WithCaller(context.Background(), types.Caller{TenantID: 42, UserID: "u", Role: role})
}
scopedKey := func(capability types.APIKeyCapability) context.Context {
scope := types.TenantAPIKeyScope{Capabilities: types.StringArray{string(capability)}}
return types.WithTenantAPIKeyScope(caller(types.TenantRoleViewer), scope)
}
cases := []struct {
name string
ctx context.Context
allowed bool
}{
{"contributor", caller(types.TenantRoleContributor), false},
{"admin", caller(types.TenantRoleAdmin), true},
{"scoped key without manage_models", scopedKey(types.APIKeyCapabilityManageKnowledgeBases), false},
{"scoped key with manage_models", scopedKey(types.APIKeyCapabilityManageModels), true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
svc := &stubTenantStampModelService{getModelByID: func(_ context.Context, id string) (*types.Model, error) {
if id == stored.ID {
copied := *stored
return &copied, nil
}
return nil, nil
}}
h := &InitializationHandler{
modelService: svc,
config: &config.Config{Tenant: &config.TenantConfig{EnableRBAC: &enforced}},
}
_, err := h.processInitializationModels(tc.ctx, kb, "kb-1", newTenantStampRequest())
if tc.allowed {
if err != nil || len(svc.updated) != 1 {
t.Fatalf("err = %v, updated = %d, want one update", err, len(svc.updated))
}
return
}
requireForbidden(t, err)
if len(svc.updated) != 0 {
t.Fatalf("model was updated despite missing authority")
}
})
}
}
type stubInitializationKBRepo struct {
interfaces.KnowledgeBaseRepository
updated *types.KnowledgeBase
}
func (r *stubInitializationKBRepo) UpdateKnowledgeBase(_ context.Context, kb *types.KnowledgeBase) error {
r.updated = kb
return nil
}
// PUT /initialization/config shares the route guard (KBAccessWrite) that
// admits share editors. KB settings belong to the owner and to admin shares
// only, and a share admin still cannot rebind the owner's storage.
func TestUpdateKBConfigFromAnotherWorkspace(t *testing.T) {
backend := "backend-of-owner"
cases := []struct {
name string
permission types.OrgMemberRole
body string
wantStatus int
}{
{
name: "share editor", permission: types.OrgRoleEditor,
body: `{"llmModelId":"m-llm"}`, wantStatus: http.StatusForbidden,
},
{
name: "share admin rebinding storage", permission: types.OrgRoleAdmin,
body: `{"llmModelId":"m-llm","storageBackendId":"backend-of-receiver"}`, wantStatus: http.StatusForbidden,
},
{
name: "share admin keeping storage", permission: types.OrgRoleAdmin,
body: `{"llmModelId":"m-llm","storageBackendId":"backend-of-owner","storageProvider":"minio"}`,
wantStatus: http.StatusOK,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 7, StorageBackendID: &backend}
repo := &stubInitializationKBRepo{}
models := &stubTenantStampModelService{getModelByID: func(context.Context, string) (*types.Model, error) {
return &types.Model{ID: "m-llm", TenantID: 7}, nil
}}
h := &InitializationHandler{
kbService: &stubInitializationKBService{kb: kb},
kbRepository: repo,
modelService: models,
}
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Params = gin.Params{{Key: "kbId", Value: "kb-1"}}
req := httptest.NewRequest(http.MethodPut, "/", strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
caller := types.Caller{TenantID: 42, UserID: "u", Role: types.TenantRoleAdmin}
ctx := types.WithExecutionTenant(types.WithCaller(req.Context(), caller), 7)
c.Request = req.WithContext(ctx)
c.Set(middleware.KBAccessContextKey, &access.KBAccess{
KnowledgeBase: kb, Caller: caller, EffectiveTenantID: 7, Permission: tc.permission,
})
h.UpdateKBConfig(c)
if tc.wantStatus == http.StatusOK {
require.Empty(t, c.Errors)
require.NotNil(t, repo.updated)
require.Equal(t, backend, *repo.updated.StorageBackendID)
return
}
require.Len(t, c.Errors, 1)
requireForbidden(t, c.Errors[0].Err)
require.Nil(t, repo.updated, "KB must not be written")
})
}
}
+81
View File
@@ -0,0 +1,81 @@
package handler
import (
stderrors "errors"
"academy/internal/application/access"
"academy/internal/application/repository"
apperrors "academy/internal/errors"
"academy/internal/logger"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// resolvedKBAccess reuses only a grant for this caller and this resource. A
// Viewer grant cannot satisfy an Editor check after the tenant context switches.
func resolvedKBAccess(c *gin.Context, kbID string, required types.OrgMemberRole) (*access.KBAccess, bool) {
grant, ok := middleware.KBAccessFromContext(c)
return grant, ok && grant.KnowledgeBase != nil && grant.KnowledgeBase.ID == kbID &&
grant.Caller == middleware.KBAccessRequest(c).Caller &&
access.HasKBGrant(grant.WithGrant(c.Request.Context()), kbID, grant.EffectiveTenantID, required)
}
// resolveHandlerKBAccess is also used by body/query-based endpoints that cannot
// resolve a single KB in route middleware. It always enforces access, preserving
// the handler checks even when the middleware's RBAC rollout flag is disabled.
func resolveHandlerKBAccess(c *gin.Context, kbID string, kbService middleware.KBLookup,
shares interfaces.KBShareService, agents interfaces.AgentShareService,
) (*access.KBAccess, error) {
return resolveHandlerKBAccessFor(c, kbID, kbService, shares, agents, types.OrgRoleViewer)
}
func resolveHandlerKBAccessFor(c *gin.Context, kbID string, kbService middleware.KBLookup,
shares interfaces.KBShareService, agents interfaces.AgentShareService, required types.OrgMemberRole,
) (*access.KBAccess, error) {
ctx := c.Request.Context()
request := middleware.KBAccessRequest(c)
if request.Caller.TenantID == 0 {
return nil, apperrors.NewUnauthorizedError("Unauthorized")
}
if kbID == "" {
return nil, apperrors.NewBadRequestError("Knowledge base ID cannot be empty")
}
if err := requireTenantAPIKeyKnowledgeBase(ctx, kbID); err != nil {
return nil, err
}
if grant, ok := resolvedKBAccess(c, kbID, required); ok {
return grant, nil
}
kb, err := kbService.GetKnowledgeBaseByID(ctx, kbID)
if err != nil {
if stderrors.Is(err, repository.ErrKnowledgeBaseNotFound) {
return nil, apperrors.NewNotFoundError("knowledge base not found")
}
logger.ErrorWithFields(ctx, err, nil)
return nil, apperrors.NewInternalServerError(err.Error())
}
grant, err := access.ResolveKB(ctx, request, kb, required, shares, agents)
if err == nil {
// Preserve authorization for body-based routes without changing the
// execution tenant until the handler performs its resource operation.
c.Request = c.Request.WithContext(grant.WithGrant(ctx))
}
return grant, kbAccessHTTPError(err)
}
func kbAccessHTTPError(err error) error {
switch {
case stderrors.Is(err, access.ErrUnauthorized):
return apperrors.NewUnauthorizedError("Unauthorized")
case stderrors.Is(err, access.ErrNotFound):
return apperrors.NewNotFoundError("knowledge base not found")
case stderrors.Is(err, access.ErrForbidden):
return apperrors.NewForbiddenError("Permission denied to access this knowledge base")
case stderrors.Is(err, access.ErrInvalidAgentSource):
return apperrors.NewBadRequestError("invalid agent_source_tenant_id")
default:
return err
}
}
+229
View File
@@ -0,0 +1,229 @@
package handler
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/config"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type handlerKBShareStub struct {
interfaces.KBShareService
calls int
caller uint64
}
func (s *handlerKBShareStub) CheckTenantKBPermission(
_ context.Context,
_ string,
caller uint64,
_ types.TenantRole,
) (types.OrgMemberRole, bool, error) {
s.calls++
s.caller = caller
return types.OrgRoleViewer, true, nil
}
type handlerKnowledgeAccessStub struct {
interfaces.KnowledgeService
knowledge *types.Knowledge
}
func (s *handlerKnowledgeAccessStub) GetKnowledgeByIDOnly(context.Context, string) (*types.Knowledge, error) {
return s.knowledge, nil
}
func TestKBGuardAndHandlersShareResolution(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, ginCallerKey := range []bool{true, false} {
name := "request context only"
if ginCallerKey {
name = "both context surfaces"
}
t.Run(name, func(t *testing.T) {
kb := &types.KnowledgeBase{ID: "kb", TenantID: 2}
lookups := 0
svc := &stubKBOnlyService{getByID: func(context.Context, string) (*types.KnowledgeBase, error) {
lookups++
return kb, nil
}}
shares := &handlerKBShareStub{}
kg := &handlerKnowledgeAccessStub{
knowledge: &types.Knowledge{ID: "doc", KnowledgeBaseID: "kb", TenantID: 2},
}
h := &KnowledgeHandler{kbService: svc, kgService: kg, kbShareService: shares}
kbHandler := &KnowledgeBaseHandler{service: svc, kbShareService: shares}
r := gin.New()
r.Use(middleware.ErrorHandler(), func(c *gin.Context) {
ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(1))
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleViewer)
c.Request = c.Request.WithContext(ctx)
if ginCallerKey {
c.Set(types.TenantIDContextKey.String(), uint64(1))
}
c.Next()
})
enabled := true
r.GET("/:id", middleware.RequireKBAccess(
middleware.KBIDFromParam("id"),
types.OrgRoleViewer,
svc,
shares,
nil,
&config.Config{Tenant: &config.TenantConfig{EnableRBAC: &enabled}},
), func(c *gin.Context) {
_, _, effective, permission, err := kbHandler.validateAndGetKnowledgeBase(c)
require.NoError(t, err)
require.Equal(t, uint64(2), effective)
require.Equal(t, types.OrgRoleViewer, permission)
_, _, _, permission, err = h.validateKnowledgeBaseAccess(c)
require.NoError(t, err)
require.Equal(t, types.OrgRoleViewer, permission)
_, ctx, err := h.resolveKnowledgeAndValidateKBAccess(c, "doc", types.OrgRoleViewer)
require.NoError(t, err)
require.Equal(t, uint64(2), types.MustTenantIDFromContext(ctx))
require.Equal(t, uint64(1), types.CallerFromContext(ctx).TenantID)
require.Equal(t, 1, lookups, "handlers must reuse the guarded KB")
require.Equal(t, 1, shares.calls, "handlers must reuse the permission decision")
// The effective tenant is 2, but the write must still be checked
// as caller 1 and rejected, not upgraded to resource ownership.
_, _, err = h.resolveKnowledgeAndValidateKBAccess(c, "doc", types.OrgRoleEditor)
require.Error(t, err)
require.Equal(t, uint64(1), shares.caller)
c.Status(http.StatusNoContent)
})
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/kb", nil))
require.Equal(t, http.StatusNoContent, w.Code, w.Body.String())
})
}
}
func TestKBHandlerDoesNotReuseGrantForAnotherResourceOrCaller(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tt := range []struct {
name, requestedID string
caller uint64
}{
{name: "another KB", requestedID: "other", caller: 1},
{name: "another caller", requestedID: "kb", caller: 3},
} {
t.Run(tt.name, func(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
c.Set(types.TenantIDContextKey.String(), tt.caller)
c.Set(middleware.KBAccessContextKey, &middleware.KBAccess{
KnowledgeBase: &types.KnowledgeBase{ID: "kb", TenantID: 2},
Caller: types.Caller{
TenantID: 1,
Role: types.TenantRoleViewer,
}, EffectiveTenantID: 2, Permission: types.OrgRoleAdmin,
})
svc := &stubKBOnlyService{getByID: func(context.Context, string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: tt.requestedID, TenantID: 2}, nil
}}
_, err := resolveHandlerKBAccess(c, tt.requestedID, svc, nil, nil)
require.Error(t, err)
})
}
}
func TestKBHandlerAPIKeyScopeStillAppliesToCachedGrant(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
ctx := types.WithTenantAPIKeyScope(
context.Background(),
types.TenantAPIKeyScope{KnowledgeBaseIDs: types.StringArray{"other"}},
)
c.Request = httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx)
c.Set(types.TenantIDContextKey.String(), uint64(1))
c.Set(middleware.KBAccessContextKey, &middleware.KBAccess{
KnowledgeBase: &types.KnowledgeBase{ID: "kb", TenantID: 1},
Caller: types.Caller{
TenantID: 1,
Role: types.TenantRoleViewer,
}, EffectiveTenantID: 1, Permission: types.OrgRoleAdmin,
})
_, err := resolveHandlerKBAccess(c, "kb", nil, nil, nil)
require.Error(t, err)
}
type handlerAgentAccessStub struct {
interfaces.AgentShareService
anyCalls int
}
func (s *handlerAgentAccessStub) GetSharedAgentForTenant(
context.Context,
uint64,
types.TenantRole,
string,
...uint64,
) (*types.CustomAgent, error) {
return &types.CustomAgent{TenantID: 2, Config: types.CustomAgentConfig{KBSelectionMode: "none"}}, nil
}
func (s *handlerAgentAccessStub) TenantCanAccessKBViaSomeSharedAgent(
context.Context,
uint64,
types.TenantRole,
*types.KnowledgeBase,
) (bool, error) {
s.anyCalls++
return true, nil
}
func TestKBHandlersHonorExplicitAgentWithoutRouteGuard(t *testing.T) {
for _, query := range []string{"", "?agent_id=restricted"} {
t.Run(query, func(t *testing.T) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, "/kb"+query, nil)
c.Set(types.TenantIDContextKey.String(), uint64(1))
c.Params = gin.Params{{Key: "id", Value: "kb"}}
svc := &stubKBOnlyService{getByID: func(context.Context, string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "kb", TenantID: 2}, nil
}}
agents := &handlerAgentAccessStub{}
h := &KnowledgeHandler{kbService: svc, agentShareService: agents}
kbHandler := &KnowledgeBaseHandler{service: svc, agentShareService: agents}
_, _, _, _, kbErr := kbHandler.validateAndGetKnowledgeBase(c)
_, _, _, _, knowledgeErr := h.validateKnowledgeBaseAccessWithKBID(c, "kb")
if query == "" {
require.NoError(t, kbErr)
require.NoError(t, knowledgeErr)
require.Equal(t, 2, agents.anyCalls)
} else {
require.Error(t, kbErr)
require.Error(t, knowledgeErr)
require.Zero(t, agents.anyCalls)
}
})
}
}
func TestKBHandlerEnforcesAccessWhenRouteRBACIsDisabled(t *testing.T) {
svc := &stubKBOnlyService{getByID: func(context.Context, string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "kb", TenantID: 2}, nil
}}
r := gin.New()
r.Use(middleware.ErrorHandler(), func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(1))
c.Next()
})
disabled := false
r.GET("/:id", middleware.RequireKBAccess(middleware.KBIDFromParam("id"), types.OrgRoleViewer,
svc, nil, nil, &config.Config{Tenant: &config.TenantConfig{EnableRBAC: &disabled}}), func(c *gin.Context) {
_, err := resolveHandlerKBAccess(c, c.Param("id"), svc, nil, nil)
require.Error(t, err)
_ = c.Error(err)
})
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/kb", nil))
require.Equal(t, http.StatusForbidden, w.Code)
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,88 @@
package handler
import (
"context"
"testing"
"academy/internal/types"
)
func TestRequireTenantAPIKeyKnowledgeBaseAllowsUnrestrictedCaller(t *testing.T) {
ctx := context.Background()
if err := requireTenantAPIKeyKnowledgeBase(ctx, "kb-1"); err != nil {
t.Fatalf("unrestricted caller error = %v, want nil", err)
}
}
func TestRequireTenantAPIKeyKnowledgeBaseRejectsOutOfScopeKB(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
KnowledgeBaseIDs: types.StringArray{"kb-1"},
})
if err := requireTenantAPIKeyKnowledgeBase(ctx, "kb-2"); err == nil {
t.Fatal("expected forbidden for out-of-scope kb_id")
}
}
func TestIntersectKBAllowSetCombinesAgentAndAPIKeyScopes(t *testing.T) {
got := intersectKBAllowSet(
map[string]bool{"kb-1": true, "kb-2": true},
map[string]bool{"kb-2": true, "kb-3": true},
)
if len(got) != 1 || !got["kb-2"] {
t.Fatalf("intersection = %#v, want only kb-2", got)
}
}
func TestFilterKnowledgesByKBAllowSet(t *testing.T) {
in := []*types.Knowledge{
{ID: "k1", KnowledgeBaseID: "kb-1"},
{ID: "k2", KnowledgeBaseID: "kb-2"},
}
got := filterKnowledgesByKBAllowSet(in, map[string]bool{"kb-1": true})
if len(got) != 1 || got[0].ID != "k1" {
t.Fatalf("filtered = %#v, want only k1", got)
}
}
func TestFilterKnowledgeSearchScopesForAPIKey(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
KnowledgeBaseIDs: types.StringArray{"kb-1"},
})
scopes := []types.KnowledgeSearchScope{
{TenantID: 1, KBID: "kb-1"},
{TenantID: 1, KBID: "kb-2"},
}
got := filterKnowledgeSearchScopesForAPIKey(ctx, scopes)
if len(got) != 1 || got[0].KBID != "kb-1" {
t.Fatalf("filtered scopes = %#v, want only kb-1", got)
}
}
func TestTenantAPIKeySearchScopesUsesCallerTenant(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
KnowledgeBaseIDs: types.StringArray{"kb-1", "kb-2"},
})
ctx = context.WithValue(ctx, types.TenantIDContextKey, uint64(42))
scopes, restricted := tenantAPIKeySearchScopes(ctx)
if !restricted {
t.Fatal("expected restricted search scopes")
}
if len(scopes) != 2 {
t.Fatalf("scopes len = %d, want 2", len(scopes))
}
for _, scope := range scopes {
if scope.TenantID != 42 {
t.Fatalf("scope tenant_id = %d, want 42", scope.TenantID)
}
}
}
func TestRequireTenantAPIKeyKnowledgeBasesRejectsPartialOverlap(t *testing.T) {
ctx := types.WithTenantAPIKeyScope(context.Background(), types.TenantAPIKeyScope{
KnowledgeBaseIDs: types.StringArray{"kb-1"},
})
if err := requireTenantAPIKeyKnowledgeBases(ctx, "kb-1", "kb-2"); err == nil {
t.Fatal("expected forbidden when one kb_id is out of scope")
}
}
+361
View File
@@ -0,0 +1,361 @@
package handler
import (
"archive/zip"
"context"
stderrors "errors"
"fmt"
"io"
"net/http"
"os"
"path"
"strings"
"time"
"unicode"
"academy/internal/errors"
"academy/internal/filetransport"
"academy/internal/logger"
"academy/internal/types"
"github.com/gin-gonic/gin"
)
const (
maxBatchDownloadFiles = 200
maxBatchDownloadBytes int64 = 512 * 1024 * 1024
maxConcurrentBatchDownloads = 4
)
var batchDownloadSlots = make(chan struct{}, maxConcurrentBatchDownloads)
// BatchDownloadKnowledgeRequest 指定同一知识库中需要下载的文档。
type BatchDownloadKnowledgeRequest struct {
IDs []string `json:"ids" binding:"required,min=1,max=200,dive,required,max=128"`
}
type knowledgeDownloadEntry struct {
ID string
FolderPath string
}
// BatchDownloadKnowledge godoc
// @Summary 批量下载知识文件
// @Description 将同一知识库的最多 200 个文档打包为 ZIP,原始内容合计不超过 512 MiB。无原文件的条目会被跳过;无权访问、跨库或读取失败时不返回残缺压缩包。
// @Tags 知识管理
// @Accept json
// @Produce application/zip
// @Param id path string true "知识库ID"
// @Param request body BatchDownloadKnowledgeRequest true "文档ID列表"
// @Success 200 {file} file "ZIP 压缩包"
// @Failure 400 {object} errors.AppError
// @Failure 401 {object} errors.AppError
// @Failure 403 {object} errors.AppError
// @Failure 404 {object} errors.AppError
// @Failure 429 {object} errors.AppError
// @Failure 500 {object} errors.AppError
// @Security Bearer
// @Security ApiKeyAuth
// @Router /knowledge-bases/{id}/knowledge/batch-download [post]
func (h *KnowledgeHandler) BatchDownloadKnowledge(c *gin.Context) {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 64*1024)
var req BatchDownloadKnowledgeRequest
if err := c.ShouldBindJSON(&req); err != nil {
_ = c.Error(errors.NewBadRequestError("请选择 1~200 个文档进行批量下载"))
return
}
kbID := c.Param("id")
grant, err := resolveHandlerKBAccessFor(
c, kbID, h.kbService, h.kbShareService, h.agentShareService, types.OrgRoleEditor,
)
if err != nil {
_ = c.Error(err)
return
}
tenantID := grant.EffectiveTenantID
ctx := types.WithExecutionTenant(c.Request.Context(), tenantID)
ids := uniqueKnowledgeDownloadIDs(req.IDs)
if len(ids) == 0 {
_ = c.Error(errors.NewBadRequestError("文档 ID 不能为空"))
return
}
items, err := h.kgService.GetKnowledgeBatch(ctx, tenantID, ids)
if err != nil {
_ = c.Error(errors.NewInternalServerError("无法获取待下载文档,请稍后重试"))
return
}
byID := make(map[string]*types.Knowledge, len(items))
for _, item := range items {
if item != nil && item.KnowledgeBaseID == kbID && item.TenantID == tenantID {
byID[item.ID] = item
}
}
entries := make([]knowledgeDownloadEntry, 0, len(ids))
// 在读取任何文件之前检查整批文档,防止混入其他知识库或租户的 ID。
for _, id := range ids {
item := byID[id]
if item == nil {
_ = c.Error(errors.NewNotFoundError("部分文档不存在或不属于当前知识库,请刷新列表后重试"))
return
}
if !item.IsManual() && item.FilePath == "" {
continue
}
entries = append(entries, knowledgeDownloadEntry{ID: id, FolderPath: item.FolderPath})
}
if len(entries) == 0 {
_ = c.Error(errors.NewBadRequestError("所选文档没有可下载的原始文件,请取消选择后重试"))
return
}
if !tryAcquireBatchDownloadSlot() {
_ = c.Error(errors.NewTooManyRequestsError("当前批量下载过多,请稍后重试"))
return
}
defer releaseBatchDownloadSlot()
// 先在临时文件中完整生成压缩包,避免读取失败时向用户返回残缺 ZIP。
archive, err := os.CreateTemp("", "academy-download-*.zip")
if err != nil {
_ = c.Error(errors.NewInternalServerError("无法创建下载压缩包,请稍后重试"))
return
}
archivePath := archive.Name()
defer func() {
_ = archive.Close()
_ = os.Remove(archivePath)
}()
if err := writeKnowledgeDownloadArchive(
ctx, archive, entries, h.kgService.GetKnowledgeFile, maxBatchDownloadBytes,
); err != nil {
mapped := mapKnowledgeDownloadError(err)
if appErr, ok := errors.IsAppError(mapped); !ok || appErr.HTTPCode >= 500 {
logger.ErrorWithFields(ctx, err, nil)
}
_ = c.Error(mapped)
return
}
if _, err := archive.Seek(0, io.SeekStart); err != nil {
_ = c.Error(errors.NewInternalServerError("无法读取下载压缩包,请稍后重试"))
return
}
filename := "knowledge-files-" + time.Now().Format("20060102-150405") + ".zip"
if err := filetransport.Serve(c.Writer, c.Request, archive, filetransport.Options{
Filename: filename, Download: true, ContentType: "application/zip", CacheControl: "private, no-store",
}); err != nil {
logger.Errorf(ctx, "Failed to send knowledge archive: %v", err)
}
}
func tryAcquireBatchDownloadSlot() bool {
select {
case batchDownloadSlots <- struct{}{}:
return true
default:
return false
}
}
func releaseBatchDownloadSlot() {
<-batchDownloadSlots
}
func uniqueKnowledgeDownloadIDs(input []string) []string {
ids := make([]string, 0, len(input))
seen := make(map[string]bool, len(input))
for _, id := range input {
id = strings.TrimSpace(id)
if id != "" && !seen[id] {
seen[id] = true
ids = append(ids, id)
}
}
return ids
}
func isKnowledgeDownloadCanceled(err error) bool {
return err != nil && (stderrors.Is(err, context.Canceled) || stderrors.Is(err, context.DeadlineExceeded))
}
func mapKnowledgeDownloadError(err error) error {
if err == nil {
return nil
}
if _, ok := errors.IsAppError(err); ok {
return err
}
if isKnowledgeDownloadCanceled(err) {
return errors.NewBadRequestError("下载已取消")
}
return err
}
type knowledgeDownloadOpener func(context.Context, string) (io.ReadCloser, string, error)
func writeKnowledgeDownloadArchive(
ctx context.Context,
output io.Writer,
entries []knowledgeDownloadEntry,
open knowledgeDownloadOpener,
limit int64,
) error {
writer := zip.NewWriter(output)
usedNames := make(map[string]bool, len(entries))
var total int64
for _, entry := range entries {
if err := ctx.Err(); err != nil {
return err
}
file, filename, err := open(ctx, entry.ID)
if err != nil {
if isKnowledgeDownloadCanceled(err) {
return err
}
return errors.NewInternalServerError("部分文件无法读取,未生成压缩包,请检查文档后重试").WithDetails(
gin.H{"knowledge_id": entry.ID},
)
}
name := uniqueKnowledgeDownloadZipPath(entry.FolderPath, filename, usedNames)
// 原样存储可避免 PDF、Office 等已压缩文件再次压缩的 CPU 开销。
zipEntry, err := writer.CreateHeader(&zip.FileHeader{Name: name, Method: zip.Store})
if err != nil {
_ = file.Close()
return errors.NewInternalServerError("无法写入下载压缩包,请稍后重试")
}
n, copyErr := io.Copy(zipEntry, io.LimitReader(
&knowledgeDownloadReader{ctx: ctx, reader: file}, limit-total+1,
))
closeErr := file.Close()
total += n
if total > limit {
return errors.NewBadRequestError("所选文件合计超过 512 MiB,请分批下载")
}
if isKnowledgeDownloadCanceled(copyErr) {
return copyErr
}
if copyErr != nil || closeErr != nil {
return errors.NewInternalServerError("部分文件读取失败,未生成压缩包,请稍后重试").WithDetails(
gin.H{"knowledge_id": entry.ID},
)
}
}
if err := writer.Close(); err != nil {
return errors.NewInternalServerError("无法完成下载压缩包,请稍后重试")
}
return nil
}
// 每次读取前检查取消信号,用户离开页面后停止继续打包。
type knowledgeDownloadReader struct {
ctx context.Context
reader io.Reader
}
func (r *knowledgeDownloadReader) Read(p []byte) (int, error) {
if err := r.ctx.Err(); err != nil {
return 0, err
}
return r.reader.Read(p)
}
func uniqueKnowledgeDownloadName(filename string, used map[string]bool) string {
return uniqueKnowledgeDownloadZipPath("", filename, used)
}
func uniqueKnowledgeDownloadZipPath(folderPath, filename string, used map[string]bool) string {
base := sanitizeDownloadFileName(filename)
ext := path.Ext(base)
stem := strings.TrimSuffix(base, ext)
dir := sanitizeDownloadFolderPath(folderPath)
name := base
if dir != "" {
name = dir + "/" + base
}
for index := 2; used[strings.ToLower(name)]; index++ {
suffixed := fmt.Sprintf("%s (%d)%s", stem, index, ext)
if dir != "" {
name = dir + "/" + suffixed
} else {
name = suffixed
}
}
used[strings.ToLower(name)] = true
return name
}
func sanitizeDownloadFileName(filename string) string {
filename = path.Base(strings.ReplaceAll(filename, "\\", "/"))
filename = sanitizeDownloadRunes(filename)
filename = strings.Trim(filename, " .")
if filename == "" {
filename = "document"
}
ext := path.Ext(filename)
if len(ext) > 20 {
ext = ""
}
stem := strings.TrimSuffix(filename, ext)
stem = shortenDownloadName(stem, 180)
stem = strings.TrimRight(stem, " .")
if stem == "" {
stem = "document"
}
return escapeWindowsReservedName(stem) + ext
}
func sanitizeDownloadFolderPath(folderPath string) string {
folderPath = strings.ReplaceAll(folderPath, "\\", "/")
var parts []string
var total int
for _, part := range strings.Split(folderPath, "/") {
part = sanitizeDownloadRunes(part)
part = strings.Trim(part, " .")
if part == "" || part == "." || part == ".." {
continue
}
part = shortenDownloadName(part, 80)
part = strings.TrimRight(part, " .")
if part == "" {
continue
}
part = escapeWindowsReservedName(part)
if total+len(part)+1 > 160 {
break
}
parts = append(parts, part)
total += len(part) + 1
}
return strings.Join(parts, "/")
}
func sanitizeDownloadRunes(value string) string {
return strings.Map(func(r rune) rune {
if unicode.IsControl(r) || strings.ContainsRune(`<>:"/\|?*`, r) {
return '_'
}
return r
}, value)
}
func shortenDownloadName(value string, limit int) string {
var shortened strings.Builder
for _, r := range value {
if shortened.Len()+len(string(r)) > limit {
break
}
shortened.WriteRune(r)
}
return shortened.String()
}
func escapeWindowsReservedName(stem string) string {
reserved := strings.ToUpper(strings.Split(stem, ".")[0])
reservedRunes := []rune(reserved)
if reserved == "CON" || reserved == "PRN" || reserved == "AUX" || reserved == "NUL" ||
(len(reservedRunes) == 4 && (strings.HasPrefix(reserved, "COM") || strings.HasPrefix(reserved, "LPT")) &&
strings.ContainsRune("123456789¹²³", reservedRunes[3])) {
return "_" + stem
}
return stem
}
+393
View File
@@ -0,0 +1,393 @@
package handler
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"unicode/utf8"
apperrors "academy/internal/errors"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type downloadKnowledgeStub struct {
interfaces.KnowledgeService
items []*types.Knowledge
names map[string]string
opened []string
failID string
expectedTenant uint64
}
func (s *downloadKnowledgeStub) GetKnowledgeBatch(context.Context, uint64, []string) ([]*types.Knowledge, error) {
return s.items, nil
}
func (s *downloadKnowledgeStub) GetKnowledgeFile(ctx context.Context, id string) (io.ReadCloser, string, error) {
want := s.expectedTenant
if want == 0 {
want = 7
}
if types.MustTenantIDFromContext(ctx) != want {
return nil, "", fmt.Errorf("错误的租户上下文")
}
s.opened = append(s.opened, id)
if s.failID == id {
return nil, "", fmt.Errorf("模拟存储读取失败")
}
return io.NopCloser(strings.NewReader("原文-" + id)), s.names[id], nil
}
type downloadKBStub struct {
interfaces.KnowledgeBaseService
kb *types.KnowledgeBase
}
func (s *downloadKBStub) GetKnowledgeBaseByID(context.Context, string) (*types.KnowledgeBase, error) {
return s.kb, nil
}
type downloadShareStub struct {
interfaces.KBShareService
permission types.OrgMemberRole
}
func (s *downloadShareStub) CheckTenantKBPermission(
context.Context, string, uint64, types.TenantRole,
) (types.OrgMemberRole, bool, error) {
return s.permission, true, nil
}
func runBatchDownload(
t *testing.T,
svc *downloadKnowledgeStub,
ids []string,
kb *types.KnowledgeBase,
share interfaces.KBShareService,
scope *types.TenantAPIKeyScope,
) *httptest.ResponseRecorder {
t.Helper()
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(middleware.ErrorHandler(), func(c *gin.Context) {
ctx := types.WithCaller(c.Request.Context(), types.Caller{
TenantID: 7, UserID: "user-1", Role: types.TenantRoleContributor,
})
ctx = types.WithExecutionTenant(ctx, 7)
if scope != nil {
ctx = types.WithTenantAPIKeyScope(ctx, *scope)
}
c.Request = c.Request.WithContext(ctx)
c.Set(types.TenantIDContextKey.String(), uint64(7))
c.Set(types.UserIDContextKey.String(), "user-1")
c.Next()
})
h := &KnowledgeHandler{
kgService: svc,
kbService: &downloadKBStub{kb: kb},
kbShareService: share,
}
router.POST("/knowledge-bases/:id/knowledge/batch-download", h.BatchDownloadKnowledge)
body, err := json.Marshal(BatchDownloadKnowledgeRequest{IDs: ids})
require.NoError(t, err)
req := httptest.NewRequest(
http.MethodPost, "/knowledge-bases/kb-1/knowledge/batch-download", bytes.NewReader(body),
)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
return w
}
func TestBatchDownloadKnowledgeProducesCompleteZIP(t *testing.T) {
t.Setenv("TMPDIR", t.TempDir())
svc := &downloadKnowledgeStub{
items: []*types.Knowledge{
{ID: "a", TenantID: 7, KnowledgeBaseID: "kb-1", FilePath: "stored-a"},
{ID: "b", TenantID: 7, KnowledgeBaseID: "kb-1", Type: types.KnowledgeTypeManual},
{ID: "c", TenantID: 7, KnowledgeBaseID: "kb-1", FilePath: "stored-c"},
},
names: map[string]string{"a": "设计说明.md", "b": "设计说明.md", "c": `..\设计说明 (2).md`},
}
w := runBatchDownload(t, svc, []string{"a", "b", "a", "c"},
&types.KnowledgeBase{ID: "kb-1", TenantID: 7}, nil, nil)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
require.Equal(t, "application/zip", w.Header().Get("Content-Type"))
require.Equal(t, "private, no-store", w.Header().Get("Cache-Control"))
require.Contains(t, w.Header().Get("Content-Disposition"), "attachment")
reader, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len()))
require.NoError(t, err)
require.Len(t, reader.File, 3)
for index, name := range []string{"设计说明.md", "设计说明 (2).md", "设计说明 (2) (2).md"} {
entry := reader.File[index]
require.Equal(t, name, entry.Name)
file, err := entry.Open()
require.NoError(t, err)
content, err := io.ReadAll(file)
require.NoError(t, err)
require.NoError(t, file.Close())
require.Equal(t, "原文-"+[]string{"a", "b", "c"}[index], string(content))
}
require.Equal(t, []string{"a", "b", "c"}, svc.opened)
entries, err := os.ReadDir(os.TempDir())
require.NoError(t, err)
require.Empty(t, entries, "请求完成后不应留下临时压缩包")
}
func TestBatchDownloadKnowledgeRejectsInvalidSelectionsBeforeReading(t *testing.T) {
cases := []struct {
name string
ids []string
item *types.Knowledge
kb *types.KnowledgeBase
share interfaces.KBShareService
scope *types.TenantAPIKeyScope
status int
}{
{
name: "空列表", status: 400,
kb: &types.KnowledgeBase{ID: "kb-1", TenantID: 7},
},
{
name: "空白ID", ids: []string{" "}, status: 400,
kb: &types.KnowledgeBase{ID: "kb-1", TenantID: 7},
},
{
name: "超出数量", ids: make([]string, maxBatchDownloadFiles+1), status: 400,
kb: &types.KnowledgeBase{ID: "kb-1", TenantID: 7},
},
{
name: "文档缺失", ids: []string{"missing"}, status: 404,
kb: &types.KnowledgeBase{ID: "kb-1", TenantID: 7},
},
{
name: "跨知识库", ids: []string{"a"}, status: 404,
item: &types.Knowledge{ID: "a", TenantID: 7, KnowledgeBaseID: "other", FilePath: "secret"},
kb: &types.KnowledgeBase{ID: "kb-1", TenantID: 7},
},
{
name: "跨租户", ids: []string{"a"}, status: 404,
item: &types.Knowledge{ID: "a", TenantID: 8, KnowledgeBaseID: "kb-1", FilePath: "secret"},
kb: &types.KnowledgeBase{ID: "kb-1", TenantID: 7},
},
{
name: "仅无原文件", ids: []string{"a"}, status: 400,
item: &types.Knowledge{ID: "a", TenantID: 7, KnowledgeBaseID: "kb-1", Type: "url"},
kb: &types.KnowledgeBase{ID: "kb-1", TenantID: 7},
},
{
name: "共享只读", ids: []string{"a"}, status: 403,
kb: &types.KnowledgeBase{ID: "kb-1", TenantID: 8},
share: &downloadShareStub{permission: types.OrgRoleViewer},
},
{
name: "密钥无此库权限", ids: []string{"a"}, status: 403,
kb: &types.KnowledgeBase{ID: "kb-1", TenantID: 7},
scope: &types.TenantAPIKeyScope{KnowledgeBaseIDs: types.StringArray{"other"}},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
svc := &downloadKnowledgeStub{}
if tc.item != nil {
svc.items = []*types.Knowledge{tc.item}
}
w := runBatchDownload(t, svc, tc.ids, tc.kb, tc.share, tc.scope)
require.Equal(t, tc.status, w.Code, w.Body.String())
require.Empty(t, svc.opened)
require.NotContains(t, w.Header().Get("Content-Type"), "zip")
})
}
}
func TestBatchDownloadKnowledgeFailureDoesNotReturnPartialZIP(t *testing.T) {
t.Setenv("TMPDIR", t.TempDir())
svc := &downloadKnowledgeStub{
items: []*types.Knowledge{
{ID: "a", TenantID: 7, KnowledgeBaseID: "kb-1", FilePath: "a"},
{ID: "b", TenantID: 7, KnowledgeBaseID: "kb-1", FilePath: "b"},
},
names: map[string]string{"a": "first.txt"}, failID: "b",
}
w := runBatchDownload(t, svc, []string{"a", "b"},
&types.KnowledgeBase{ID: "kb-1", TenantID: 7}, nil, nil)
require.Equal(t, http.StatusInternalServerError, w.Code)
require.Contains(t, w.Header().Get("Content-Type"), "json")
require.Empty(t, w.Header().Get("Content-Disposition"))
entries, err := os.ReadDir(os.TempDir())
require.NoError(t, err)
require.Empty(t, entries)
}
type downloadTrackingReader struct {
io.Reader
closed bool
}
func (r *downloadTrackingReader) Close() error {
r.closed = true
return nil
}
func TestBatchDownloadKnowledgeSkipsEntriesWithoutOriginalFiles(t *testing.T) {
t.Setenv("TMPDIR", t.TempDir())
svc := &downloadKnowledgeStub{
items: []*types.Knowledge{
{ID: "a", TenantID: 7, KnowledgeBaseID: "kb-1", FilePath: "stored-a"},
{ID: "url", TenantID: 7, KnowledgeBaseID: "kb-1", Type: "url"},
},
names: map[string]string{"a": "keep.txt"},
}
w := runBatchDownload(t, svc, []string{"a", "url"},
&types.KnowledgeBase{ID: "kb-1", TenantID: 7}, nil, nil)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
reader, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len()))
require.NoError(t, err)
require.Len(t, reader.File, 1)
require.Equal(t, "keep.txt", reader.File[0].Name)
require.Equal(t, []string{"a"}, svc.opened)
}
func TestBatchDownloadKnowledgeAllowsSharedEditor(t *testing.T) {
t.Setenv("TMPDIR", t.TempDir())
svc := &downloadKnowledgeStub{
items: []*types.Knowledge{{ID: "a", TenantID: 8, KnowledgeBaseID: "kb-1", FilePath: "stored-a"}},
names: map[string]string{"a": "shared.txt"},
expectedTenant: 8,
}
w := runBatchDownload(t, svc, []string{"a"},
&types.KnowledgeBase{ID: "kb-1", TenantID: 8},
&downloadShareStub{permission: types.OrgRoleEditor}, nil)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
require.Equal(t, []string{"a"}, svc.opened)
}
func TestBatchDownloadKnowledgeRejectsWhenBusy(t *testing.T) {
for i := 0; i < maxConcurrentBatchDownloads; i++ {
batchDownloadSlots <- struct{}{}
}
t.Cleanup(func() {
for i := 0; i < maxConcurrentBatchDownloads; i++ {
<-batchDownloadSlots
}
})
svc := &downloadKnowledgeStub{
items: []*types.Knowledge{{ID: "a", TenantID: 7, KnowledgeBaseID: "kb-1", FilePath: "a"}},
names: map[string]string{"a": "a.txt"},
}
w := runBatchDownload(t, svc, []string{"a"},
&types.KnowledgeBase{ID: "kb-1", TenantID: 7}, nil, nil)
require.Equal(t, http.StatusTooManyRequests, w.Code, w.Body.String())
require.Empty(t, svc.opened)
}
func TestKnowledgeDownloadArchiveEnforcesActualByteLimitAndClosesFiles(t *testing.T) {
for _, limit := range []int64{4, 5} {
var output bytes.Buffer
file := &downloadTrackingReader{Reader: strings.NewReader("12345")}
err := writeKnowledgeDownloadArchive(context.Background(), &output,
[]knowledgeDownloadEntry{{ID: "a"}},
func(context.Context, string) (io.ReadCloser, string, error) { return file, "a.txt", nil }, limit)
if limit == 4 {
require.Error(t, err)
} else {
require.NoError(t, err)
}
require.True(t, file.closed)
}
}
func TestKnowledgeDownloadArchiveStopsWhenCancelled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
var output bytes.Buffer
err := writeKnowledgeDownloadArchive(ctx, &output, []knowledgeDownloadEntry{{ID: "a"}},
func(context.Context, string) (io.ReadCloser, string, error) {
t.Fatal("取消后不应继续读取文件")
return nil, "", nil
}, 100)
require.ErrorIs(t, err, context.Canceled)
require.Zero(t, output.Len())
}
func TestKnowledgeDownloadArchiveCancelsAfterOpenAndClosesFile(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
file := &downloadTrackingReader{Reader: strings.NewReader("12345")}
err := writeKnowledgeDownloadArchive(ctx, io.Discard, []knowledgeDownloadEntry{{ID: "a"}},
func(context.Context, string) (io.ReadCloser, string, error) {
cancel()
return file, "a.txt", nil
}, 100)
require.True(t, isKnowledgeDownloadCanceled(err), err)
require.True(t, file.closed)
requireAppHTTP(t, mapKnowledgeDownloadError(err), http.StatusBadRequest)
}
func TestMapKnowledgeDownloadError(t *testing.T) {
requireAppHTTP(t, mapKnowledgeDownloadError(context.Canceled), http.StatusBadRequest)
requireAppHTTP(t, mapKnowledgeDownloadError(context.DeadlineExceeded), http.StatusBadRequest)
}
func requireAppHTTP(t *testing.T, err error, status int) {
t.Helper()
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok, err)
require.Equal(t, status, appErr.HTTPCode)
}
func TestKnowledgeDownloadNamesAreSafeForWindowsAndUTF8(t *testing.T) {
used := map[string]bool{}
for _, name := range []string{
"../报告.txt", `C:\secret\Report.TXT`, "report.txt", "CON.txt", "COM¹.txt", "a:b?.txt", "..",
strings.Repeat("中", 100) + ".pdf",
} {
got := uniqueKnowledgeDownloadName(name, used)
require.True(t, utf8.ValidString(got))
require.NotContains(t, got, "/")
require.NotContains(t, got, "\\")
require.NotContains(t, got, ":")
require.NotEqual(t, "CON.txt", got)
require.NotEqual(t, "COM¹.txt", got)
require.Less(t, len(got), 255)
}
require.True(t, used["report (2).txt"])
}
func TestKnowledgeDownloadZipPathKeepsSafeFolders(t *testing.T) {
used := map[string]bool{}
require.Equal(t, "docs/spec/a.md", uniqueKnowledgeDownloadZipPath(`..\docs/spec`, "a.md", used))
require.Equal(t, "docs/spec/a (2).md", uniqueKnowledgeDownloadZipPath("docs/spec", "../a.md", used))
got := uniqueKnowledgeDownloadZipPath("/abs/../secret", "CON.txt", map[string]bool{})
require.Equal(t, "abs/secret/_CON.txt", got)
require.NotContains(t, got, "..")
require.False(t, strings.HasPrefix(got, "/"))
}
func TestBatchDownloadKnowledgePreservesFolderPaths(t *testing.T) {
t.Setenv("TMPDIR", t.TempDir())
svc := &downloadKnowledgeStub{
items: []*types.Knowledge{{
ID: "a", TenantID: 7, KnowledgeBaseID: "kb-1", FilePath: "stored-a", FolderPath: "docs/spec",
}},
names: map[string]string{"a": "design.md"},
}
w := runBatchDownload(t, svc, []string{"a"},
&types.KnowledgeBase{ID: "kb-1", TenantID: 7}, nil, nil)
require.Equal(t, http.StatusOK, w.Code, w.Body.String())
reader, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len()))
require.NoError(t, err)
require.Len(t, reader.File, 1)
require.Equal(t, "docs/spec/design.md", reader.File[0].Name)
}
+147
View File
@@ -0,0 +1,147 @@
package handler
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
)
type stubFolderKBService struct {
interfaces.KnowledgeBaseService
}
func (s *stubFolderKBService) GetKnowledgeBaseByID(_ context.Context, id string) (*types.KnowledgeBase, error) {
if id != "kb-1" {
return nil, errors.New("kb not found")
}
return &types.KnowledgeBase{ID: "kb-1", TenantID: 1, Type: types.KnowledgeBaseTypeDocument}, nil
}
type stubFolderKGService struct {
interfaces.KnowledgeService
gotFilter types.KnowledgeListFilter
tree *types.KnowledgeFolderTree
treeErr error
}
func (s *stubFolderKGService) ListPagedKnowledgeByKnowledgeBaseID(
_ context.Context,
_ string,
page *types.Pagination,
filter types.KnowledgeListFilter,
) (*types.PageResult, error) {
s.gotFilter = filter
return types.NewPageResult(0, page, []*types.Knowledge{}), nil
}
func (s *stubFolderKGService) ListKnowledgeFolderTree(
_ context.Context,
_ string,
) (*types.KnowledgeFolderTree, error) {
return s.tree, s.treeErr
}
func newFolderRouter(kg interfaces.KnowledgeService) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
r.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(1))
c.Set(types.UserIDContextKey.String(), "u-test")
c.Next()
})
h := &KnowledgeHandler{kbService: &stubFolderKBService{}, kgService: kg}
r.GET("/knowledge-bases/:id/knowledge", h.ListKnowledge)
r.GET("/knowledge-bases/:id/knowledge/folders", h.ListKnowledgeFolders)
return r
}
// The folder dimension is keyed off parameter presence, because an empty
// folder_path is a meaningful value (the knowledge base root) and must be
// distinguishable from "browse every folder".
func TestListKnowledge_FolderScopeFromQuery(t *testing.T) {
tests := []struct {
name string
query string
wantPath string
wantScope types.KnowledgeFolderScope
}{
{"absent parameter keeps the flat listing", "", "", types.FolderScopeAny},
{"empty parameter selects the root", "?folder_path=", "", types.FolderScopeExact},
{"folder selects that folder only", "?folder_path=docs/spec", "docs/spec", types.FolderScopeExact},
{"recursive selects the subtree", "?folder_path=docs&folder_recursive=true", "docs", types.FolderScopeSubtree},
{"recursive false stays exact", "?folder_path=docs&folder_recursive=false", "docs", types.FolderScopeExact},
{"path is normalized", "?folder_path=/docs//spec/", "docs/spec", types.FolderScopeExact},
{"traversal cannot escape the root", "?folder_path=../../spec", "spec", types.FolderScopeExact},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
kg := &stubFolderKGService{}
router := newFolderRouter(kg)
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/knowledge"+tt.query, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
}
if kg.gotFilter.FolderPath != tt.wantPath {
t.Fatalf("folder path = %q, want %q", kg.gotFilter.FolderPath, tt.wantPath)
}
if kg.gotFilter.FolderScope != tt.wantScope {
t.Fatalf("folder scope = %q, want %q", kg.gotFilter.FolderScope, tt.wantScope)
}
})
}
}
func TestListKnowledgeFolders_ReturnsTree(t *testing.T) {
kg := &stubFolderKGService{
tree: types.BuildKnowledgeFolderTree([]*types.KnowledgeFolderCount{
{FolderPath: "", Count: 1},
{FolderPath: "docs/spec", Count: 2},
}),
}
router := newFolderRouter(kg)
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/knowledge/folders", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
}
var body struct {
Success bool `json:"success"`
Data types.KnowledgeFolderTree `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
t.Fatalf("unmarshal response: %v; body=%s", err, w.Body.String())
}
if !body.Success {
t.Fatalf("success = false; body=%s", w.Body.String())
}
if body.Data.RootDocumentCount != 1 || body.Data.TotalDocumentCount != 3 {
t.Fatalf("counts = root %d total %d, want 1 / 3",
body.Data.RootDocumentCount, body.Data.TotalDocumentCount)
}
if len(body.Data.Folders) != 1 || body.Data.Folders[0].Path != "docs" {
t.Fatalf("folders = %+v, want a single \"docs\" root folder", body.Data.Folders)
}
if len(body.Data.Folders[0].Children) != 1 || body.Data.Folders[0].Children[0].Path != "docs/spec" {
t.Fatalf("children = %+v, want \"docs/spec\"", body.Data.Folders[0].Children)
}
}
+137
View File
@@ -0,0 +1,137 @@
package handler
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// stubGalleryChunkService records the knowledge ids one images-listing call
// received, so tests can assert how the GET cap and the POST body cap differ.
type stubGalleryChunkService struct {
interfaces.ChunkService
gotIDs []string
}
func (s *stubGalleryChunkService) ListImagesByKnowledgeBaseID(
_ context.Context,
_ string,
page *types.Pagination,
filter *types.ImageListFilter,
) (*types.PageResult, error) {
s.gotIDs = filter.KnowledgeIDs
return types.NewPageResult(0, page, []types.ImageAssetRow{}), nil
}
func newImagesRouter(chunks interfaces.ChunkService) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
r.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(1))
c.Set(types.UserIDContextKey.String(), "u-test")
c.Next()
})
h := &KnowledgeHandler{kbService: &stubFolderKBService{}, chunkService: chunks}
r.GET("/knowledge-bases/:id/images", h.ListImages)
r.POST("/knowledge-bases/:id/images", h.ListImagesPost)
return r
}
// commaIDs builds "id-0,id-1,..." of the requested size.
func commaIDs(n int) []string {
ids := make([]string, n)
for i := range ids {
ids[i] = fmt.Sprintf("0198c0de-0000-7000-8000-%012d", i)
}
return ids
}
func TestListImagesPost_KnowledgeIDBody(t *testing.T) {
tests := []struct {
name string
ids int
wantCap int
wantHTT int
}{
{
name: "60 ids pass the POST body although the GET cap is 50",
ids: 60,
wantCap: 60,
wantHTT: http.StatusOK,
},
{
name: "the body cap still guards abuse",
ids: maxKnowledgeIDFilterBody + 1,
wantCap: 0,
wantHTT: http.StatusBadRequest,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
svc := &stubGalleryChunkService{}
router := newImagesRouter(svc)
ids := commaIDs(tt.ids)
payload, _ := json.Marshal(map[string]any{"knowledge_ids": ids})
req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/kb-1/images",
strings.NewReader(string(payload)))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != tt.wantHTT {
t.Fatalf("status = %d, want %d; body=%s", w.Code, tt.wantHTT, w.Body.String())
}
if len(svc.gotIDs) != tt.wantCap {
t.Fatalf("got %d knowledge ids, want %d", len(svc.gotIDs), tt.wantCap)
}
})
}
}
func TestListImagesPost_EmptyBody(t *testing.T) {
svc := &stubGalleryChunkService{}
router := newImagesRouter(svc)
req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/kb-1/images", nil)
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
}
if len(svc.gotIDs) != 0 {
t.Fatalf("got %d knowledge ids, want none", len(svc.gotIDs))
}
}
func TestListImagesGet_KnowledgeIDCap(t *testing.T) {
svc := &stubGalleryChunkService{}
router := newImagesRouter(svc)
// 60 ids on the URL: the GET cap of 50 truncates them.
url := "/knowledge-bases/kb-1/images?knowledge_ids=" + strings.Join(commaIDs(60), ",")
req := httptest.NewRequest(http.MethodGet, url, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
}
if len(svc.gotIDs) != maxKnowledgeIDFilter {
t.Fatalf("got %d knowledge ids, want the GET cap %d", len(svc.gotIDs), maxKnowledgeIDFilter)
}
}
@@ -0,0 +1,134 @@
package handler
import (
"context"
"errors"
"fmt"
"testing"
"time"
"academy/internal/application/repository"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type lastActivitySpanRepo struct {
repository.KnowledgeSpanRepository
activity map[string]time.Time
err error
asked []string
}
func (r *lastActivitySpanRepo) LastActivity(_ context.Context, ids []string) (map[string]time.Time, error) {
r.asked = ids
return r.activity, r.err
}
// Only in-flight rows get last_activity_at, and a span write newer than the
// row's updated_at wins.
func TestAttachLastActivity(t *testing.T) {
base := time.Date(2026, 9, 22, 10, 0, 0, 0, time.UTC)
spans := &lastActivitySpanRepo{activity: map[string]time.Time{
"processing": base.Add(10 * time.Minute),
"finalizing": base.Add(-time.Hour),
}}
h := &KnowledgeHandler{spanRepo: spans}
rows := []*types.Knowledge{
{ID: "processing", ParseStatus: types.ParseStatusProcessing, UpdatedAt: base},
{ID: "finalizing", ParseStatus: types.ParseStatusFinalizing, UpdatedAt: base},
{ID: "pending", ParseStatus: types.ParseStatusPending, UpdatedAt: base},
{ID: "completed", ParseStatus: types.ParseStatusCompleted, UpdatedAt: base},
nil,
}
h.attachLastActivity(context.Background(), rows)
assert.Equal(t, []string{"processing", "finalizing", "pending"}, spans.asked)
require.NotNil(t, rows[0].LastActivityAt)
assert.Equal(t, base.Add(10*time.Minute), *rows[0].LastActivityAt)
require.NotNil(t, rows[1].LastActivityAt)
assert.Equal(t, base, *rows[1].LastActivityAt)
require.NotNil(t, rows[2].LastActivityAt)
assert.Equal(t, base, *rows[2].LastActivityAt)
assert.Nil(t, rows[3].LastActivityAt)
}
// A failed span lookup still reports the row's own updated_at.
func TestAttachLastActivityFallsBackToUpdatedAt(t *testing.T) {
base := time.Date(2026, 9, 22, 10, 0, 0, 0, time.UTC)
h := &KnowledgeHandler{spanRepo: &lastActivitySpanRepo{err: errors.New("db down")}}
rows := []*types.Knowledge{{ID: "k", ParseStatus: types.ParseStatusProcessing, UpdatedAt: base}}
h.attachLastActivity(context.Background(), rows)
require.NotNil(t, rows[0].LastActivityAt)
assert.Equal(t, base, *rows[0].LastActivityAt)
}
func TestSpansLastActivity(t *testing.T) {
base := time.Date(2026, 9, 22, 10, 0, 0, 0, time.UTC)
rows := []types.KnowledgeProcessingSpan{
{UpdatedAt: base.Add(-time.Minute)},
{UpdatedAt: base.Add(5 * time.Minute)},
}
assert.Equal(t, base.Add(5*time.Minute), spansLastActivity(base, rows))
assert.Equal(t, base, spansLastActivity(base, nil))
}
type fakeBacklog struct {
queued map[string]bool
err error
asked []string
}
func (f *fakeBacklog) QueuedWork(_ context.Context, ids []string) (map[string]bool, error) {
f.asked = append(f.asked, ids...)
if f.err != nil {
return nil, f.err
}
out := make(map[string]bool, len(ids))
for _, id := range ids {
out[id] = f.queued[id]
}
return out, nil
}
// Every row quiet past the stall hint gets a verdict, however many there
// are; rows still progressing are not probed.
func TestAttachLastActivityGivesEveryQuietRowAVerdict(t *testing.T) {
now := time.Now()
backlog := &fakeBacklog{queued: map[string]bool{"quiet-0": true}}
h := &KnowledgeHandler{spanRepo: &lastActivitySpanRepo{}, backlog: backlog}
rows := []*types.Knowledge{{ID: "recent", ParseStatus: types.ParseStatusProcessing, UpdatedAt: now}}
for i := 0; i < 40; i++ {
rows = append(rows, &types.Knowledge{
ID: fmt.Sprintf("quiet-%d", i), ParseStatus: types.ParseStatusProcessing, UpdatedAt: now.Add(-time.Hour),
})
}
h.attachLastActivity(context.Background(), rows)
assert.Len(t, backlog.asked, 40)
assert.Empty(t, rows[0].StallState)
assert.Equal(t, types.StallStateQueued, rows[1].StallState)
for _, k := range rows[2:] {
assert.Equal(t, types.StallStateStalled, k.StallState, k.ID)
}
}
// A failed probe leaves the verdict unknown instead of calling rows stuck.
func TestAttachLastActivityLeavesVerdictUnknownWhenProbeFails(t *testing.T) {
h := &KnowledgeHandler{
spanRepo: &lastActivitySpanRepo{},
backlog: &fakeBacklog{err: errors.New("redis down")},
}
rows := []*types.Knowledge{
{ID: "quiet", ParseStatus: types.ParseStatusProcessing, UpdatedAt: time.Now().Add(-time.Hour)},
}
h.attachLastActivity(context.Background(), rows)
require.NotNil(t, rows[0].LastActivityAt)
assert.Empty(t, rows[0].StallState)
}
@@ -0,0 +1,136 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// MoveKnowledge cross-store reuse_vectors gate — handler-level pre-flight tests.
//
// reuse_vectors copies vector indices between KBs through the source store only;
// a cross-store reuse_vectors move would corrupt vector data. The handler must
// reject it synchronously (before enqueueing the async move) and point the
// caller at reparse mode. reparse moves and same-store reuse_vectors must pass
// the gate (they fail later here only because the stub knowledge does not exist,
// which proves the gate did not short-circuit them).
type stubMoveKBService struct {
interfaces.KnowledgeBaseService
byID func(ctx context.Context, id string) (*types.KnowledgeBase, error)
}
func (s *stubMoveKBService) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) {
return s.byID(ctx, id)
}
// stubMoveKGService.GetKnowledgeByID always reports not-found, so any request
// that PASSES the store gate fails at the later knowledge-ID validation with a
// distinct message — letting the test tell "rejected by gate" apart from
// "passed the gate."
type stubMoveKGService struct {
interfaces.KnowledgeService
}
func (s *stubMoveKGService) GetKnowledgeByID(_ context.Context, _ string) (*types.Knowledge, error) {
return nil, errors.New("knowledge not found")
}
func newMoveGateRouter(kb interfaces.KnowledgeBaseService, kg interfaces.KnowledgeService) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
r.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(1))
c.Set(types.UserIDContextKey.String(), "u-test")
c.Next()
})
// asynqClient stays nil: every case here either rejects at the gate or
// fails at knowledge-ID validation, so enqueue is never reached. A nil
// deref would mean the gate let a request through to enqueue unexpectedly.
h := &KnowledgeHandler{kbService: kb, kgService: kg}
r.POST("/move", h.MoveKnowledge)
return r
}
func TestMoveKnowledge_CrossStoreGate(t *testing.T) {
storeA, storeB := "store-a", "store-b"
kbWith := func(id string, store *string) *types.KnowledgeBase {
return &types.KnowledgeBase{ID: id, TenantID: 1, Type: "document",
EmbeddingModelID: "m1", VectorStoreID: store}
}
tests := []struct {
name string
mode string
srcStore *string
dstStore *string
wantStatus int
wantBodyHas string // substring that must appear
wantBodyNotHas string // substring that must NOT appear (gate message)
}{
{
name: "reuse_vectors cross-store rejected by gate",
mode: "reuse_vectors", srcStore: &storeA, dstStore: &storeB,
wantStatus: http.StatusBadRequest, wantBodyHas: "different vector stores",
},
{
name: "reparse cross-store passes gate (fails later at knowledge lookup)",
mode: "reparse", srcStore: &storeA, dstStore: &storeB,
wantStatus: http.StatusBadRequest, wantBodyNotHas: "different vector stores",
},
{
name: "reuse_vectors same-store passes gate",
mode: "reuse_vectors", srcStore: &storeA, dstStore: &storeA,
wantStatus: http.StatusBadRequest, wantBodyNotHas: "different vector stores",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
kb := &stubMoveKBService{byID: func(_ context.Context, id string) (*types.KnowledgeBase, error) {
switch id {
case "kb-src":
return kbWith("kb-src", tt.srcStore), nil
case "kb-dst":
return kbWith("kb-dst", tt.dstStore), nil
}
return nil, errors.New("kb not found")
}}
router := newMoveGateRouter(kb, &stubMoveKGService{})
body, _ := json.Marshal(map[string]any{
"knowledge_ids": []string{"k1"},
"source_kb_id": "kb-src",
"target_kb_id": "kb-dst",
"mode": tt.mode,
})
req := httptest.NewRequest(http.MethodPost, "/move", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != tt.wantStatus {
t.Fatalf("status = %d, want %d; body=%s", w.Code, tt.wantStatus, w.Body.String())
}
if tt.wantBodyHas != "" && !strings.Contains(w.Body.String(), tt.wantBodyHas) {
t.Fatalf("body %q does not contain %q", w.Body.String(), tt.wantBodyHas)
}
if tt.wantBodyNotHas != "" && strings.Contains(w.Body.String(), tt.wantBodyNotHas) {
t.Fatalf("body %q unexpectedly contains gate message %q (gate short-circuited a valid move)",
w.Body.String(), tt.wantBodyNotHas)
}
})
}
}
@@ -0,0 +1,253 @@
package handler
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/application/access"
apperrors "academy/internal/errors"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type mutationAdmissionKnowledge struct {
interfaces.KnowledgeService
rows []*types.Knowledge
err error
tagsCalled bool
writeGrant bool
}
func (s *mutationAdmissionKnowledge) GetKnowledgeByIDOnly(context.Context, string) (*types.Knowledge, error) {
return s.rows[0], nil
}
func (s *mutationAdmissionKnowledge) GetKnowledgeByID(context.Context, string) (*types.Knowledge, error) {
return s.rows[0], nil
}
func (s *mutationAdmissionKnowledge) GetKnowledgeBatch(
ctx context.Context,
_ uint64,
_ []string,
) ([]*types.Knowledge, error) {
s.writeGrant = access.RequireKBWrite(ctx, &types.KnowledgeBase{ID: "kb", TenantID: 7}) == nil
return s.rows, nil
}
func (s *mutationAdmissionKnowledge) ListKnowledgeByKnowledgeBaseID(
context.Context,
string,
) ([]*types.Knowledge, error) {
return s.rows, nil
}
func (s *mutationAdmissionKnowledge) UpdateKnowledge(context.Context, *types.Knowledge) error {
return s.err
}
func (s *mutationAdmissionKnowledge) UpdateImageInfo(context.Context, string, string, string) error {
return s.err
}
func (s *mutationAdmissionKnowledge) RegenerateKnowledgeSummary(context.Context, string) (*types.Knowledge, error) {
return nil, s.err
}
func (s *mutationAdmissionKnowledge) UpdateKnowledgeTagBatch(context.Context, string, map[string][]string) error {
s.tagsCalled = true
return s.err
}
func mutationRequest(r *gin.Engine, method, path, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func admissionKnowledge(moving bool) *types.Knowledge {
k := &types.Knowledge{ID: "doc", TenantID: 7, KnowledgeBaseID: "kb"}
if moving {
k.Metadata = []byte(`{"_knowledge_transfer":{"operation":"move","phase":"moving"}}`)
}
return k
}
func admissionKB(creator string) *stubKBService {
return &stubKBService{get: func(context.Context, string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "kb", TenantID: 7, CreatorID: creator}, nil
}}
}
func TestMovingDocumentAdmissionRejectsBeforeEnqueue(t *testing.T) {
for _, route := range []string{"single", "batch", "clear", "reparse"} {
t.Run(route, func(t *testing.T) {
kg := &mutationAdmissionKnowledge{rows: []*types.Knowledge{admissionKnowledge(true)}}
if route == "batch" || route == "reparse" {
kg.rows = append([]*types.Knowledge{{ID: "other", TenantID: 7, KnowledgeBaseID: "kb"}}, kg.rows...)
}
queue := &documentDeleteEnqueuer{}
h := &KnowledgeHandler{
cfg: transferHandlerConfig(),
kbService: admissionKB("user"),
kgService: kg,
asynqClient: queue,
}
r := documentHandlerRouter()
method, path, body := http.MethodDelete, "/doc", ""
switch route {
case "single":
r.DELETE("/:id", h.DeleteKnowledge)
case "batch":
r.POST("/batch", h.BatchDeleteKnowledge)
method, path, body = http.MethodPost, "/batch", `{"kb_id":"kb","ids":["other","doc"]}`
case "clear":
r.DELETE("/:id", h.ClearKnowledgeBaseContents)
path = "/kb"
case "reparse":
r.POST("/reparse", h.BatchReparseKnowledge)
method, path, body = http.MethodPost, "/reparse", `{"kb_id":"kb","ids":["other","doc"]}`
}
w := mutationRequest(r, method, path, body)
require.Equal(t, 409, w.Code, w.Body.String())
require.Nil(t, queue.task)
})
}
}
func TestBatchMutationRequiresCreatorOrAdminAndWriteGrant(t *testing.T) {
for _, route := range []string{"reparse", "tags explicit", "tags inferred"} {
for _, creator := range []string{"user", "colleague"} {
t.Run(route+creator, func(t *testing.T) {
kg := &mutationAdmissionKnowledge{rows: []*types.Knowledge{admissionKnowledge(false)}}
queue := &documentDeleteEnqueuer{}
h := &KnowledgeHandler{
cfg: transferHandlerConfig(),
kbService: admissionKB(creator),
kgService: kg,
asynqClient: queue,
}
r := transferHandlerRouter(nil)
method, body := http.MethodPost, `{"kb_id":"kb","ids":["doc"]}`
if route == "reparse" {
r.POST("/batch", h.BatchReparseKnowledge)
} else {
r.PUT("/batch", h.UpdateKnowledgeTagBatch)
method = http.MethodPut
body = `{"kb_id":"kb","updates":{"doc":["tag"]}}`
if route == "tags inferred" {
body = `{"updates":{"doc":["tag"]}}`
}
}
w := mutationRequest(r, method, "/batch", body)
if creator == "user" {
require.Equal(t, 200, w.Code, w.Body.String())
if route == "reparse" {
require.True(t, kg.writeGrant)
require.NotNil(t, queue.task)
} else {
require.True(t, kg.tagsCalled)
}
} else {
require.Equal(t, 403, w.Code, w.Body.String())
require.Nil(t, queue.task)
require.False(t, kg.tagsCalled)
}
})
}
}
}
type mutationChunkService struct {
interfaces.ChunkService
err error
}
func (s *mutationChunkService) GetChunkByID(context.Context, string) (*types.Chunk, error) {
return &types.Chunk{ID: "chunk", KnowledgeID: "doc"}, nil
}
func (s *mutationChunkService) UpdateDocumentChunk(
context.Context,
string,
*string,
*bool,
*int,
) (*types.Chunk, error) {
return nil, s.err
}
func (s *mutationChunkService) RevertDocumentChunk(context.Context, string, int, *int) (*types.Chunk, error) {
return nil, s.err
}
func TestMutationHandlersPreserveApplicationStatus(t *testing.T) {
for _, status := range []int{409, 403} {
for _, route := range []string{"metadata", "image", "summary", "chunk", "revert"} {
t.Run(fmt.Sprint(status)+route, func(t *testing.T) {
app := apperrors.NewConflictError("moving")
if status == 403 {
app = apperrors.NewForbiddenError("binding changed")
}
failure := fmt.Errorf("operation: %w", app)
kg := &mutationAdmissionKnowledge{rows: []*types.Knowledge{admissionKnowledge(false)}, err: failure}
h := &KnowledgeHandler{kgService: kg}
chunks := &ChunkHandler{service: &mutationChunkService{err: failure}}
r := documentHandlerRouter()
method, path, body := http.MethodPut, "/doc", `{"title":"new"}`
switch route {
case "metadata":
r.PUT("/:id", h.UpdateKnowledge)
case "image":
r.PUT("/:id/:chunk_id", h.UpdateImageInfo)
path = "/doc/chunk"
body = `{"image_info":"[]"}`
case "summary":
r.POST("/:id", h.RegenerateKnowledgeSummary)
method = http.MethodPost
body = ""
case "chunk":
r.PUT("/:knowledge_id/:id", chunks.UpdateChunk)
path = "/doc/chunk"
body = `{"content":"new"}`
case "revert":
r.POST("/:knowledge_id/:id", chunks.RevertChunk)
method = http.MethodPost
path = "/doc/chunk"
body = `{"revision":0}`
}
w := mutationRequest(r, method, path, body)
require.Equal(t, status, w.Code, w.Body.String())
})
}
}
}
func TestBatchReparsePreservesAdminAndRBACRolloutPolicy(t *testing.T) {
for _, enforced := range []bool{true, false} {
t.Run(fmt.Sprint(enforced), func(t *testing.T) {
cfg := transferHandlerConfig()
cfg.Tenant.EnableRBAC = &enforced
kg := &mutationAdmissionKnowledge{rows: []*types.Knowledge{admissionKnowledge(false)}}
queue := &documentDeleteEnqueuer{}
h := &KnowledgeHandler{cfg: cfg, kbService: admissionKB("colleague"), kgService: kg, asynqClient: queue}
r := transferHandlerRouter(nil)
if enforced {
r = documentHandlerRouter()
} // Admin may edit another creator's KB.
r.POST("/batch", h.BatchReparseKnowledge)
w := mutationRequest(r, http.MethodPost, "/batch", `{"kb_id":"kb","ids":["doc"]}`)
require.Equal(t, 200, w.Code, w.Body.String())
require.True(t, kg.writeGrant)
require.NotNil(t, queue.task)
})
}
}
@@ -0,0 +1,157 @@
package handler
import (
"context"
stderrors "errors"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/application/repository"
"academy/internal/config"
"academy/internal/middleware"
"academy/internal/types"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestBodyKBOwnershipSkipsUnnecessaryLookup(t *testing.T) {
for _, tt := range []struct {
name string
role types.TenantRole
apiKey, superuser, disabled bool
}{
{name: "admin", role: types.TenantRoleAdmin},
{name: "owner", role: types.TenantRoleOwner},
{name: "API key", role: types.TenantRoleViewer, apiKey: true},
{name: "cross tenant superuser", role: types.TenantRoleViewer, superuser: true},
{name: "RBAC disabled", role: types.TenantRoleContributor, disabled: true},
} {
t.Run(tt.name, func(t *testing.T) {
c := newKBLookupCtx(t, 1, "kb")
ctx := context.WithValue(c.Request.Context(), types.TenantRoleContextKey, tt.role)
ctx = context.WithValue(
ctx,
types.UserContextKey,
&types.User{ID: "user", CanAccessAllTenants: tt.superuser},
)
if tt.apiKey {
ctx = types.WithTenantAPIKeyScope(
ctx,
types.TenantAPIKeyScope{KnowledgeBaseIDs: types.StringArray{"kb"}},
)
}
c.Request = c.Request.WithContext(ctx)
enabled := !tt.disabled
h := &KnowledgeHandler{
cfg: &config.Config{
Tenant: &config.TenantConfig{EnableRBAC: &enabled, EnableCrossTenantAccess: tt.superuser},
},
kbService: &stubKBService{get: func(context.Context, string) (*types.KnowledgeBase, error) {
t.Fatal("body-carried KB ownership must be looked up lazily")
return nil, stderrors.New("unavailable")
}},
}
require.NoError(t, h.requireKBOwnershipOrAdmin(c, "kb"))
})
}
}
func TestBodyKBOwnershipPreservesStatusAndTenantBoundary(t *testing.T) {
for _, tt := range []struct {
name string
kb *types.KnowledgeBase
lookupErr error
status int
}{
{
name: "creator",
kb: &types.KnowledgeBase{
ID: "kb",
TenantID: 1,
CreatorID: "user",
},
status: http.StatusNoContent,
},
{
name: "noncreator",
kb: &types.KnowledgeBase{
ID: "kb",
TenantID: 1,
CreatorID: "other",
},
status: http.StatusForbidden,
},
{name: "tenant owned", kb: &types.KnowledgeBase{ID: "kb", TenantID: 1}, status: http.StatusForbidden},
{
name: "same creator in another tenant",
kb: &types.KnowledgeBase{
ID: "kb",
TenantID: 2,
CreatorID: "user",
},
status: http.StatusNotFound,
},
{name: "nil resource", status: http.StatusNotFound},
{
name: "wrapped not found",
lookupErr: fmt.Errorf("lookup: %w",
repository.ErrKnowledgeBaseNotFound),
status: http.StatusNotFound,
},
{
name: "database failure",
lookupErr: stderrors.New("database unavailable"),
status: http.StatusInternalServerError,
},
} {
t.Run(tt.name, func(t *testing.T) {
enabled := true
calls := 0
h := &KnowledgeHandler{
cfg: &config.Config{Tenant: &config.TenantConfig{EnableRBAC: &enabled}},
kbService: &stubKBService{get: func(context.Context, string) (*types.KnowledgeBase, error) {
calls++
return tt.kb, tt.lookupErr
}},
}
r := gin.New()
r.Use(middleware.ErrorHandler(), func(c *gin.Context) {
ctx := context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(1))
ctx = context.WithValue(ctx, types.TenantRoleContextKey, types.TenantRoleContributor)
ctx = context.WithValue(ctx, types.UserIDContextKey, "user")
c.Request = c.Request.WithContext(ctx)
c.Next()
})
r.POST("/write", func(c *gin.Context) {
if err := h.requireKBOwnershipOrAdmin(c, "kb"); err != nil {
_ = c.Error(err)
return
}
c.Status(http.StatusNoContent)
})
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/write", nil))
require.Equal(t, tt.status, w.Code, w.Body.String())
require.Equal(t, 1, calls)
})
}
}
func TestBodyWriteStillEnforcesAPIKeyKBScope(t *testing.T) {
c := newKBLookupCtx(t, 1, "kb")
c.Set(types.TenantIDContextKey.String(), uint64(1))
ctx := types.WithTenantAPIKeyScope(
c.Request.Context(),
types.TenantAPIKeyScope{KnowledgeBaseIDs: types.StringArray{"allowed"}},
)
c.Request = c.Request.WithContext(ctx)
h := &KnowledgeHandler{}
_, _, err := h.requireKnowledgeWriteAccess(c, "outside-scope")
require.Error(t, err, "skipping human ownership checks must not skip KB scope")
}
@@ -0,0 +1,67 @@
package handler
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
type previewKnowledgeServiceStub struct {
interfaces.KnowledgeService
filename string
}
type closeNotifyRecorder struct {
*httptest.ResponseRecorder
}
func (r *closeNotifyRecorder) CloseNotify() <-chan bool {
ch := make(chan bool, 1)
return ch
}
func (s *previewKnowledgeServiceStub) GetKnowledgeByIDOnly(context.Context, string) (*types.Knowledge, error) {
return &types.Knowledge{ID: "k1", TenantID: 42, KnowledgeBaseID: "kb1"}, nil
}
func (s *previewKnowledgeServiceStub) GetKnowledgeFile(context.Context, string) (io.ReadCloser, string, error) {
return io.NopCloser(strings.NewReader(`<html><script>alert(1)</script></html>`)), s.filename, nil
}
func TestPreviewKnowledgeFileForcesActiveContentDownload(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(middleware.ErrorHandler())
router.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(42))
c.Next()
})
h := &KnowledgeHandler{kgService: &previewKnowledgeServiceStub{filename: "payload.html"}}
router.GET("/knowledge/:id/preview", h.PreviewKnowledgeFile)
req := httptest.NewRequest(http.MethodGet, "/knowledge/k1/preview", nil)
w := &closeNotifyRecorder{ResponseRecorder: httptest.NewRecorder()}
router.ServeHTTP(w, req)
if got, want := w.Code, http.StatusOK; got != want {
t.Fatalf("status = %d, want %d; body=%s", got, want, w.Body.String())
}
if got := w.Header().Get("Content-Type"); got != "application/octet-stream" {
t.Fatalf("Content-Type = %q, want application/octet-stream", got)
}
if got := w.Header().Get("X-Content-Type-Options"); got != "nosniff" {
t.Fatalf("X-Content-Type-Options = %q, want nosniff", got)
}
if got := w.Header().Get("Content-Disposition"); !strings.HasPrefix(got, "attachment") {
t.Fatalf("Content-Disposition = %q, want attachment", got)
}
}
+78
View File
@@ -0,0 +1,78 @@
package handler
import (
"net/http"
"net/http/httptest"
"testing"
"academy/internal/types"
)
func TestListKnowledgeSortQuery(t *testing.T) {
tests := []struct {
name string
query string
wantCode int
wantBy types.KnowledgeListSortField
wantOrder types.KnowledgeListSortOrder
}{
{
name: "未传参数时默认最新创建",
wantCode: http.StatusOK,
wantBy: types.KnowledgeListSortByCreatedAt,
wantOrder: types.KnowledgeListSortDescending,
},
{
name: "接受创建时间升序",
query: "?sort_by=created_at&sort_order=asc",
wantCode: http.StatusOK,
wantBy: types.KnowledgeListSortByCreatedAt,
wantOrder: types.KnowledgeListSortAscending,
},
{
name: "接受文件名称降序",
query: "?sort_by=file_name&sort_order=desc",
wantCode: http.StatusOK,
wantBy: types.KnowledgeListSortByFileName,
wantOrder: types.KnowledgeListSortDescending,
},
{
name: "拒绝未知排序字段",
query: "?sort_by=deleted_at&sort_order=desc",
wantCode: http.StatusBadRequest,
},
{
name: "拒绝未知排序方向",
query: "?sort_by=updated_at&sort_order=random",
wantCode: http.StatusBadRequest,
},
{
name: "拒绝排序字段中的 SQL 片段",
query: "?sort_by=updated_at%3BDELETE%20FROM%20knowledges",
wantCode: http.StatusBadRequest,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
kg := &stubFolderKGService{}
router := newFolderRouter(kg)
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/kb-1/knowledge"+tt.query, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != tt.wantCode {
t.Fatalf("status = %d, want %d; body=%s", w.Code, tt.wantCode, w.Body.String())
}
if tt.wantCode == http.StatusOK {
if kg.gotFilter.SortBy != tt.wantBy {
t.Fatalf("sort_by = %q, want %q", kg.gotFilter.SortBy, tt.wantBy)
}
if kg.gotFilter.SortOrder != tt.wantOrder {
t.Fatalf("sort_order = %q, want %q", kg.gotFilter.SortOrder, tt.wantOrder)
}
}
})
}
}
+351
View File
@@ -0,0 +1,351 @@
package handler
import (
"testing"
"time"
"academy/internal/types"
"github.com/stretchr/testify/assert"
)
// TestBuildSpanTree_AssemblesParentChild covers the basic shape: a root
// with stage children and an image generation grandchild. The handler's
// JSON contract depends on this tree topology; if the linking logic
// regresses, the UI sees a flat list and renders nothing.
func TestBuildSpanTree_AssemblesParentChild(t *testing.T) {
now := time.Now()
rows := []types.KnowledgeProcessingSpan{
{KnowledgeID: "kid", Attempt: 1, SpanID: "root", Name: "knowledge_processing", Kind: types.SpanKindRoot, Status: types.SpanStatusRunning, StartedAt: &now},
{KnowledgeID: "kid", Attempt: 1, SpanID: "doc", ParentSpanID: "root", Name: types.StageDocReader, Kind: types.SpanKindStage, Status: types.SpanStatusDone, StartedAt: &now},
{KnowledgeID: "kid", Attempt: 1, SpanID: "mm", ParentSpanID: "root", Name: types.StageMultimodal, Kind: types.SpanKindStage, Status: types.SpanStatusRunning, StartedAt: &now},
{KnowledgeID: "kid", Attempt: 1, SpanID: "img0", ParentSpanID: "mm", Name: "multimodal.image[0]", Kind: types.SpanKindGeneration, Status: types.SpanStatusRunning, StartedAt: &now},
}
tree, currentStage, lastFail := buildSpanTree("kid", 1, rows, types.ParseStatusProcessing)
require := assert.New(t)
require.NotNil(tree)
require.Equal("root", tree.SpanID)
require.Equal(types.StageMultimodal, currentStage,
"running stage span surfaces as current_stage")
require.Nil(lastFail)
// The 5 canonical stages must all appear under root (real or
// synthesized placeholder).
stageNames := map[string]string{}
for _, child := range tree.Children {
if child.Kind == types.SpanKindStage {
stageNames[child.Name] = child.Status
}
}
for _, name := range types.AllStages {
_, ok := stageNames[name]
require.True(ok, "stage %s must appear in tree", name)
}
require.Equal(types.SpanStatusDone, stageNames[types.StageDocReader])
require.Equal(types.SpanStatusRunning, stageNames[types.StageMultimodal])
require.Equal(types.SpanStatusPending, stageNames[types.StageEmbedding],
"missing stage rows must synthesize as pending placeholders")
// The image subspan must hang under multimodal, not at root level.
var mmNode *types.SpanTreeNode
for _, c := range tree.Children {
if c.Name == types.StageMultimodal {
mmNode = c
break
}
}
require.NotNil(mmNode)
require.Len(mmNode.Children, 1, "image generation subspan must be a child of multimodal stage")
require.Equal("multimodal.image[0]", mmNode.Children[0].Name)
}
// TestBuildSpanTree_NoRows_SynthesizesPlaceholderRoot ensures the API
// keeps a stable shape for fresh / never-parsed knowledge: the frontend
// always gets a `trace` with five pending stage children, never a
// nil/empty response.
func TestBuildSpanTree_NoRows_SynthesizesPlaceholderRoot(t *testing.T) {
tree, currentStage, lastFail := buildSpanTree("kid-empty", 0, nil, "")
a := assert.New(t)
a.NotNil(tree)
a.Equal(types.SpanKindRoot, tree.Kind)
a.Equal(types.SpanStatusPending, tree.Status)
a.Equal("", currentStage, "no rows means no running stage")
a.Nil(lastFail)
// All 5 stages must be present as pending placeholders so the UI
// renders a complete timeline even pre-parse.
a.Len(tree.Children, len(types.AllStages))
for _, child := range tree.Children {
a.Equal(types.SpanStatusPending, child.Status)
a.Equal(types.SpanKindStage, child.Kind)
}
}
// TestBuildSpanTree_LegacyCompletedRendersAsDone records the regression
// for historical knowledge parsed before span tracking was wired: rows
// is empty but parse_status is "completed", so the synthesized timeline
// must reflect the actual terminal state instead of looking forever
// "pending". Same contract for failed parses — synthesizes "failed".
func TestBuildSpanTree_LegacyCompletedRendersAsDone(t *testing.T) {
a := assert.New(t)
completedTree, _, _ := buildSpanTree("kid-legacy", 0, nil, types.ParseStatusCompleted)
a.Equal(types.SpanStatusDone, completedTree.Status,
"legacy completed knowledge with no rows must render the synthesized root as done")
a.Len(completedTree.Children, len(types.AllStages))
for _, child := range completedTree.Children {
a.Equal(types.SpanStatusDone, child.Status,
"legacy completed knowledge: every synthesized stage placeholder must be done, not pending")
}
failedTree, _, _ := buildSpanTree("kid-legacy-fail", 0, nil, types.ParseStatusFailed)
a.Equal(types.SpanStatusFailed, failedTree.Status)
for _, child := range failedTree.Children {
a.Equal(types.SpanStatusFailed, child.Status)
}
}
// TestBuildSpanTree_LastFailureSurfaces records that a failed stage is
// reported as last_error so the UI can highlight the responsible step
// even if a later stage was cancelled by cascade.
func TestBuildSpanTree_LastFailureSurfaces(t *testing.T) {
now := time.Now()
finished := now.Add(5 * time.Second)
rows := []types.KnowledgeProcessingSpan{
{KnowledgeID: "kid", Attempt: 1, SpanID: "root", Name: "knowledge_processing", Kind: types.SpanKindRoot, Status: types.SpanStatusFailed, StartedAt: &now, FinishedAt: &finished},
{KnowledgeID: "kid", Attempt: 1, SpanID: "doc", ParentSpanID: "root", Name: types.StageDocReader, Kind: types.SpanKindStage, Status: types.SpanStatusFailed, ErrorCode: "DOCREADER_TIMEOUT", ErrorMessage: "slow", StartedAt: &now, FinishedAt: &finished},
{KnowledgeID: "kid", Attempt: 1, SpanID: "chunk", ParentSpanID: "root", Name: types.StageChunking, Kind: types.SpanKindStage, Status: types.SpanStatusCancelled, ErrorCode: "UPSTREAM_FAILED"},
}
_, _, lastFail := buildSpanTree("kid", 1, rows, types.ParseStatusFailed)
a := assert.New(t)
a.NotNil(lastFail)
a.Equal(types.StageDocReader, lastFail.Name,
"last_error must point at the actually-failed span, not the cascade-cancelled downstream")
a.Equal("DOCREADER_TIMEOUT", lastFail.ErrorCode)
}
func TestKnowledgeSpansLastError_PrefersSpanFailure(t *testing.T) {
now := time.Now()
spanFail := &types.KnowledgeProcessingSpan{
Name: types.StageDocReader,
ErrorCode: "DOCREADER_TIMEOUT",
ErrorMessage: "slow",
FinishedAt: &now,
}
got := knowledgeSpansLastError(2, 2, types.ParseStatusFailed, "recovery blew up", now, spanFail)
a := assert.New(t)
a.Equal(types.StageDocReader, got.Name)
a.Equal("DOCREADER_TIMEOUT", got.ErrorCode)
a.Equal("slow", got.ErrorMessage)
}
func TestKnowledgeSpansLastError_RecoveryFallbackUsesKnowledgeMessage(t *testing.T) {
now := time.Now()
got := knowledgeSpansLastError(2, 2, types.ParseStatusFailed, "wiki ingest timed out", now, nil)
a := assert.New(t)
a.NotNil(got)
a.Equal("knowledge_processing", got.Name)
a.Equal("UNKNOWN", got.ErrorCode)
a.Equal("wiki ingest timed out", got.ErrorMessage)
a.Equal(&now, got.FinishedAt)
}
func TestKnowledgeSpansLastError_ClassifiesServerRestart(t *testing.T) {
now := time.Now()
got := knowledgeSpansLastError(2, 2, types.ParseStatusFailed,
"Task interrupted due to application restart", now, nil)
a := assert.New(t)
a.NotNil(got)
a.Equal("SERVER_RESTART", got.ErrorCode)
a.Equal("SERVER_RESTART", got.Code)
}
func TestKnowledgeSpansLastError_SkipsRecoveryFallbackForHistoricalAttempt(t *testing.T) {
now := time.Now()
got := knowledgeSpansLastError(1, 2, types.ParseStatusFailed, "wiki ingest timed out", now, nil)
assert.Nil(t, got)
}
func TestKnowledgeSpansLastError_SkipsRecoveryFallbackWithoutMessage(t *testing.T) {
now := time.Now()
got := knowledgeSpansLastError(2, 2, types.ParseStatusFailed, "", now, nil)
assert.Nil(t, got)
}
// stageStatuses maps each canonical stage to the status it renders as.
func stageStatuses(t *testing.T, tree *types.SpanTreeNode) map[string]string {
t.Helper()
got := map[string]string{}
for _, child := range tree.Children {
if child.Kind == types.SpanKindStage {
got[child.Name] = child.Status
}
}
return got
}
// #3452: a text passage has no docreader stage, so an embedding failure used to
// synthesize docreader as failed and the UI named it as the broken step.
func TestBuildSpanTree_MissingStagesAroundRealFailure(t *testing.T) {
now := time.Now()
finished := now.Add(2 * time.Second)
rows := []types.KnowledgeProcessingSpan{
{
KnowledgeID: "kid", Attempt: 1, SpanID: "root",
Name: "knowledge_processing", Kind: types.SpanKindRoot,
Status: types.SpanStatusFailed, StartedAt: &now, FinishedAt: &finished,
},
{
KnowledgeID: "kid", Attempt: 1, SpanID: "chunk", ParentSpanID: "root",
Name: types.StageChunking, Kind: types.SpanKindStage,
Status: types.SpanStatusDone, StartedAt: &now, FinishedAt: &finished,
},
{
KnowledgeID: "kid", Attempt: 1, SpanID: "emb", ParentSpanID: "root",
Name: types.StageEmbedding, Kind: types.SpanKindStage,
Status: types.SpanStatusFailed, ErrorCode: "EMBED_UNREACHABLE",
StartedAt: &now, FinishedAt: &finished,
},
}
tree, _, lastFail := buildSpanTree("kid", 1, rows, types.ParseStatusFailed)
a := assert.New(t)
got := stageStatuses(t, tree)
a.Equal(types.SpanStatusFailed, got[types.StageEmbedding],
"the stage that actually failed keeps its real row")
a.Equal(types.SpanStatusSkipped, got[types.StageDocReader],
"a stage before the failure with no row never ran; a text passage has no document to parse")
a.Equal(types.SpanStatusCancelled, got[types.StageMultimodal],
"a stage after the failure with no row was abandoned, not broken")
a.Equal(types.SpanStatusCancelled, got[types.StagePostProcess],
"postprocess depends on embedding, so it is cancelled rather than failed")
// The UI focuses the first failed stage in canonical order.
var firstFailed string
for _, name := range types.AllStages {
if got[name] == types.SpanStatusFailed {
firstFailed = name
break
}
}
a.Equal(types.StageEmbedding, firstFailed,
"the timeline must name embedding, not an earlier stage that never ran")
a.NotNil(lastFail)
a.Equal(types.StageEmbedding, lastFail.Name)
}
// No failed row means no position to reason from, so the fallback still applies.
func TestBuildSpanTree_MissingStagesWithoutFailureKeepFallback(t *testing.T) {
now := time.Now()
rows := []types.KnowledgeProcessingSpan{
{
KnowledgeID: "kid", Attempt: 1, SpanID: "root",
Name: "knowledge_processing", Kind: types.SpanKindRoot,
Status: types.SpanStatusRunning, StartedAt: &now,
},
{
KnowledgeID: "kid", Attempt: 1, SpanID: "doc", ParentSpanID: "root",
Name: types.StageDocReader, Kind: types.SpanKindStage,
Status: types.SpanStatusDone, StartedAt: &now,
},
}
tree, _, _ := buildSpanTree("kid", 1, rows, types.ParseStatusProcessing)
got := stageStatuses(t, tree)
a := assert.New(t)
a.Equal(types.SpanStatusPending, got[types.StageChunking],
"a run still in flight keeps pending placeholders")
a.Equal(types.SpanStatusPending, got[types.StagePostProcess])
}
// parse_status "cancelled" fell through to pending, leaving spinners on
// stages the document never reached.
func TestBuildSpanTree_CancelledParseRendersCancelled(t *testing.T) {
tree, _, _ := buildSpanTree("kid-cancelled", 0, nil, types.ParseStatusCancelled)
a := assert.New(t)
a.Equal(types.SpanStatusCancelled, tree.Status)
a.Len(tree.Children, len(types.AllStages))
for _, child := range tree.Children {
a.Equal(types.SpanStatusCancelled, child.Status,
"a cancelled parse must not render its unreached stages as pending")
}
}
// Failure at the first stage: nothing precedes it, so nothing is skipped.
func TestBuildSpanTree_DocReaderFailureCancelsEverythingAfter(t *testing.T) {
now := time.Now()
rows := []types.KnowledgeProcessingSpan{
{
KnowledgeID: "kid", Attempt: 1, SpanID: "root",
Name: "knowledge_processing", Kind: types.SpanKindRoot,
Status: types.SpanStatusFailed, StartedAt: &now,
},
{
KnowledgeID: "kid", Attempt: 1, SpanID: "doc", ParentSpanID: "root",
Name: types.StageDocReader, Kind: types.SpanKindStage,
Status: types.SpanStatusFailed, ErrorCode: "DOCREADER_TIMEOUT",
StartedAt: &now,
},
}
tree, _, _ := buildSpanTree("kid", 1, rows, types.ParseStatusFailed)
got := stageStatuses(t, tree)
a := assert.New(t)
a.Equal(types.SpanStatusFailed, got[types.StageDocReader])
for _, name := range []string{
types.StageChunking, types.StageEmbedding,
types.StageMultimodal, types.StagePostProcess,
} {
a.Equal(types.SpanStatusCancelled, got[name],
"%s follows the failed docreader and never ran", name)
}
a.NotContains(got, types.SpanStatusSkipped)
}
// Post-process closes its stage once the enrichment tasks are fanned out, so
// the stage owning a still-running subspan is the current one.
func TestBuildSpanTree_CurrentStageFallsBackToRunningSubspan(t *testing.T) {
rows := []types.KnowledgeProcessingSpan{
{SpanID: "root", Name: "knowledge_processing", Kind: types.SpanKindRoot, Status: types.SpanStatusDone},
{
SpanID: "post", ParentSpanID: "root", Name: types.StagePostProcess,
Kind: types.SpanKindStage, Status: types.SpanStatusDone,
},
{
SpanID: "wiki", ParentSpanID: "post", Name: "postprocess.wiki",
Kind: types.SpanKindSubSpan, Status: types.SpanStatusRunning,
},
{
SpanID: "page", ParentSpanID: "wiki", Name: "postprocess.wiki.page[a]",
Kind: types.SpanKindSubSpan, Status: types.SpanStatusRunning,
},
}
_, currentStage, _ := buildSpanTree("kid", 1, rows, types.ParseStatusFinalizing)
assert.Equal(t, types.StagePostProcess, currentStage)
}
// A later subtask failure must not hide the stage housekeeping marked stalled.
func TestBuildSpanTree_StallFailureWinsOverLaterFailures(t *testing.T) {
rows := []types.KnowledgeProcessingSpan{
{SpanID: "root", Name: "knowledge_processing", Kind: types.SpanKindRoot, Status: types.SpanStatusRunning},
{
SpanID: "mm", ParentSpanID: "root", Name: types.StageMultimodal, Kind: types.SpanKindStage,
Status: types.SpanStatusFailed, ErrorCode: "TASK_STALLED",
},
{
SpanID: "img0", ParentSpanID: "mm", Name: "multimodal.image[0]", Kind: types.SpanKindGeneration,
Status: types.SpanStatusFailed, ErrorCode: "MULTIMODAL_VLM_FAILED",
},
}
_, _, lastFailure := buildSpanTree("kid", 1, rows, types.ParseStatusFailed)
if assert.NotNil(t, lastFailure) {
assert.Equal(t, "mm", lastFailure.SpanID)
}
rows[1].ErrorCode = "UNKNOWN"
_, _, lastFailure = buildSpanTree("kid", 1, rows, types.ParseStatusFailed)
if assert.NotNil(t, lastFailure) {
assert.Equal(t, "img0", lastFailure.SpanID, "without a stall, the latest failure still wins")
}
}
@@ -0,0 +1,36 @@
package handler
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestApplyKnowledgeTagBatch(t *testing.T) {
req := &KnowledgeTagBatchRequest{
KnowledgeIDs: []string{" k-1 ", "k-2"},
TagIDs: []string{"t-1"},
}
require.NoError(t, applyKnowledgeTagBatch(req))
assert.Equal(t, map[string][]string{"k-1": {"t-1"}, "k-2": {"t-1"}}, req.Updates)
cleared := &KnowledgeTagBatchRequest{KnowledgeIDs: []string{"k-1"}, TagIDs: []string{}}
require.NoError(t, applyKnowledgeTagBatch(cleared))
assert.Empty(t, cleared.Updates["k-1"])
kept := &KnowledgeTagBatchRequest{Updates: map[string][]string{"k-1": {"t-1"}}}
require.NoError(t, applyKnowledgeTagBatch(kept))
assert.Equal(t, map[string][]string{"k-1": {"t-1"}}, kept.Updates)
cases := []*KnowledgeTagBatchRequest{
{},
{KnowledgeIDs: []string{"k-1"}, Updates: map[string][]string{"k-2": nil}},
{KnowledgeIDs: []string{"k-1"}},
{KnowledgeIDs: []string{"k-1", "k-1"}, TagIDs: []string{}},
{KnowledgeIDs: []string{" "}, TagIDs: []string{}},
}
for _, bad := range cases {
require.Error(t, applyKnowledgeTagBatch(bad))
}
}
@@ -0,0 +1,14 @@
package handler
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestParseCommaSeparatedTagIDs(t *testing.T) {
assert.Nil(t, parseCommaSeparatedTagIDs(""))
assert.Equal(t, []string{"a", "b"}, parseCommaSeparatedTagIDs("a,b"))
assert.Equal(t, []string{"a", "b"}, parseCommaSeparatedTagIDs(" a , b "))
assert.Equal(t, []string{"a"}, parseCommaSeparatedTagIDs("a,__untagged__,,"))
}
+176
View File
@@ -0,0 +1,176 @@
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/config"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type transferHandlerKnowledge struct{ interfaces.KnowledgeService }
func (*transferHandlerKnowledge) SaveKBCloneProgress(context.Context, *types.KBCloneProgress) error {
return nil
}
func (*transferHandlerKnowledge) SaveKnowledgeMoveProgress(context.Context, *types.KnowledgeMoveProgress) error {
return nil
}
func (*transferHandlerKnowledge) GetKnowledgeByID(_ context.Context, id string) (*types.Knowledge, error) {
return &types.Knowledge{
ID: id,
TenantID: 7,
KnowledgeBaseID: "source",
ParseStatus: types.ParseStatusCompleted,
}, nil
}
func transferHandlerRouter(scope *types.TenantAPIKeyScope) *gin.Engine {
r := gin.New()
r.Use(middleware.ErrorHandler(), func(c *gin.Context) {
ctx := types.WithCaller(
c.Request.Context(),
types.Caller{TenantID: 7, UserID: "user", Role: types.TenantRoleContributor},
)
ctx = types.WithExecutionTenant(ctx, 7)
if scope != nil {
ctx = types.WithTenantAPIKeyScope(ctx, *scope)
}
c.Set(types.TenantIDContextKey.String(), uint64(7))
c.Request = c.Request.WithContext(ctx)
c.Next()
})
return r
}
func transferHandlerConfig() *config.Config {
enabled := true
return &config.Config{Tenant: &config.TenantConfig{EnableRBAC: &enabled}}
}
func transferHandlerKB() *stubKBService {
return &stubKBService{get: func(_ context.Context, id string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: id, TenantID: 7, CreatorID: "user"}, nil
}}
}
func transferRequest(r *gin.Engine, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/transfer", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}
func TestCopyAdmissionReservesDestinationAndPreservesCreator(t *testing.T) {
q := &documentDeleteEnqueuer{}
h := &KnowledgeBaseHandler{
cfg: transferHandlerConfig(),
service: transferHandlerKB(),
knowledgeService: &transferHandlerKnowledge{},
asynqClient: q,
}
r := transferHandlerRouter(nil)
r.POST("/transfer", h.CopyKnowledgeBase)
w := transferRequest(r, `{"source_id":"source"}`)
require.Equal(t, 200, w.Code, w.Body.String())
require.NotNil(t, q.task)
var payload types.KBClonePayload
require.NoError(t, json.Unmarshal(q.task.Payload(), &payload))
require.NotEmpty(t, payload.TargetID)
require.NotEqual(t, "source", payload.TargetID)
require.True(t, payload.CreateTarget)
require.Equal(t, "user", payload.CreatorID)
require.Equal(t, uint64(7), payload.TenantID)
require.Contains(t, w.Body.String(), payload.TargetID)
}
func TestCopyAdmissionRequiresExistingDestinationOwnership(t *testing.T) {
q := &documentDeleteEnqueuer{}
kb := &stubKBService{get: func(_ context.Context, id string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: id, TenantID: 7, CreatorID: "someone-else"}, nil
}}
h := &KnowledgeBaseHandler{
cfg: transferHandlerConfig(),
service: kb,
knowledgeService: &transferHandlerKnowledge{},
asynqClient: q,
}
r := transferHandlerRouter(nil)
r.POST("/transfer", h.CopyKnowledgeBase)
w := transferRequest(r, `{"source_id":"source","target_id":"target"}`)
require.Equal(t, 403, w.Code, w.Body.String())
require.Nil(t, q.task)
}
func TestCopyAdmissionKeepsManageCapabilityForNewDestination(t *testing.T) {
for _, capability := range []string{"manage_kbs", "ingest"} {
t.Run(capability, func(t *testing.T) {
q := &documentDeleteEnqueuer{}
h := &KnowledgeBaseHandler{
cfg: transferHandlerConfig(),
service: transferHandlerKB(),
knowledgeService: &transferHandlerKnowledge{},
asynqClient: q,
}
r := transferHandlerRouter(
&types.TenantAPIKeyScope{
Capabilities: types.StringArray{capability},
KnowledgeBaseIDs: types.StringArray{"source"},
},
)
r.POST("/transfer", h.CopyKnowledgeBase)
w := transferRequest(r, `{"source_id":"source"}`)
if capability == "manage_kbs" {
require.Equal(t, 200, w.Code, w.Body.String())
require.NotNil(t, q.task)
} else {
require.Equal(t, 403, w.Code, w.Body.String())
require.Nil(t, q.task)
}
})
}
}
func TestMoveAdmissionDeduplicatesIDsAndRequiresBothKBs(t *testing.T) {
for _, both := range []bool{true, false} {
ids := types.StringArray{"source"}
if both {
ids = append(ids, "target")
}
q := &documentDeleteEnqueuer{}
h := &KnowledgeHandler{
cfg: transferHandlerConfig(),
kbService: transferHandlerKB(),
kgService: &transferHandlerKnowledge{},
asynqClient: q,
}
r := transferHandlerRouter(
&types.TenantAPIKeyScope{Capabilities: types.StringArray{"ingest"}, KnowledgeBaseIDs: ids},
)
r.POST("/transfer", h.MoveKnowledge)
w := transferRequest(
r,
`{"source_kb_id":"source","target_kb_id":"target","knowledge_ids":["doc","doc"],"mode":"reuse_vectors"}`,
)
if !both {
require.Equal(t, 403, w.Code, w.Body.String())
require.Nil(t, q.task)
continue
}
require.Equal(t, 200, w.Code, w.Body.String())
var payload types.KnowledgeMovePayload
require.NoError(t, json.Unmarshal(q.task.Payload(), &payload))
require.Equal(t, []string{"doc"}, payload.KnowledgeIDs)
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,183 @@
package handler
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"academy/internal/application/repository"
apperrors "academy/internal/errors"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// stubKBCopyService provides only the methods the duplicate handler reaches.
// Other interface methods stay embedded so accidental new calls panic in tests.
type stubKBCopyService struct {
interfaces.KnowledgeBaseService
byID func(ctx context.Context, id string) (*types.KnowledgeBase, error)
duplicate func(ctx context.Context, sourceID string) (*types.KnowledgeBase, error)
}
func (s *stubKBCopyService) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) {
return s.byID(ctx, id)
}
func (s *stubKBCopyService) DuplicateKnowledgeBase(
ctx context.Context,
sourceID string,
) (*types.KnowledgeBase, error) {
return s.duplicate(ctx, sourceID)
}
func newDuplicateRouter(svc interfaces.KnowledgeBaseService) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
r.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(1))
c.Set(types.UserIDContextKey.String(), "u-test")
c.Next()
})
h := &KnowledgeBaseHandler{service: svc}
r.POST("/knowledge-bases/:id/duplicate", h.DuplicateKnowledgeBase)
return r
}
func TestDuplicateHandler_ReturnsCreatedKnowledgeBase(t *testing.T) {
var gotSourceID string
svc := &stubKBCopyService{
byID: func(_ context.Context, id string) (*types.KnowledgeBase, error) {
if id != "src" {
t.Fatalf("handler should only load the source KB, got id=%s", id)
}
return &types.KnowledgeBase{ID: "src", TenantID: 1, Name: "Source"}, nil
},
duplicate: func(_ context.Context, sourceID string) (*types.KnowledgeBase, error) {
gotSourceID = sourceID
return &types.KnowledgeBase{
ID: "copy-id",
TenantID: 1,
Name: "Source Copy",
CreatorID: "u-test",
}, nil
},
}
r := newDuplicateRouter(svc)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/src/duplicate", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusCreated {
t.Fatalf("expected 201 for duplicate, got %d body=%s", w.Code, w.Body.String())
}
if gotSourceID != "src" {
t.Fatalf("duplicate service called with source=%q", gotSourceID)
}
body := w.Body.String()
for _, want := range []string{`"source_id":"src"`, `"target_id":"copy-id"`, `"knowledge_base"`} {
if !strings.Contains(body, want) {
t.Fatalf("response missing %s: %s", want, body)
}
}
}
func TestDuplicateHandler_RejectsCrossTenantSource(t *testing.T) {
calledDuplicate := false
svc := &stubKBCopyService{
byID: func(_ context.Context, id string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: id, TenantID: 2, Name: "Shared"}, nil
},
duplicate: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
calledDuplicate = true
return nil, nil
},
}
r := newDuplicateRouter(svc)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/src/duplicate", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusForbidden {
t.Fatalf("expected 403 for cross-tenant source, got %d body=%s", w.Code, w.Body.String())
}
if calledDuplicate {
t.Fatal("duplicate service must not be called when source KB is outside the caller tenant")
}
}
func TestDuplicateHandler_SourceNotFound(t *testing.T) {
calledDuplicate := false
svc := &stubKBCopyService{
byID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return nil, repository.ErrKnowledgeBaseNotFound
},
duplicate: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
calledDuplicate = true
return nil, nil
},
}
r := newDuplicateRouter(svc)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/missing/duplicate", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("expected 404 for missing source, got %d body=%s", w.Code, w.Body.String())
}
if calledDuplicate {
t.Fatal("duplicate service must not be called when source KB is missing")
}
}
func TestDuplicateHandler_PropagatesServiceAppError(t *testing.T) {
svc := &stubKBCopyService{
byID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "src", TenantID: 1, Name: "Source"}, nil
},
duplicate: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return nil, apperrors.NewBadRequestError("invalid vector store binding")
},
}
r := newDuplicateRouter(svc)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/src/duplicate", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("expected 400 for service app error, got %d body=%s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), "invalid vector store binding") {
t.Fatalf("expected service error message in body: %s", w.Body.String())
}
}
func TestDuplicateHandler_ServiceUnexpectedError(t *testing.T) {
svc := &stubKBCopyService{
byID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: "src", TenantID: 1, Name: "Source"}, nil
},
duplicate: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return nil, errors.New("database unavailable")
},
}
r := newDuplicateRouter(svc)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/knowledge-bases/src/duplicate", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusInternalServerError {
t.Fatalf("expected 500 for unexpected service error, got %d body=%s", w.Code, w.Body.String())
}
}
@@ -0,0 +1,109 @@
package handler
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
)
func newHybridSearchResourceURLRouter(svc interfaces.KnowledgeBaseService, fileSvc interfaces.FileService) *gin.Engine {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(middleware.ErrorHandler())
router.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(1))
c.Set(types.UserIDContextKey.String(), "u-test")
c.Next()
})
h := &KnowledgeBaseHandler{service: svc, fileService: fileSvc}
router.POST("/knowledge-bases/:id/hybrid-search", h.HybridSearch)
router.GET("/knowledge-bases/:id/hybrid-search", h.HybridSearch)
return router
}
func performHybridSearchResourceURLRequest(
svc interfaces.KnowledgeBaseService,
fileSvc interfaces.FileService,
method, query, body string,
) *httptest.ResponseRecorder {
response := httptest.NewRecorder()
request := httptest.NewRequest(
method,
"/knowledge-bases/kb-1/hybrid-search"+query,
bytes.NewBufferString(body),
)
request.Header.Set("Content-Type", "application/json")
newHybridSearchResourceURLRouter(svc, fileSvc).ServeHTTP(response, request)
return response
}
func TestHybridSearch_PublicResourceURLs(t *testing.T) {
svc := &hybridSearchTestService{
results: []*types.SearchResult{{
Content: "chunk ![c](" + testResourceHandle + ")",
MatchedImages: []types.MatchedImage{{ChunkID: "image-1", URL: testResourceHandle}},
ImageInfo: `[{"url":"` + testResourceHandle + `"}]`,
}},
}
fileSvc := &stubResourceFileService{url: "https://cdn.example.com/signed.png"}
for _, method := range []string{http.MethodPost, http.MethodGet} {
t.Run(method, func(t *testing.T) {
response := performHybridSearchResourceURLRequest(
svc, fileSvc, method, "?resource_urls=public",
`{"query_text":"diagram"}`,
)
require.Equal(t, http.StatusOK, response.Code, "body=%s", response.Body.String())
assert.NotContains(t, response.Body.String(), testResourceHandle)
assert.Contains(t, response.Body.String(), "cdn.example.com")
})
}
}
func TestHybridSearch_InvalidResourceURLMode(t *testing.T) {
svc := &hybridSearchTestService{}
response := performHybridSearchResourceURLRequest(
svc, &stubResourceFileService{url: "https://cdn.example.com/signed.png"},
http.MethodPost, "?resource_urls=signed",
`{"query_text":"diagram"}`,
)
require.Equal(t, http.StatusBadRequest, response.Code, "body=%s", response.Body.String())
assert.Contains(t, response.Body.String(), "resource_urls")
assert.Equal(t, 0, svc.searchCalls, "invalid mode must not reach HybridSearch")
}
func TestHybridSearch_DefaultKeepsHandles(t *testing.T) {
svc := &hybridSearchTestService{
results: []*types.SearchResult{{
Content: "chunk ![c](" + testResourceHandle + ")",
}},
}
response := performHybridSearchResourceURLRequest(
svc, &stubResourceFileService{url: "https://cdn.example.com/signed.png"},
http.MethodPost, "",
`{"query_text":"diagram"}`,
)
require.Equal(t, http.StatusOK, response.Code, "body=%s", response.Body.String())
var resp struct {
Data []struct {
Content string `json:"content"`
} `json:"data"`
}
require.NoError(t, json.Unmarshal(response.Body.Bytes(), &resp))
require.Len(t, resp.Data, 1)
assert.Contains(t, resp.Data[0].Content, testResourceHandle)
}
@@ -0,0 +1,204 @@
package handler
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
)
type hybridSearchTestService struct {
interfaces.KnowledgeBaseService
searchCalls int
rerankCalls int
searchParams types.SearchParams
results []*types.SearchResult
}
func (s *hybridSearchTestService) GetKnowledgeBaseByID(_ context.Context, id string) (*types.KnowledgeBase, error) {
return &types.KnowledgeBase{ID: id, TenantID: 1}, nil
}
func (s *hybridSearchTestService) HybridSearch(
_ context.Context,
_ string,
params types.SearchParams,
) ([]*types.SearchResult, error) {
s.searchCalls++
s.searchParams = params
if s.results != nil {
return s.results, nil
}
return []*types.SearchResult{}, nil
}
func (s *hybridSearchTestService) HybridSearchWithRerank(
_ context.Context,
_ string,
params types.SearchParams,
) (*types.RetrievalResult, error) {
s.rerankCalls++
s.searchParams = params
return &types.RetrievalResult{
Results: []*types.SearchResult{{ID: "c1", Score: 0.8}},
Meta: types.RetrievalMeta{Rerank: &types.RerankDiagnostics{
Applied: true, Outcome: types.RerankOutcomeOK, ModelID: "rr-1",
}},
}, nil
}
func newHybridSearchTestRouter(svc interfaces.KnowledgeBaseService) *gin.Engine {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(middleware.ErrorHandler())
router.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(1))
c.Set(types.UserIDContextKey.String(), "u-test")
c.Next()
})
handler := &KnowledgeBaseHandler{service: svc}
router.POST("/knowledge-bases/:id/hybrid-search", handler.HybridSearch)
return router
}
func TestHybridSearchRejectsMissingQueryText(t *testing.T) {
tests := []struct {
name string
body string
}{
{name: "missing field", body: `{}`},
{name: "empty field", body: `{"query_text":""}`},
{name: "whitespace field", body: `{"query_text":" "}`},
{name: "wrong field name", body: `{"query":"MiniMax"}`},
{name: "embedding with keyword matching", body: `{"query_embedding":[0.1]}`},
{
name: "embedding with all matching disabled",
body: `{"query_embedding":[0.1],"disable_keywords_match":true,"disable_vector_match":true}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
svc := &hybridSearchTestService{}
response := performHybridSearchRequest(svc, tt.body)
if response.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d body=%s", response.Code, response.Body.String())
}
if svc.searchCalls != 0 {
t.Fatalf("invalid request reached HybridSearch %d time(s)", svc.searchCalls)
}
if !strings.Contains(response.Body.String(), `"code":1000`) {
t.Fatalf("expected bad-request envelope, got %s", response.Body.String())
}
})
}
}
func TestHybridSearchRejectsInvalidRerank(t *testing.T) {
for name, body := range map[string]string{
"negative top_k": `{"query_text":"q","rerank":{"top_k":-1}}`,
"rerank without query_text": `{"query_embedding":[0.1],"disable_keywords_match":true,` +
`"rerank":{"model_id":"rr-1"}}`,
} {
t.Run(name, func(t *testing.T) {
svc := &hybridSearchTestService{}
response := performHybridSearchRequest(svc, body)
if response.Code != http.StatusBadRequest {
t.Fatalf("expected 400, got %d body=%s", response.Code, response.Body.String())
}
if svc.searchCalls+svc.rerankCalls != 0 {
t.Fatal("invalid request reached the service")
}
})
}
}
func TestHybridSearchWithoutRerankKeepsResponseShape(t *testing.T) {
svc := &hybridSearchTestService{}
response := performHybridSearchRequest(svc, `{"query_text":"q"}`)
if response.Code != http.StatusOK || svc.searchCalls != 1 || svc.rerankCalls != 0 {
t.Fatalf("code=%d search=%d rerank=%d", response.Code, svc.searchCalls, svc.rerankCalls)
}
if strings.Contains(response.Body.String(), `"meta"`) {
t.Fatalf("plain hybrid search must not grow a meta field: %s", response.Body.String())
}
}
func TestHybridSearchWithRerankReturnsMeta(t *testing.T) {
svc := &hybridSearchTestService{}
response := performHybridSearchRequest(svc,
`{"query_text":"q","match_count":5,"rerank":{"model_id":"rr-1","top_k":3,"threshold":0}}`)
if response.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", response.Code, response.Body.String())
}
if svc.rerankCalls != 1 || svc.searchCalls != 0 {
t.Fatalf("search=%d rerank=%d", svc.searchCalls, svc.rerankCalls)
}
rr := svc.searchParams.Rerank
if rr == nil || rr.ModelID != "rr-1" || rr.TopK != 3 || rr.Threshold == nil || *rr.Threshold != 0 {
t.Fatalf("rerank options not passed through: %+v", rr)
}
body := response.Body.String()
if !strings.Contains(body, `"meta":{"rerank":{"applied":true,"outcome":"ok","model_id":"rr-1"`) {
t.Fatalf("expected rerank meta, got %s", body)
}
}
func TestHybridSearchAcceptsQueryText(t *testing.T) {
svc := &hybridSearchTestService{}
response := performHybridSearchRequest(svc, `{"query_text":"MiniMax","match_count":3}`)
if response.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", response.Code, response.Body.String())
}
if svc.searchCalls != 1 {
t.Fatalf("expected one HybridSearch call, got %d", svc.searchCalls)
}
if svc.searchParams.QueryText != "MiniMax" {
t.Fatalf("query text = %q, want MiniMax", svc.searchParams.QueryText)
}
if svc.searchParams.MatchCount != 3 {
t.Fatalf("match count = %d, want 3", svc.searchParams.MatchCount)
}
}
func TestHybridSearchAcceptsPrecomputedVectorWithoutQueryText(t *testing.T) {
svc := &hybridSearchTestService{}
response := performHybridSearchRequest(
svc,
`{"query_embedding":[0.1,0.2],"disable_keywords_match":true}`,
)
if response.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", response.Code, response.Body.String())
}
if svc.searchCalls != 1 {
t.Fatalf("expected one HybridSearch call, got %d", svc.searchCalls)
}
if len(svc.searchParams.QueryEmbedding) != 2 {
t.Fatalf("query embedding length = %d, want 2", len(svc.searchParams.QueryEmbedding))
}
if !svc.searchParams.DisableKeywordsMatch || svc.searchParams.DisableVectorMatch {
t.Fatalf("expected vector-only params, got %+v", svc.searchParams)
}
}
func performHybridSearchRequest(svc interfaces.KnowledgeBaseService, body string) *httptest.ResponseRecorder {
response := httptest.NewRecorder()
request := httptest.NewRequest(
http.MethodPost,
"/knowledge-bases/kb-1/hybrid-search",
strings.NewReader(body),
)
request.Header.Set("Content-Type", "application/json")
newHybridSearchTestRouter(svc).ServeHTTP(response, request)
return response
}
@@ -0,0 +1,135 @@
package handler
import (
"context"
stderrors "errors"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"academy/internal/application/repository"
apperrors "academy/internal/errors"
"academy/internal/middleware"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// validateAndGetKnowledgeBase (knowledgebase.go) and the four sibling
// helpers in faq.go / knowledge.go / tag.go / initialization.go used to
// wrap every Get*ByID error — including the well-known
// repository.ErrKnowledgeBaseNotFound sentinel — as a 500. That turned
// every probe of a stale or cross-tenant KB id into a fake "internal
// server error" envelope. These tests pin the corrected mapping (404)
// at the HTTP boundary so a future refactor can't quietly regress it.
//
// The wrapped-sentinel cases are the actual security boundary: if a
// caller drops the stderrors.Is comparison and reverts to `==`, the
// fmt.Errorf("%w") path silently fails over to 500 and the tests below
// fail before the change ships.
// stubKBOnlyService implements just enough of KnowledgeBaseService to
// drive validateAndGetKnowledgeBase. Embedding the interface keeps every
// other method nil-panicky on purpose so a future test that reaches
// outside the contract fails loudly.
type stubKBOnlyService struct {
interfaces.KnowledgeBaseService
getByID func(ctx context.Context, id string) (*types.KnowledgeBase, error)
fillKnowledgeBaseCounts func(ctx context.Context, kb *types.KnowledgeBase) error
}
func (s *stubKBOnlyService) GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error) {
return s.getByID(ctx, id)
}
func (s *stubKBOnlyService) FillKnowledgeBaseCounts(ctx context.Context, kb *types.KnowledgeBase) error {
if s.fillKnowledgeBaseCounts != nil {
return s.fillKnowledgeBaseCounts(ctx, kb)
}
return nil
}
// newKBHandlerTestRouter mounts the production ErrorHandler so
// c.Error(NewNotFoundError(...)) renders as the real 404 envelope.
// Tenant id and user id are injected by a tiny middleware so
// validateAndGetKnowledgeBase doesn't bail at the unauthorized branch.
func newKBHandlerTestRouter(svc interfaces.KnowledgeBaseService) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(middleware.ErrorHandler())
r.Use(func(c *gin.Context) {
c.Set(types.TenantIDContextKey.String(), uint64(1))
c.Set(types.UserIDContextKey.String(), "u-test")
c.Next()
})
h := &KnowledgeBaseHandler{service: svc}
r.GET("/knowledge-bases/:id", h.GetKnowledgeBase)
return r
}
func TestKBHandlerMapsErrKnowledgeBaseNotFoundToNotFound(t *testing.T) {
svc := &stubKBOnlyService{
getByID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return nil, repository.ErrKnowledgeBaseNotFound
},
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/missing-kb", nil)
newKBHandlerTestRouter(svc).ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("ErrKnowledgeBaseNotFound must map to 404, got %d body=%s", w.Code, w.Body.String())
}
}
func TestKBHandlerHonoursWrappedErrKnowledgeBaseNotFound(t *testing.T) {
// Regression test against a stale `==` sentinel comparison: errors.Is
// unwraps fmt.Errorf("%w", ...); a literal `==` does not. If anyone
// reverts the comparison this test fails before the change ships.
svc := &stubKBOnlyService{
getByID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return nil, fmt.Errorf("loading kb: %w", repository.ErrKnowledgeBaseNotFound)
},
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/missing-kb", nil)
newKBHandlerTestRouter(svc).ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("wrapped ErrKnowledgeBaseNotFound must still map to 404, got %d body=%s",
w.Code, w.Body.String())
}
// Defence-in-depth: the response body should expose the AppError
// envelope (ErrorHandler renders {success,error:{code,message}}),
// not the bare gin error string. Code 1003 is ErrNotFound.
if !strings.Contains(w.Body.String(), `"code":1003`) {
t.Fatalf("expected NotFound envelope with code=1003, got body=%s", w.Body.String())
}
}
func TestKBHandlerKeeps500ForGenuineInfraErrors(t *testing.T) {
// The mapping is *only* for the not-found sentinel — every other
// error must still surface as a real 5xx so monitoring catches
// genuine DB / repo failures.
svc := &stubKBOnlyService{
getByID: func(_ context.Context, _ string) (*types.KnowledgeBase, error) {
return nil, stderrors.New("connection refused")
},
}
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/knowledge-bases/some-kb", nil)
newKBHandlerTestRouter(svc).ServeHTTP(w, req)
if w.Code != http.StatusInternalServerError {
t.Fatalf("non-sentinel errors must remain 500, got %d body=%s", w.Code, w.Body.String())
}
}
// guardAgainstStaleSentinelEquality is a compile-time assertion: if a
// future refactor accidentally drops the apperrors / stderrors imports
// from THIS file, the test stops compiling and the human gets a clear
// signal that something tied to the not-found mapping went away.
var (
_ = stderrors.Is
_ = apperrors.NewNotFoundError
)
Loaded 100 of 5767 files, more files were not shown because too many files have changed in this diff. Show more