diff --git a/README.md b/README.md index 2eb38c9..a60d472 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,24 @@ client, err := sdk.New(..., sdk.WithFingerprintFunc(func() (string, error) { Linux 采集 machine-id + DMI product_uuid;macOS 采集 IOPlatformUUID;容器内默认拒绝自动采集(容器自身 ID 不稳定),需挂载宿主 `/etc/machine-id` 并注入自定义采集器,或显式指定指纹。 +## 缓存与降级 + +```go +client, err := sdk.New( + sdk.WithRemoteServer("https://license.vendor.com"), + sdk.WithLicenseKey("ef-XXXX-XXXX-XXXX-XXXX"), + sdk.WithCacheDir("/var/lib/app"), // AES-256-GCM,密钥 HKDF(机器指纹) + sdk.WithGracePolicy(sdk.GraceKeepBooleans), // 过期后保留布尔开关 + sdk.WithHeartbeatInterval(5*time.Minute), // 仅在小于 license pol 时生效 + sdk.WithAutoActivate(func() string { return os.Getenv("EF_LICENSE_KEY") }), +) +``` + +- 远程/代理模式进程重启时优先从加密缓存恢复 `GRACE`(宽限期内免网络),心跳 401/410 自动重新激活。 +- `server_time` 参与时间校正(`trustedNow = 本地时钟 + 偏移`)。 +- `Deactivate(ctx, reason)` 主动停用并清理本地缓存。 +- `WithLicenseBytes` 支持 ConfigMap/env 注入;`WithHTTPClient` 可注入 mTLS 客户端;`WithOnEntitlementsChange` 订阅授权变更。 + ## 吊销与强制校验 - 心跳响应携带的 CRL 会自动验签并应用(版本单调,防回滚);命中当前 license 立即转 `REVOKED`。 diff --git a/sdk/cache.go b/sdk/cache.go new file mode 100644 index 0000000..f20a766 --- /dev/null +++ b/sdk/cache.go @@ -0,0 +1,189 @@ +package sdk + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/hkdf" + "crypto/rand" + "crypto/sha256" + "encoding/json" + "errors" + "os" + "path/filepath" +) + +// cacheFileName 是远程/代理模式的加密租约缓存(docs/design/07-sdk.md §4)。 +const cacheFileName = "license.cache" + +// cacheEntry 是缓存载荷;整体 AES-256-GCM 加密,密钥 HKDF-SHA256(指纹)。 +type cacheEntry struct { + Lease string `json:"lease"` + ActToken string `json:"activation_token"` + Heartbeat int64 `json:"heartbeat_interval"` + Grace int64 `json:"grace_period"` + SavedAt int64 `json:"saved_at"` +} + +// cacheKeyMaterial 返回稳定的缓存密钥材料;容器内无法采集时退回 hostname。 +func (c *Client) cacheKeyMaterial() string { + if c.opts.fingerprint != "" { + return c.opts.fingerprint + } + if c.opts.fingerprintFn != nil { + if fp, err := c.opts.fingerprintFn(); err == nil && fp != "" { + return fp + } + } + if fp, err := machineFingerprintProvider(); err == nil && fp != "" { + return fp + } + return defaultFingerprint() +} + +func (c *Client) cacheKey() ([]byte, error) { + return hkdf.Key(sha256.New, []byte(c.cacheKeyMaterial()), nil, "ef-sdk-cache-v1", 32) +} + +func (c *Client) cachePath() string { + return filepath.Join(c.opts.cacheDir, cacheFileName) +} + +// saveCache 加密写入当前租约快照(尽力而为:失败仅告警)。 +func (c *Client) saveCache() { + if c.opts.cacheDir == "" { + return + } + s := c.snap.Load() + if s == nil || s.rawToken == "" { + return + } + c.mu.Lock() + entry := cacheEntry{ + Lease: s.rawToken, ActToken: c.actToken, + Heartbeat: c.heartbeatEvery, Grace: c.gracePeriod, + SavedAt: c.opts.clock.Now(), + } + c.mu.Unlock() + raw, err := json.Marshal(entry) + if err != nil { + return + } + key, err := c.cacheKey() + if err != nil { + c.opts.logger.Warn("缓存密钥派生失败", "logger", "pkg.sdk.Client.saveCache", "error", err) + return + } + block, err := aes.NewCipher(key) + if err != nil { + return + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return + } + nonce := make([]byte, gcm.NonceSize()) + if _, err := rand.Read(nonce); err != nil { + return + } + sealed := gcm.Seal(nonce, nonce, raw, nil) + if err := os.MkdirAll(c.opts.cacheDir, 0o700); err != nil { + c.opts.logger.Warn("缓存目录创建失败", "logger", "pkg.sdk.Client.saveCache", "error", err) + return + } + tmp := c.cachePath() + ".tmp" + if err := os.WriteFile(tmp, sealed, 0o600); err != nil { + c.opts.logger.Warn("缓存写入失败", "logger", "pkg.sdk.Client.saveCache", "error", err) + return + } + if err := os.Rename(tmp, c.cachePath()); err != nil { + os.Remove(tmp) //nolint:errcheck + } +} + +// loadCache 解密并验证缓存;有效且未超过宽限期时恢复 GRACE 快照。 +func (c *Client) loadCache() bool { + const logField = "pkg.sdk.Client.loadCache" + sealed, err := os.ReadFile(c.cachePath()) + if err != nil { + return false + } + key, err := c.cacheKey() + if err != nil { + return false + } + block, err := aes.NewCipher(key) + if err != nil { + return false + } + gcm, err := cipher.NewGCM(block) + if err != nil || len(sealed) <= gcm.NonceSize() { + c.clearCache() + return false + } + raw, err := gcm.Open(nil, sealed[:gcm.NonceSize()], sealed[gcm.NonceSize():], nil) + if err != nil { + c.opts.logger.Warn("缓存解密失败(指纹变化或文件损坏),已忽略", "logger", logField) + c.clearCache() + return false + } + var entry cacheEntry + if err := json.Unmarshal(raw, &entry); err != nil || entry.Lease == "" { + c.clearCache() + return false + } + + now := c.opts.clock.Now() + grace := entry.Grace + if grace <= 0 { + grace = 259200 + } + if entry.SavedAt+2*grace < now { + c.opts.logger.Info("缓存已超过宽限窗口,忽略", "logger", logField) + c.clearCache() + return false + } + payload, err := c.verifyToken(entry.Lease) + if err != nil { + c.opts.logger.Info("缓存 lease 验证失败,忽略", "logger", logField, "error", err) + c.clearCache() + return false + } + deadline := entry.SavedAt + grace + if err := payload.TimeValid(now, 0); err != nil { + c.clearCache() + return false + } + c.snap.Store(&snapshot{payload: payload, rawToken: entry.Lease, state: StateGrace, graceDeadline: deadline}) + c.mu.Lock() + c.actToken = entry.ActToken + c.heartbeatEvery = c.effectiveHeartbeat(entry.Heartbeat) + c.gracePeriod = grace + c.mu.Unlock() + c.crlVersion.Store(0) + c.lastCheckAt.Store(now) + c.opts.logger.Info("已从缓存恢复授权(GRACE)", "logger", logField, + "jti", payload.JTI, "grace_deadline", deadline) + return true +} + +// clearCache 删除加密缓存。 +func (c *Client) clearCache() { + if c.opts.cacheDir == "" { + return + } + if err := os.Remove(c.cachePath()); err != nil && !errors.Is(err, os.ErrNotExist) { + c.opts.logger.Warn("缓存删除失败", "logger", "pkg.sdk.Client.clearCache", "error", err) + } +} + +// effectiveHeartbeat 应用 WithHeartbeatInterval 覆写(取更小值,设计 §3.1)。 +func (c *Client) effectiveHeartbeat(current int64) int64 { + if c.opts.heartbeatOverride <= 0 { + return current + } + override := int64(c.opts.heartbeatOverride.Seconds()) + if current <= 0 || override < current { + return override + } + return current +} diff --git a/sdk/client.go b/sdk/client.go index 66c52ac..cd7576b 100644 --- a/sdk/client.go +++ b/sdk/client.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "log/slog" + "net/http" "os" "strings" "sync" @@ -55,6 +56,7 @@ var defaultTierOrder = []string{"free", "starter", "pro", "business", "enterpris type options struct { licenseFile string + licenseBytes []byte remoteServer string licenseKey string productKey string @@ -65,19 +67,65 @@ type options struct { clock Clock logger *slog.Logger onState func(from, to State) + onEntitlements func(old, new map[string]license.Entitlement) pollInterval time.Duration validationServer string // 文件模式强制校验点(POST /v1/validate) + cacheDir string + heartbeatOverride time.Duration + autoActivate func() string + gracePolicy GracePolicy + httpClient *http.Client + // Proxy 模式(docs/design/08-k8s-proxy.md §4) proxyAddr string saToken string saTokenFile string } +// GracePolicy 定义宽限/过期后的查询降级策略(docs/design/07-sdk.md §5)。 +type GracePolicy int + +const ( + // GraceZeroAll 是默认策略:过期后所有查询返回零值(安全优先)。 + GraceZeroAll GracePolicy = iota + // GraceKeepBooleans 在 EXPIRED 后仍放行 payload 中为 true 的布尔 Feature。 + GraceKeepBooleans + // GraceCustom 保留给应用自定义(v1 行为同 ZeroAll)。 + GraceCustom +) + // Option 配置项(docs/design/07-sdk.md §3.1)。 type Option func(*options) -func WithLicenseFile(path string) Option { return func(o *options) { o.licenseFile = path } } +func WithLicenseFile(path string) Option { return func(o *options) { o.licenseFile = path } } + +// WithLicenseBytes 从内存字节加载 license(ConfigMap/env 注入场景)。 +func WithLicenseBytes(b []byte) Option { return func(o *options) { o.licenseBytes = b } } + +// WithCacheDir 启用加密租约缓存(远程/代理模式;重启免网络恢复 GRACE)。 +func WithCacheDir(dir string) Option { return func(o *options) { o.cacheDir = dir } } + +// WithHeartbeatInterval 覆写心跳间隔(仅在小于 license 内 pol 时生效)。 +func WithHeartbeatInterval(d time.Duration) Option { + return func(o *options) { o.heartbeatOverride = d } +} + +// WithAutoActivate 在 Start 时从回调取 license key 自动激活(容器一次性交付)。 +func WithAutoActivate(keyFn func() string) Option { + return func(o *options) { o.autoActivate = keyFn } +} + +// WithGracePolicy 设置过期后的降级策略。 +func WithGracePolicy(p GracePolicy) Option { return func(o *options) { o.gracePolicy = p } } + +// WithHTTPClient 注入自定义 HTTP 客户端(mTLS/代理/测试)。 +func WithHTTPClient(hc *http.Client) Option { return func(o *options) { o.httpClient = hc } } + +// WithOnEntitlementsChange 订阅授权集合变更(基于签名 payload 比对)。 +func WithOnEntitlementsChange(cb func(old, new map[string]license.Entitlement)) Option { + return func(o *options) { o.onEntitlements = cb } +} func WithRemoteServer(baseURL string) Option { return func(o *options) { o.remoteServer = baseURL } } func WithLicenseKey(key string) Option { return func(o *options) { o.licenseKey = key } } func WithProductKey(pk string) Option { return func(o *options) { o.productKey = pk } } @@ -136,7 +184,22 @@ type Client struct { crlVersion atomic.Int64 // 最近应用/上报的 CRL 版本 lastCheckAt atomic.Int64 // 最近一次在线校验成功时刻(强制校验点计时) + clockSkew atomic.Int64 // 服务端时间 - 本地时间(trustedNow = 本地 + skew) noCheckWarn sync.Once + fromCache bool +} + +// trustedNow 返回经 server_time 校正的可信时间。 +func (c *Client) trustedNow() int64 { + return c.opts.clock.Now() + c.clockSkew.Load() +} + +// applyServerTime 用服务端时间更新本地偏移估计。 +func (c *Client) applyServerTime(serverTime int64) { + if serverTime <= 0 { + return + } + c.clockSkew.Store(serverTime - c.opts.clock.Now()) } // New 创建 Client。 @@ -153,20 +216,31 @@ func New(opts ...Option) (*Client, error) { if o.trust == nil { return nil, errors.New("sdk: 需要 WithTrustChain(SDK 须锚定 root 公钥)") } - if o.licenseFile == "" && o.remoteServer == "" && o.proxyAddr == "" { - return nil, errors.New("sdk: 需要 WithLicenseFile、WithRemoteServer 或 WithProxy") + if o.licenseFile == "" && len(o.licenseBytes) == 0 && o.remoteServer == "" && o.proxyAddr == "" { + return nil, errors.New("sdk: 需要 WithLicenseFile、WithLicenseBytes、WithRemoteServer 或 WithProxy") } if o.tierOrder == nil { o.tierOrder = defaultTierOrder } c := &Client{opts: o, stop: make(chan struct{}), hc: defaultHTTPClient()} + if o.httpClient != nil { + c.hc = o.httpClient + } c.snap.Store(&snapshot{state: StateUnverified}) if o.licenseFile != "" { if err := c.reloadFile(); err != nil { return nil, fmt.Errorf("sdk: %w", err) } + } else if len(o.licenseBytes) > 0 { + if err := c.installVerified(strings.TrimSpace(string(o.licenseBytes))); err != nil { + return nil, fmt.Errorf("sdk: %w", err) + } + } + // 远程/代理模式:优先从加密缓存恢复(GRACE),失败再等 Start 激活 + if o.cacheDir != "" && (o.remoteServer != "" || o.proxyAddr != "") { + c.fromCache = c.loadCache() } return c, nil } @@ -180,12 +254,14 @@ func (c *Client) Start(ctx context.Context) error { return nil } if c.opts.remoteServer != "" { - if c.opts.licenseKey != "" { - if err := c.Activate(ctx, c.opts.licenseKey); err != nil { + key := c.activationKey() + // 缓存恢复的 GRACE 无需立即激活;心跳 401/410 时会自动重激活 + if key != "" && !c.fromCache { + if err := c.Activate(ctx, key); err != nil { return fmt.Errorf("sdk: 自动激活: %w", err) } } else if c.State() == StateUnverified { - return errors.New("sdk: 远程模式需要 WithLicenseKey(或先手动 Activate)") + return errors.New("sdk: 远程模式需要 WithLicenseKey/WithAutoActivate(或先手动 Activate)") } go c.heartbeatLoop(ctx) c.opts.logger.Info("SDK 远程模式已启动", "logger", logField, "server", c.opts.remoteServer) @@ -233,6 +309,9 @@ func (c *Client) transition(s *snapshot, to State, graceDeadline int64) { ns.state = to ns.graceDeadline = graceDeadline c.snap.Store(&ns) + if to == StateExpired || to == StateRevoked { + c.clearCache() // 终态/过期不再复用本地租约 + } if from != to && c.opts.onState != nil { c.opts.onState(from, to) } @@ -240,7 +319,7 @@ func (c *Client) transition(s *snapshot, to State, graceDeadline int64) { // verifyToken 验证并装载一个 license/lease token(信任链 + 产品匹配 + 时间窗)。 func (c *Client) verifyToken(token string) (*license.Payload, error) { - p, err := crypto.VerifyToken(token, c.opts.trust, c.opts.clock.Now()) + p, err := crypto.VerifyToken(token, c.opts.trust, c.trustedNow()) if err != nil { return nil, err } @@ -269,17 +348,62 @@ func (c *Client) installVerified(token string) error { old := c.snap.Load() ns := &snapshot{payload: p, rawToken: token, state: StateActive} c.snap.Store(ns) - c.lastCheckAt.Store(c.opts.clock.Now()) + c.lastCheckAt.Store(c.trustedNow()) if old == nil || old.state != StateActive { c.opts.logger.Info("授权已装载", "logger", "pkg.sdk.Client.installVerified", "jti", p.JTI) } - if old != nil && old.payload != nil && c.opts.onState != nil { - // entitlements 变更回调(07 §3):v1 以状态回调承载,实体 diff 由应用层比对 Entitlements() - _ = old + if c.opts.onEntitlements != nil && old != nil && old.payload != nil && + license.EntitlementsHash(old.payload.Ent) != license.EntitlementsHash(p.Ent) { + c.opts.onEntitlements(copyEnt(old.payload.Ent), copyEnt(p.Ent)) } return nil } +func copyEnt(in map[string]license.Entitlement) map[string]license.Entitlement { + out := make(map[string]license.Entitlement, len(in)) + for k, v := range in { + out[k] = v + } + return out +} + +// activationKey 返回当前可用的 license key(显式或自动激活回调)。 +func (c *Client) activationKey() string { + if c.opts.licenseKey != "" { + return c.opts.licenseKey + } + if c.opts.autoActivate != nil { + return c.opts.autoActivate() + } + return "" +} + +// Deactivate 主动停用并清理本地状态与缓存(docs/design/09-api-spec.md §2.4)。 +func (c *Client) Deactivate(ctx context.Context, reason string) error { + c.mu.Lock() + token := c.actToken + c.mu.Unlock() + if token == "" { + return errors.New("sdk: 当前没有可停用的激活凭证") + } + if c.opts.proxyAddr != "" { + return errors.New("sdk: 代理模式不支持客户端停用(由 Proxy/上游回收)") + } + if reason == "" { + reason = "sdk-deactivate" + } + if err := c.postNoContent(ctx, "/v1/deactivate", token, map[string]any{"reason": reason}); err != nil { + return err + } + c.mu.Lock() + c.actToken = "" + c.mu.Unlock() + c.snap.Store(&snapshot{state: StateUnverified}) + c.clearCache() + c.opts.logger.Info("已停用激活", "logger", "pkg.sdk.Client.Deactivate") + return nil +} + // tick 周期性重估:过期迁移、宽限耗尽、文件重载。测试直接调用以推进假时钟。 func (c *Client) tick() { const logField = "pkg.sdk.Client.tick" @@ -287,7 +411,7 @@ func (c *Client) tick() { if s == nil || s.payload == nil { return } - now := c.opts.clock.Now() + now := c.trustedNow() // 终态不迁移 if s.state == StateRevoked || s.state == StateInvalid { return @@ -338,6 +462,22 @@ func (c *Client) forcedCheckDue(s *snapshot, now int64) bool { return last > 0 && now-last >= forced } +// startMode 返回启动模式(用于测试/诊断)。 +func (c *Client) startMode() string { + switch { + case c.opts.licenseFile != "": + return "file" + case len(c.opts.licenseBytes) > 0 && c.opts.remoteServer == "" && c.opts.proxyAddr == "": + return "bytes" + case c.opts.proxyAddr != "": + return "proxy" + case c.opts.remoteServer != "": + return "remote" + default: + return "none" + } +} + // validateOnline 调用 /v1/validate 并验签 verdict;成功则刷新强制校验计时。 func (c *Client) validateOnline(ctx context.Context) error { const logField = "pkg.sdk.Client.validateOnline" diff --git a/sdk/query.go b/sdk/query.go index 1c09d73..bf29cb7 100644 --- a/sdk/query.go +++ b/sdk/query.go @@ -27,9 +27,20 @@ func (c *Client) usable() bool { } // Enabled 布尔开关查询;未授权或状态不可用一律 false(docs/design/05-entitlement-model.md §4 规则 1)。 +// WithGracePolicy(GraceKeepBooleans) 时,EXPIRED 后仍放行 payload 中为 true 的布尔 Feature。 func (c *Client) Enabled(fid string) bool { - ok, _ := c.Check(fid) - return ok + if ok, _ := c.Check(fid); ok { + return true + } + if c.opts.gracePolicy != GraceKeepBooleans || c.State() != StateExpired { + return false + } + s := c.snap.Load() + if s == nil || s.payload == nil { + return false + } + ent, ok := s.payload.Ent[fid] + return ok && ent.AsBool() } // Quantity 数量配额查询;未授权返回 0。 diff --git a/sdk/remote.go b/sdk/remote.go index c7768c7..58189d3 100644 --- a/sdk/remote.go +++ b/sdk/remote.go @@ -47,14 +47,17 @@ func (c *Client) Activate(ctx context.Context, licenseKey string) error { if err := c.postJSON(ctx, "/v1/activate", "", body, &resp); err != nil { return err } + c.applyServerTime(resp.ServerTime) if err := c.installVerified(resp.Lease); err != nil { return fmt.Errorf("sdk: 服务端 lease 验证失败: %w", err) } c.mu.Lock() c.actToken = resp.Token - c.heartbeatEvery = resp.HeartbeatInterval + c.heartbeatEvery = c.effectiveHeartbeat(resp.HeartbeatInterval) c.gracePeriod = resp.GracePeriod c.mu.Unlock() + c.fromCache = false + c.saveCache() c.opts.logger.Info("激活成功", "logger", logField, "activation", resp.ActivationID) return nil } @@ -69,6 +72,7 @@ type activateResp struct { LeaseTTL int64 `json:"lease_ttl"` HeartbeatInterval int64 `json:"heartbeat_interval"` GracePeriod int64 `json:"grace_period"` + ServerTime int64 `json:"server_time"` } type heartbeatResp struct { @@ -156,6 +160,8 @@ func (c *Client) renewProxy(ctx context.Context) error { if s.state == StateGrace { c.transition(c.snap.Load(), StateActive, 0) } + c.fromCache = false + c.saveCache() return nil } @@ -183,9 +189,19 @@ func (c *Client) heartbeatOnce(ctx context.Context) error { var resp heartbeatResp err := c.postJSON(ctx, "/v1/heartbeat", token, body, &resp) if err != nil { + var se *statusError + if errors.As(err, &se) && (se.code == http.StatusUnauthorized || se.code == http.StatusGone) { + if key := c.activationKey(); key != "" { + c.opts.logger.Info("激活凭证失效,尝试重新激活", "logger", logField, "status", se.code) + if aerr := c.Activate(ctx, key); aerr == nil { + return nil + } + } + } c.enterGrace(grace, err) return err } + c.applyServerTime(resp.ServerTime) // 先应用 CRL:命中当前 jti 直接转 REVOKED(docs/design/04-crypto.md §4) if resp.CRL != "" { @@ -215,6 +231,11 @@ func (c *Client) heartbeatOnce(ctx context.Context) error { ns := c.snap.Load() c.transition(ns, StateActive, 0) } + c.mu.Lock() + c.heartbeatEvery = c.effectiveHeartbeat(c.heartbeatEvery) + c.mu.Unlock() + c.fromCache = false + c.saveCache() _ = grace return nil } @@ -292,12 +313,46 @@ func (c *Client) postJSONTo(ctx context.Context, base, path, bearer string, body defer resp.Body.Close() raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if resp.StatusCode != http.StatusOK { - return fmt.Errorf("sdk: %s 状态码 %d", path, resp.StatusCode) + return &statusError{path: path, code: resp.StatusCode} } return json.Unmarshal(raw, out) } -const sdkVersion = "0.1.0" +// statusError 携带 HTTP 状态码(心跳据此判断是否需要重新激活)。 +type statusError struct { + path string + code int +} + +func (e *statusError) Error() string { return fmt.Sprintf("sdk: %s 状态码 %d", e.path, e.code) } + +// postNoContent 发送 POST 并接受 200/204(停用端点)。 +func (c *Client) postNoContent(ctx context.Context, path, bearer string, body any) error { + b, err := json.Marshal(body) + if err != nil { + return err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.opts.remoteServer+path, bytes.NewReader(b)) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + if bearer != "" { + req.Header.Set("Authorization", "Bearer "+bearer) + } + resp, err := c.hc.Do(req) + if err != nil { + return fmt.Errorf("sdk: 请求 %s: %w", path, err) + } + defer resp.Body.Close() //nolint:errcheck,gosec + io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20)) //nolint:errcheck,gosec + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent { + return &statusError{path: path, code: resp.StatusCode} + } + return nil +} + +const sdkVersion = "0.4.0" // defaultFingerprint 是自动采集失败时的最后退路(仅 hostname),用于无绑定 license 的席位标识。 // 有 bind.fp 的 license 在文件模式会 fail-closed(见 MachineFingerprint / verifyToken)。 diff --git a/sdk/v04_test.go b/sdk/v04_test.go new file mode 100644 index 0000000..69cb2f2 --- /dev/null +++ b/sdk/v04_test.go @@ -0,0 +1,330 @@ +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) + } +}