Files
ai_academy/internal/middleware/mcp_endpoint_auth_test.go
runny 9058149576
Build & Publish (dsh-academy) / End-to-end inside dsh (latest, advisory) (push) Skipped
CLI / test (macos-latest / go 1.26) (push) Canceled after 0s
CLI / test (ubuntu-latest / go 1.26) (push) Canceled after 0s
CLI / test (windows-latest / go 1.26) (push) Canceled after 0s
Build and Push Docker Image / build-ui (push) Canceled after 0s
Build and Push Docker Image / build-docreader (push) Canceled after 0s
Build and Push Docker Image / build-sandbox (push) Canceled after 0s
Build and Push Docker Image / build-app (amd64, linux/amd64, ubuntu-latest) (push) Canceled after 0s
Build and Push Docker Image / build-app (arm64, linux/arm64, ubuntu-24.04-arm) (push) Canceled after 0s
Build and Push Docker Image / merge (push) Canceled after 0s
Frontend / Test, type-check, and build (push) Canceled after 0s
Frontend / Docker multi-stage image (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.10) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.11) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.12) (push) Canceled after 0s
Build & Publish (mcp-server) / Test (Python 3.13) (push) Canceled after 0s
Build & Publish (mcp-server) / Build sdist + wheel (push) Canceled after 0s
Build & Publish (mcp-server) / Publish to PyPI (push) Canceled after 0s
Anydoc / anydoc parser engine (push) Canceled after 0s
App / Format, vet, test, and build (push) Canceled after 0s
DocReader / Python tests and Go client tests (push) Canceled after 0s
Build & Publish (dsh-academy) / Typecheck, test, pack (push) Canceled after 0s
Build & Publish (dsh-academy) / End-to-end inside dsh (pinned) (push) Canceled after 0s
Build & Publish (dsh-academy) / Publish to npm (push) Canceled after 0s
Go Lint Cache / warm lint cache (.) (push) Canceled after 0s
Go Lint Cache / warm lint cache (cli) (push) Canceled after 0s
Go Lint Cache / warm lint cache (client) (push) Canceled after 0s
Helm / chart (push) Canceled after 0s
refactor: 项目更名 WeKnora → Academy
- 全量替换代码/配置/文档中的项目名(保留上游 GitHub 链接、weixin 文档域名、Docker Hub 镜像名)
- 重命名 32 个含项目名的文件/目录;Go module 路径改为 academy(含 client/cli 子模块)
- docreader proto 描述符采用等长替换,保持序列化字节布局有效
- Dockerfile.app 构建网络修复: browserskill 离线产物通道、PyPI/apt 国内镜像
- 运行验证: go build ✓ docker compose up ✓ 健康检查 ✓
2026-11-13 20:52:51 +08:00

131 lines
4.2 KiB
Go

package middleware
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/application/service"
"academy/internal/types"
"academy/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
type fakeMCPEndpointService struct {
interfaces.MCPEndpointService
ep *types.MCPEndpoint
token string
}
func (f *fakeMCPEndpointService) Authenticate(_ context.Context, endpointID, token string) (*types.MCPEndpoint, error) {
if f.ep == nil || endpointID != f.ep.ID || token != f.token {
return nil, service.ErrMCPEndpointTokenInvalid
}
if !f.ep.Enabled {
return nil, service.ErrMCPEndpointDisabled
}
return f.ep, nil
}
func newMCPAuthTestEngine(svc *fakeMCPEndpointService, capture *map[string]any) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.ContextWithFallback = true
tenantSvc := &fakeTenantService{tenant: &types.Tenant{ID: 42, Status: "active"}}
r.POST("/mcp/:endpoint_id", MCPEndpointAuth(svc, tenantSvc), func(c *gin.Context) {
ctx := c.Request.Context()
ep, _ := MCPEndpointFromContext(ctx)
scope, _ := types.TenantAPIKeyScopeFromContext(ctx)
tenantID, _ := types.TenantIDFromContext(ctx)
principal, _ := types.PrincipalFromContext(ctx)
*capture = map[string]any{
"endpoint": ep,
"scope": scope,
"tenant": tenantID,
"principal": principal,
"authSource": types.PrincipalAuthSourceFromContext(ctx),
}
c.Status(http.StatusNoContent)
})
return r
}
func TestMCPEndpointAuthAttachesScopeAndPrincipal(t *testing.T) {
ep := &types.MCPEndpoint{
ID: "ep-1", TenantID: 42, Enabled: true,
KnowledgeBaseIDs: types.StringArray{"kb-9"},
Tools: types.StringArray{types.MCPEndpointToolAsk},
}
svc := &fakeMCPEndpointService{ep: ep, token: "mcp_secret"}
var captured map[string]any
r := newMCPAuthTestEngine(svc, &captured)
req := httptest.NewRequest(http.MethodPost, "/mcp/ep-1", nil)
req.Header.Set("Authorization", "Bearer mcp_secret")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusNoContent {
t.Fatalf("status %d body %s", w.Code, w.Body.String())
}
if got, _ := captured["endpoint"].(*types.MCPEndpoint); got == nil || got.ID != "ep-1" {
t.Fatalf("endpoint missing from context: %v", captured["endpoint"])
}
if got, _ := captured["tenant"].(uint64); got != 42 {
t.Fatalf("tenant = %v", captured["tenant"])
}
scope := captured["scope"].(types.TenantAPIKeyScope)
if scope.FullAccess || !scope.AllowsKnowledgeBase("kb-9") || scope.AllowsKnowledgeBase("kb-1") {
t.Fatalf("scope not derived from endpoint: %+v", scope)
}
if !scope.HasCapability(types.APIKeyCapabilityChat) {
t.Fatalf("ask tool must grant chat capability: %+v", scope)
}
principal := captured["principal"].(types.Principal)
if principal.Type != types.PrincipalMCPEndpoint || principal.ID != "42:ep-1" {
t.Fatalf("principal = %+v", principal)
}
if got, _ := captured["authSource"].(string); got != types.AuthSourceMCPEndpoint {
t.Fatalf("auth source = %q", got)
}
}
func TestMCPEndpointAuthRejectsBadTokens(t *testing.T) {
ep := &types.MCPEndpoint{ID: "ep-1", TenantID: 42, Enabled: true}
svc := &fakeMCPEndpointService{ep: ep, token: "mcp_secret"}
var captured map[string]any
r := newMCPAuthTestEngine(svc, &captured)
cases := []struct {
name string
path string
header string
want int
}{
{"missing header", "/mcp/ep-1", "", http.StatusUnauthorized},
{"wrong scheme", "/mcp/ep-1", "Embed mcp_secret", http.StatusUnauthorized},
{"wrong token", "/mcp/ep-1", "Bearer mcp_other", http.StatusUnauthorized},
{"wrong endpoint", "/mcp/ep-2", "Bearer mcp_secret", http.StatusUnauthorized},
}
for _, tc := range cases {
req := httptest.NewRequest(http.MethodPost, tc.path, nil)
if tc.header != "" {
req.Header.Set("Authorization", tc.header)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != tc.want {
t.Errorf("%s: status %d, want %d", tc.name, w.Code, tc.want)
}
}
ep.Enabled = false
req := httptest.NewRequest(http.MethodPost, "/mcp/ep-1", nil)
req.Header.Set("Authorization", "Bearer mcp_secret")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusForbidden {
t.Fatalf("disabled endpoint: status %d, want 403", w.Code)
}
}