- 加密租约缓存(AES-256-GCM + HKDF(指纹)):重启恢复 GRACE,401/410 自动重新激活 - WithGracePolicy(KeepBooleans)、WithLicenseBytes、WithHeartbeatInterval、WithHTTPClient、WithAutoActivate、WithOnEntitlementsChange、Deactivate - 心跳/激活 server_time 参与可信时间校正 - 新增缓存/降级/时钟/重激活/回调测试
331 lines
9.2 KiB
Go
331 lines
9.2 KiB
Go
package sdk
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"os"
|
||
"path/filepath"
|
||
"sync"
|
||
"testing"
|
||
"time"
|
||
|
||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
|
||
)
|
||
|
||
// newLifecycleServer 提供 activate/heartbeat/deactivate 的最小服务端。
|
||
type lifecycleServer struct {
|
||
mu sync.Mutex
|
||
server *httptest.Server
|
||
lease string
|
||
activationTime int64
|
||
activations int
|
||
deactivations int
|
||
heartbeatCode int
|
||
heartbeatTime int64
|
||
heartbeatLease string
|
||
}
|
||
|
||
func newLifecycleServer(t *testing.T, e *testEnv) *lifecycleServer {
|
||
ls := &lifecycleServer{lease: e.leaseToken(), activationTime: e.now, heartbeatTime: e.now}
|
||
mux := http.NewServeMux()
|
||
mux.HandleFunc("POST /v1/activate", func(w http.ResponseWriter, r *http.Request) {
|
||
ls.mu.Lock()
|
||
ls.activations++
|
||
ls.mu.Unlock()
|
||
json.NewEncoder(w).Encode(map[string]any{ //nolint:errcheck
|
||
"activation_id": "act-lifecycle", "activation_token": "tok-lifecycle",
|
||
"lease": ls.lease, "lease_ttl": int64(3600), "heartbeat_interval": 900,
|
||
"grace_period": 259200, "server_time": ls.activationTime, "crl_version": 0,
|
||
})
|
||
})
|
||
mux.HandleFunc("POST /v1/heartbeat", func(w http.ResponseWriter, r *http.Request) {
|
||
ls.mu.Lock()
|
||
code := ls.heartbeatCode
|
||
st := ls.heartbeatTime
|
||
lease := ls.heartbeatLease
|
||
ls.mu.Unlock()
|
||
if code != 0 && code != http.StatusOK {
|
||
w.WriteHeader(code)
|
||
return
|
||
}
|
||
resp := map[string]any{"changed": lease != "", "server_time": st, "crl_version": 0}
|
||
if lease != "" {
|
||
resp["lease"] = lease
|
||
}
|
||
json.NewEncoder(w).Encode(resp) //nolint:errcheck
|
||
})
|
||
mux.HandleFunc("POST /v1/deactivate", func(w http.ResponseWriter, r *http.Request) {
|
||
ls.mu.Lock()
|
||
ls.deactivations++
|
||
ls.mu.Unlock()
|
||
w.WriteHeader(http.StatusNoContent)
|
||
})
|
||
ls.server = httptest.NewServer(mux)
|
||
t.Cleanup(ls.server.Close)
|
||
return ls
|
||
}
|
||
|
||
func (ls *lifecycleServer) setHeartbeat(code int, st int64) {
|
||
ls.mu.Lock()
|
||
ls.heartbeatCode, ls.heartbeatTime = code, st
|
||
ls.mu.Unlock()
|
||
}
|
||
|
||
func (ls *lifecycleServer) setHeartbeatLease(lease string) {
|
||
ls.mu.Lock()
|
||
ls.heartbeatLease = lease
|
||
ls.mu.Unlock()
|
||
}
|
||
|
||
func (ls *lifecycleServer) counts() (activations, deactivations int) {
|
||
ls.mu.Lock()
|
||
defer ls.mu.Unlock()
|
||
return ls.activations, ls.deactivations
|
||
}
|
||
|
||
func TestCache_RestoresGraceAndSurvivesRestart(t *testing.T) {
|
||
e := newEnv(t)
|
||
ls := newLifecycleServer(t, e)
|
||
clock := &fakeClock{now: e.now}
|
||
dir := t.TempDir()
|
||
opts := []Option{
|
||
WithRemoteServer(ls.server.URL), WithProductKey("prod_test"),
|
||
WithTrustChain(e.trust()), WithClock(clock), WithLicenseKey("ef-KEY"),
|
||
WithCacheDir(dir), WithFingerprint("sha256:cache-test"),
|
||
}
|
||
c1, err := New(opts...)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := c1.Start(context.Background()); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
c1.Close()
|
||
if _, err := os.Stat(filepath.Join(dir, cacheFileName)); err != nil {
|
||
t.Fatalf("激活后应写入缓存: %v", err)
|
||
}
|
||
|
||
// 重启且网络离线:应从缓存恢复 GRACE
|
||
offline := &lifecycleServer{lease: ls.lease, activationTime: e.now, heartbeatTime: e.now}
|
||
offline.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
w.WriteHeader(http.StatusServiceUnavailable)
|
||
}))
|
||
defer offline.server.Close()
|
||
opts[0] = WithRemoteServer(offline.server.URL)
|
||
c2, err := New(opts...)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if c2.State() != StateGrace {
|
||
t.Fatalf("缓存应恢复 GRACE: %s", c2.State())
|
||
}
|
||
if c2.Quantity("seats") != 50 {
|
||
t.Error("GRACE 期间查询应可用")
|
||
}
|
||
c2.Close()
|
||
}
|
||
|
||
func TestCache_RejectsWrongFingerprint(t *testing.T) {
|
||
e := newEnv(t)
|
||
ls := newLifecycleServer(t, e)
|
||
clock := &fakeClock{now: e.now}
|
||
dir := t.TempDir()
|
||
base := []Option{
|
||
WithProductKey("prod_test"), WithTrustChain(e.trust()), WithClock(clock),
|
||
WithLicenseKey("ef-KEY"), WithCacheDir(dir), WithFingerprint("sha256:cache-test"),
|
||
}
|
||
c1, _ := New(append(base, WithRemoteServer(ls.server.URL))...)
|
||
if err := c1.Start(context.Background()); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
c1.Close()
|
||
|
||
// 不同指纹派生的密钥无法解密缓存
|
||
wrong := []Option{
|
||
WithProductKey("prod_test"), WithTrustChain(e.trust()), WithClock(clock),
|
||
WithLicenseKey("ef-KEY"), WithCacheDir(dir), WithFingerprint("sha256:other"),
|
||
WithRemoteServer(ls.server.URL),
|
||
}
|
||
c2, err := New(wrong...)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if c2.State() != StateUnverified {
|
||
t.Fatalf("错误指纹不应恢复缓存: %s", c2.State())
|
||
}
|
||
c2.Close()
|
||
}
|
||
|
||
func TestDeactivate_ClearsStateAndCache(t *testing.T) {
|
||
e := newEnv(t)
|
||
ls := newLifecycleServer(t, e)
|
||
clock := &fakeClock{now: e.now}
|
||
dir := t.TempDir()
|
||
c, err := New(WithRemoteServer(ls.server.URL), WithProductKey("prod_test"),
|
||
WithTrustChain(e.trust()), WithClock(clock), WithLicenseKey("ef-KEY"),
|
||
WithCacheDir(dir), WithFingerprint("sha256:d"))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := c.Start(context.Background()); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := c.Deactivate(context.Background(), "test"); err != nil {
|
||
t.Fatalf("Deactivate: %v", err)
|
||
}
|
||
if c.State() != StateUnverified {
|
||
t.Fatalf("停用后状态: %s", c.State())
|
||
}
|
||
if _, err := os.Stat(filepath.Join(dir, cacheFileName)); !os.IsNotExist(err) {
|
||
t.Errorf("停用后缓存应删除")
|
||
}
|
||
if _, deact := ls.counts(); deact != 1 {
|
||
t.Errorf("应调用一次停用端点: %d", deact)
|
||
}
|
||
}
|
||
|
||
func TestLicenseBytes_LoadsWithoutFile(t *testing.T) {
|
||
e := newEnv(t)
|
||
token := e.sign(nil)
|
||
c, err := New(WithLicenseBytes([]byte(token)), WithProductKey("prod_test"),
|
||
WithTrustChain(e.trust()), WithClock(&fakeClock{now: e.now}))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer c.Close()
|
||
if c.State() != StateActive || !c.Enabled("module.audit-log") {
|
||
t.Fatalf("内存 license 应直接可用: %s", c.State())
|
||
}
|
||
if c.startMode() != "bytes" {
|
||
t.Errorf("mode: %s", c.startMode())
|
||
}
|
||
}
|
||
|
||
func TestGracePolicy_KeepBooleans(t *testing.T) {
|
||
e := newEnv(t)
|
||
clock := &fakeClock{now: e.now}
|
||
path := writeFileLicense(t, e, 0)
|
||
c, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
|
||
WithTrustChain(e.trust()), WithClock(clock), WithGracePolicy(GraceKeepBooleans))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer c.Close()
|
||
clock.Advance(86400 + 1200) // 越过 exp
|
||
c.tick()
|
||
if c.State() != StateExpired {
|
||
t.Fatalf("应 EXPIRED: %s", c.State())
|
||
}
|
||
if !c.Enabled("module.audit-log") {
|
||
t.Error("KeepBooleans 应在过期后放行 true 布尔项")
|
||
}
|
||
if c.Quantity("seats") != 0 {
|
||
t.Error("KeepBooleans 不应放行数量项")
|
||
}
|
||
}
|
||
|
||
func TestClockSkew_UsesServerTime(t *testing.T) {
|
||
e := newEnv(t)
|
||
ls := newLifecycleServer(t, e)
|
||
clock := &fakeClock{now: e.now}
|
||
// 心跳下发短租约(exp=e.now+2000),服务端时间 e.now+1500;
|
||
// 本地时钟前进 3000 后按本地判定已过期,但可信时间仍有效。
|
||
shortLease := e.sign(func(p *license.Payload) {
|
||
p.LT = license.TypeLease
|
||
p.ST = license.StateRenewed
|
||
p.EXP = e.now + 2000
|
||
})
|
||
c, err := New(WithRemoteServer(ls.server.URL), WithProductKey("prod_test"),
|
||
WithTrustChain(e.trust()), WithClock(clock), WithLicenseKey("ef-KEY"))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer c.Close()
|
||
if err := c.Start(context.Background()); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
ls.setHeartbeat(0, clock.Now()+1500)
|
||
ls.setHeartbeatLease(shortLease)
|
||
clock.Advance(3000)
|
||
if err := c.heartbeatOnce(context.Background()); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
c.tick()
|
||
if c.State() != StateActive {
|
||
t.Fatalf("server_time 校正后应保持 ACTIVE: %s", c.State())
|
||
}
|
||
}
|
||
|
||
func TestHeartbeat_ReactivatesOnUnauthorized(t *testing.T) {
|
||
e := newEnv(t)
|
||
ls := newLifecycleServer(t, e)
|
||
clock := &fakeClock{now: e.now}
|
||
c, err := New(WithRemoteServer(ls.server.URL), WithProductKey("prod_test"),
|
||
WithTrustChain(e.trust()), WithClock(clock), WithLicenseKey("ef-KEY"))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer c.Close()
|
||
if err := c.Start(context.Background()); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
ls.setHeartbeat(http.StatusUnauthorized, e.now)
|
||
if err := c.heartbeatOnce(context.Background()); err != nil {
|
||
t.Fatalf("应自动重新激活: %v", err)
|
||
}
|
||
act, _ := ls.counts()
|
||
if act != 2 {
|
||
t.Errorf("激活次数应为 2: %d", act)
|
||
}
|
||
if c.State() != StateActive {
|
||
t.Errorf("重新激活后状态: %s", c.State())
|
||
}
|
||
}
|
||
|
||
func TestHeartbeat_OverrideAndEntitlementsCallback(t *testing.T) {
|
||
e := newEnv(t)
|
||
ls := newLifecycleServer(t, e)
|
||
clock := &fakeClock{now: e.now}
|
||
var mu sync.Mutex
|
||
var oldEnt, newEnt map[string]license.Entitlement
|
||
c, err := New(WithRemoteServer(ls.server.URL), WithProductKey("prod_test"),
|
||
WithTrustChain(e.trust()), WithClock(clock), WithLicenseKey("ef-KEY"),
|
||
WithHeartbeatInterval(60*time.Second),
|
||
WithOnEntitlementsChange(func(old, new map[string]license.Entitlement) {
|
||
mu.Lock()
|
||
oldEnt, newEnt = old, new
|
||
mu.Unlock()
|
||
}))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer c.Close()
|
||
if err := c.Start(context.Background()); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
act, _ := ls.counts()
|
||
if act != 1 {
|
||
t.Fatalf("激活次数: %d", act)
|
||
}
|
||
c.mu.Lock()
|
||
every := c.heartbeatEvery
|
||
c.mu.Unlock()
|
||
if every != 60 {
|
||
t.Errorf("心跳覆写应生效: %d", every)
|
||
}
|
||
|
||
changed := e.sign(func(p *license.Payload) {
|
||
p.Ent["seats"] = license.Quantity(99)
|
||
})
|
||
if err := c.installVerified(changed); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
mu.Lock()
|
||
defer mu.Unlock()
|
||
if oldEnt == nil || newEnt == nil || newEnt["seats"].AsInt() != 99 {
|
||
t.Errorf("entitlements 回调未触发: old=%v new=%v", oldEnt, newEnt)
|
||
}
|
||
}
|