一次收口 2026-11-06 的九项能力(CHANGELOG 1.5.4 → 1.8.0): - 自检探针(readiness.go):check_readiness / check_answerable 两个只读探针,把 「本体里没有」「我没权限看」「模型没抽全」三种空结果原因拆开 - 读路径语义钉死(scope.go):标记与分级的可见范围统一由 Scope 产出,实例分级 为空时继承类型默认级(fail-closed),列表与详情口径一致 - 行级可改性轴(object_owner.go):归属只收窄不宽于 grants,所有对象写路径统一 走 canWriteObject,归属查询失败即拒绝 - 公理第 6 类 certification:认证位保护人工策展内容,AI 重摄取不再覆盖已认证条目 - 跨版本结构 diff(schema_diff.go):schema_snapshots 全量快照 + diff 端点,机器 事实与人工策展分组呈现 - 分区维度 zone:分区绑类型、命中任一即可见,读路径一律带 zone 条件 - 统一分页信封(pagination.go):列表回包统一 count/total/limit/offset/has_more/ truncated,total 与 items 同源 - MCP 长任务进度(mcp_progress.go):客户端带 progressToken 才走 SSE 进度帧 - 本体 schema 导入(ontology_import.go):Turtle 导入 + 四道 fail-fast 闸门 + 整事务 + (source, external_id) 幂等 + IRI 往返不变式 MCP 工具清单并入单一注册表(mcp_registry.go),对外声明与实际可调不再各说各话; 工具数 42 → 54(只读 27 / 写入 27),注册表与分发 case 的双向漂移由 AST 单测拦截。 CHANGELOG 编号整理:新「认证位 + 行级归属」条目由 1.6.0 改为 1.5.6(1.6.x 留给 分区与结构 diff),2026-09-20 的 GB/T 规划稿改标「规划稿·未发布」——该能力已并入 v1.5.1,避免与正式发布的版本号重复。 Co-Authored-By: Claude Code <[email protected]>
618 lines
21 KiB
Go
618 lines
21 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"
|
||
"fmt"
|
||
"log"
|
||
"strings"
|
||
"sync"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
// ---------- 数据模型 ----------
|
||
|
||
// 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
|
||
// Zones 主体持有的分区(分区维度的可见范围,见 zone.go)。
|
||
Zones map[string]bool
|
||
}
|
||
|
||
// AllowedMarking 判断 principal 是否能读取带该 marking 的对象
|
||
//
|
||
// 口径与可见范围 Scope 一致(见 scope.go):
|
||
// - 无标记 = 公开 → 可见(除非主体一条 clearance 都没有,那等于什么都看不到);
|
||
// - 有标记 → 必须在该主体的 clearance 内。
|
||
func (a *Authz) AllowedMarking(marking string) bool {
|
||
sc := markingScope(a)
|
||
if marking == "" {
|
||
return !sc.IsDenyAll()
|
||
}
|
||
return sc.Allows(marking)
|
||
}
|
||
|
||
// ---------- Principal 识别 ----------
|
||
|
||
// principalFromRequest 从请求头推断主体。
|
||
// 鉴权唯一来源是 principals 表的 api_key(首次启动由 seed 注入随机值,之后由 Access Control 页管理);
|
||
// 不再读取任何 .env 显式密钥。
|
||
// 优先级:进程内注入的 request context > cookie session > principals 表的 api_key(X-API-Key 头或 key 查询参数)。
|
||
//
|
||
// 未携带任何有效 key 时:
|
||
// - 若 manager 主体尚未配置 api_key(全新库、seed 未运行)→ 开放为 manager,便于首次引导;
|
||
// - 否则匿名回退 public(L0 只读)。
|
||
// 生产环境首次启动后 manager 必然已有随机 key,故真实鉴权默认生效。
|
||
//
|
||
// 2026-10-17 修复越权洞:原实现把 `X-Principal` 请求头列为最高优先级且完全不校验,
|
||
// 而该头客户端可任意设置 → 任何请求 `X-Principal: manager` 即取得平台最高权限。
|
||
// 该头已彻底移除;进程内自调用改走 request context(见 principal_ctx.go)。
|
||
func (a *app) principalFromRequest(c *gin.Context) string {
|
||
// 进程内自调用注入的主体(外部不可伪造)。
|
||
if p := injectedPrincipal(c.Request.Context()); p != "" {
|
||
return p
|
||
}
|
||
// cookie session(账号密码登录后写入)
|
||
if tok, err := c.Cookie(SessionCookieName); err == nil && tok != "" {
|
||
if p := principalFromSession(tok); p != "" {
|
||
return p
|
||
}
|
||
}
|
||
// 解析 key:仅查 principals 表的 api_key(seed 随机值或 UI 设置)。
|
||
resolve := func(key string) string {
|
||
if key == "" {
|
||
return ""
|
||
}
|
||
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
|
||
}
|
||
return ""
|
||
}
|
||
if p := resolve(c.GetHeader("X-API-Key")); p != "" {
|
||
return p
|
||
}
|
||
if p := resolve(c.Query("key")); p != "" {
|
||
return p
|
||
}
|
||
// 无任何有效 key:manager 尚未配置密钥则开放(首次引导),否则匿名回退 public。
|
||
if !a.managerKeySet() {
|
||
return "manager"
|
||
}
|
||
return "public"
|
||
}
|
||
|
||
// principalKeySet 报告某内置主体是否已在 principals 表配置了 api_key(非空)。
|
||
func (a *app) principalKeySet(name string) bool {
|
||
var n int
|
||
if err := a.pool.QueryRow(context.Background(),
|
||
"SELECT 1 FROM principals WHERE name=$1 AND api_key IS NOT NULL AND api_key<>'' LIMIT 1", name).Scan(&n); err == nil {
|
||
return true
|
||
}
|
||
return false
|
||
}
|
||
|
||
// managerKeySet 报告 manager 主体是否已配置 api_key(用于判定是否进入真实鉴权模式)。
|
||
func (a *app) managerKeySet() bool {
|
||
return a.principalKeySet("manager")
|
||
}
|
||
|
||
// anyPrincipalKeySet 报告全库任意主体是否已配置非空 api_key(用于 connectorAuth 在
|
||
// 全库无密钥时放行、否则要求带 key 的判定)。修复 issue #8 v2:原 connectorKeySet 仅看
|
||
// connector 一个主体,现在需要看任意主体。
|
||
func (a *app) anyPrincipalKeySet() bool {
|
||
var n int
|
||
if err := a.pool.QueryRow(context.Background(),
|
||
"SELECT 1 FROM principals WHERE api_key IS NOT NULL AND api_key<>'' LIMIT 1").Scan(&n); err == nil {
|
||
return true
|
||
}
|
||
return false
|
||
}
|
||
|
||
// builtinKey 读取某内置主体当前存于 principals 表的 api_key(用于内部进程调用注入鉴权头)。
|
||
func (a *app) builtinKey(name string) string {
|
||
var k string
|
||
if err := a.pool.QueryRow(context.Background(),
|
||
"SELECT COALESCE(api_key,'') FROM principals WHERE name=$1", name).Scan(&k); err == nil {
|
||
return k
|
||
}
|
||
return ""
|
||
}
|
||
|
||
// 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{}, Zones: map[string]bool{}}
|
||
|
||
// 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()
|
||
}
|
||
|
||
// zones(分区维度:主体持有哪些分区)
|
||
rows, err = a.pool.Query(c, `SELECT zone_name FROM principal_zones WHERE principal=$1`, principal)
|
||
if err == nil {
|
||
for rows.Next() {
|
||
var z string
|
||
if rows.Scan(&z) == nil {
|
||
authz.Zones[z] = 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,因为读几乎全开)
|
||
//
|
||
// 与列表路径的 visibilityCond 同一套 Scope 语义,避免「列表看不到、详情能看到」。
|
||
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
|
||
}
|
||
return markingScope(a).AllowsMarkings(markings)
|
||
}
|
||
|
||
// 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 幂等建立 7 张访问控制表
|
||
func ensureAccessControlSchema(ctx context.Context, p dbExec) 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)
|
||
);
|
||
|
||
-- 行级可改性轴(2026-11-06):与 clearance(可见性轴)正交。
|
||
-- clearance/marking 决定「看不看得到」;owner 决定「能不能改这一行」。
|
||
-- 对象无 owner 行 = 未启用行级归属 = 行为与从前完全一致(向后兼容)。
|
||
CREATE TABLE IF NOT EXISTS object_owners (
|
||
object_type TEXT NOT NULL,
|
||
object_pk TEXT NOT NULL,
|
||
owner_kind TEXT NOT NULL DEFAULT 'principal',
|
||
owner_name TEXT NOT NULL,
|
||
created_at TIMESTAMPTZ DEFAULT now(),
|
||
PRIMARY KEY (object_type, object_pk, owner_kind, owner_name)
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_object_owners_obj ON object_owners(object_type, object_pk);
|
||
CREATE INDEX IF NOT EXISTS idx_object_owners_name ON object_owners(owner_name);
|
||
|
||
-- 主体分组:owner 可为「账号」或「组」。组成员获得的行级可改性仅限该行,
|
||
-- 不扩大任何全局权限(组不是 grant 的主体)。
|
||
CREATE TABLE IF NOT EXISTS principal_groups (
|
||
principal TEXT NOT NULL,
|
||
group_name TEXT NOT NULL,
|
||
created_at TIMESTAMPTZ DEFAULT now(),
|
||
PRIMARY KEY (principal, group_name)
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_principal_groups_group ON principal_groups(group_name);
|
||
|
||
-- 分区维度(zone,2026-11-06):目录分区 + 授权边界(类型级)。
|
||
-- object_zones —— 对象类型归属哪些分区(分区绑在类型上 ⇒ 一次判定覆盖全部实例);
|
||
-- principal_zones—— 主体持有哪些分区。
|
||
-- 类型未入任何分区 = 公共区(全体可见);类型入区后,持有该分区的主体才看得见它的实例。
|
||
-- 与 marking / 分级叠加(AND),不是互斥关系。
|
||
CREATE TABLE IF NOT EXISTS zones (
|
||
zone_name TEXT PRIMARY KEY,
|
||
description TEXT DEFAULT '',
|
||
created_at TIMESTAMPTZ DEFAULT now()
|
||
);
|
||
CREATE TABLE IF NOT EXISTS object_zones (
|
||
object_type TEXT NOT NULL,
|
||
zone_name TEXT NOT NULL,
|
||
created_at TIMESTAMPTZ DEFAULT now(),
|
||
PRIMARY KEY (object_type, zone_name)
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_object_zones_zone ON object_zones(zone_name);
|
||
CREATE TABLE IF NOT EXISTS principal_zones (
|
||
principal TEXT NOT NULL,
|
||
zone_name TEXT NOT NULL,
|
||
created_at TIMESTAMPTZ DEFAULT now(),
|
||
PRIMARY KEY (principal, zone_name)
|
||
);
|
||
CREATE INDEX IF NOT EXISTS idx_principal_zones_zone ON principal_zones(zone_name);
|
||
`
|
||
_, err := p.Exec(ctx, ddl)
|
||
return err
|
||
}
|
||
|
||
// seedAccessControlDefaults 幂等灌入内置主体/clearances/grants;
|
||
// 若已存在则跳过。对象 marking 默认全部 L0(公开),可通过 API 升级。
|
||
// 所有内置主体(manager/connector/public/ingest)的 api_key 由下方随机 seed 统一生成,
|
||
// 不再依赖任何 .env 显式密钥;生成的随机值只在首次启动时打印一次。
|
||
// 默认密码 hash(dev)由 DefaultBuiltinPassword 决定;已存在 hash 不覆盖(首次启动后用户改密不会被回滚)。
|
||
func seedAccessControlDefaults(ctx context.Context, p dbExec) 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)
|
||
}
|
||
|
||
// 内置主体默认 api_key:仅在为空时随机生成(幂等),避免空 key / 固定值被冒用或暴力破解。
|
||
// 生成的值只在生产首次启动时打印一次,之后由管理员在 Access Control 页查看/重置。
|
||
builtinKeys := []string{"manager", "connector", "public", "ingest"}
|
||
generated := map[string]string{}
|
||
for _, pn := range builtinKeys {
|
||
k := generateAPIKey()
|
||
tag, err := p.Exec(ctx,
|
||
`UPDATE principals SET api_key=$1 WHERE name=$2 AND (api_key IS NULL OR api_key='')`, k, pn)
|
||
if err != nil {
|
||
return fmt.Errorf("生成 %s 初始密钥失败: %w", pn, err)
|
||
}
|
||
if tag.RowsAffected() > 0 {
|
||
generated[pn] = k
|
||
}
|
||
}
|
||
if len(generated) > 0 {
|
||
log.Printf("[access] 已为内置主体生成随机初始 API Key(请妥善保存;首次启动后可在 Access Control 页重置):")
|
||
for _, pn := range builtinKeys {
|
||
if k, ok := generated[pn]; ok {
|
||
log.Printf("[access] %-9s = %s", pn, k)
|
||
}
|
||
}
|
||
}
|
||
|
||
// 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
|
||
} |