Files
EntitleForge-SDK-go/crypto/trust.go
T
iceking2nd fc4ef4e644
sdk-ci / test (push) Successful in 2m19s
sdk-release / release (push) Failing after 50s
sdk-release / cleanup (push) Successful in 5s
refactor(crypto): 拆分签发与验证,新增 sign 包
- crypto 仅保留验证:验签、信任链、CRL/verdict、指纹
- 新增 sign 包:SignToken/SignBundle、密钥生成、私钥加解密
- TrustChain 移除 SignBundle 方法,改由 Bundle() 导出快照,
  避免反射可达性把 SignToken 链入纯验证二进制
- Bundle 快照单次读锁,修复旧 SignBundle 递归读锁死锁窗口
- 新增 golden token 与 go tool nm 符号级回归测试
2026-11-15 13:26:50 +08:00

398 lines
12 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 crypto
import (
"crypto/ed25519"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"sync"
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
)
// KeyStatus 是签名密钥状态机(docs/design/04-crypto.md §1.2):
// pending → active → retired → destroyed。
const (
KeyStatusPending = "pending"
KeyStatusActive = "active"
KeyStatusRetired = "retired"
KeyStatusDestroyed = "destroyed"
)
var (
// ErrUnknownKey 表示 kid 不在信任链中。
ErrUnknownKey = errors.New("crypto: kid 不在信任链中")
// ErrBadSignature 表示验签失败。
ErrBadSignature = errors.New("crypto: 签名验证失败")
// ErrRevoked 表示 license 被 CRL 命中(硬吊销)。
ErrRevoked = errors.New("crypto: license 已被吊销")
)
// SigningKeyInfo 是 trust bundle 中签名公钥的元数据。
type SigningKeyInfo struct {
Kid string `json:"kid"`
Pub string `json:"key"` // base64url(Ed25519 公钥)
Status string `json:"status"` // active | retired
NotAfter int64 `json:"not_after"` // retired 时可填,0=不限
}
// TrustBundle 是信任链的分发载荷(docs/design/03-license-format.md §6),
// 整体由 root 签名(typ=trust 三段式)。
type TrustBundle struct {
V int `json:"v"`
Signing []SigningKeyInfo `json:"signing"`
CRL []string `json:"crl,omitempty"`
}
type signingEntry struct {
info SigningKeyInfo
pub ed25519.PublicKey
}
// proxyEntry 是受约束的 Proxy Key 信任项(root 签名证书装载)。
type proxyEntry struct {
pub ed25519.PublicKey
cluster string
maxEnt map[string]license.Entitlement
notAfter int64
}
// TrustChain 是验证方的信任根集合:root 公钥 + signing 公钥(按 kid)+
// 受约束 Proxy Key(按 kid)+ 本地 CRL。并发安全:读多写少,RWMutex 保护。
type TrustChain struct {
mu sync.RWMutex
root ed25519.PublicKey
keys map[string]signingEntry
proxies map[string]proxyEntry
revoked map[string]struct{}
crlVersion int64
}
// NewTrustChain 以 root 公钥为锚点创建空信任链。
func NewTrustChain(root ed25519.PublicKey) *TrustChain {
return &TrustChain{
root: root,
keys: make(map[string]signingEntry),
proxies: make(map[string]proxyEntry),
revoked: make(map[string]struct{}),
}
}
// AddSigningKey 登记一把签名公钥;重复 kid 报错。
func (tc *TrustChain) AddSigningKey(kid string, pub ed25519.PublicKey, status string, notAfter int64) error {
if kid == "" {
return fmt.Errorf("crypto: kid 不能为空")
}
if len(pub) != ed25519.PublicKeySize {
return fmt.Errorf("crypto: 公钥长度 %d 非法", len(pub))
}
tc.mu.Lock()
defer tc.mu.Unlock()
if _, dup := tc.keys[kid]; dup {
return fmt.Errorf("crypto: kid %q 已存在", kid)
}
tc.keys[kid] = signingEntry{
info: SigningKeyInfo{Kid: kid, Pub: base64.RawURLEncoding.EncodeToString(pub), Status: status, NotAfter: notAfter},
pub: pub,
}
return nil
}
// SetKeyStatus 更新密钥状态(轮换流程使用)。
func (tc *TrustChain) SetKeyStatus(kid, status string) error {
tc.mu.Lock()
defer tc.mu.Unlock()
e, ok := tc.keys[kid]
if !ok {
return fmt.Errorf("crypto: kid %q 不存在", kid)
}
e.info.Status = status
tc.keys[kid] = e
return nil
}
// KeyFor 按 kid 查找公钥。retired 公钥同样命中(存量 license 验证依赖),
// destroyed 由装载方在 bundle 阶段排除。
func (tc *TrustChain) KeyFor(kid string) (ed25519.PublicKey, bool) {
tc.mu.RLock()
defer tc.mu.RUnlock()
e, ok := tc.keys[kid]
if !ok || e.info.Status == KeyStatusDestroyed {
return nil, false
}
return e.pub, true
}
// AddProxyKey 装载受约束的 Proxy Key:校验证书 root 签名、结构与有效期后
// 登记其授权上限(docs/design/08-k8s-proxy.md §3 实现注记)。
// 证书 payload:{v, kid, scope:"proxy", cluster, max_ent, exp};公钥经受控
// 渠道随证书分发(cert.kid 必须与 pub 匹配由签发仪式保证)。
func (tc *TrustChain) AddProxyKey(certToken string, pub ed25519.PublicKey, now int64) error {
h, payload, sig, err := license.Decode(certToken)
if err != nil {
return err
}
if h.Typ != license.TypProxyCert {
return fmt.Errorf("crypto: typ %q 非 proxycert", h.Typ)
}
content, err := license.SignedContent(certToken)
if err != nil {
return err
}
tc.mu.RLock()
root := tc.root
tc.mu.RUnlock()
if len(root) == 0 || !ed25519.Verify(root, []byte(content), sig) {
return fmt.Errorf("crypto: proxycert 验签失败(非本 root 签发)")
}
var cert struct {
V int `json:"v"`
Kid string `json:"kid"`
Scope string `json:"scope"`
Cluster string `json:"cluster"`
MaxEnt map[string]license.Entitlement `json:"max_ent"`
EXP int64 `json:"exp"`
}
if err := json.Unmarshal(payload, &cert); err != nil {
return fmt.Errorf("crypto: proxycert 载荷: %w", err)
}
if cert.V != 1 || cert.Scope != "proxy" || cert.Kid == "" {
return fmt.Errorf("crypto: proxycert 结构非法")
}
if cert.EXP != 0 && cert.EXP <= now {
return fmt.Errorf("crypto: proxycert 已过期")
}
if len(pub) != ed25519.PublicKeySize {
return fmt.Errorf("crypto: proxy 公钥长度非法")
}
tc.mu.Lock()
defer tc.mu.Unlock()
tc.proxies[cert.Kid] = proxyEntry{
pub: pub, cluster: cert.Cluster, maxEnt: cert.MaxEnt, notAfter: cert.EXP,
}
return nil
}
// ProxyKeyFor 按 kid 查找受约束 Proxy Key。
func (tc *TrustChain) ProxyKeyFor(kid string) (ed25519.PublicKey, proxyEntry, bool) {
tc.mu.RLock()
defer tc.mu.RUnlock()
e, ok := tc.proxies[kid]
return e.pub, e, ok
}
// Revoke 将 license jti 加入本地 CRL。
func (tc *TrustChain) Revoke(jti string) error {
if jti == "" {
return fmt.Errorf("crypto: jti 不能为空")
}
tc.mu.Lock()
defer tc.mu.Unlock()
tc.revoked[jti] = struct{}{}
return nil
}
// IsRevoked 判断 jti 是否被本地 CRL 命中。
func (tc *TrustChain) IsRevoked(jti string) bool {
tc.mu.RLock()
defer tc.mu.RUnlock()
_, ok := tc.revoked[jti]
return ok
}
// RevokedList 返回 CRL 的拷贝(排序保证确定性)。
func (tc *TrustChain) RevokedList() []string {
tc.mu.RLock()
defer tc.mu.RUnlock()
out := make([]string, 0, len(tc.revoked))
for jti := range tc.revoked {
out = append(out, jti)
}
sortStrings(out)
return out
}
// CRLPayload 是服务端物化 CRL 的载荷(docs/design/04-crypto.md §4)。
type CRLPayload struct {
V int `json:"v"`
Version int64 `json:"version"`
UpdatedAt int64 `json:"updated_at"`
Revoked []string `json:"revoked"`
}
// LoadCRL 校验并应用服务端下发的 CRL(typ=crl,active signing key 签名)。
// 版本单调:版本号不大于本地已应用版本时忽略(防回滚),返回 applied=false。
// 已吊销条目只增不减——即使新 CRL 遗漏旧条目也不会“复活”。
func (tc *TrustChain) LoadCRL(token string) (version int64, applied bool, err error) {
h, payload, sig, err := license.Decode(token)
if err != nil {
return 0, false, err
}
if h.Typ != license.TypCRL {
return 0, false, fmt.Errorf("%w: typ %q 非 crl", license.ErrUnsupported, h.Typ)
}
pub, ok := tc.KeyFor(h.Kid)
if !ok {
return 0, false, fmt.Errorf("%w: kid %q", ErrUnknownKey, h.Kid)
}
content, err := license.SignedContent(token)
if err != nil {
return 0, false, err
}
if !ed25519.Verify(pub, []byte(content), sig) {
return 0, false, ErrBadSignature
}
var p CRLPayload
if err := json.Unmarshal(payload, &p); err != nil {
return 0, false, fmt.Errorf("%w: crl payload: %v", license.ErrMalformed, err)
}
if p.V != 1 || p.Version <= 0 {
return 0, false, fmt.Errorf("%w: crl 版本字段非法(v=%d version=%d)", license.ErrMalformed, p.V, p.Version)
}
tc.mu.Lock()
defer tc.mu.Unlock()
if p.Version <= tc.crlVersion {
return p.Version, false, nil
}
for _, jti := range p.Revoked {
if jti != "" {
tc.revoked[jti] = struct{}{}
}
}
tc.crlVersion = p.Version
return p.Version, true, nil
}
// CRLVersion 返回本地已应用的最大 CRL 版本(0 = 尚未应用)。
func (tc *TrustChain) CRLVersion() int64 {
tc.mu.RLock()
defer tc.mu.RUnlock()
return tc.crlVersion
}
// Verdict 是在线校验结论(typ=verdict)的载荷。
type Verdict struct {
JTI string `json:"jti"`
State string `json:"state"`
At int64 `json:"at"`
}
// VerdictMaxAgeSeconds 是 verdict 的保鲜窗口:过期结论不得用于放行(防重放)。
const VerdictMaxAgeSeconds int64 = 600
// VerifyVerdict 校验在线校验结论的签名与时效,返回可采信的结论。
func (tc *TrustChain) VerifyVerdict(token string, now int64) (*Verdict, error) {
h, payload, sig, err := license.Decode(token)
if err != nil {
return nil, err
}
if h.Typ != license.TypVerdict {
return nil, fmt.Errorf("%w: typ %q 非 verdict", license.ErrUnsupported, h.Typ)
}
pub, ok := tc.KeyFor(h.Kid)
if !ok {
return nil, fmt.Errorf("%w: kid %q", ErrUnknownKey, h.Kid)
}
content, err := license.SignedContent(token)
if err != nil {
return nil, err
}
if !ed25519.Verify(pub, []byte(content), sig) {
return nil, ErrBadSignature
}
var v Verdict
if err := json.Unmarshal(payload, &v); err != nil {
return nil, fmt.Errorf("%w: verdict payload: %v", license.ErrMalformed, err)
}
if v.JTI == "" || v.State == "" {
return nil, fmt.Errorf("%w: verdict 缺少 jti/state", license.ErrMalformed)
}
if v.At != 0 && now-v.At > VerdictMaxAgeSeconds {
return nil, fmt.Errorf("%w: verdict 已过期(age=%ds)", license.ErrMalformed, now-v.At)
}
return &v, nil
}
// Bundle 返回信任链的分发快照:未销毁的 signing 公钥元数据 + CRL。
// 快照只含公钥数据,不含任何私钥;签发方以 sign.SignBundle 对其签名。
// 单次读锁内完成拷贝与排序,避免持锁期间再次获取读锁。
func (tc *TrustChain) Bundle() TrustBundle {
tc.mu.RLock()
defer tc.mu.RUnlock()
bundle := TrustBundle{V: 1}
for _, e := range tc.keys {
if e.info.Status != KeyStatusDestroyed {
bundle.Signing = append(bundle.Signing, e.info)
}
}
bundle.CRL = make([]string, 0, len(tc.revoked))
for jti := range tc.revoked {
bundle.CRL = append(bundle.CRL, jti)
}
sortStrings(bundle.CRL)
sortByKid(bundle.Signing)
return bundle
}
// LoadBundle 校验 bundle token 的 root 签名后装载信任链。
// expectRoot 为验证方锚定的 root 公钥;bundle 载荷的任何篡改都会验签失败。
func (tc *TrustChain) LoadBundle(token string, expectRoot ed25519.PublicKey) error {
h, payload, sig, err := license.Decode(token)
if err != nil {
return err
}
if h.Typ != license.TypTrust {
return fmt.Errorf("%w: typ %q 非 trust", license.ErrUnsupported, h.Typ)
}
content, err := license.SignedContent(token)
if err != nil {
return err
}
if !ed25519.Verify(expectRoot, []byte(content), sig) {
return ErrBadSignature
}
var bundle TrustBundle
if err := json.Unmarshal(payload, &bundle); err != nil {
return fmt.Errorf("%w: bundle payload: %v", license.ErrMalformed, err)
}
if bundle.V != 1 {
return fmt.Errorf("%w: bundle 版本 %d", license.ErrUnsupported, bundle.V)
}
tc.mu.Lock()
defer tc.mu.Unlock()
for _, info := range bundle.Signing {
pub, err := base64.RawURLEncoding.DecodeString(info.Pub)
if err != nil || len(pub) != ed25519.PublicKeySize {
return fmt.Errorf("%w: kid %q 公钥非法", license.ErrMalformed, info.Kid)
}
tc.keys[info.Kid] = signingEntry{info: info, pub: pub}
}
for _, jti := range bundle.CRL {
tc.revoked[jti] = struct{}{}
}
return nil
}
func sortStrings(s []string) {
for i := 1; i < len(s); i++ {
for j := i; j > 0 && s[j] < s[j-1]; j-- {
s[j], s[j-1] = s[j-1], s[j]
}
}
}
func sortByKid(keys []SigningKeyInfo) {
for i := 1; i < len(keys); i++ {
for j := i; j > 0 && keys[j].Kid < keys[j-1].Kid; j-- {
keys[j], keys[j-1] = keys[j-1], keys[j]
}
}
}