Files
EntitleForge-SDK-go/sdk/client_test.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

393 lines
11 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 sdk
import (
"context"
"crypto/ed25519"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"sync"
"testing"
"time"
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/crypto"
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/sign"
)
// ---- 测试环境 ----
type testEnv struct {
t *testing.T
priv ed25519.PrivateKey
kid string
rootPub []byte
chain *crypto.TrustChain
now int64
}
func newEnv(t *testing.T) *testEnv {
root, _ := sign.GenerateRootKey()
sk, _ := sign.GenerateSigningKey()
chain := crypto.NewTrustChain(root.Pub)
chain.AddSigningKey(sk.Kid, sk.Pub, crypto.KeyStatusActive, 0) //nolint:errcheck
return &testEnv{t: t, priv: sk.Priv, kid: sk.Kid, rootPub: root.Pub, chain: chain, now: int64(1762665600)}
}
// sign 签发测试 license token
func (e *testEnv) sign(mut func(*license.Payload)) string {
e.t.Helper()
p := e.payload(mut)
b, err := json.Marshal(p)
if err != nil {
e.t.Fatal(err)
}
token, err := sign.SignToken(e.priv, e.kid, license.TypLicense, b)
if err != nil {
e.t.Fatal(err)
}
return token
}
func (e *testEnv) payload(mut func(*license.Payload)) license.Payload {
p := license.Payload{
JTI: "01JDTEST000000000000000000", ISS: "EntitleForge",
TID: "01JDTENANT0000000000000000", TName: "测试租户",
Prod: "prod_test", IAT: e.now - 100, NBF: e.now - 100, EXP: e.now + 86400,
LT: license.TypeSubscription, ST: license.StateIssued,
Ent: map[string]license.Entitlement{
"module.audit-log": license.Bool(true),
"seats": license.Quantity(50),
"tier": license.TierValue("enterprise"),
"allowed-regions": license.Constraint([]string{"cn-north", "cn-east"}),
},
Pol: &license.PolicySnapshot{Heartbeat: 900, LeaseTTL: 3600, Grace: 259200, ForcedCheck: 86400},
}
if mut != nil {
mut(&p)
}
return p
}
func (e *testEnv) trust() *crypto.TrustChain { return e.chain }
// fakeClock 可注入时钟(GRACE 演进测试)
type fakeClock struct {
mu sync.Mutex
now int64
}
func (c *fakeClock) Now() int64 {
c.mu.Lock()
defer c.mu.Unlock()
return c.now
}
func (c *fakeClock) Advance(d int64) {
c.mu.Lock()
defer c.mu.Unlock()
c.now += d
}
// ---- 文件模式 ----
func TestFileMode_BasicLifecycle(t *testing.T) {
e := newEnv(t)
dir := t.TempDir()
path := filepath.Join(dir, "license.eflic")
os.WriteFile(path, []byte(e.sign(nil)), 0o600) //nolint:errcheck
clock := &fakeClock{now: e.now}
c, err := New(WithLicenseFile(path), WithProductKey("prod_test"), WithTrustChain(e.trust()), WithClock(clock))
if err != nil {
t.Fatalf("New: %v", err)
}
if err := c.Start(context.Background()); err != nil {
t.Fatalf("Start: %v", err)
}
defer c.Close()
if c.State() != StateActive {
t.Fatalf("初始状态: %s", c.State())
}
// 查询 API
if !c.Enabled("module.audit-log") {
t.Error("module.audit-log 应启用")
}
if c.Enabled("module.nonexistent") {
t.Error("未授权 feature 应返回 false(缺省即无权)")
}
if got := c.Quantity("seats"); got != 50 {
t.Errorf("seats: %d", got)
}
if got := c.Tier(); got != "enterprise" {
t.Errorf("tier: %q", got)
}
if !c.TierAtLeast("pro") {
t.Error("enterprise >= pro")
}
if c.TierAtLeast("ultimate") {
t.Error("enterprise < ultimate")
}
if !c.Allows("allowed-regions", "cn-north") || c.Allows("allowed-regions", "us-west") {
t.Error("Allows 语义错误")
}
if len(c.Entitlements()) != 4 {
t.Errorf("Entitlements: %d", len(c.Entitlements()))
}
// Check Reason
ok, reason := c.Check("module.audit-log")
if !ok || reason != ReasonOK {
t.Errorf("Check: %v %s", ok, reason)
}
ok, reason = c.Check("module.no")
if ok || reason != ReasonNotEntitled {
t.Errorf("Check 未授权: %v %s", ok, reason)
}
// Info
info := c.Info()
if info.JTI != "01JDTEST000000000000000000" || info.ProductKey != "prod_test" {
t.Errorf("Info: %+v", info)
}
}
func TestFileMode_ExpiredTransition(t *testing.T) {
e := newEnv(t)
dir := t.TempDir()
path := filepath.Join(dir, "license.eflic")
os.WriteFile(path, []byte(e.sign(nil)), 0o600) //nolint:errcheck
clock := &fakeClock{now: e.now}
var states []State
c, _ := New(WithLicenseFile(path), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock), WithOnStateChange(func(from, to State) {
states = append(states, to)
}))
c.Start(context.Background()) //nolint:errcheck
defer c.Close()
// 推进至 exp + skew 容忍之外 → EXPIRED
clock.Advance(86400 + 1200)
c.tick()
if c.State() != StateExpired {
t.Fatalf("过期后状态: %s", c.State())
}
if c.Enabled("module.audit-log") {
t.Error("EXPIRED 下查询应全部零值")
}
if c.Quantity("seats") != 0 || c.Tier() != "" {
t.Error("EXPIRED 零值语义")
}
_, reason := c.Check("module.audit-log")
if reason != ReasonStateExpired {
t.Errorf("过期 Check reason: %s", reason)
}
}
func TestFileMode_TamperedFile_Invalid(t *testing.T) {
e := newEnv(t)
dir := t.TempDir()
path := filepath.Join(dir, "license.eflic")
token := e.sign(nil)
os.WriteFile(path, []byte(token[:len(token)-4]+"AAAA"), 0o600) //nolint:errcheck
c, err := New(WithLicenseFile(path), WithProductKey("prod_test"), WithTrustChain(e.trust()))
if err == nil {
c.Close()
t.Fatal("验签失败应在 New 报错")
}
}
func TestFileMode_ProductMismatch(t *testing.T) {
e := newEnv(t)
dir := t.TempDir()
path := filepath.Join(dir, "license.eflic")
os.WriteFile(path, []byte(e.sign(nil)), 0o600) //nolint:errcheck
if _, err := New(WithLicenseFile(path), WithProductKey("prod_other"), WithTrustChain(e.trust())); err == nil {
t.Fatal("产品不符应拒绝")
}
}
func TestFileMode_HotReload(t *testing.T) {
e := newEnv(t)
dir := t.TempDir()
path := filepath.Join(dir, "license.eflic")
os.WriteFile(path, []byte(e.sign(nil)), 0o600) //nolint:errcheck
clock := &fakeClock{now: e.now}
c, _ := New(WithLicenseFile(path), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock))
c.Start(context.Background()) //nolint:errcheck
defer c.Close()
if c.Quantity("seats") != 50 {
t.Fatal("前置失败")
}
// 热更新:seats → 100(mtimer 触发由 tick 模拟)
os.WriteFile(path, []byte(e.sign(func(p *license.Payload) {
p.Ent["seats"] = license.Quantity(100)
p.ST = license.StateRenewed
})), 0o600) //nolint:errcheck
c.tick()
if c.Quantity("seats") != 100 {
t.Errorf("热更新未生效: %d", c.Quantity("seats"))
}
}
// ---- 远程模式(httptest 假数据面) ----
// fakeRemote 模拟数据面:激活 + 心跳(可控 terminate/变更)
type fakeRemote struct {
mu sync.Mutex
server *httptest.Server
lease string // 当前应答的 lease
token string
terminate bool
crl string
fail bool // 网络故障开关(503)
heartbeats int
}
func newFakeRemote(t *testing.T, e *testEnv) *fakeRemote {
fr := &fakeRemote{}
fr.lease = e.leaseToken()
mux := http.NewServeMux()
mux.HandleFunc("POST /v1/activate", func(w http.ResponseWriter, r *http.Request) {
fr.mu.Lock()
defer fr.mu.Unlock()
fr.token = "tok-" + time.Now().Format("150405.000")
json.NewEncoder(w).Encode(map[string]any{ //nolint:errcheck
"activation_id": "act-01JDFAKE00000000000000000",
"activation_token": fr.token,
"lease": fr.lease,
"lease_ttl": int64(3600),
"heartbeat_interval": 900,
"grace_period": 259200,
"server_time": e.now,
"crl_version": 0,
})
})
mux.HandleFunc("POST /v1/heartbeat", func(w http.ResponseWriter, r *http.Request) {
fr.mu.Lock()
defer fr.mu.Unlock()
fr.heartbeats++
if fr.fail {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
resp := map[string]any{"changed": false, "server_time": e.now, "crl_version": 0}
if fr.terminate {
resp["terminate"] = true
resp["crl"] = fr.crl
}
json.NewEncoder(w).Encode(resp) //nolint:errcheck
})
fr.server = httptest.NewServer(mux)
t.Cleanup(fr.server.Close)
return fr
}
func (e *testEnv) leaseToken() string {
p := e.payload(func(p *license.Payload) {
p.LT = license.TypeLease
p.ST = license.StateRenewed
p.ACT = "act-01JDFAKE00000000000000000"
p.EXP = e.now + 3600
})
b, _ := json.Marshal(p)
token, _ := sign.SignToken(e.priv, e.kid, license.TypLease, b)
return token
}
func TestRemoteMode_GraceCycle(t *testing.T) {
e := newEnv(t)
fr := newFakeRemote(t, e)
clock := &fakeClock{now: e.now}
c, err := New(WithRemoteServer(fr.server.URL), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock), WithLicenseKey("ef-TEST-TEST-TEST-TEST"))
if err != nil {
t.Fatalf("New: %v", err)
}
if err := c.Start(context.Background()); err != nil {
t.Fatalf("Start(自动激活): %v", err)
}
defer c.Close()
if c.State() != StateActive {
t.Fatalf("激活后状态: %s", c.State())
}
if c.Quantity("seats") != 50 {
t.Errorf("seats: %d", c.Quantity("seats"))
}
// 网络故障 → GRACE(查询仍可用)
fr.mu.Lock()
fr.fail = true
fr.mu.Unlock()
c.heartbeatOnce(context.Background())
if c.State() != StateGrace {
t.Fatalf("断连后应 GRACE: %s", c.State())
}
if c.Quantity("seats") != 50 {
t.Error("GRACE 期间查询应正常")
}
_, reason := c.Check("seats")
if reason != ReasonStateGrace {
t.Errorf("GRACE reason: %s", reason)
}
// 恢复 → ACTIVE
fr.mu.Lock()
fr.fail = false
fr.mu.Unlock()
c.heartbeatOnce(context.Background())
if c.State() != StateActive {
t.Fatalf("恢复后应 ACTIVE: %s", c.State())
}
// 宽限期耗尽 → EXPIRED
fr.mu.Lock()
fr.fail = true
fr.mu.Unlock()
c.heartbeatOnce(context.Background())
clock.Advance(259200 + 600) // grace 72h + skew
c.tick()
if c.State() != StateExpired {
t.Fatalf("宽限耗尽应 EXPIRED: %s", c.State())
}
}
func TestRemoteMode_TerminateRevoked(t *testing.T) {
e := newEnv(t)
fr := newFakeRemote(t, e)
clock := &fakeClock{now: e.now}
c, _ := New(WithRemoteServer(fr.server.URL), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock), WithLicenseKey("ef-TEST-TEST-TEST-TEST"))
c.Start(context.Background()) //nolint:errcheck
defer c.Close()
if c.State() != StateActive {
t.Fatal("前置失败")
}
fr.mu.Lock()
fr.terminate = true
fr.mu.Unlock()
c.heartbeatOnce(context.Background())
if c.State() != StateRevoked {
t.Fatalf("terminate 后应 REVOKED: %s", c.State())
}
if c.Enabled("module.audit-log") {
t.Error("REVOKED 下应零值")
}
// REVOKED 是终态:不因后续成功心跳复活
fr.mu.Lock()
fr.terminate = false
fr.mu.Unlock()
c.heartbeatOnce(context.Background())
if c.State() != StateRevoked {
t.Fatalf("REVOKED 应为终态: %s", c.State())
}
}