按用户反馈「每个主体都有 mcp 访问 key,就应该是各自主体身份」—— v1 方案「注入 connector key + 手动 X-Principal」本质是「模拟身份」, 绕开了主体解析链。v2 改为透传调用方真实鉴权。 ### 改动 - callConn 接受源 *gin.Context,透传 X-API-Key / session cookie 给内层请求, 让 principalFromRequest 自然解析到 manager / connector / analyst / 等。 - connectorAuth 放宽到「任一主体 api_key 即放行」: - 移除 WHERE name='connector' 的硬约束 - 助手 anyPrincipalKeySet() 判断全库是否已有密钥(有则要求带 key,无则放行兼容无密钥只读) - 6 个调用点去掉 principal 参数,改传 c。 ### 影响 - 之前:MCP 读工具一律以 connector 执行,manager 走 MCP 只能看 L0-L2。 - 现在:各主体按自己 clearance 视图读,manager 走 MCP 见全部分级(含 L3)。 - callConn 路径与 connectorAuth 路径身份解析统一(都走 principalFromRequest 自然解析)。 ### 验证 - 3 个新集成测试全绿(issue8_mcp_read_principal_test.go): 按 connector / manager / analyst 三种 api_key 调 MCP get_objects_by_type, 分别见 2 / 3 / 1 条(符合各自 clearance)。 - 既有 issue #6/#7 的 6 个测试 + SetObjectTypeClassification 全绿。 ### CHANGELOG 风格 按用户反馈「只有改了什么 / 有什么影响,不要流水账」, 重写 [Unreleased] / [1.3.3] / [1.3.2] 三段:每段只留「影响 + 改动 [+ 设计]」, 去掉过程叙述、commit hash、调试日志、issue 评论引用等。
615 lines
19 KiB
Go
615 lines
19 KiB
Go
package main
|
||
|
||
// 访问控制管理接口(manager 主体可见)
|
||
// /api/v1/access/principals 主体 CRUD
|
||
// /api/v1/access/principals/:name/clearances 主体可读标记集
|
||
// /api/v1/access/grants 授权规则 CRUD
|
||
// /api/v1/access/markings 对象标记 CRUD(按对象)
|
||
// /api/v1/access/field-policies 字段策略 CRUD
|
||
// /api/v1/access/preview?principal=alice 以某主体视角预览可见性统计
|
||
// /api/v1/access/whoami 当前请求的主体与可见标记集
|
||
|
||
import (
|
||
"crypto/rand"
|
||
"encoding/hex"
|
||
"strconv"
|
||
"strings"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
// ---------- 主体 ----------
|
||
|
||
func (a *app) listPrincipals(c *gin.Context) {
|
||
rows, err := a.pool.Query(c, `SELECT name, description, is_builtin, COALESCE(api_key,'') FROM principals ORDER BY is_builtin DESC, name`)
|
||
if err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
defer rows.Close()
|
||
type pRow struct {
|
||
Principal
|
||
HasAPIKey bool `json:"has_api_key"`
|
||
APIKeyHint string `json:"api_key_hint"`
|
||
APIKeyCreatedAt string `json:"api_key_created_at,omitempty"`
|
||
// 修复 issue #7:clearances 一并回显,否则管理员看不到当前主体的可见级别集。
|
||
Clearances []string `json:"clearances"`
|
||
}
|
||
var out []pRow
|
||
for rows.Next() {
|
||
var p Principal
|
||
var key string
|
||
var builtin bool
|
||
if err := rows.Scan(&p.Name, &p.Description, &builtin, &key); err == nil {
|
||
p.IsBuiltin = builtin
|
||
row := pRow{Principal: p, HasAPIKey: key != "", Clearances: []string{}}
|
||
if key != "" {
|
||
row.APIKeyHint = maskAPIKey(key)
|
||
row.APIKeyCreatedAt = "已绑定"
|
||
}
|
||
out = append(out, row)
|
||
}
|
||
}
|
||
// 单独查询所有 clearances(按 principal 分组),避免 N+1
|
||
if len(out) > 0 {
|
||
clRows, err := a.pool.Query(c, `SELECT principal, marking FROM principal_clearances ORDER BY principal, marking`)
|
||
if err == nil {
|
||
idx := map[string]int{}
|
||
for i, p := range out {
|
||
idx[p.Name] = i
|
||
}
|
||
for clRows.Next() {
|
||
var pn, mk string
|
||
if clRows.Scan(&pn, &mk) == nil {
|
||
if i, ok := idx[pn]; ok {
|
||
out[i].Clearances = append(out[i].Clearances, mk)
|
||
}
|
||
}
|
||
}
|
||
clRows.Close()
|
||
}
|
||
}
|
||
c.JSON(200, gin.H{"principals": out, "count": len(out)})
|
||
}
|
||
|
||
// getPrincipal 返回单个主体,manager 可拿到完整 api_key(仅展示一次以外不会在 list 中回)。
|
||
// 修复 issue #7:响应同时回显 clearances 数组,否则前端拿不到主体可见级别集。
|
||
func (a *app) getPrincipal(c *gin.Context) {
|
||
name := c.Param("name")
|
||
var description string
|
||
var builtin bool
|
||
var key string
|
||
err := a.pool.QueryRow(c,
|
||
`SELECT description, is_builtin, COALESCE(api_key,'') FROM principals WHERE name=$1`,
|
||
name).Scan(&description, &builtin, &key)
|
||
if err != nil {
|
||
c.JSON(404, gin.H{"error": "主体不存在: " + name})
|
||
return
|
||
}
|
||
p := Principal{Name: name, Description: description, IsBuiltin: builtin}
|
||
resp := gin.H{
|
||
"name": p.Name,
|
||
"description": p.Description,
|
||
"is_builtin": p.IsBuiltin,
|
||
"has_api_key": key != "",
|
||
}
|
||
if key != "" {
|
||
resp["api_key"] = key
|
||
resp["api_key_hint"] = maskAPIKey(key)
|
||
}
|
||
// 拉 clearances(保证非 nil,序列化成 [] 而不是 null)
|
||
cls := []string{}
|
||
clRows, clErr := a.pool.Query(c,
|
||
`SELECT marking FROM principal_clearances WHERE principal=$1 ORDER BY marking`, name)
|
||
if clErr == nil {
|
||
defer clRows.Close()
|
||
for clRows.Next() {
|
||
var m string
|
||
if clRows.Scan(&m) == nil {
|
||
cls = append(cls, m)
|
||
}
|
||
}
|
||
}
|
||
resp["clearances"] = cls
|
||
c.JSON(200, resp)
|
||
}
|
||
|
||
// maskAPIKey 对 key 做末尾脱敏,仅留前 4 + 后 4 字符
|
||
func maskAPIKey(key string) string {
|
||
if len(key) <= 8 {
|
||
return strings.Repeat("*", len(key))
|
||
}
|
||
return key[:4] + strings.Repeat("*", len(key)-8) + key[len(key)-4:]
|
||
}
|
||
|
||
// generateAPIKey 生成 32 字节随机 key(hex 64 字符)
|
||
func generateAPIKey() string {
|
||
b := make([]byte, 32)
|
||
_, _ = rand.Read(b)
|
||
return hex.EncodeToString(b)
|
||
}
|
||
|
||
type principalInput struct {
|
||
Name string `json:"name"`
|
||
Description string `json:"description"`
|
||
APIKey string `json:"api_key"`
|
||
GenerateAPIKey bool `json:"generate_api_key"`
|
||
}
|
||
|
||
type principalUpdateInput struct {
|
||
Description *string `json:"description"`
|
||
APIKey *string `json:"api_key"`
|
||
ClearAPIKey bool `json:"clear_api_key"`
|
||
GenerateAPIKey bool `json:"generate_api_key"`
|
||
// 修复 issue #7:之前 PUT /principals/:name 完全不接受 clearances 字段(用户传时静默忽略),
|
||
// 现允许一次性替换主体的 clearance 集(与 PUT /principals/:name/clearances 同义)。
|
||
// nil=不动;[]=清空;非空=全量替换(DELETE + INSERT)。
|
||
Clearances *[]string `json:"clearances"`
|
||
}
|
||
|
||
// updatePrincipal 修改主体的说明、api_key、clearances(合并语义)。
|
||
// 修复 issue #7:之前 clearances 字段被静默忽略;现支持在同一次 PUT 中同时改 description / api_key / clearances。
|
||
func (a *app) updatePrincipal(c *gin.Context) {
|
||
name := c.Param("name")
|
||
var in principalUpdateInput
|
||
if err := c.ShouldBindJSON(&in); err != nil {
|
||
c.JSON(400, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
// 内置主体(manager/connector/public)的 api_key 均允许通过管理接口设置/重置/清空。
|
||
// - 鉴权时 principalFromRequest 仅查 principals 表的 api_key(seed 随机值或 UI 设置),不再读 .env。
|
||
// - public 即便持有 key 也只是匿名 L0 只读身份,不会升权;DB 里的 key 仅作为其匿名身份的显式别名。
|
||
tx, err := a.pool.Begin(c)
|
||
if err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
defer tx.Rollback(c)
|
||
if in.Description != nil {
|
||
if _, err := tx.Exec(c, `UPDATE principals SET description=$1 WHERE name=$2`, *in.Description, name); err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
}
|
||
finalKey := ""
|
||
if in.ClearAPIKey {
|
||
if _, err := tx.Exec(c, `UPDATE principals SET api_key=NULL WHERE name=$1`, name); err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
} else if in.GenerateAPIKey {
|
||
finalKey = generateAPIKey()
|
||
if _, err := tx.Exec(c, `UPDATE principals SET api_key=$1 WHERE name=$2`, finalKey, name); err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
} else if in.APIKey != nil && *in.APIKey != "" {
|
||
finalKey = *in.APIKey
|
||
if _, err := tx.Exec(c, `UPDATE principals SET api_key=$1 WHERE name=$2`, finalKey, name); err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
}
|
||
// 修复 issue #7:clearances 字段支持。nil=不动;非空数组(含 [])= 全量替换。
|
||
if in.Clearances != nil {
|
||
if _, err := tx.Exec(c, `DELETE FROM principal_clearances WHERE principal=$1`, name); err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
for _, m := range *in.Clearances {
|
||
if m = strings.TrimSpace(m); m != "" {
|
||
if _, err := tx.Exec(c,
|
||
`INSERT INTO principal_clearances(principal,marking) VALUES($1,$2) ON CONFLICT DO NOTHING`,
|
||
name, m); err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if err := tx.Commit(c); err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
a.InvalidateAuthzCache(name)
|
||
// 回读,让前端能立即核对(同时验证上面 writes)
|
||
resp := gin.H{"ok": true, "name": name}
|
||
keyTouched := in.ClearAPIKey || in.GenerateAPIKey || (in.APIKey != nil && *in.APIKey != "")
|
||
if keyTouched {
|
||
// 这次请求确实动了 api_key,按结果回显
|
||
if finalKey != "" {
|
||
resp["api_key"] = finalKey
|
||
resp["api_key_hint"] = maskAPIKey(finalKey)
|
||
resp["has_api_key"] = true
|
||
} else if in.ClearAPIKey {
|
||
resp["has_api_key"] = false
|
||
} else {
|
||
resp["has_api_key"] = finalKey != ""
|
||
}
|
||
} else {
|
||
// 未提供 api_key 相关字段:回显 DB 真实状态,避免误导。
|
||
// 修复 issue #8 附注:之前此处错误地把 "未传 api_key" 当作 "key 不存在"。
|
||
var cur string
|
||
_ = a.pool.QueryRow(c, `SELECT COALESCE(api_key,'') FROM principals WHERE name=$1`, name).Scan(&cur)
|
||
resp["has_api_key"] = cur != ""
|
||
}
|
||
if in.Clearances != nil {
|
||
resp["clearances"] = *in.Clearances
|
||
}
|
||
c.JSON(200, resp)
|
||
}
|
||
|
||
func (a *app) createPrincipal(c *gin.Context) {
|
||
var in principalInput
|
||
if err := c.ShouldBindJSON(&in); err != nil {
|
||
c.JSON(400, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
if strings.TrimSpace(in.Name) == "" {
|
||
c.JSON(400, gin.H{"error": "name 必填"})
|
||
return
|
||
}
|
||
key := strings.TrimSpace(in.APIKey)
|
||
if key == "" && in.GenerateAPIKey {
|
||
key = generateAPIKey()
|
||
}
|
||
var id int64
|
||
err := a.pool.QueryRow(c,
|
||
`INSERT INTO principals(name,description,api_key,is_builtin) VALUES($1,$2,$3,false) RETURNING id`,
|
||
in.Name, in.Description, key).Scan(&id)
|
||
if err != nil {
|
||
c.JSON(409, gin.H{"error": "创建失败: " + err.Error()})
|
||
return
|
||
}
|
||
a.InvalidateAuthzCache(in.Name)
|
||
c.JSON(201, gin.H{
|
||
"ok": true,
|
||
"id": id,
|
||
"name": in.Name,
|
||
"description": in.Description,
|
||
"has_api_key": key != "",
|
||
"api_key": key,
|
||
"api_key_hint": maskAPIKey(key),
|
||
})
|
||
}
|
||
|
||
func (a *app) deletePrincipal(c *gin.Context) {
|
||
name := c.Param("name")
|
||
if name == "manager" || name == "connector" || name == "public" {
|
||
c.JSON(400, gin.H{"error": "内置主体不可删除"})
|
||
return
|
||
}
|
||
tag, err := a.pool.Exec(c, `DELETE FROM principals WHERE name=$1 AND is_builtin=false`, name)
|
||
if err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
if tag.RowsAffected() == 0 {
|
||
c.JSON(404, gin.H{"error": "主体不存在或为内置"})
|
||
return
|
||
}
|
||
// 同步清理 grants/clearances/field_policies
|
||
_, _ = a.pool.Exec(c, `DELETE FROM grants WHERE principal=$1`, name)
|
||
_, _ = a.pool.Exec(c, `DELETE FROM principal_clearances WHERE principal=$1`, name)
|
||
_, _ = a.pool.Exec(c, `DELETE FROM field_policies WHERE principal=$1`, name)
|
||
a.InvalidateAuthzCache(name)
|
||
c.JSON(200, gin.H{"ok": true})
|
||
}
|
||
|
||
// ---------- clearances ----------
|
||
|
||
func (a *app) getClearances(c *gin.Context) {
|
||
name := c.Param("name")
|
||
rows, _ := a.pool.Query(c, `SELECT marking FROM principal_clearances WHERE principal=$1 ORDER BY marking`, name)
|
||
defer rows.Close()
|
||
var out []string
|
||
for rows.Next() {
|
||
var m string
|
||
if rows.Scan(&m) == nil {
|
||
out = append(out, m)
|
||
}
|
||
}
|
||
c.JSON(200, gin.H{"principal": name, "clearances": out})
|
||
}
|
||
|
||
func (a *app) putClearances(c *gin.Context) {
|
||
name := c.Param("name")
|
||
var in struct {
|
||
Markings []string `json:"markings"`
|
||
}
|
||
if err := c.ShouldBindJSON(&in); err != nil {
|
||
c.JSON(400, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
tx, err := a.pool.Begin(c)
|
||
if err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
defer tx.Rollback(c)
|
||
if _, err := tx.Exec(c, `DELETE FROM principal_clearances WHERE principal=$1`, name); err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
for _, m := range in.Markings {
|
||
if m = strings.TrimSpace(m); m != "" {
|
||
if _, err := tx.Exec(c, `INSERT INTO principal_clearances(principal,marking) VALUES($1,$2) ON CONFLICT DO NOTHING`, name, m); err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
}
|
||
}
|
||
if err := tx.Commit(c); err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
a.InvalidateAuthzCache(name)
|
||
c.JSON(200, gin.H{"ok": true, "principal": name, "clearances": in.Markings})
|
||
}
|
||
|
||
// ---------- grants ----------
|
||
|
||
func (a *app) listGrants(c *gin.Context) {
|
||
rows, _ := a.pool.Query(c, `SELECT id, principal, action, scope_type, scope_pk, effect FROM grants ORDER BY principal, action, scope_type`)
|
||
defer rows.Close()
|
||
var out []Grant
|
||
for rows.Next() {
|
||
var g Grant
|
||
if rows.Scan(&g.ID, &g.Principal, &g.Action, &g.ScopeType, &g.ScopePK, &g.Effect) == nil {
|
||
out = append(out, g)
|
||
}
|
||
}
|
||
c.JSON(200, gin.H{"grants": out, "count": len(out)})
|
||
}
|
||
|
||
func (a *app) createGrant(c *gin.Context) {
|
||
var g Grant
|
||
if err := c.ShouldBindJSON(&g); err != nil {
|
||
c.JSON(400, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
if g.Principal == "" || g.Action == "" {
|
||
c.JSON(400, gin.H{"error": "principal 与 action 必填"})
|
||
return
|
||
}
|
||
if g.ScopeType == "" {
|
||
g.ScopeType = "*"
|
||
}
|
||
if g.ScopePK == "" {
|
||
g.ScopePK = "*"
|
||
}
|
||
if g.Effect == "" {
|
||
g.Effect = "allow"
|
||
}
|
||
var id int64
|
||
err := a.pool.QueryRow(c,
|
||
`INSERT INTO grants(principal,action,scope_type,scope_pk,effect) VALUES($1,$2,$3,$4,$5) RETURNING id`,
|
||
g.Principal, g.Action, g.ScopeType, g.ScopePK, g.Effect).Scan(&id)
|
||
if err != nil {
|
||
c.JSON(409, gin.H{"error": "授权规则重复或冲突: " + err.Error()})
|
||
return
|
||
}
|
||
a.InvalidateAuthzCache(g.Principal)
|
||
g.ID = id
|
||
c.JSON(201, g)
|
||
}
|
||
|
||
func (a *app) deleteGrant(c *gin.Context) {
|
||
id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
|
||
var principal string
|
||
_ = a.pool.QueryRow(c, `SELECT principal FROM grants WHERE id=$1`, id).Scan(&principal)
|
||
tag, err := a.pool.Exec(c, `DELETE FROM grants WHERE id=$1`, id)
|
||
if err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
if tag.RowsAffected() == 0 {
|
||
c.JSON(404, gin.H{"error": "授权规则不存在"})
|
||
return
|
||
}
|
||
a.InvalidateAuthzCache(principal)
|
||
c.JSON(200, gin.H{"ok": true})
|
||
}
|
||
|
||
// ---------- markings ----------
|
||
|
||
// getObjectMarkings 取某对象的标记集
|
||
func (a *app) getObjectMarkings(c *gin.Context) {
|
||
typ := c.Param("type")
|
||
pk := c.Param("pk")
|
||
rows, _ := a.pool.Query(c, `SELECT marking FROM object_markings WHERE object_type=$1 AND object_pk=$2 ORDER BY marking`, typ, pk)
|
||
defer rows.Close()
|
||
var out []string
|
||
for rows.Next() {
|
||
var m string
|
||
if rows.Scan(&m) == nil {
|
||
out = append(out, m)
|
||
}
|
||
}
|
||
c.JSON(200, gin.H{"object_type": typ, "object_pk": pk, "markings": out})
|
||
}
|
||
|
||
func (a *app) putObjectMarkings(c *gin.Context) {
|
||
typ := c.Param("type")
|
||
pk := c.Param("pk")
|
||
var in struct {
|
||
Markings []string `json:"markings"`
|
||
}
|
||
if err := c.ShouldBindJSON(&in); err != nil {
|
||
c.JSON(400, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
tx, err := a.pool.Begin(c)
|
||
if err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
defer tx.Rollback(c)
|
||
if _, err := tx.Exec(c, `DELETE FROM object_markings WHERE object_type=$1 AND object_pk=$2`, typ, pk); err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
for _, m := range in.Markings {
|
||
if m = strings.TrimSpace(m); m != "" {
|
||
if _, err := tx.Exec(c, `INSERT INTO object_markings(object_type,object_pk,marking) VALUES($1,$2,$3) ON CONFLICT DO NOTHING`, typ, pk, m); err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
}
|
||
}
|
||
if err := tx.Commit(c); err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
a.InvalidateAuthzCache()
|
||
c.JSON(200, gin.H{"ok": true, "object_type": typ, "object_pk": pk, "markings": in.Markings})
|
||
}
|
||
|
||
// listMarkings 列出所有使用过的标记 + 使用次数
|
||
func (a *app) listMarkings(c *gin.Context) {
|
||
rows, _ := a.pool.Query(c, `SELECT marking, count(*) FROM object_markings GROUP BY marking ORDER BY marking`)
|
||
defer rows.Close()
|
||
type mkRow struct {
|
||
Marking string `json:"marking"`
|
||
Count int64 `json:"count"`
|
||
}
|
||
var out []mkRow
|
||
for rows.Next() {
|
||
var m mkRow
|
||
if rows.Scan(&m.Marking, &m.Count) == nil {
|
||
out = append(out, m)
|
||
}
|
||
}
|
||
c.JSON(200, gin.H{"markings": out, "count": len(out)})
|
||
}
|
||
|
||
// ---------- 字段策略 ----------
|
||
|
||
func (a *app) listFieldPolicies(c *gin.Context) {
|
||
rows, _ := a.pool.Query(c, `SELECT id, object_type, property, principal, effect FROM field_policies ORDER BY object_type, property, principal`)
|
||
defer rows.Close()
|
||
var out []FieldPolicy
|
||
for rows.Next() {
|
||
var f FieldPolicy
|
||
if rows.Scan(&f.ID, &f.ObjectType, &f.Property, &f.Principal, &f.Effect) == nil {
|
||
out = append(out, f)
|
||
}
|
||
}
|
||
c.JSON(200, gin.H{"field_policies": out, "count": len(out)})
|
||
}
|
||
|
||
func (a *app) createFieldPolicy(c *gin.Context) {
|
||
var f FieldPolicy
|
||
if err := c.ShouldBindJSON(&f); err != nil {
|
||
c.JSON(400, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
if f.ObjectType == "" || f.Property == "" || f.Principal == "" {
|
||
c.JSON(400, gin.H{"error": "object_type/property/principal 必填"})
|
||
return
|
||
}
|
||
if f.Effect == "" {
|
||
f.Effect = "redact"
|
||
}
|
||
var id int64
|
||
err := a.pool.QueryRow(c,
|
||
`INSERT INTO field_policies(object_type,property,principal,effect) VALUES($1,$2,$3,$4) RETURNING id`,
|
||
f.ObjectType, f.Property, f.Principal, f.Effect).Scan(&id)
|
||
if err != nil {
|
||
c.JSON(409, gin.H{"error": "字段策略重复或冲突: " + err.Error()})
|
||
return
|
||
}
|
||
a.InvalidateAuthzCache(f.Principal)
|
||
f.ID = id
|
||
c.JSON(201, f)
|
||
}
|
||
|
||
func (a *app) deleteFieldPolicy(c *gin.Context) {
|
||
id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
|
||
var principal string
|
||
_ = a.pool.QueryRow(c, `SELECT principal FROM field_policies WHERE id=$1`, id).Scan(&principal)
|
||
tag, err := a.pool.Exec(c, `DELETE FROM field_policies WHERE id=$1`, id)
|
||
if err != nil {
|
||
c.JSON(500, gin.H{"error": err.Error()})
|
||
return
|
||
}
|
||
if tag.RowsAffected() == 0 {
|
||
c.JSON(404, gin.H{"error": "字段策略不存在"})
|
||
return
|
||
}
|
||
a.InvalidateAuthzCache(principal)
|
||
c.JSON(200, gin.H{"ok": true})
|
||
}
|
||
|
||
// ---------- 预览:以某主体视角 ----------
|
||
|
||
func (a *app) previewAsPrincipal(c *gin.Context) {
|
||
principal := c.Query("principal")
|
||
if principal == "" {
|
||
c.JSON(400, gin.H{"error": "principal 必填"})
|
||
return
|
||
}
|
||
// 临时构造 Authz(不走缓存,因为可能是不存在的主体)
|
||
authz := &Authz{Principal: principal, Clearances: map[string]bool{}, Grants: []Grant{}, FieldPols: []FieldPolicy{}}
|
||
rows, _ := a.pool.Query(c, `SELECT marking FROM principal_clearances WHERE principal=$1`, principal)
|
||
for rows.Next() {
|
||
var m string
|
||
if rows.Scan(&m) == nil {
|
||
authz.Clearances[m] = true
|
||
}
|
||
}
|
||
rows.Close()
|
||
rows, _ = a.pool.Query(c, `SELECT id, principal, action, scope_type, scope_pk, effect FROM grants WHERE principal=$1`, principal)
|
||
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()
|
||
// 统计可见对象数
|
||
totalRows, _ := a.pool.Query(c, `SELECT count(*) FROM objects`)
|
||
var total int64
|
||
if totalRows.Next() {
|
||
totalRows.Scan(&total)
|
||
}
|
||
totalRows.Close()
|
||
var visible int64
|
||
for typRows, _ := a.pool.Query(c, `SELECT DISTINCT type_api_name FROM objects`); typRows.Next(); {
|
||
var t string
|
||
typRows.Scan(&t)
|
||
var cnt int64
|
||
_ = a.pool.QueryRow(c, `SELECT count(*) FROM objects WHERE type_api_name=$1`, t).Scan(&cnt)
|
||
vRows, _ := a.pool.Query(c, `SELECT pk FROM objects WHERE type_api_name=$1`, t)
|
||
for vRows.Next() {
|
||
var pk string
|
||
vRows.Scan(&pk)
|
||
mks := a.loadObjectMarkings(c, t, pk)
|
||
if authz.CanRead(t, pk, mks) {
|
||
visible++
|
||
}
|
||
}
|
||
vRows.Close()
|
||
}
|
||
c.JSON(200, gin.H{
|
||
"principal": principal,
|
||
"clearances": authz.Clearances,
|
||
"grants": authz.Grants,
|
||
"visible_count": visible,
|
||
"total_count": total,
|
||
})
|
||
}
|
||
|
||
// whoami 当前请求主体信息
|
||
func (a *app) whoami(c *gin.Context) {
|
||
authz, principal := a.authzOf(c)
|
||
cls := make([]string, 0, len(authz.Clearances))
|
||
for m := range authz.Clearances {
|
||
cls = append(cls, m)
|
||
}
|
||
c.JSON(200, gin.H{
|
||
"principal": principal,
|
||
"clearances": cls,
|
||
"grants": authz.Grants,
|
||
})
|
||
} |