Files
ssw-ontology/server/access_control.go
T
ssw f1b687c2d2 目录扁平化:子目录内容提升至仓库根,文档归入 docs/
- 将 shangshu-ontology/ 子目录内容移至仓库根一级
- 修复 run.sh 的 REPO_ROOT 计算(扁平化后不再需要 cd ..),ARCHIVE_DIR 正确指向仓库根/archive
- 文档(README/PLAN/USAGE/IMPORT/product-intro)移至 docs/,同步更新结构树与导入命令中的旧路径
- 新增根 README.md 索引指向 docs/
- 新增 .gitignore:忽略 bin/、web/node_modules/、web/dist/、server/webroot/、.env、.workbuddy/ 等噪音
- main.go 的 ARCHIVE_DIR fallback 基于可执行文件相邻上级,扁平化后仍正确,无需改动
2026-08-07 14:21:34 +08:00

468 lines
14 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"
"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 升级。
func seedAccessControlDefaults(ctx context.Context, p *pgxpool.Pool) error {
// 1. 内置主体
builtins := []Principal{
{Name: "manager", Description: "管理员:拥有全部权限(manage)", IsBuiltin: true},
{Name: "connector", Description: "连接器/MCP 调用方:默认仅读 L0~L2", IsBuiltin: true},
{Name: "public", Description: "匿名访客:仅读 L0 公开对象", 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
}
}
// 2. clearances:默认五级 L0~L4
levels := []string{"L0", "L1", "L2", "L3", "L4"}
matrix := map[string][]string{
"manager": levels,
"connector": {"L0", "L1", "L2"},
"public": {"L0"},
}
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"},
}
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
}