feat(sdk): 加密缓存、GracePolicy、时钟校正与剩余规划 API
- 加密租约缓存(AES-256-GCM + HKDF(指纹)):重启恢复 GRACE,401/410 自动重新激活 - WithGracePolicy(KeepBooleans)、WithLicenseBytes、WithHeartbeatInterval、WithHTTPClient、WithAutoActivate、WithOnEntitlementsChange、Deactivate - 心跳/激活 server_time 参与可信时间校正 - 新增缓存/降级/时钟/重激活/回调测试
This commit is contained in:
6 files changed
+760
-17
No files matched your search
+152
-12
@@ -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"
|
||||
|
||||
Reference in new issue
Block a user