Files
ssw-ontology/server/access_control.go
T
admin 901c2d55f4 feat(auth): 账号密码登录 + session cookie + 导入核对工作台
**账号密码登录与会话体系**

- 后端 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 兼容版本
2026-08-21 17:06:17 +08:00

499 lines
16 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
// 访问控制元原语(与 object_types / link_types / action_types 平级)
//
// 设计目标:
// - Principal:谁能调用(由 API Key 或匿名映射)
// - Marking:贴在对象上的访问标签(默认 5 级:L0~L4)
// - Grant:(principal, action, scope) -> allow/deny 规则
// - FieldPolicy:字段级 redact/hide 策略
//
// 强制生效点:所有 connector/objects/ontology 的读与写路径都过授权检查;
// 标记过滤掉的整条记录直接不返回,字段策略命中的属性返回 "***" 或直接省略。
import (
"context"
"errors"
"fmt"
"log"
"strings"
"sync"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgxpool"
)
// ---------- 数据模型 ----------
// Principal 调用主体
type Principal struct {
Name string `json:"name"`
Description string `json:"description"`
IsBuiltin bool `json:"is_builtin"`
}
// Grant 授权规则(scope_type='*' 表示通配;scope_type='type:DataProduct' 限定到类型)
type Grant struct {
ID int64 `json:"id"`
Principal string `json:"principal"`
Action string `json:"action"` // read | write | create | delete | execute | manage
ScopeType string `json:"scope_type"` // '*' 或 'type:DataProduct'
ScopePK string `json:"scope_pk"`
Effect string `json:"effect"` // allow | deny
}
// FieldPolicy 字段级策略
type FieldPolicy struct {
ID int64 `json:"id"`
ObjectType string `json:"object_type"`
Property string `json:"property"`
Principal string `json:"principal"`
Effect string `json:"effect"` // redact | hide | full
}
// ---------- 鉴权上下文(per-request 缓存)----------
// Authz 一次请求的鉴权上下文,包含主体身份、可读标记集、grant 列表。
type Authz struct {
Principal string
Clearances map[string]bool
Grants []Grant
FieldPols []FieldPolicy
}
// AllowedMarking 判断 principal 是否能读取带该 marking 的对象
func (a *Authz) AllowedMarking(marking string) bool {
if marking == "" {
return true // 无标记视为公开
}
return a.Clearances[marking]
}
// ---------- Principal 识别 ----------
// principalFromRequest 从请求头推断主体。
// 优先级:X-Principal > cookie session > 查 principals 表的 api_key > MANAGER_API_KEY/CONNECTOR_API_KEY 内置映射 > public
//
// dev 模式(MANAGER_API_KEY 与 CONNECTOR_API_KEY 都为空)→ 视为 manager(开放,保留旧的开发体验)。
// 一旦设置了任何一个 API KEY,真实鉴权就生效。
func (a *app) principalFromRequest(c *gin.Context) string {
if p := strings.TrimSpace(c.GetHeader("X-Principal")); p != "" {
return p
}
// cookie session(账号密码登录后写入)
if tok, err := c.Cookie(SessionCookieName); err == nil && tok != "" {
if p := principalFromSession(tok); p != "" {
return p
}
}
if key := c.GetHeader("X-API-Key"); key != "" {
// 先查自定义 principal(按 api_key 字段)
var name string
if err := a.pool.QueryRow(c, "SELECT name FROM principals WHERE api_key=$1", key).Scan(&name); err == nil && name != "" {
return name
}
// 内置密钥映射
if a.cfg.ManagerAPIKey != "" && key == a.cfg.ManagerAPIKey {
return "manager"
}
if a.cfg.ConnectorAPIKey != "" && key == a.cfg.ConnectorAPIKey {
return "connector"
}
}
if k := c.Query("key"); k != "" {
var name string
if err := a.pool.QueryRow(c, "SELECT name FROM principals WHERE api_key=$1", k).Scan(&name); err == nil && name != "" {
return name
}
if a.cfg.ManagerAPIKey != "" && k == a.cfg.ManagerAPIKey {
return "manager"
}
if a.cfg.ConnectorAPIKey != "" && k == a.cfg.ConnectorAPIKey {
return "connector"
}
}
// dev 模式:两个 API KEY 都为空 → 默认 manager(兼容旧工作流)
if a.cfg.ManagerAPIKey == "" && a.cfg.ConnectorAPIKey == "" {
return "manager"
}
return "public"
}
// authzFor 加载(并缓存)一次请求的完整鉴权上下文。
var authzCache sync.Map // principal -> *Authz
func (a *app) authzFor(c *gin.Context, principal string) (*Authz, error) {
if v, ok := authzCache.Load(principal); ok {
return v.(*Authz), nil
}
return a.loadAuthz(c, principal, true)
}
func (a *app) loadAuthz(c context.Context, principal string, useCache bool) (*Authz, error) {
if useCache {
if v, ok := authzCache.Load(principal); ok {
return v.(*Authz), nil
}
}
authz := &Authz{Principal: principal, Clearances: map[string]bool{}, Grants: []Grant{}, FieldPols: []FieldPolicy{}}
// clearances
rows, err := a.pool.Query(c, `SELECT marking FROM principal_clearances WHERE principal=$1`, principal)
if err == nil {
for rows.Next() {
var m string
if rows.Scan(&m) == nil {
authz.Clearances[m] = true
}
}
rows.Close()
}
// grants
rows, err = a.pool.Query(c, `SELECT id, principal, action, scope_type, scope_pk, effect FROM grants WHERE principal=$1`, principal)
if err == nil {
for rows.Next() {
var g Grant
if rows.Scan(&g.ID, &g.Principal, &g.Action, &g.ScopeType, &g.ScopePK, &g.Effect) == nil {
authz.Grants = append(authz.Grants, g)
}
}
rows.Close()
}
// field policies
rows, err = a.pool.Query(c, `SELECT id, object_type, property, principal, effect FROM field_policies WHERE principal=$1`, principal)
if err == nil {
for rows.Next() {
var f FieldPolicy
if rows.Scan(&f.ID, &f.ObjectType, &f.Property, &f.Principal, &f.Effect) == nil {
authz.FieldPols = append(authz.FieldPols, f)
}
}
rows.Close()
}
authzCache.Store(principal, authz)
return authz, nil
}
// InvalidateAuthzCache 访问控制变更时清除缓存(无参=清全部)
func (a *app) InvalidateAuthzCache(principal ...string) {
if len(principal) == 0 {
authzCache.Range(func(k, _ any) bool { authzCache.Delete(k); return true })
return
}
for _, p := range principal {
authzCache.Delete(p)
}
}
// ---------- 授权决策 ----------
// grantMatches 判断单条 grant 是否作用于 (action, scope_type, scope_pk)
func grantMatches(g Grant, action, scopeType, scopePK string) bool {
if g.Action != action && g.Action != "manage" {
return false
}
if g.ScopeType == "*" {
return true
}
// scope_type 形如 "type:DataProduct"
if strings.HasPrefix(g.ScopeType, "type:") {
return strings.TrimPrefix(g.ScopeType, "type:") == scopeType
}
if strings.HasPrefix(g.ScopeType, "instance:") {
// scope_type="instance:Type"
want := strings.TrimPrefix(g.ScopeType, "instance:")
if want != scopeType {
return false
}
return g.ScopePK == "*" || g.ScopePK == scopePK
}
return false
}
// Allowed 检查当前 principal 是否被授权对 (objType, objPk) 执行 action
// 先按 deny 优先,再看 allow;manage 隐含所有 action。
func (a *Authz) Allowed(action, objType, objPK string) bool {
hasAllow, hasDeny := false, false
for _, g := range a.Grants {
if !grantMatches(g, action, objType, objPK) {
continue
}
if g.Effect == "deny" {
hasDeny = true
} else {
hasAllow = true
}
}
if hasDeny {
return false
}
return hasAllow
}
// CanRead 仅检查授权 + marking(不检查 grant,因为读几乎全开)
func (a *Authz) CanRead(objType, objPK string, markings []string) bool {
if a.Principal == "manager" {
return true // manager 永远可见
}
if !a.Allowed("read", objType, objPK) {
return false
}
for _, m := range markings {
if !a.AllowedMarking(m) {
return false
}
}
return true
}
// CanWrite 仅检查授权
func (a *Authz) CanWrite(action, objType, objPK string) bool {
if a.Principal == "manager" {
return true
}
return a.Allowed(action, objType, objPK)
}
// ApplyFieldPolicy 对 properties 应用字段策略:redact=替换为 ***,hide=删除,full=保持。
func (a *Authz) ApplyFieldPolicy(objType string, props map[string]interface{}) map[string]interface{} {
if props == nil {
return props
}
if a.Principal == "manager" {
return props
}
for _, fp := range a.FieldPols {
if fp.ObjectType != objType {
continue
}
val, ok := props[fp.Property]
if !ok {
continue
}
switch fp.Effect {
case "hide":
delete(props, fp.Property)
case "redact":
props[fp.Property] = "***"
case "full":
// 显式 full = 允许覆盖默认 redact
// 恢复原值(已经在 props 里,无需操作)
_ = val
}
}
return props
}
// ---------- 加载对象的 marking ----------
// loadObjectMarkings 取一个对象的所有 marking(无则返回空)
func (a *app) loadObjectMarkings(c context.Context, objType, objPK string) []string {
rows, err := a.pool.Query(c, `SELECT marking FROM object_markings WHERE object_type=$1 AND object_pk=$2`, objType, objPK)
if err != nil {
return nil
}
defer rows.Close()
var out []string
for rows.Next() {
var m string
if rows.Scan(&m) == nil {
out = append(out, m)
}
}
return out
}
// filterByMarking 过滤对象数组:丢掉任何 marking 不在 principal clearance 内 的对象。
// objects 形如 [{type,pk,...}, ...]
// 命中返回过滤后的数组
func (a *app) filterByMarking(c context.Context, authz *Authz, items []map[string]interface{}) []map[string]interface{} {
if authz.Principal == "manager" {
return items
}
out := make([]map[string]interface{}, 0, len(items))
for _, it := range items {
t, _ := it["type"].(string)
pk, _ := it["pk"].(string)
if t == "" || pk == "" {
out = append(out, it) // 缺 type/pk 的不强制过滤
continue
}
mks := a.loadObjectMarkings(c, t, pk)
if authz.CanRead(t, pk, mks) {
out = append(out, it)
}
}
return out
}
// filterByMarkingWithLog 在 gin 上下文里标 decision;connector 调用时可改用这个
func (a *app) filterByMarkingWithLog(ginCtx *gin.Context, c context.Context, authz *Authz, items []map[string]interface{}) []map[string]interface{} {
out := a.filterByMarking(c, authz, items)
if authz.Principal != "manager" && len(out) < len(items) {
ginCtx.Set("authz_decision", "filter")
}
return out
}
// ---------- Schema 升级 + 默认 seed ----------
// ensureAccessControlSchema 幂等建立 5 张访问控制表
func ensureAccessControlSchema(ctx context.Context, p *pgxpool.Pool) error {
ddl := `
CREATE TABLE IF NOT EXISTS principals (
id BIGSERIAL PRIMARY KEY,
name TEXT UNIQUE NOT NULL,
description TEXT DEFAULT '',
api_key TEXT DEFAULT '',
password_hash TEXT DEFAULT NULL,
is_builtin BOOLEAN DEFAULT FALSE,
created_at TIMESTAMPTZ DEFAULT now()
);
CREATE TABLE IF NOT EXISTS principal_clearances (
principal TEXT NOT NULL,
marking TEXT NOT NULL,
PRIMARY KEY (principal, marking)
);
CREATE TABLE IF NOT EXISTS object_markings (
object_type TEXT NOT NULL,
object_pk TEXT NOT NULL,
marking TEXT NOT NULL,
created_at TIMESTAMPTZ DEFAULT now(),
PRIMARY KEY (object_type, object_pk, marking)
);
CREATE INDEX IF NOT EXISTS idx_obj_markings_type_pk ON object_markings(object_type, object_pk);
CREATE INDEX IF NOT EXISTS idx_obj_markings_marking ON object_markings(marking);
CREATE TABLE IF NOT EXISTS grants (
id BIGSERIAL PRIMARY KEY,
principal TEXT NOT NULL,
action TEXT NOT NULL,
scope_type TEXT DEFAULT '*',
scope_pk TEXT DEFAULT '*',
effect TEXT DEFAULT 'allow',
created_at TIMESTAMPTZ DEFAULT now(),
UNIQUE (principal, action, scope_type, scope_pk)
);
CREATE INDEX IF NOT EXISTS idx_grants_principal ON grants(principal);
ALTER TABLE principals ADD COLUMN IF NOT EXISTS password_hash TEXT DEFAULT NULL;
CREATE TABLE IF NOT EXISTS field_policies (
id BIGSERIAL PRIMARY KEY,
object_type TEXT NOT NULL,
property TEXT NOT NULL,
principal TEXT NOT NULL,
effect TEXT NOT NULL DEFAULT 'redact',
created_at TIMESTAMPTZ DEFAULT now(),
UNIQUE (object_type, property, principal)
);
`
_, err := p.Exec(ctx, ddl)
return err
}
// seedAccessControlDefaults 幂等灌入内置主体/clearances/grants;
// 若已存在则跳过。对象 marking 默认全部 L0(公开),可通过 API 升级。
// ingestKey 非空时写入 ingest 主体的 api_key(供 MCP/agent 知识导入鉴权)。
// 默认密码 hash(dev)由 DefaultBuiltinPassword 决定;已存在 hash 不覆盖(首次启动后用户改密不会被回滚)。
func seedAccessControlDefaults(ctx context.Context, p *pgxpool.Pool, ingestKey string) error {
// 1. 内置主体
builtins := []Principal{
{Name: "manager", Description: "管理员:拥有全部权限(manage)", IsBuiltin: true},
{Name: "connector", Description: "连接器/MCP 调用方:默认仅读 L0~L2", IsBuiltin: true},
{Name: "public", Description: "匿名访客:仅读 L0 公开对象", IsBuiltin: true},
{Name: "ingest", Description: "知识导入主体:供 MCP/agent 写入知识库(建文件夹/上传/抽取/删除)", IsBuiltin: true},
}
for _, b := range builtins {
if _, err := p.Exec(ctx,
`INSERT INTO principals(name,description,is_builtin) VALUES($1,$2,true)
ON CONFLICT(name) DO NOTHING`, b.Name, b.Description); err != nil {
return err
}
}
// 内置主体默认密码(仅在 hash 为 NULL 时写入;用户改密后不会被覆盖)
defaultHash, err := bcryptHashPassword(DefaultBuiltinPassword)
if err != nil {
return fmt.Errorf("默认密码 hash 失败: %w", err)
}
if _, err := p.Exec(ctx,
`UPDATE principals SET password_hash=$1 WHERE is_builtin=true AND password_hash IS NULL`, defaultHash); err != nil {
return fmt.Errorf("写入默认密码失败: %w", err)
}
// ingest 主体的 api_key(若有):优先用传入值,已设置则保留
if ingestKey != "" {
if _, err := p.Exec(ctx,
`UPDATE principals SET api_key=$1 WHERE name='ingest' AND (api_key IS NULL OR api_key='')`, ingestKey); err != nil {
return err
}
}
// 2. clearances:默认五级 L0~L4
levels := []string{"L0", "L1", "L2", "L3", "L4"}
matrix := map[string][]string{
"manager": levels,
"connector": {"L0", "L1", "L2"},
"public": {"L0"},
"ingest": levels,
}
for pname, cls := range matrix {
for _, m := range cls {
if _, err := p.Exec(ctx,
`INSERT INTO principal_clearances(principal,marking) VALUES($1,$2)
ON CONFLICT DO NOTHING`, pname, m); err != nil {
return err
}
}
}
// 3. grants:默认
defaults := []Grant{
{Principal: "manager", Action: "manage", ScopeType: "*", ScopePK: "*", Effect: "allow"},
{Principal: "connector", Action: "read", ScopeType: "*", ScopePK: "*", Effect: "allow"},
{Principal: "connector", Action: "execute", ScopeType: "*", ScopePK: "*", Effect: "allow"},
{Principal: "public", Action: "read", ScopeType: "*", ScopePK: "*", Effect: "allow"},
{Principal: "ingest", Action: "manage", ScopeType: "*", ScopePK: "*", Effect: "allow"},
}
for _, g := range defaults {
if _, err := p.Exec(ctx,
`INSERT INTO grants(principal,action,scope_type,scope_pk,effect)
VALUES($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING`,
g.Principal, g.Action, g.ScopeType, g.ScopePK, g.Effect); err != nil {
return err
}
}
// 4. 对象默认 marking:仅对还没有任何 marking 的对象补 L0(公开)。
tag, err := p.Exec(ctx,
`INSERT INTO object_markings(object_type,object_pk,marking)
SELECT type_api_name, pk, 'L0' FROM objects o
WHERE NOT EXISTS (SELECT 1 FROM object_markings m WHERE m.object_type=o.type_api_name AND m.object_pk=o.pk)
ON CONFLICT DO NOTHING`)
if err != nil {
return err
}
log.Printf("[access] 内置主体/授权/标记就绪(manager/connector/public + %d 个对象默认标记 L0)", tag.RowsAffected())
return nil
}
// ---------- HTTP 辅助:拒绝响应 ----------
var errForbidden = errors.New("forbidden")
// abortForbidden 写 403 + JSON,并标记 access_log.decision=deny
func (a *app) abortForbidden(c *gin.Context, msg string) {
c.Set("authz_decision", "deny")
c.AbortWithStatusJSON(403, gin.H{"error": msg, "principal": a.principalFromRequest(c)})
}
// authzOf 一次性取 principal + authz
func (a *app) authzOf(c *gin.Context) (*Authz, string) {
p := a.principalFromRequest(c)
az, _ := a.authzFor(c, p)
return az, p
}