- SDK-01:时钟回拨补偿只做一次(水位线跟随回拨后的时钟),避免 trustedNow 重复膨胀 - SDK-02:代理请求显式传 proxyAddr,消除运行期改写共享 opts 的数据竞争 - SDK-03:Decode 增加 256KB 结构层上限(与服务端 license 字节流上限对齐) - SDK-04:修正 license key 熵注释为 80bit - SDK-05:兼容服务端 version=0 空 CRL(携带吊销条目仍拒绝) - SDK-06:Validate 状态显式枚举,UNKNOWN/空值给出明确 fail-closed 错误 - SDK-08:缓存密钥混合 0600 随机 secret(旧 HKDF(指纹) 缓存读取后自动迁移) - SDK-07:README 记录 proxycert/Proxy 公钥旁路分发的设计信任假设 - 新增对应回归测试,go test -race -shuffle=on 全绿
401 lines
12 KiB
Go
401 lines
12 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"
|
||
)
|
||
|
||
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)
|
||
}
|
||
// version=0 表示服务端尚无任何硬吊销(此时 revoked 必须为空),
|
||
// 与 GET /v1/crl 的初始响应兼容(SDK-05);version<0 或 0 版本携带条目均非法。
|
||
if p.V != 1 || p.Version < 0 || (p.Version == 0 && len(p.Revoked) > 0) {
|
||
return 0, false, fmt.Errorf("%w: crl 版本字段非法(v=%d version=%d revoked=%d)",
|
||
license.ErrMalformed, p.V, p.Version, len(p.Revoked))
|
||
}
|
||
|
||
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]
|
||
}
|
||
}
|
||
}
|