**账号密码登录与会话体系**
- 后端 handlers_auth.go:bcrypt 校验 + 进程内 session store (TTL 8h)
/api/v1/auth/{login,logout,me,change-password}
- access_control.go:principalFromRequest 优先识别 session cookie;
API KEY + session 双轨并存(dev 模式两个 KEY 都为空 → 跳过 loginRequired
保留旧开发体验,任一 KEY 设置后立即开启真实鉴权)
- handlers_mcp.go:所有受管接口复用 authMiddleware,过期 session 401
- handlers_connector.go:连接器读路径同样接入
- main.go:挂 /api/v1/auth/* + 新增 loginRequired() 中间件
- 启动时为 manager/connector/ingest 三个内置主体写 bcrypt('changeme')
首次登录后强制改密(前端 App.vue 弹修改密码对话框)
**前端登录 UI**
- LoginView.vue:账号+密码登录表单(默认密码 changeme)
- App.vue:登录守卫 + 顶栏用户菜单(修改密码 / 退出登录)
- api.js:所有 request 默认 credentials: include 携带 cookie
新增 authLogin/authLogout/authMe/changePassword + mcpCall (JSON-RPC over SSE)
**导入核对工作台 (manager-only)**
- ReviewView.vue + components/ReviewWorkbench.vue +
composables/useReviewWorkbench.js(多 tab:扫描 / 资料 / 核对 / 应用)
- import-review.html + entry-review.js 多入口(vite.config.js 加 rollup input)
- 对应 ssw-ontology-reviewer skill:本体差距自动扫描 + JSON 执行清单
→ 应用到 ontology
**依赖升级**
- go.mod:go 1.25.0 精确化 + golang.org/x/{crypto,net,sync,sys,text}
升级到 bcrypt 兼容版本
378 lines
12 KiB
Go
378 lines
12 KiB
Go
package main
|
||
|
||
import (
|
||
"context"
|
||
"embed"
|
||
"io/fs"
|
||
"log"
|
||
"net/http"
|
||
"os"
|
||
"path/filepath"
|
||
"strconv"
|
||
"strings"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
"github.com/jackc/pgx/v5/pgxpool"
|
||
"github.com/joho/godotenv"
|
||
|
||
"shangshu-ontology/server/ai"
|
||
)
|
||
|
||
func pathExists(p string) bool {
|
||
st, err := os.Stat(p)
|
||
return err == nil && st.IsDir()
|
||
}
|
||
func pathExistsAbs(p string) bool {
|
||
abs, err := filepath.Abs(p)
|
||
if err != nil {
|
||
return false
|
||
}
|
||
return pathExists(abs)
|
||
}
|
||
|
||
//go:embed all:webroot
|
||
var webFS embed.FS
|
||
|
||
type app struct {
|
||
cfg *Config
|
||
pool *pgxpool.Pool
|
||
ai ai.Provider
|
||
archiveRoot string
|
||
engine *gin.Engine // 供 MCP 端点做进程内子请求,复用连接器逻辑
|
||
}
|
||
|
||
func main() {
|
||
if err := run(); err != nil {
|
||
log.Fatalf("启动失败: %v", err)
|
||
}
|
||
}
|
||
|
||
func run() error {
|
||
_ = godotenv.Load()
|
||
cfg := loadConfig()
|
||
log.Printf("[boot] 配置: %s", cfg.String())
|
||
|
||
ctx := context.Background()
|
||
p, err := initDB(ctx, cfg.dsn())
|
||
if err != nil {
|
||
return err
|
||
}
|
||
pool = p
|
||
defer pool.Close()
|
||
|
||
if cfg.SeedOnStart {
|
||
if err := seedIfEmpty(ctx, pool); err != nil {
|
||
log.Printf("[boot] 种子数据警告: %v", err)
|
||
}
|
||
// 访问控制元原语:principal/marking/grant/field_policy schema 幂等升级 + 默认 seed
|
||
if err := ensureAccessControlSchema(ctx, pool); err != nil {
|
||
log.Printf("[boot] 访问控制 schema 警告: %v", err)
|
||
}
|
||
if err := seedAccessControlDefaults(ctx, pool, cfg.IngestAPIKey); err != nil {
|
||
log.Printf("[boot] 访问控制种子警告: %v", err)
|
||
}
|
||
// Kinetic 层 ⑤Function builtin 函数同步
|
||
if err := ensureBuiltinFunctions(ctx, pool); err != nil {
|
||
log.Printf("[boot] builtin 函数同步警告: %v", err)
|
||
}
|
||
// Semantic 层 ⑦Interface 同步(注册 6 个 connector REST 端点)
|
||
if err := ensureBuiltinInterfaces(ctx, &app{cfg: cfg, pool: pool}); err != nil {
|
||
log.Printf("[boot] builtin interface 同步警告: %v", err)
|
||
}
|
||
}
|
||
|
||
provider := ai.NewProvider(ai.Config{
|
||
BaseURL: cfg.AIBaseURL,
|
||
Key: cfg.AIKey,
|
||
Model: cfg.AIModel,
|
||
})
|
||
log.Printf("[boot] AI 提供者: %s", provider.Name())
|
||
|
||
// ARCHIVE_DIR 在进程 cwd 不同时会指向不一致目录,自动 fallback 到可执行文件相邻路径
|
||
if cfg.ArchiveDir != "" && !filepath.IsAbs(cfg.ArchiveDir) {
|
||
if abs, _ := filepath.Abs(cfg.ArchiveDir); !pathExists(abs) {
|
||
if exe, err := os.Executable(); err == nil {
|
||
if try := filepath.Join(filepath.Dir(exe), "..", cfg.ArchiveDir); pathExistsAbs(try) {
|
||
cfg.ArchiveDir = try
|
||
}
|
||
}
|
||
}
|
||
}
|
||
a := &app{cfg: cfg, pool: pool, ai: provider, archiveRoot: cfg.ArchiveDir}
|
||
log.Printf("[boot] 知识文件根目录: %s", a.archiveRoot)
|
||
|
||
gin.SetMode(gin.ReleaseMode)
|
||
r := gin.New()
|
||
r.Use(gin.Recovery())
|
||
if cfg.AllowCORS {
|
||
r.Use(corsMiddleware())
|
||
}
|
||
// Dynamic Security 审计日志中间件(自动记录每次请求的访问决策)
|
||
r.Use(a.accessLogMiddleware())
|
||
startAccessLogFlusher(pool)
|
||
|
||
registerRoutes(r, a)
|
||
|
||
// 静态资源(内嵌 Vue 构建产物),SPA 回退
|
||
webroot, err := fs.Sub(webFS, "webroot")
|
||
if err != nil {
|
||
return err
|
||
}
|
||
fileServer := http.FileServer(http.FS(webroot))
|
||
r.NoRoute(func(c *gin.Context) {
|
||
if strings.HasPrefix(c.Request.URL.Path, "/api/") {
|
||
log.Printf("[warn] NoRoute 404 (API): %s %s", c.Request.Method, c.Request.URL.Path)
|
||
c.JSON(http.StatusNotFound, gin.H{"error": "not found"})
|
||
return
|
||
}
|
||
// 真实静态文件(assets 等)直接返回;其余路径回退到 index.html(SPA 路由)
|
||
rel := strings.TrimPrefix(c.Request.URL.Path, "/")
|
||
if rel == "" {
|
||
rel = "index.html"
|
||
}
|
||
if f, openErr := webroot.Open(rel); openErr == nil {
|
||
f.Close()
|
||
fileServer.ServeHTTP(c.Writer, c.Request)
|
||
return
|
||
}
|
||
data, readErr := fs.ReadFile(webroot, "index.html")
|
||
if readErr != nil {
|
||
c.Status(http.StatusNotFound)
|
||
return
|
||
}
|
||
c.Data(http.StatusOK, "text/html; charset=utf-8", data)
|
||
})
|
||
|
||
addr := ":" + strconv.Itoa(cfg.HTTPPort)
|
||
log.Printf("[boot] 尚数网本体管理平台监听 %s", addr)
|
||
return r.Run(addr)
|
||
}
|
||
|
||
func registerRoutes(r *gin.Engine, a *app) {
|
||
a.engine = r // 供 MCP 端点在进程内复用连接器 handler
|
||
r.GET("/health", func(c *gin.Context) { c.JSON(200, gin.H{"status": "ok"}) })
|
||
|
||
api := r.Group("/api/v1")
|
||
|
||
// 账号密码登录(公开端点,登录前访问)
|
||
api.POST("/auth/login", a.authLogin)
|
||
api.POST("/auth/logout", a.authLogout)
|
||
api.GET("/auth/me", a.authMe)
|
||
api.POST("/auth/change-password", a.changePassword)
|
||
|
||
// 管理类接口(本体/实例/AI摄取),可配置 MANAGER_API_KEY
|
||
mgmt := api.Group("")
|
||
mgmt.Use(a.loginRequired(), a.managerAuth())
|
||
{
|
||
ot := mgmt.Group("/ontology")
|
||
ot.GET("/object-types", a.listObjectTypes)
|
||
ot.POST("/object-types", a.createObjectType)
|
||
ot.GET("/object-types/:name", a.getObjectType)
|
||
ot.PUT("/object-types/:name", a.updateObjectType)
|
||
ot.DELETE("/object-types/:name", a.deleteObjectType)
|
||
ot.POST("/object-types/:name/properties", a.addProperty)
|
||
ot.PUT("/properties/:id", a.updateProperty)
|
||
ot.DELETE("/properties/:id", a.deleteProperty)
|
||
|
||
ot.GET("/link-types", a.listLinkTypes)
|
||
ot.POST("/link-types", a.createLinkType)
|
||
ot.DELETE("/link-types/:name", a.deleteLinkType)
|
||
|
||
// 类型梳理 (analyze / merge-preview / merge-execute / delete-zero-inst)
|
||
ot.POST("/types/analyze", a.analyzeTypes)
|
||
ot.POST("/types/merge-preview", a.mergePreview)
|
||
ot.POST("/types/merge-execute", a.mergeExecute)
|
||
ot.POST("/types/delete-zero-inst", a.deleteZeroInstTypes)
|
||
|
||
ot.GET("/action-types", a.listActionTypes)
|
||
ot.POST("/action-types", a.createActionType)
|
||
|
||
ot.GET("/function-types", a.listFunctionTypes)
|
||
ot.GET("/function-types/:name", a.getFunctionType)
|
||
ot.POST("/function-types", a.createFunctionType)
|
||
ot.DELETE("/function-types/:name", a.deleteFunctionType)
|
||
ot.POST("/function-types/:name/invoke", a.invokeFunctionType)
|
||
|
||
ot.GET("/interface-types", a.listInterfaceTypes)
|
||
ot.GET("/interface-types/:name", a.getInterfaceType)
|
||
ot.POST("/interface-types", a.createInterfaceType)
|
||
ot.DELETE("/interface-types/:name", a.deleteInterfaceType)
|
||
|
||
ot.GET("/graph", a.getGraph)
|
||
|
||
obj := mgmt.Group("/objects")
|
||
obj.GET("", a.listObjects)
|
||
obj.POST("", a.createObject)
|
||
obj.GET("/:type/:pk", a.getObject)
|
||
obj.PUT("/:type/:pk", a.updateObject)
|
||
obj.DELETE("/:type/:pk", a.deleteObject)
|
||
|
||
lk := mgmt.Group("/links")
|
||
lk.POST("", a.createLink)
|
||
lk.DELETE("/:id", a.deleteLink)
|
||
|
||
ing := mgmt.Group("/ai")
|
||
ing.POST("/ingest", a.aiIngest)
|
||
ing.GET("/ingest", a.listIngestions)
|
||
ing.GET("/ingest/:id", a.getIngestion)
|
||
}
|
||
|
||
// 知识管理:文件管理 + 数据连接资源(manager 或 ingest 主体可写,供 MCP/agent 导入)
|
||
km := api.Group("/km")
|
||
km.Use(a.ingestOrManagerAuth())
|
||
{
|
||
km.GET("/tree", a.kmTree)
|
||
km.GET("/files", a.kmListFiles)
|
||
km.POST("/folders", a.kmCreateFolder)
|
||
km.POST("/upload", a.kmUpload)
|
||
km.GET("/file", a.kmFileMeta)
|
||
km.POST("/put-text", a.kmPutText)
|
||
km.POST("/extract", a.kmExtract)
|
||
km.DELETE("/files", a.kmDeleteFiles)
|
||
|
||
km.GET("/connections", a.kmListConnections)
|
||
km.POST("/connections", a.kmCreateConnection)
|
||
km.GET("/connections/:id", a.kmConnectionDetail)
|
||
km.DELETE("/connections/:id", a.kmDeleteConnection)
|
||
km.POST("/connections/:id/import", a.kmImportConnection)
|
||
km.POST("/connections/extract", a.kmExtractConnections)
|
||
}
|
||
|
||
// 连接器接口(只读查询),可配置 CONNECTOR_API_KEY,供 WorkBuddy 等接入
|
||
conn := api.Group("/connector")
|
||
conn.Use(a.connectorAuth())
|
||
{
|
||
conn.GET("/object-types", a.connObjectTypes)
|
||
conn.GET("/objects/:type", a.connObjects)
|
||
conn.GET("/object/:type/:pk", a.connObject)
|
||
conn.GET("/search", a.connSearch)
|
||
conn.GET("/facets", a.connFacets)
|
||
conn.POST("/query", a.connQuery)
|
||
conn.GET("/graph", a.connGraph)
|
||
}
|
||
|
||
// 访问控制元原语管理接口(manager 主体可见)
|
||
// whoami 任何 principal 都可调(诊断当前身份)——挂在 mgmt 外,登录即可查
|
||
api.GET("/access/whoami", a.whoami)
|
||
acc := mgmt.Group("/access")
|
||
{
|
||
acc.GET("/principals", a.listPrincipals)
|
||
acc.GET("/principals/:name", a.getPrincipal)
|
||
acc.POST("/principals", a.createPrincipal)
|
||
acc.PUT("/principals/:name", a.updatePrincipal)
|
||
acc.DELETE("/principals/:name", a.deletePrincipal)
|
||
acc.GET("/principals/:name/clearances", a.getClearances)
|
||
acc.PUT("/principals/:name/clearances", a.putClearances)
|
||
|
||
acc.GET("/grants", a.listGrants)
|
||
acc.POST("/grants", a.createGrant)
|
||
acc.DELETE("/grants/:id", a.deleteGrant)
|
||
|
||
acc.GET("/markings", a.listMarkings)
|
||
acc.GET("/objects/:type/:pk/markings", a.getObjectMarkings)
|
||
acc.PUT("/objects/:type/:pk/markings", a.putObjectMarkings)
|
||
|
||
acc.GET("/field-policies", a.listFieldPolicies)
|
||
acc.POST("/field-policies", a.createFieldPolicy)
|
||
acc.DELETE("/field-policies/:id", a.deleteFieldPolicy)
|
||
|
||
acc.GET("/preview", a.previewAsPrincipal)
|
||
acc.GET("/log", a.listAccessLog)
|
||
acc.GET("/log/stats", a.accessLogStats)
|
||
}
|
||
|
||
// MCP 协议端点(Streamable HTTP):WorkBuddy 以 url 方式一键注册
|
||
api.Any("/mcp", a.mcpAuth(), a.mcpHandle)
|
||
// MCP 工具清单(人类可读的自描述,供参考/调试)
|
||
api.GET("/mcp/manifest", a.mcpManifest)
|
||
}
|
||
|
||
func (a *app) managerAuth() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
// 仅放行 manager 主体(含 dev 模式默认 manager)
|
||
p := a.principalFromRequest(c)
|
||
if p != "manager" {
|
||
c.Set("authz_decision", "deny")
|
||
c.AbortWithStatusJSON(401, gin.H{"error": "需要 manager 主体", "principal": p})
|
||
return
|
||
}
|
||
c.Next()
|
||
}
|
||
}
|
||
|
||
// loginRequired 强制要求已登录(cookie session 或 X-API-Key)。
|
||
// dev 模式(两个 API KEY env 都为空)→ 跳过,保持旧开发体验。
|
||
// 真实鉴权模式开启时,凡到达此中间件的请求必须带 session 或 API Key,否则 401。
|
||
// 注意:本中间件不区分角色(manager/ingest/connector 都可过);
|
||
// 角色门由 managerAuth / ingestOrManagerAuth 等下游中间件把控。
|
||
func (a *app) loginRequired() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
// dev 模式保留旧体验:无人也能进(默认 manager)
|
||
if a.cfg.ManagerAPIKey == "" && a.cfg.ConnectorAPIKey == "" {
|
||
c.Next()
|
||
return
|
||
}
|
||
p := a.principalFromRequest(c)
|
||
if p == "" || p == "public" {
|
||
c.AbortWithStatusJSON(401, gin.H{"error": "需要登录或有效 API Key", "principal": p})
|
||
return
|
||
}
|
||
c.Next()
|
||
}
|
||
}
|
||
|
||
func (a *app) connectorAuth() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
if a.cfg.ConnectorAPIKey == "" {
|
||
c.Next()
|
||
return
|
||
}
|
||
if c.GetHeader("X-API-Key") != a.cfg.ConnectorAPIKey && c.Query("key") != a.cfg.ConnectorAPIKey {
|
||
c.AbortWithStatusJSON(401, gin.H{"error": "需要 X-API-Key 连接器鉴权"})
|
||
return
|
||
}
|
||
c.Next()
|
||
}
|
||
}
|
||
|
||
// ingestOrManagerAuth 知识管理写接口鉴权:仅放行 manager 或 ingest 主体。
|
||
// ingest 主体由 MCP/agent 使用(持有 INGEST_API_KEY),可按需限定 clearance 与 grant。
|
||
func (a *app) ingestOrManagerAuth() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
p := a.principalFromRequest(c)
|
||
if p != "manager" && p != "ingest" {
|
||
c.Set("authz_decision", "deny")
|
||
c.AbortWithStatusJSON(403, gin.H{"error": "需要 manager 或 ingest 主体", "principal": p})
|
||
return
|
||
}
|
||
c.Next()
|
||
}
|
||
}
|
||
|
||
// mcpAuth MCP 端点鉴权:允许 manager/ingest/connector 调用;生产环境拒绝匿名 public。
|
||
// dev 模式(MANAGER_API_KEY 与 CONNECTOR_API_KEY 均为空)下 principalFromRequest 返回 manager,自然放行。
|
||
func (a *app) mcpAuth() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
p := a.principalFromRequest(c)
|
||
if p == "public" {
|
||
c.Set("authz_decision", "deny")
|
||
c.AbortWithStatusJSON(401, gin.H{"error": "MCP 需要鉴权(manager/ingest/connector 主体)", "principal": p})
|
||
return
|
||
}
|
||
c.Next()
|
||
}
|
||
}
|
||
|
||
func corsMiddleware() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
c.Header("Access-Control-Allow-Origin", "*")
|
||
c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
|
||
c.Header("Access-Control-Allow-Headers", "Content-Type,X-API-Key,Authorization")
|
||
if c.Request.Method == http.MethodOptions {
|
||
c.AbortWithStatus(204)
|
||
return
|
||
}
|
||
c.Next()
|
||
}
|
||
}
|