register

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 24, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

README

Capability Register (能力注册中心)

AI Agent 细粒度权限控制的标准能力定义注册中心。 能力规范以可执行的 JSON 文件(capability.json)为载体,支持 PKCS#7 签名, 并可从规范文件生成 authz.json 授权策略(gen-authz 工具)。

设计理念

产品方注册能力              Agent 查询能力
┌──────────────┐          ┌──────────┐
│ varwof/core  │          │ Agent A  │
│ core:        │◄────────►│ 持有 AIC │
│  cert:issue  │          │ 声明能力 │
│  ca:list     │          └──────────┘
└──────────────┘
     全球统一规则:同一产品,同一能力定义
     单一来源:capability.json → gen-authz → authz.json

scheme_id 命名规范

类型 格式 示例
公共标准 <vendor>/<product> varwof/core, varwof/gateway, oracle/mysql
私有扩展 x-<vendor>/<product> x-vendor/acme
系统约束 varwof/constraint-v1 固定,不可私有
  • 目录布局:<root>/<vendor>/<product>/v<version>.json
  • x- 前缀标识私有扩展,与 HTTP X- 头惯例一致
  • 能力完整标识:vendor/product:capability_id(如 varwof/core:cert:issue)

目录结构

register/
├── schema.go              # 能力定义结构体(SchemeDefinition/CapabilityEntry/RoleDef)
├── registry.go            # 注册/查询/验证
├── validator.go           # 权限校验引擎(MatchCapability/ValidateRoles)
├── genauthz.go            # authz.json 生成器(GenAuthz/GenAuthzToFile)
├── gendocs.go             # markdown 权限说明文档生成器(GenDocs)
├── mincap.go              # 最小权限校验器(合法/冗余/越权检测)
├── loader.go              # 嵌入式/磁盘加载器
├── sign.go                # PKCS#7 签名/验签
├── AI_PROMPT.md           # AI 最小权限 capability 生成 Prompt 模板
├── cmd/
│   ├── gen-authz/         # 从 capability.json 生成 authz.json 工具
│   ├── gen-docs/          # 从 capability.json 生成 markdown 权限说明
│   ├── gen-capability/    # 校验 AI 生成的能力集 + 最小权限建议
│   ├── sign/              # 签名 capability.json(.p7s)
│   └── verify/            # 验签 capability.json
├── demo/main.go           # 演示程序
├── docs/                  # 文档
│   ├── quickstart.md      # 快速入门
│   ├── reference.md       # API 参考
│   └── architecture.md    # 架构设计
│
├── varwof/
│   ├── core/              # varwof/core:PKI 核心权限(37 能力 + 10 角色)
│   ├── gateway/           # varwof/gateway:网关权限(21 能力 + 5 角色)
│   └── constraint/        # varwof/constraint-v1:系统约束
├── oracle/
│   └── mysql/             # oracle/mysql:MySQL 操作权限
└── x-vendor/
    └── acme/              # 私有扩展示例

快速开始

cd register

# 列出所有能力
go run ./cmd/gen-authz -list varwof/core/v1.json varwof/gateway/v1.json

# 查看某产品能力
go run ./demo get varwof/core

# 生成 authz.json(核心授权策略)
go run ./cmd/gen-authz -out /tmp/authz.json varwof/core/v1.json varwof/gateway/v1.json

# 验证单个能力
go run ./demo validate varwof/core:cert:issue

# 批量验证
go run ./demo check varwof/core:cert:issue varwof/gateway:proxy:http

# 检查子集关系
go run ./demo subset 'varwof/core:cert:issue,varwof/core:ca:list' 'varwof/core:cert:*'

# 搜索能力
go run ./demo search issue

gen-authz:从规范生成授权策略

authz.json 是派生产物,由 capability.json(权威规范)生成,避免手工维护漂移。

# 生成 authz.json(角色 + OU 映射 + 网关命名空间 + 参数默认值)
go run ./cmd/gen-authz -out /tmp/authz.json \
    varwof/core/v1.json \
    varwof/gateway/v1.json

# 验签保护(capability.json 有 .p7s 时强制校验,缺失报错)
go run ./cmd/gen-authz -verify-required -trust-roots ca.pem \
    -out /tmp/authz.json varwof/core/v1.json

