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 + 零依赖断言 + 三平台交叉编译冒烟)
392 lines
10 KiB
Go
392 lines
10 KiB
Go
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"
|
||
)
|
||
|
||
// ---- 测试环境 ----
|
||
|
||
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, _ := crypto.GenerateRootKey()
|
||
sk, _ := crypto.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 := crypto.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, _ := crypto.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())
|
||
}
|
||
}
|