新增 Dockerfile + docker/entrypoint.sh: - 基础 crpi-.../ssw188/postgres:16-alpine + ontology 二进制,单镜像 - 默认端口 8081 / 库 ssw-ontology / 用户 ssw / 密码 ssw - /data/pg 自动挂 PG 数据,/data/archive 挂文档根目录 - trap 收尸保证 PG + ontology 同生命周期 seed 极简化为 1 个对象类型「合作企业」+ 3 条示例 (尚数网/腾讯/阿里巴巴),便于演示也便于清理。 默认 HTTP_PORT 统一为 8081(覆盖 server/config.go、run.sh、 vite.config.js、importer/import-from-xeo.js、docs/README.md、 docs/USAGE.md、docs/IMPORT.md、.env.example 等所有文档/代码)。 docs/README.md / .env.example 默认 DATABASE_URL 改为 ssw/[email protected]:5432/ssw-ontology(与 Docker 镜像自带 PG 一致); run.sh 删 dacli 硬编码 fallback,改从 .env 读(不存在则报错退出)。 README 重整:分「方式 A Docker 镜像 / 方式 B 本机 ./run.sh」, 新增 AI 智能导入(-e AI_*)与管理接口鉴权(-e MANAGER_API_KEY)说明。
479 lines
15 KiB
Go
479 lines
15 KiB
Go
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"
|
||
"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 > 查 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
|
||
}
|
||
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 '',
|
||
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);
|
||
|
||
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 知识导入鉴权)。
|
||
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
|
||
}
|
||
}
|
||
// 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
|
||
} |