# 仅列出能力目录
go run ./cmd/gen-authz -list varwof/core/v1.json
映射规则
capability.json authz.json
主方案 roles(如 varwof/core 的 admin/operator) roles
角色 ous ou_mapping
命名空间角色(gateway:admin 等,跨全部方案聚合) gateway_namespaces
能力 parameters.default capability_parameters(scheme:cap_id → 默认值)
校验
  • 非通配 grant 必须被本方案 capabilities 覆盖(错误)
  • 通配 grant(如 gateway:*)未命中本地时视为跨 scheme 命名空间授权(警告)
  • 有 .p7s 签名时强制 PKCS#7 验签(-verify-required)

gen-docs:从规范生成权限说明文档

每个 capability.json 可生成一份人/AI 可读的 markdown 权限说明文档, 完整描述每个能力的语义(何时需要/何时不应授予/示例/参数),作为 AI 生成 最小权限 capability 时的依据。

# 生成 varwof/core 与 varwof/gateway 的权限说明文档
go run ./cmd/gen-docs varwof/core/v1.json varwof/gateway/v1.json

# 目录模式:一次生成全部方案
go run ./cmd/gen-docs -all register/

生成的文档(core-capabilities.md / gateway-capabilities.md)包含: 能力目录表、能力详细语义、通配符与匹配规则、角色与授权映射、最小权限生成指南。

AI 闭环:任务 → 最小权限 capability → 消费

核心目标:把 capability 规范(JSON + Markdown)交给 AI 大模型, AI 根据任务自动生成最小权限的 capability 集合,从生成到消费完整闭环。

任务描述(如"为生产 HTTPS 服务签发证书")
    │
    ▼
AI 大模型(读取 capability.json + capabilities.md + AI_PROMPT.md)
    │  判断任务类型、逐能力裁决、参数收窄
    ▼
最小权限 capability 集合(JSON claims)
    │
    ▼
gen-capability 校验器(合法性 + 冗余 + 越权检测)
    │
    ▼
最小权限集合 ──→ 签入 AIC/PA ──→ 网关消费(register 校验)
使用步骤
  1. 准备材料(已内置):

    • varwof/core/v1.json + varwof/core/core-capabilities.md
    • varwof/gateway/v1.json + varwof/gateway/gateway-capabilities.md
    • AI_PROMPT.md(指导 AI 的完整 prompt 模板)
  2. AI 生成:将上述材料 + 任务描述交给 AI,AI 输出 claims JSON 文件。

  3. 机器校验:

# 校验合法性(scheme/能力/参数)+ 冗余 + 越权检测
go run ./cmd/gen-capability -grants "cert:issue,ca:list,ca:info" claims.json

# 输出最小权限集合建议
go run ./cmd/gen-capability -grants "cert:issue,ca:list,ca:info" -minimal claims.json
  1. 消费:校验通过的最小权限集合签入 AIC/PA,网关在数据面据此鉴权。
校验能力

gen-capability 检测三类问题:

类别 说明 示例
非法声明 scheme 未知 / 能力不存在 / 参数未定义 bogus/vendor:foo:bar
冗余声明 被通配覆盖或重复 ca:list 被 ca:* 覆盖
越权能力 身份 grants 未授权 key:recover 不在 grants 内

校验通过(最小权限: true)即可交付签入。

运行时接入(Phase D:register 权威 schema → 运行时校验)

能力规范闭环除生成派生产物外,还在运行时做能力注册校验(fail-closed): AIC 中声明的能力必须来自 register 方案,未注册的 scheme/capability 声明即拒绝。

core(签发侧)
  • 配置项 capability_schemes(空 = 嵌入式方案;指定目录 = 磁盘 override)
  • 启动/reloadConfigNowWithMuxes 时 loadCapRegistry → Server.SetCapRegistry
  • 签发 AIC / agent-proxy 证书时经 SignConfig.ValidateCapabilities 钩子校验全部能力 (internal/capregistry,嵌入优先 + 磁盘覆盖 + 热重载原子替换)
