feat: 益铸 EntitleForge SDK 独立仓库首个版本
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 + 零依赖断言 + 三平台交叉编译冒烟)
This commit is contained in:
iceking2nd committed 2026-11-09 15:42:22 +08:00
commit 81c7295893
32 files changed
+3940

No files matched your search

+19
View File
@@ -0,0 +1,19 @@
package crypto
import (
"crypto/sha256"
"encoding/hex"
"slices"
"strings"
)
// Fingerprint 计算机器指纹摘要(docs/design/04-crypto.md §5)。
//
// 输入为原始采集字段;输出 "sha256:" + hex,服务端与日志只见摘要。
// 字段排序后拼接保证顺序无关(采集器返回顺序不稳定)。
func Fingerprint(fields ...string) string {
sorted := slices.Clone(fields)
slices.Sort(sorted)
sum := sha256.Sum256([]byte(strings.Join(sorted, " ")))
return "sha256:" + hex.EncodeToString(sum[:])
}
+42
View File
@@ -0,0 +1,42 @@
// Package crypto 实现 EntitleForge 的密钥体系:签名/验签、信任链、
// 私钥加密存储与机器指纹。设计依据:docs/design/04-crypto.md。
//
// 安全约定:全部使用 Go 标准库,禁止引入第三方密码学依赖。
package crypto
import (
"crypto/ed25519"
"crypto/rand"
"encoding/hex"
)
// KeyPair 是一对 Ed25519 密钥。Signing Key 携带 kid;Root Key 的 kid 为空
// (root 不签发 license,只签 trust bundle)。
type KeyPair struct {
Kid string
Pub ed25519.PublicKey
Priv ed25519.PrivateKey
}
// GenerateSigningKey 生成签发密钥。kid 为私钥随机 8 字节的 hex(16 字符),
// 不派生自公钥(防指纹追踪,docs/design/04-crypto.md §1.2)。
func GenerateSigningKey() (*KeyPair, error) {
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
var kidRaw [8]byte
if _, err := rand.Read(kidRaw[:]); err != nil {
return nil, err
}
return &KeyPair{Kid: hex.EncodeToString(kidRaw[:]), Pub: pub, Priv: priv}, nil
}
// GenerateRootKey 生成根密钥(离线保管,只用于签 trust bundle)。
func GenerateRootKey() (*KeyPair, error) {
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
return &KeyPair{Pub: pub, Priv: priv}, nil
}
+97
View File
@@ -0,0 +1,97 @@
package crypto
import (
"bytes"
"strings"
"testing"
)
func TestGenerateKey(t *testing.T) {
kp, err := GenerateSigningKey()
if err != nil {
t.Fatalf("GenerateSigningKey: %v", err)
}
if len(kp.Priv) != 64 || len(kp.Pub) != 32 {
t.Fatalf("Ed25519 密钥长度错误: priv=%d pub=%d", len(kp.Priv), len(kp.Pub))
}
// kid 为 8 字节随机数的 hex(16 字符),且不派生自公钥(两次生成不同)
if len(kp.Kid) != 16 {
t.Errorf("kid 长度 %d != 16", len(kp.Kid))
}
if !isHex(kp.Kid) {
t.Errorf("kid 应为 hex: %q", kp.Kid)
}
kp2, _ := GenerateSigningKey()
if kp.Kid == kp2.Kid {
t.Error("两次生成的 kid 不应相同")
}
}
func TestGenerateRootKey(t *testing.T) {
kp, err := GenerateRootKey()
if err != nil {
t.Fatalf("GenerateRootKey: %v", err)
}
if kp.Kid != "" {
t.Errorf("root key 不需要 kid, got %q", kp.Kid)
}
}
func TestKeyFile_RoundTrip(t *testing.T) {
kp, _ := GenerateSigningKey()
data, err := EncryptPrivateKey(kp.Priv, "correct-horse")
if err != nil {
t.Fatalf("EncryptPrivateKey: %v", err)
}
if bytes.Contains(data, []byte("correct-horse")) {
t.Error("密文不应包含口令明文")
}
got, err := DecryptPrivateKey(data, "correct-horse")
if err != nil {
t.Fatalf("DecryptPrivateKey: %v", err)
}
if !bytes.Equal(got, kp.Priv) {
t.Error("私钥往返不一致")
}
}
func TestKeyFile_WrongPassphrase(t *testing.T) {
kp, _ := GenerateSigningKey()
data, _ := EncryptPrivateKey(kp.Priv, "right")
if _, err := DecryptPrivateKey(data, "wrong"); err == nil {
t.Error("错误口令应解密失败")
}
}
func TestKeyFile_TamperedData(t *testing.T) {
kp, _ := GenerateSigningKey()
data, _ := EncryptPrivateKey(kp.Priv, "pass")
cases := []struct {
name string
mut func([]byte) []byte
}{
{"坏 magic", func(b []byte) []byte { b[0] = 'X'; return b }},
{"截断", func(b []byte) []byte { return b[:len(b)-4] }},
{"翻转密文字节", func(b []byte) []byte { b[len(b)-1] ^= 0xFF; return b }},
{"空数据", func(b []byte) []byte { return nil }},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if _, err := DecryptPrivateKey(tc.mut(data), "pass"); err == nil {
t.Error("应解密失败")
}
})
}
}
func isHex(s string) bool {
for _, c := range s {
if !strings.ContainsRune("0123456789abcdef", c) {
return false
}
}
return len(s) > 0
}
+101
View File
@@ -0,0 +1,101 @@
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/ed25519"
"crypto/hkdf"
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
)
// 私钥文件格式(docs/design/04-crypto.md §2):
//
// "EFKEY1" || salt(32) || nonce(12) || AES-256-GCM(priv)
//
// AEAD 密钥由口令经 HKDF-SHA256 派生,口令本身不落盘。
const (
keyFileMagic = "EFKEY1"
keyFileSaltLen = 32
keyFileNonceSz = 12
keyFileKeyLen = 32
)
// ErrBadKeyFile 表示私钥文件损坏或口令错误。
var ErrBadKeyFile = errors.New("crypto: 私钥文件损坏或口令错误")
func deriveKey(passphrase string, salt []byte) ([]byte, error) {
return hkdf.Key(sha256.New, []byte(passphrase), salt, "entitleforge-private-key", keyFileKeyLen)
}
// EncryptPrivateKey 用口令加密私钥,产出可直接落盘(0600)的字节。
func EncryptPrivateKey(priv ed25519.PrivateKey, passphrase string) ([]byte, error) {
if len(passphrase) == 0 {
return nil, fmt.Errorf("crypto: 口令不能为空")
}
salt := make([]byte, keyFileSaltLen)
if _, err := rand.Read(salt); err != nil {
return nil, err
}
key, err := deriveKey(passphrase, salt)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aead, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, keyFileNonceSz)
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
out := make([]byte, 0, len(keyFileMagic)+keyFileSaltLen+keyFileNonceSz+len(priv)+aead.Overhead())
out = append(out, keyFileMagic...)
out = append(out, salt...)
out = append(out, nonce...)
return aead.Seal(out, nonce, priv, nil), nil
}
// DecryptPrivateKey 解密 EncryptPrivateKey 产出的数据。
func DecryptPrivateKey(data []byte, passphrase string) (ed25519.PrivateKey, error) {
fail := func() (ed25519.PrivateKey, error) {
return nil, ErrBadKeyFile
}
if len(data) < len(keyFileMagic)+keyFileSaltLen+keyFileNonceSz {
return fail()
}
if string(data[:len(keyFileMagic)]) != keyFileMagic {
return fail()
}
salt := data[len(keyFileMagic) : len(keyFileMagic)+keyFileSaltLen]
off := len(keyFileMagic) + keyFileSaltLen
nonce := data[off : off+keyFileNonceSz]
ct := data[off+keyFileNonceSz:]
key, err := deriveKey(passphrase, salt)
if err != nil {
return fail()
}
block, err := aes.NewCipher(key)
if err != nil {
return fail()
}
aead, err := cipher.NewGCM(block)
if err != nil {
return fail()
}
priv, err := aead.Open(nil, nonce, ct, nil)
if err != nil {
return fail()
}
if len(priv) != ed25519.PrivateKeySize {
return fail()
}
return ed25519.PrivateKey(priv), nil
}
+175
View File
@@ -0,0 +1,175 @@
package crypto
import (
"encoding/json"
"strings"
"testing"
"time"
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
)
// proxyFixture 构造 root + signing + proxy 三层密钥与受约束证书。
type proxyFixture struct {
root, signing, proxy *KeyPair
chain *TrustChain // SDK 侧信任链(root + signing + proxy 约束)
cert string // root 签名的 Proxy 受约束证书
}
func newProxyFixture(t *testing.T) *proxyFixture {
t.Helper()
root, _ := GenerateRootKey()
signing, _ := GenerateSigningKey()
proxy, _ := GenerateSigningKey() // Proxy Key 也是 Ed25519 对
// 受约束证书:声明 proxy key 的授权上限(集群 ent 快照)
maxEnt := map[string]license.Entitlement{
"seats": license.Quantity(100),
"tier": license.TierValue("enterprise"),
}
certPayload, _ := json.Marshal(map[string]any{
"v": 1, "kid": proxy.Kid, "scope": "proxy", "cluster": "cluster-demo",
"max_ent": maxEnt, "iat": testNow - 60, "exp": testNow + 86400,
})
// 证书由 root 签名
certToken, err := SignToken(root.Priv, "root", license.TypProxyCert, certPayload)
if err != nil {
t.Fatal(err)
}
chain := NewTrustChain(root.Pub)
if err := chain.AddSigningKey(signing.Kid, signing.Pub, KeyStatusActive, 0); err != nil {
t.Fatal(err)
}
// SDK 装载 proxy 受约束信任(校验证书 root 签名)
if err := chain.AddProxyKey(certToken, proxy.Pub, testNow); err != nil {
t.Fatalf("AddProxyKey: %v", err)
}
return &proxyFixture{root: root, signing: signing, proxy: proxy, chain: chain, cert: certToken}
}
// proxyLease 用 Proxy Key 签 per-workload lease。
func (f *proxyFixture) proxyLease(t *testing.T, mut func(*license.Payload)) string {
t.Helper()
p := validPayload()
p.LT = license.TypeLease
p.ST = license.StateRenewed
p.ACT = "system:serviceaccount:payments:api"
p.EXP = testNow + 600
p.Pol = &license.PolicySnapshot{LeaseTTL: 600, Heartbeat: 300, Grace: 259200}
p.Proxy = &license.ProxyScope{Cluster: "cluster-demo", MaxEnt: map[string]license.Entitlement{
"seats": license.Quantity(100), "tier": license.TierValue("enterprise"),
}}
if mut != nil {
mut(&p)
}
b, _ := json.Marshal(p)
token, err := SignToken(f.proxy.Priv, f.proxy.Kid, license.TypLease, b)
if err != nil {
t.Fatal(err)
}
return token
}
func TestProxyLease_SubsetVerifies(t *testing.T) {
f := newProxyFixture(t)
// 裁剪后的子集授权(seats 20 < 100)
token := f.proxyLease(t, func(p *license.Payload) {
p.Ent = map[string]license.Entitlement{"seats": license.Quantity(20)}
})
got, err := VerifyToken(token, f.chain, testNow)
if err != nil {
t.Fatalf("子集授权应验证通过: %v", err)
}
if got.Ent["seats"].AsInt() != 20 {
t.Errorf("seats: %d", got.Ent["seats"].AsInt())
}
if got.Proxy == nil || got.Proxy.Cluster != "cluster-demo" {
t.Errorf("proxy scope 缺失: %+v", got.Proxy)
}
}
func TestProxyLease_EscalationRejected(t *testing.T) {
f := newProxyFixture(t)
// 攻破 Proxy 后尝试扩权:seats 500 > max 100、新增未授权 feature
cases := []struct {
name string
mut func(*license.Payload)
}{
{"数量越权", func(p *license.Payload) {
p.Ent = map[string]license.Entitlement{"seats": license.Quantity(500)}
}},
{"新增未授权项", func(p *license.Payload) {
p.Ent = map[string]license.Entitlement{"module.secret": license.Bool(true)}
}},
{"档位越权", func(p *license.Payload) {
p.Ent = map[string]license.Entitlement{"tier": license.TierValue("ultimate")}
}},
{"隐匿 scope(绕过约束校验)", func(p *license.Payload) {
p.Proxy = nil
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
token := f.proxyLease(t, func(p *license.Payload) {
tc.mut(p)
// 越权时同步抬高 scope 上限尝试绕过(scope 本身来自证书,此处伪造)
if p.Proxy != nil {
p.Proxy.MaxEnt = map[string]license.Entitlement{
"seats": license.Quantity(5000), "tier": license.TierValue("ultimate"),
"module.secret": license.Bool(true),
}
}
})
if _, err := VerifyToken(token, f.chain, testNow); err == nil {
t.Error("越权 lease 应被拒绝")
}
})
}
}
func TestProxyLease_UnknownKeyRejected(t *testing.T) {
// 未在信任链登记的 proxy key(无证书)签的 lease 拒绝
f := newProxyFixture(t)
rogue, _ := GenerateSigningKey()
p := validPayload()
p.LT = license.TypeLease
p.ST = license.StateRenewed
p.EXP = testNow + 600
p.Proxy = &license.ProxyScope{Cluster: "x", MaxEnt: p.Ent}
b, _ := json.Marshal(p)
token, _ := SignToken(rogue.Priv, rogue.Kid, license.TypLease, b)
if _, err := VerifyToken(token, f.chain, testNow); err == nil {
t.Error("未登记 proxy key 应拒绝")
} else if !strings.Contains(err.Error(), "kid") {
t.Errorf("错误语义: %v", err)
}
}
func TestProxyCert_ForgedRejected(t *testing.T) {
// 伪造证书(非 root 签名)装载失败
root, _ := GenerateRootKey()
attacker, _ := GenerateSigningKey()
chain := NewTrustChain(root.Pub)
certPayload, _ := json.Marshal(map[string]any{
"v": 1, "kid": attacker.Kid, "scope": "proxy", "max_ent": map[string]any{},
})
forged, _ := SignToken(attacker.Priv, "root", license.TypProxyCert, certPayload)
if err := chain.AddProxyKey(forged, attacker.Pub, testNow); err == nil {
t.Error("伪造证书应装载失败")
}
}
func TestProxyCert_Expired(t *testing.T) {
f := newProxyFixture(t)
// 证书过期:用旧时间验证
token := f.proxyLease(t, func(p *license.Payload) {
p.Ent = map[string]license.Entitlement{"seats": license.Quantity(20)}
p.IAT, p.NBF, p.EXP = testNow-7200, testNow-7200, testNow-3600 // lease 自身过期也会拒
})
if _, err := VerifyToken(token, f.chain, testNow); err == nil {
t.Error("过期 lease 应拒绝")
}
}
var _ = time.Now
+145
View File
@@ -0,0 +1,145 @@
package crypto
import (
"crypto/ed25519"
"encoding/json"
"fmt"
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
)
// DefaultClockSkewSeconds 是时间窗校验容忍的时钟偏移(±10 分钟),
// 依据 docs/design/04-crypto.md §6。
const DefaultClockSkewSeconds int64 = 600
// SignToken 以 Ed25519 私钥签发三段式 token。
// typ 决定封装类型(license/lease/trust/crl/bundle),kid 写入 header。
func SignToken(priv ed25519.PrivateKey, kid, typ string, payload []byte) (string, error) {
if len(priv) != ed25519.PrivateKeySize {
return "", fmt.Errorf("crypto: 私钥长度非法")
}
h := license.Header{V: license.FormatVersion, Alg: license.AlgEd25519, Kid: kid, Typ: typ}
return license.Encode(h, payload, func(content string) ([]byte, error) {
return ed25519.Sign(priv, []byte(content)), nil
})
}
// VerifyToken 验证 license / lease token 并返回解析后的载荷。
// 编排顺序(docs/design/03-license-format.md §7):
// 结构解码 → typ 白名单 → 信任链找公钥(signing / 受约束 proxy)→ Ed25519 验签 →
// 严格 payload 解析 → 语义校验 → 本地 CRL → 时间窗 →(proxy 路径)授权上限校验。
func VerifyToken(token string, tc *TrustChain, now int64) (*license.Payload, error) {
h, payload, sig, err := license.Decode(token)
if err != nil {
return nil, err
}
if h.Typ != license.TypLicense && h.Typ != license.TypLease {
return nil, fmt.Errorf("%w: typ %q 不能按 license/lease 验证", license.ErrUnsupported, h.Typ)
}
// proxy 路径优先(kid 命中受约束 Proxy Key)
if pub, entry, ok := tc.ProxyKeyFor(h.Kid); ok {
return verifyProxyLease(token, h, payload, sig, pub, entry, tc, now)
}
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 p license.Payload
if err := json.Unmarshal(payload, &p); err != nil {
return nil, fmt.Errorf("%w: payload: %v", license.ErrMalformed, err)
}
if err := p.Validate(); err != nil {
return nil, err
}
if tc.IsRevoked(p.JTI) {
return nil, ErrRevoked
}
if err := p.TimeValid(now, DefaultClockSkewSeconds); err != nil {
return nil, err
}
return &p, nil
}
// verifyProxyLease 验证 Proxy Key 派发的 per-workload lease:
// 验签 + 常规校验 + 受约束(Proxy scope 必带、ent ⊆ 证书上限、证书未过期、
// 集群一致)。任何越权(数量超限/新增授权/档位抬升/隐匿 scope)拒绝。
func verifyProxyLease(token string, h license.Header, payload, sig []byte,
pub ed25519.PublicKey, entry proxyEntry, tc *TrustChain, now int64) (*license.Payload, error) {
content, err := license.SignedContent(token)
if err != nil {
return nil, err
}
if !ed25519.Verify(pub, []byte(content), sig) {
return nil, ErrBadSignature
}
if entry.notAfter != 0 && entry.notAfter <= now {
return nil, fmt.Errorf("%w: proxycert 已过期", ErrUnknownKey)
}
var p license.Payload
if err := json.Unmarshal(payload, &p); err != nil {
return nil, fmt.Errorf("%w: payload: %v", license.ErrMalformed, err)
}
if err := p.Validate(); err != nil {
return nil, err
}
if tc.IsRevoked(p.JTI) {
return nil, ErrRevoked
}
if err := p.TimeValid(now, DefaultClockSkewSeconds); err != nil {
return nil, err
}
// 受约束校验(docs/design/08-k8s-proxy.md §3:Proxy 被攻破也无法扩权)
if p.Proxy == nil {
return nil, fmt.Errorf("%w: proxy lease 缺少受约束声明", ErrBadSignature)
}
if entry.cluster != "" && p.Proxy.Cluster != entry.cluster {
return nil, fmt.Errorf("%w: proxy cluster 不符", ErrBadSignature)
}
for fid, ent := range p.Ent {
max, ok := entry.maxEnt[fid]
if !ok {
return nil, fmt.Errorf("%w: proxy 越权(授权项 %q 未在证书上限内)", ErrBadSignature, fid)
}
if !withinEntitlement(ent, max) {
return nil, fmt.Errorf("%w: proxy 越权(授权项 %q 超出上限)", ErrBadSignature, fid)
}
}
return &p, nil
}
// withinEntitlement 判断授权值是否不超上限(保守策略):
// q: v ≤ max;b: true 需 max 为 true;t: 必须等于证书档位(档位序在调用方);
// c: 列表必须为上限子集。
func withinEntitlement(v, max license.Entitlement) bool {
switch v.Type {
case license.TypeQuantity:
return max.Type == license.TypeQuantity && v.Int <= max.Int
case license.TypeBool:
return max.Type == license.TypeBool && (!v.Bool || max.Bool)
case license.TypeTier:
return max.Type == license.TypeTier && v.Str == max.Str
case license.TypeConstraint:
if max.Type != license.TypeConstraint {
return false
}
for _, item := range v.List {
if !max.Allows(item) {
return false
}
}
return true
}
return false
}
+212
View File
@@ -0,0 +1,212 @@
package crypto
import (
"crypto/ed25519"
"encoding/base64"
"encoding/json"
"strings"
"testing"
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
)
const testNow = int64(1762665600)
type fixture struct {
priv ed25519.PrivateKey
chain *TrustChain
kid string
}
func newFixture(t *testing.T) *fixture {
t.Helper()
root, err := GenerateRootKey()
if err != nil {
t.Fatalf("GenerateRootKey: %v", err)
}
sk, err := GenerateSigningKey()
if err != nil {
t.Fatalf("GenerateSigningKey: %v", err)
}
chain := NewTrustChain(root.Pub)
if err := chain.AddSigningKey(sk.Kid, sk.Pub, KeyStatusActive, 0); err != nil {
t.Fatalf("AddSigningKey: %v", err)
}
return &fixture{priv: sk.Priv, chain: chain, kid: sk.Kid}
}
func (f *fixture) sign(t *testing.T, p license.Payload) string {
t.Helper()
b, err := json.Marshal(p)
if err != nil {
t.Fatalf("marshal: %v", err)
}
token, err := SignToken(f.priv, f.kid, license.TypLicense, b)
if err != nil {
t.Fatalf("SignToken: %v", err)
}
return token
}
func validPayload() license.Payload {
return license.Payload{
JTI: "01JD8Z9W7S8XB5K2M3N4Q5R6TV",
ISS: "EntitleForge",
TID: "01JD8Y3N2M1K5J7H9G0F2E4D6R",
Prod: "prod_01JD8Y5P4Q3R2S1T0U9V8W7X6",
IAT: testNow - 100,
NBF: testNow - 100,
EXP: testNow + 86400,
LT: license.TypeSubscription,
Ent: map[string]license.Entitlement{"tier": license.TierValue("pro")},
ST: license.StateIssued,
}
}
func TestSignVerify_RoundTrip(t *testing.T) {
f := newFixture(t)
token := f.sign(t, validPayload())
got, err := VerifyToken(token, f.chain, testNow)
if err != nil {
t.Fatalf("VerifyToken: %v", err)
}
if got.JTI != "01JD8Z9W7S8XB5K2M3N4Q5R6TV" {
t.Errorf("jti 还原错误: %q", got.JTI)
}
if !got.Ent["tier"].Equal(license.TierValue("pro")) {
t.Errorf("entitlement 还原错误: %+v", got.Ent["tier"])
}
}
func TestVerify_TamperMatrix(t *testing.T) {
f := newFixture(t)
token := f.sign(t, validPayload())
parts := strings.Split(token, ".")
manglePayload := func() string {
var p license.Payload
b, _ := base64.RawURLEncoding.DecodeString(parts[1])
json.Unmarshal(b, &p)
p.Ent["tier"] = license.TierValue("enterprise") // 越权提档
nb, _ := json.Marshal(p)
return parts[0] + "." + base64.RawURLEncoding.EncodeToString(nb) + "." + parts[2]
}
mangleSig := func() string {
sig, _ := base64.RawURLEncoding.DecodeString(parts[2])
sig[0] ^= 0x01
return parts[0] + "." + parts[1] + "." + base64.RawURLEncoding.EncodeToString(sig)
}
mangleKid := func() string {
b, _ := base64.RawURLEncoding.DecodeString(parts[0])
var h map[string]any
json.Unmarshal(b, &h)
h["kid"] = "ffffffffffffffff"
nb, _ := json.Marshal(h)
return base64.RawURLEncoding.EncodeToString(nb) + "." + parts[1] + "." + parts[2]
}
cases := []struct {
name string
token string
}{
{"篡改 payload(提档)", manglePayload()},
{"篡改签名", mangleSig()},
{"伪造 kid", mangleKid()},
{"空 token", ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if _, err := VerifyToken(tc.token, f.chain, testNow); err == nil {
t.Error("应验签失败")
}
})
}
}
func TestVerify_TimeWindow(t *testing.T) {
f := newFixture(t)
token := f.sign(t, validPayload())
if _, err := VerifyToken(token, f.chain, testNow+86400+601); err != license.ErrExpired {
t.Errorf("过期应返回 ErrExpired, got %v", err)
}
p := validPayload()
p.NBF = testNow + 3600
if _, err := VerifyToken(f.sign(t, p), f.chain, testNow); err != license.ErrNotYetValid {
t.Errorf("未生效应返回 ErrNotYetValid, got %v", err)
}
}
func TestVerify_Revoked(t *testing.T) {
f := newFixture(t)
token := f.sign(t, validPayload())
if err := f.chain.Revoke("01JD8Z9W7S8XB5K2M3N4Q5R6TV"); err != nil {
t.Fatalf("Revoke: %v", err)
}
if _, err := VerifyToken(token, f.chain, testNow); err != ErrRevoked {
t.Errorf("CRL 命中应返回 ErrRevoked, got %v", err)
}
}
func TestVerify_RetiredKeyStillVerifies(t *testing.T) {
// retired 公钥必须持续可验证(docs/design/04-crypto.md §1.2)
f := newFixture(t)
token := f.sign(t, validPayload())
f.chain.SetKeyStatus(f.kid, KeyStatusRetired)
if _, err := VerifyToken(token, f.chain, testNow); err != nil {
t.Errorf("retired key 签发的 license 应仍可验证: %v", err)
}
}
func TestVerify_RejectsNonLicenseTyp(t *testing.T) {
// typ=trust/crl 的 token 不能当 license 验证
f := newFixture(t)
b, _ := json.Marshal(validPayload())
token, err := SignToken(f.priv, f.kid, license.TypTrust, b)
if err != nil {
t.Fatalf("SignToken: %v", err)
}
if _, err := VerifyToken(token, f.chain, testNow); err == nil {
t.Error("typ=trust 不能通过 license 验证")
}
}
func TestVerify_PayloadSemanticError(t *testing.T) {
// 验签通过但 payload 语义非法(缺 jti)应拒绝
f := newFixture(t)
p := validPayload()
p.JTI = ""
b, _ := json.Marshal(p)
token, _ := SignToken(f.priv, f.kid, license.TypLicense, b)
if _, err := VerifyToken(token, f.chain, testNow); err == nil {
t.Error("payload 语义非法应拒绝")
}
}
func TestFingerprint(t *testing.T) {
a := Fingerprint("/sys/...uuid", "aa:bb:cc:dd:ee:ff")
b := Fingerprint("aa:bb:cc:dd:ee:ff", "/sys/...uuid") // 顺序无关
if a != b {
t.Errorf("指纹应与字段顺序无关:\n%s\n%s", a, b)
}
if !strings.HasPrefix(a, "sha256:") {
t.Errorf("指纹应带 sha256: 前缀: %q", a)
}
if a == Fingerprint("different") {
t.Error("不同输入应产生不同指纹")
}
if got := Fingerprint("x"); got == Fingerprint("y") {
t.Error("碰撞")
}
}
func TestClockSkewTolerance(t *testing.T) {
// ±10min 内的时钟偏移被容忍(docs/design/04-crypto.md §6)
f := newFixture(t)
token := f.sign(t, validPayload())
if _, err := VerifyToken(token, f.chain, testNow-540); err != nil { // 本地慢 9 分钟
t.Errorf("时钟偏移容忍内应通过: %v", err)
}
}
+296
View File
@@ -0,0 +1,296 @@
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]
}
}
}
+127
View File
@@ -0,0 +1,127 @@
package crypto
import (
"encoding/base64"
"encoding/json"
"strings"
"testing"
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
)
func TestTrustChain_KeyFor(t *testing.T) {
root, _ := GenerateRootKey()
sk1, _ := GenerateSigningKey()
sk2, _ := GenerateSigningKey()
chain := NewTrustChain(root.Pub)
if err := chain.AddSigningKey(sk1.Kid, sk1.Pub, KeyStatusActive, 0); err != nil {
t.Fatal(err)
}
if err := chain.AddSigningKey(sk2.Kid, sk2.Pub, KeyStatusRetired, 1794201600); err != nil {
t.Fatal(err)
}
if pub, ok := chain.KeyFor(sk1.Kid); !ok || string(pub) != string(sk1.Pub) {
t.Error("active key 应命中")
}
if pub, ok := chain.KeyFor(sk2.Kid); !ok || string(pub) != string(sk2.Pub) {
t.Error("retired key 也应命中(存量 license 依赖)")
}
if _, ok := chain.KeyFor("deadbeefdeadbeef"); ok {
t.Error("未知 kid 不应命中")
}
if _, ok := chain.KeyFor(""); ok {
t.Error("空 kid 不应命中")
}
}
func TestTrustChain_DuplicateKid(t *testing.T) {
root, _ := GenerateRootKey()
sk, _ := GenerateSigningKey()
chain := NewTrustChain(root.Pub)
if err := chain.AddSigningKey(sk.Kid, sk.Pub, KeyStatusActive, 0); err != nil {
t.Fatal(err)
}
if err := chain.AddSigningKey(sk.Kid, sk.Pub, KeyStatusActive, 0); err == nil {
t.Error("重复 kid 应报错")
}
}
func TestTrustBundle_RoundTrip(t *testing.T) {
root, _ := GenerateRootKey()
sk, _ := GenerateSigningKey()
chain := NewTrustChain(root.Pub)
chain.AddSigningKey(sk.Kid, sk.Pub, KeyStatusActive, 0)
chain.Revoke("01JDREVOKED000000000000000")
bundleToken, err := chain.SignBundle(root.Priv)
if err != nil {
t.Fatalf("SignBundle: %v", err)
}
// 校验方:仅持有 root 公钥即可装载信任链
fresh := NewTrustChain(root.Pub)
if err := fresh.LoadBundle(bundleToken, root.Pub); err != nil {
t.Fatalf("LoadBundle: %v", err)
}
if pub, ok := fresh.KeyFor(sk.Kid); !ok || string(pub) != string(sk.Pub) {
t.Error("装载后 signing key 应可用")
}
if !fresh.IsRevoked("01JDREVOKED000000000000000") {
t.Error("装载后 CRL 应生效")
}
}
func TestTrustBundle_RejectsTampering(t *testing.T) {
root, _ := GenerateRootKey()
evil, _ := GenerateSigningKey()
chain := NewTrustChain(root.Pub)
chain.AddSigningKey(evil.Kid, evil.Pub, KeyStatusActive, 0)
bundleToken, _ := chain.SignBundle(root.Priv)
// 篡改 bundle:用自己的私钥重签 → 装载方用真 root 验证必须失败
forged, _ := chain.SignBundle(evil.Priv)
if err := NewTrustChain(root.Pub).LoadBundle(forged, root.Pub); err == nil {
t.Error("非真 root 签名的 bundle 应被拒绝")
}
// 篡改载荷字节(追加一个 key)
parts := strings.Split(bundleToken, ".")
var bundle TrustBundle
raw, _ := base64.RawURLEncoding.DecodeString(parts[1])
json.Unmarshal(raw, &bundle)
bundle.Signing = append(bundle.Signing, SigningKeyInfo{
Kid: "ffffffffffffffff", Pub: base64.RawURLEncoding.EncodeToString(evil.Pub), Status: KeyStatusActive,
})
nb, _ := json.Marshal(bundle)
tampered := parts[0] + "." + base64.RawURLEncoding.EncodeToString(nb) + "." + parts[2]
if err := NewTrustChain(root.Pub).LoadBundle(tampered, root.Pub); err == nil {
t.Error("篡改载荷的 bundle 应被拒绝")
}
}
func TestTrustBundle_IgnoresUnknownFields(t *testing.T) {
// 前向兼容:未来版本的签发方在 bundle 中加入新字段,当前版装载方应能加载
root, _ := GenerateRootKey()
sk, _ := GenerateSigningKey()
future := map[string]any{
"v": 1,
"future_field": "next-version",
"signing": []SigningKeyInfo{{
Kid: sk.Kid, Pub: base64.RawURLEncoding.EncodeToString(sk.Pub), Status: KeyStatusActive,
}},
}
payload, _ := json.Marshal(future)
token, err := SignToken(root.Priv, "root", license.TypTrust, payload)
if err != nil {
t.Fatalf("SignToken: %v", err)
}
fresh := NewTrustChain(root.Pub)
if err := fresh.LoadBundle(token, root.Pub); err != nil {
t.Fatalf("bundle 未来字段应忽略: %v", err)
}
if _, ok := fresh.KeyFor(sk.Kid); !ok {
t.Error("装载后 key 应可用")
}
}