sdk-ci / test (push) Failing after 8s
- 自主仓 git.wxccs.org/EntitleForge/EntitleForge 拆分(协议实现单一归属: license/crypto/ulid 随 SDK 迁出,服务端反向依赖本仓) - sdk:Client 三模式(文件/远程/代理)、GRACE 状态机、查询 API(6.6ns/0 alloc) - license:三段式编解码与严格解析;crypto:Ed25519 信任链 + Proxy 受约束证书 - 零第三方依赖(CI 有依赖闭包断言红线);go.mod 零 require - CI:Gitea Actions(test + 零依赖断言 + 三平台交叉编译冒烟)
297 lines
8.6 KiB
Go
297 lines
8.6 KiB
Go
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"
|
||
)
|
||
|
||
// rootKid 是 root 签 trust bundle 时 header.kid 的固定值
|
||
// (root 唯一,不需要轮换标识;装载方以公钥锚定)。
|
||
const rootKid = "root"
|
||
|
||
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{}
|
||
}
|
||
|
||
// 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
|
||
}
|
||
|
||
// SignBundle 把当前 signing 集合与 CRL 打包为 root 签名的 trust bundle token。
|
||
func (tc *TrustChain) SignBundle(rootPriv ed25519.PrivateKey) (string, error) {
|
||
tc.mu.RLock()
|
||
bundle := TrustBundle{V: 1}
|
||
for _, e := range tc.keys {
|
||
if e.info.Status != KeyStatusDestroyed {
|
||
bundle.Signing = append(bundle.Signing, e.info)
|
||
}
|
||
}
|
||
bundle.CRL = tc.RevokedList()
|
||
tc.mu.RUnlock()
|
||
|
||
sortByKid(bundle.Signing)
|
||
payload, err := json.Marshal(bundle)
|
||
if err != nil {
|
||
return "", err
|
||
}
|
||
return SignToken(rootPriv, rootKid, license.TypTrust, payload)
|
||
}
|
||
|
||
// 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]
|
||
}
|
||
}
|
||
}
|