三网关(数据面,opt-in)
  • 配置项 capability_schemes(gateway/http、gateway/tcp、gateway/udp)
  • 仅显式配置后启用(向后兼容:默认不校验,旧 AIC 不受影响)
  • gateway/capreg.Loader 统一加载(嵌入优先 + 磁盘覆盖),NewGateway/Reload 时 注入 gw.SetGlobalCapabilityRegistry;RunAccessPipeline 阶段一校验 EffectiveCaps 已注册,未注册 → 拒绝连接 + 审计
  • 改磁盘方案 JSON → SIGHUP 热重载即时生效

如何注册新能力

公共标准
  1. Fork 仓库
  2. 在 register/<vendor>/<product>/ 下创建目录(如 varwof/core/)
  3. 添加 v1.json(参考下方格式,scheme_id 用 <vendor>/<product>)
  4. 用 go run ./cmd/sign 签名生成 .p7s
  5. 提交 PR,审核后发布
私有扩展
  1. 在 register/ 下创建 x-<your-vendor>/ 目录
  2. 添加 v1.json(scheme_id 用 x-<your-vendor>/<product>)
  3. 可直接使用,无需审核

capability.json 格式

{
  "scheme_id": "varwof/core",
  "name": "Varwof PKI Core",
  "version": "1.1.0",
  "description": "Varwof PKI 核心引擎操作权限",
  "vendor": "varwof",
  "product": "core",
  "capabilities": [
    {
      "id": "cert:issue",
      "description": "签发证书",
      "parameters": {
        "max_validity_days": {
          "type": "int",
          "description": "最大有效期(天)",
          "default": 365,
          "min": 1,
          "max": 3650
        }
      }
    }
  ],
  "roles": {
    "admin": {
      "display_name": "管理员",
      "profiles": ["m-admin"],
      "ous": ["admin", "Admin"],
      "grants": ["ca:list", "cert:issue", "cert:revoke"]
    },
    "agent": {
      "display_name": "AI Agent",
      "profiles": ["agent-proxy"],
      "grants": ["gateway:*"]
    }
  }
}

字段说明

SchemeDefinition
字段 类型 必填 说明
scheme_id string ✅ 产品唯一标识(vendor/product)
name string ✅ 产品名称
version string ✅ 语义化版本号
description string ✅ 产品描述
vendor string ✅ 厂商
product string ✅ 产品名
author string 作者
license string 许可证
homepage string 主页
capabilities []CapabilityEntry ✅ 能力列表
roles map[string]RoleDef 角色定义(gen-authz 用)
RoleDef
字段 类型 必填 说明
display_name string 展示名
profiles []string 关联证书 profile
ous []string 可绑定 OU(→ ou_mapping)
grants []string ✅ 授权能力列表(支持通配,如 ca:*)
CapabilityEntry
字段 类型 必填 说明
id string ✅ 能力 ID(domain:action,如 cert:issue)
description string ✅ 能力描述
parameters map 参数定义(默认值→authz capability_parameters)
ParameterDef
字段 类型 说明
type string 参数类型(int/string/bool/list)
description string 参数描述
default any 默认值
min any 最小值
max any 最大值
enum []string 枚举值
required bool 是否必填

在 AIC 中使用

// Agent 声明能力
capabilities := []pki.Capability{
    {SchemeId: "varwof/core", CapabilityId: "cert:issue"},
    {SchemeId: "varwof/gateway", CapabilityId: "proxy:http"},
    {SchemeId: "varwof/constraint-v1", CapabilityId: "time:window:0900-1800"},
}

// 网关验证
reg, _ := register.NewRegistryWithEmbedded()
for _, cap := range capabilities {
    full := cap.SchemeId + ":" + cap.CapabilityId
    if _, _, err := reg.ValidateCapability(full); err != nil {
        // 拒绝:未注册的能力
    }
}

Documentation

Overview

Package register provides scheme registration and authorization generation for the varwof project.

Index

Constants

This section is empty.

Variables

View Source
var Version = "0.1.0"

Version is the package version, set via -ldflags -X github.com/varwof/register.Version=x.y.z.

Functions

func Deduplicate

func Deduplicate(caps []string) []string

Deduplicate removes duplicate capabilities from a list.

func FilterByScheme

func FilterByScheme(caps []string, schemeID string) []string

FilterByScheme returns only capabilities belonging to a specific scheme.

func FormatCapability

func FormatCapability(schemeID, capID string) string

FormatCapability formats a capability as "vendor/product:capability_id".

func FormatSchemeID

func FormatSchemeID(vendor, product string) string

FormatSchemeID formats vendor and product into "vendor/product".

func GenAuthzToFile

func GenAuthzToFile(cfg GenAuthzConfig, outputPath string) error

GenAuthzToFile generates and writes the authz.json file.

func GenDocs

func GenDocs(def *SchemeDefinition) (string, error)

GenDocs generates a markdown permission documentation from a capability.json scheme. The documentation targets both human readers and AI models: fully describing each capability's semantics, parameter constraints, wildcard rules, role and grants mappings, serving as the authoritative reference for AI to generate minimal privilege capability sets.

Output markdown structure:

  • Product overview + capability catalog table
  • Detailed capability semantics (summary/usage/when_not/examples/parameters/related)
  • Wildcard and matching rules
  • Role and grants mapping
  • Least privilege principle guidelines

func GenDocsToFile

func GenDocsToFile(def *SchemeDefinition, outputPath string) error

GenDocsToFile generates markdown permission documentation and writes it to a file.

func GetSignerCert

func GetSignerCert(p7sPath string) (*x509.Certificate, error)

GetSignerCert extracts the signer certificate from a .p7s file.

func HasSignature

func HasSignature(capPath string) bool

HasSignature checks if a .p7s file exists for the given capability file.

func ListCapabilities

func ListCapabilities(def *SchemeDefinition) []string

ListCapabilities returns all capability IDs for a scheme, sorted.

func LoadAllSchemes

func LoadAllSchemes(root string) (map[string]*SchemeDefinition, error)

LoadAllSchemes loads all capability JSON files under a directory tree. Expected structure: root/vendor/product/v*.json

func LoadCertFile

func LoadCertFile(path string) ([]*x509.Certificate, error)

LoadCertFile reads all certificates in a certificate chain from a PEM file.

func LoadEmbedded

func LoadEmbedded() (map[string]*SchemeDefinition, error)

LoadEmbedded is removed: capability data now lives in the separate capability module and is loaded from a directory on disk. Use LoadFromDir or LoadFromBoth with a path into the capability data tree.

func LoadFromBoth

func LoadFromBoth(diskDir string) (map[string]*SchemeDefinition, error)

LoadFromBoth requires a non-empty disk directory. Embedded schemes are gone; disk is the only source. An empty dir returns an error.

func LoadFromDir

func LoadFromDir(root string) (map[string]*SchemeDefinition, error)

LoadFromDir loads all capability JSON files from a directory tree on disk. Expected structure: root/vendor/product/v*.json

func LoadFromFS

func LoadFromFS(fsys fs.FS) (map[string]*SchemeDefinition, error)

LoadFromFS loads all capability JSON files from an embedded filesystem.

func LoadTrustRoots

func LoadTrustRoots(path string) ([]*x509.Certificate, error)

LoadTrustRoots loads PEM certificates from a file or directory.

func MatchCapability

func MatchCapability(id, pattern string) bool

MatchCapability checks if a capability id matches a pattern (glob semantics). Supports: exact match, *, ?, a:b:* prefix wildcards. Same semantics as pki-types MatchCapability.

func ParseCapability

func ParseCapability(s string) (schemeID, capID string, ok bool)

ParseCapability parses "vendor/product:capability_id" into scheme and capID. capability_id may itself contain colons (e.g., "query:users").

func ParseSchemeID

func ParseSchemeID(schemeID string) (vendor, product string, ok bool)

ParseSchemeID parses "vendor/product" into vendor and product.

func SignCapability

func SignCapability(certPath, keyPath, capPath, outputPath string) error

SignCapability signs a capability JSON file using PKCS#7 detached signature. certPath: PEM certificate chain (signer cert + intermediates) keyPath: PEM private key capPath: path to capability.json outputPath: path to write .p7s file (defaults to capPath + ".p7s")

func ValidateSchemeID

func ValidateSchemeID(schemeID string) error

ValidateSchemeID checks if scheme_id follows the naming convention. Public: vendor/product (e.g., oracle/mysql, varwof/core) Private: x-vendor/product (e.g., x-acme/order)

func VerifyCapabilityPKCS7

func VerifyCapabilityPKCS7(capPath string, trustRoots []*x509.Certificate) error

VerifyCapabilityPKCS7 verifies a capability JSON against its .p7s signature. trustRoots: PEM root/intermediate certificates for chain verification.

func WriteScheme

func WriteScheme(def *SchemeDefinition, path string) error

WriteScheme serializes a scheme definition as JSON and writes it to a file (for gen-authz tests/rewrites).

Types

type AuthzDocument

type AuthzDocument struct {
	Version              string                    `json:"version"`
	Roles                map[string]AuthzRoleDef   `json:"roles"`
	OUMapping            map[string]string         `json:"ou_mapping"`
	GatewayNamespaces    map[string]GatewayNSDef   `json:"gateway_namespaces,omitempty"`
	CapabilityParameters map[string]map[string]any `json:"capability_parameters,omitempty"`
}

AuthzDocument is the complete authz.json document generated by gen-authz. The top-level structure is compatible with core/auth.Policy; capability_parameters is an extension field (core's encoding/json deserialization ignores unknown fields).

func GenAuthz

func GenAuthz(cfg GenAuthzConfig) (*AuthzDocument, error)

GenAuthz generates an authz.json document from capability.json schemes.

Mapping rules:

  • Roles from the primary scheme (first) become authz.json roles (grants preserved as-is)
  • Each role's OUs are expanded into ou_mapping (OU → role name)
  • Role names with namespace prefixes (e.g. gateway:admin) are aggregated into gateway_namespaces
  • Capability parameter defaults from all schemes are aggregated into capability_parameters

type AuthzRoleDef

type AuthzRoleDef struct {
	DisplayName string   `json:"display_name"`
	Profiles    []string `json:"profiles"`
	Grants      []string `json:"grants"`
	Scope       []string `json:"scope,omitempty"`
}

AuthzRoleDef is a role entry for generating authz.json (compatible with core Policy.RoleDef).

type CapabilityClaim

type CapabilityClaim struct {
	SchemeID   string         `json:"scheme_id"`  // vendor/product
	Capability string         `json:"capability"` // capability_id (may contain wildcards)
	Parameters map[string]any `json:"parameters,omitempty"`
	Rationale  string         `json:"rationale,omitempty"` // Authorization rationale from AI
}

CapabilityClaim is a single AI-generated capability claim (pending validation/minimal privilege detection).

func ParseCapabilityClaims

func ParseCapabilityClaims(data []byte) ([]CapabilityClaim, error)

ParseCapabilityClaims parses a list of capability claims from JSON data. Expected structure: [{"scheme_id":"varwof/core","capability":"cert:issue",...}]

type CapabilityEntry

type CapabilityEntry struct {
	ID          string                  `json:"id"`
	Description string                  `json:"description"`
	Parameters  map[string]ParameterDef `json:"parameters,omitempty"`
	// ParamsSchema carries a JSON Schema document for structured,
	// nested capability parameters (e.g. database tables/columns/
	// row_filter). Additive: schemes using only the flat ParameterDef
	// model leave it unset.
	ParamsSchema json.RawMessage `json:"params_schema,omitempty"`
	// AI-friendly semantic description fields (used by gen-docs to generate markdown permission docs).
	// These fields help LLMs understand the exact purpose of each capability,
	// enabling them to generate minimal privilege capability sets per task.
	Summary  string   `json:"summary,omitempty"`  // One-line summary (defaults to Description)
	Usage    string   `json:"usage,omitempty"`    // When this capability is needed (typical scenarios)
	WhenNot  string   `json:"when_not,omitempty"` // When this capability should NOT be granted (avoid over-provisioning)
	Examples []string `json:"examples,omitempty"` // Typical usage examples
	Related  []string `json:"related,omitempty"`  // Related capability IDs (collaboration/alternative relationships)
}

CapabilityEntry defines a single capability within a scheme.

type ClaimResult

type ClaimResult struct {
	Claim CapabilityClaim
	Valid bool
	Error string // Reason when Valid=false
}

ClaimResult is the validation result for a single claim.

type GatewayNSDef

type GatewayNSDef struct {
	DisplayName string   `json:"display_name"`
	Prefix      string   `json:"prefix"`
	Grants      []string `json:"grants"`
}

GatewayNSDef is a gateway namespace entry for generating authz.json.

type GenAuthzConfig

type GenAuthzConfig struct {
	// SchemePaths is the list of capability.json file paths to merge.
	// The primary scheme (providing roles) must be the first; other schemes only contribute capability catalogs.
	SchemePaths []string
	// When VerifySignature is true, enforce signature verification if .p7s exists; fail on error.
	// Files without .p7s only error when VerifyRequired is true.
	VerifySignature bool
	// When VerifyRequired is true, capability files missing .p7s signature fail immediately.
	VerifyRequired bool
	// TrustRootsPEM is the trust root certificates for signature verification (PEM file paths).
	TrustRootsPEM []string
	// Version is the generated authz.json version field (default "v2").
	Version string
	// NamespacePrefix is appended to role names to generate gateway namespace prefix role grants,
	// e.g. "gateway" → gateway_namespaces["gateway:"].
	// By default, extracts the "gateway:xxx" prefix from all Roles in the primary scheme.
	NamespacePrefix string
}

GenAuthzConfig is the input configuration for GenAuthz.

type MinSetReport

type MinSetReport struct {
	// ValidClaims are valid and non-redundant claims.
	ValidClaims []CapabilityClaim
	// InvalidClaims are invalid claims (illegal capability/illegal parameters/unknown scheme).
	InvalidClaims []ClaimResult
	// RedundantClaims are claims covered by a wildcard or duplicated (recommended to remove).
	RedundantClaims []ClaimResult
	// MissingGranted are capabilities that are claimed but not covered by any role grant
	// (the AI-generated set references a capability not authorized for this identity).
	MissingGranted []string
	// AllowedPatterns are the grants actually held by the identity (wildcards expanded).
	AllowedPatterns []string
	// IsMinimal is true when the set is already minimal privilege.
	IsMinimal bool
}

MinSetReport is the complete report for minimal privilege validation.

type ParameterDef

type ParameterDef struct {
	Type        string      `json:"type"`
	Description string      `json:"description,omitempty"`
	Default     interface{} `json:"default,omitempty"`
	Min         interface{} `json:"min,omitempty"`
	Max         interface{} `json:"max,omitempty"`
	Enum        []string    `json:"enum,omitempty"`
	Required    bool        `json:"required,omitempty"`
}

ParameterDef defines a parameter for a capability.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry holds all loaded scheme definitions.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty registry.

func NewRegistryFromBoth

func NewRegistryFromBoth(diskDir string) (*Registry, error)

NewRegistryFromBoth requires a non-empty disk directory and creates a registry pre-loaded from it.

func NewRegistryFromDisk

func NewRegistryFromDisk(dir string) (*Registry, error)

NewRegistryFromDisk creates a registry pre-loaded with schemes from a directory into the capability data tree.

func NewRegistryWithEmbedded

func NewRegistryWithEmbedded() (*Registry, error)

NewRegistryWithEmbedded is removed. Use NewRegistryFromDisk instead.

func (*Registry) CheckIntersection

func (r *Registry) CheckIntersection(setA, setB []string) (common []string)

CheckIntersection returns capabilities present in both sets.

func (*Registry) CheckMinimalCapabilitySet

func (r *Registry) CheckMinimalCapabilitySet(claims []CapabilityClaim, grantedPatterns []string) *MinSetReport

CheckMinimalCapabilitySet performs minimal privilege validation:

  1. Validate each claim's legality (scheme/capability/parameters)
  2. Detect redundancy: covered by another wildcard claim, or completely duplicated
  3. Detect over-privilege: claimed capabilities not within the identity's granted authorization scope
  4. Determine whether minimal privilege has been achieved

grantedPatterns are the grants actually held by the identity (e.g. role grants, may contain wildcards). Pass nil to skip over-privilege checking (only check legality and redundancy).

func (*Registry) CheckSubset

func (r *Registry) CheckSubset(declared, allowed []string) (denied []string)

CheckSubset checks if declared capabilities are a subset of allowed capabilities. Returns denied capabilities that are not in the allowed set.

func (*Registry) Get

func (r *Registry) Get(schemeID string) (*SchemeDefinition, bool)

Get returns a scheme definition by scheme_id.

func (*Registry) Has

func (r *Registry) Has(schemeID string) bool

Has checks if a scheme_id is registered.

func (*Registry) HasCapability

func (r *Registry) HasCapability(schemeID, capID string) bool

HasCapability checks if a specific capability is registered.

func (*Registry) Register

func (r *Registry) Register(def *SchemeDefinition)

Register adds a scheme definition. Overwrites if scheme_id already exists.

func (*Registry) RoleGrantCovered

func (r *Registry) RoleGrantCovered(schemeID, grant string) bool

RoleGrantCovered checks if a single grant is covered by the scheme's capabilities (wildcard expanded).

func (*Registry) SchemeIDs

func (r *Registry) SchemeIDs() []string

SchemeIDs returns all registered scheme_ids, sorted.

func (*Registry) Summary

func (r *Registry) Summary() string

Summary returns a human-readable summary of all registered schemes.

func (*Registry) ValidateCapabilities

func (r *Registry) ValidateCapabilities(caps []string) *ValidationResult

ValidateCapabilities validates a list of "scheme:cap_id" strings against the registry.

func (*Registry) ValidateCapability

func (r *Registry) ValidateCapability(formatted string) (*SchemeDefinition, *CapabilityEntry, error)

ValidateCapability checks if "scheme:cap_id" is valid and returns the entry.

func (*Registry) ValidateClaims

func (r *Registry) ValidateClaims(claims []CapabilityClaim) []ClaimResult

ValidateClaims validates capability claims: scheme exists, capability is legal (supports wildcards). Returns the result for each claim. Does not include minimal privilege detection.

func (*Registry) ValidateRoles

func (r *Registry) ValidateRoles(schemeID string) ([]string, error)

ValidateRoles validates that all role grants in a scheme are covered by capabilities. Returns uncovered grants (wildcards expanded against capabilities for validation). Use case: ensure role grants are all legal capabilities before gen-authz generates authz.json.

type RoleDef

type RoleDef struct {
	DisplayName string   `json:"display_name,omitempty"`
	Profiles    []string `json:"profiles,omitempty"`
	Grants      []string `json:"grants"`
	// OUs is the list of certificate OrganizationalUnits this role can be bound to.
	// When generating authz.json, written into ou_mapping; if left empty, no OU mapping entry is generated.
	OUs []string `json:"ous,omitempty"`
}

RoleDef defines a role within a product (used to generate authz.json). grants is a list of capability_id values (e.g. "ca:list", "cert:*"), supports wildcards (* / a:b:*); during expansion validation, all must fall within Capabilities.

type SchemeDefinition

type SchemeDefinition struct {
	SchemeID     string            `json:"scheme_id"`
	Name         string            `json:"name"`
	Version      string            `json:"version"`
	Description  string            `json:"description"`
	Vendor       string            `json:"vendor"`
	Product      string            `json:"product"`
	Author       string            `json:"author,omitempty"`
	License      string            `json:"license,omitempty"`
	Homepage     string            `json:"homepage,omitempty"`
	Capabilities []CapabilityEntry `json:"capabilities"`
	// Roles defines roles within this product (grants reference capability_id from this scheme).
	// Used by gen-authz tool when generating authz.json; can be empty (pure capability catalog products).
	Roles map[string]RoleDef `json:"roles,omitempty"`
}

SchemeDefinition defines all capabilities for a product.

func LoadScheme

func LoadScheme(path string) (*SchemeDefinition, error)

LoadScheme reads a capability JSON file and returns the definition.

func (*SchemeDefinition) ValidateSchemeRoles

func (def *SchemeDefinition) ValidateSchemeRoles() ([]error, []string)

ValidateSchemeRoles validates the consistency of role definitions within a scheme:

  • Role names are non-empty
  • Role grants are non-empty
  • Non-wildcard grants must be covered by capabilities (strict error)
  • Wildcard grants not covered locally are treated as cross-scheme namespace authorization (e.g. core role referencing gateway:*), returning a warning

Returns (errors, warnings).

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError describes a single validation failure.

func (ValidationError) Error

func (e ValidationError) Error() string

type ValidationResult

type ValidationResult struct {
	Valid    bool
	Errors   []ValidationError
	Warnings []string
	Checked  int
}

ValidationResult holds the outcome of validating a set of capabilities.

Directories

Path Synopsis
cmd
gen-authz command
gen-capability command
gen-docs command
sign command
verify command
rule-exec command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL