- SDK-01:时钟回拨补偿只做一次(水位线跟随回拨后的时钟),避免 trustedNow 重复膨胀 - SDK-02:代理请求显式传 proxyAddr,消除运行期改写共享 opts 的数据竞争 - SDK-03:Decode 增加 256KB 结构层上限(与服务端 license 字节流上限对齐) - SDK-04:修正 license key 熵注释为 80bit - SDK-05:兼容服务端 version=0 空 CRL(携带吊销条目仍拒绝) - SDK-06:Validate 状态显式枚举,UNKNOWN/空值给出明确 fail-closed 错误 - SDK-08:缓存密钥混合 0600 随机 secret(旧 HKDF(指纹) 缓存读取后自动迁移) - SDK-07:README 记录 proxycert/Proxy 公钥旁路分发的设计信任假设 - 新增对应回归测试,go test -race -shuffle=on 全绿
766 lines
25 KiB
Go
766 lines
25 KiB
Go
// Package sdk 是嵌入客户端的益铸(EntitleForge)Go SDK。
|
||
// 设计依据:docs/design/07-sdk.md。目标:零重依赖(仅标准库 + internal 共享实现)、
|
||
// 集成三行起步、验证失败走状态机而非 panic、查询永不阻塞(atomic 快照)。
|
||
package sdk
|
||
|
||
import (
|
||
"context"
|
||
"errors"
|
||
"fmt"
|
||
"log/slog"
|
||
"net/http"
|
||
"os"
|
||
"strconv"
|
||
"strings"
|
||
"sync"
|
||
"sync/atomic"
|
||
"time"
|
||
|
||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/crypto"
|
||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
|
||
)
|
||
|
||
// State 是授权运行状态(docs/design/07-sdk.md §5)。
|
||
type State string
|
||
|
||
const (
|
||
StateUnverified State = "UNVERIFIED"
|
||
StateActive State = "ACTIVE"
|
||
StateGrace State = "GRACE"
|
||
StateExpired State = "EXPIRED"
|
||
StateRevoked State = "REVOKED"
|
||
StateInvalid State = "INVALID"
|
||
// StateOutdated 表示应用编译时间晚于 license 的编译截止(bcm=degrade)。
|
||
StateOutdated State = "OUTDATED"
|
||
)
|
||
|
||
// 服务端 /v1/validate 的状态枚举(docs/design/09-api-spec.md §2.3)。
|
||
// UNKNOWN 表示服务端无法确认该 license(不存在/验签失败/轮换异常),
|
||
// 与 REVOKED/EXPIRED 的明确拒绝语义区分(SDK-06)。
|
||
const (
|
||
validateStateActive = "ACTIVE"
|
||
validateStateRevoked = "REVOKED"
|
||
validateStateExpired = "EXPIRED"
|
||
validateStateUnknown = "UNKNOWN"
|
||
)
|
||
|
||
// Reason 是 Check 的机器可读原因。
|
||
type Reason string
|
||
|
||
const (
|
||
ReasonOK Reason = "OK"
|
||
ReasonNotEntitled Reason = "NOT_ENTITLED"
|
||
ReasonStateGrace Reason = "STATE_GRACE"
|
||
ReasonStateExpired Reason = "STATE_EXPIRED"
|
||
ReasonStateRevoked Reason = "STATE_REVOKED"
|
||
ReasonStateInvalid Reason = "STATE_INVALID"
|
||
ReasonStateUnverified Reason = "STATE_UNVERIFIED"
|
||
ReasonStateOutdated Reason = "STATE_OUTDATED"
|
||
)
|
||
|
||
// Clock 提供可信时间(测试注入用假时钟)。
|
||
type Clock interface{ Now() int64 }
|
||
|
||
type wallClock struct{}
|
||
|
||
func (wallClock) Now() int64 { return time.Now().Unix() }
|
||
|
||
// defaultTierOrder 是未注入档位序时的兜底(docs/design/05-entitlement-model.md §2.2)。
|
||
var defaultTierOrder = []string{"free", "starter", "pro", "business", "enterprise", "ultimate"}
|
||
|
||
// BuildTime 是宿主应用的编译时间注入点,供构建时通过
|
||
// -ldflags -X 'git.wxccs.org/EntitleForge/EntitleForge-SDK-go/sdk.BuildTime=...'
|
||
// 写入(RFC3339 或 Unix 秒)。WithBuildTime 优先级更高。
|
||
// license 携带编译截止(payload.bc)而未提供该值时按 fail-closed 处理。
|
||
var BuildTime string
|
||
|
||
type options struct {
|
||
licenseFile string
|
||
licenseBytes []byte
|
||
remoteServer string
|
||
licenseKey string
|
||
productKey string
|
||
fingerprint string
|
||
fingerprintFn func() (string, error)
|
||
trust *crypto.TrustChain
|
||
tierOrder []string
|
||
clock Clock
|
||
logger *slog.Logger
|
||
buildTime int64
|
||
buildTimeSet bool
|
||
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 } }
|
||
|
||
// 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 } }
|
||
|
||
// WithFingerprint 显式指定机器指纹;省略时 SDK 自动采集(见 MachineFingerprint)。
|
||
// 自定义采集(如容器内读取挂载的宿主 machine-id)使用 WithFingerprintFunc。
|
||
func WithFingerprint(fp string) Option { return func(o *options) { o.fingerprint = fp } }
|
||
|
||
// WithFingerprintFunc 自定义机器指纹采集器;仅在未显式 WithFingerprint 时生效。
|
||
func WithFingerprintFunc(fn func() (string, error)) Option {
|
||
return func(o *options) { o.fingerprintFn = fn }
|
||
}
|
||
func WithTrustChain(tc *crypto.TrustChain) Option { return func(o *options) { o.trust = tc } }
|
||
func WithTierOrder(order []string) Option { return func(o *options) { o.tierOrder = order } }
|
||
func WithClock(c Clock) Option { return func(o *options) { o.clock = c } }
|
||
func WithLogger(l *slog.Logger) Option { return func(o *options) { o.logger = l } }
|
||
|
||
// WithBuildTime 显式注入宿主应用的编译时间(优先级高于 BuildTime 注入变量)。
|
||
// license 带编译截止(payload.bc)时会与之比较;缺失时按 fail-closed 处理。
|
||
func WithBuildTime(t time.Time) Option {
|
||
return func(o *options) {
|
||
if t.IsZero() {
|
||
return
|
||
}
|
||
o.buildTime = t.Unix()
|
||
o.buildTimeSet = true
|
||
}
|
||
}
|
||
|
||
// WithBuildTimeUnix 以 Unix 秒注入宿主应用编译时间(ts<=0 视为未提供)。
|
||
func WithBuildTimeUnix(ts int64) Option {
|
||
return func(o *options) {
|
||
if ts <= 0 {
|
||
return
|
||
}
|
||
o.buildTime = ts
|
||
o.buildTimeSet = true
|
||
}
|
||
}
|
||
|
||
// parseBuildTimeValue 接受 RFC3339/RFC3339Nano 或 Unix 秒(构建脚本注入)。
|
||
func parseBuildTimeValue(raw string) (int64, bool) {
|
||
raw = strings.TrimSpace(raw)
|
||
if raw == "" {
|
||
return 0, false
|
||
}
|
||
if t, err := time.Parse(time.RFC3339Nano, raw); err == nil {
|
||
return t.Unix(), true
|
||
}
|
||
if n, err := strconv.ParseInt(raw, 10, 64); err == nil && n > 0 {
|
||
return n, true
|
||
}
|
||
return 0, false
|
||
}
|
||
func WithOnStateChange(cb func(from, to State)) Option { return func(o *options) { o.onState = cb } }
|
||
func WithPollInterval(d time.Duration) Option { return func(o *options) { o.pollInterval = d } }
|
||
|
||
// WithValidationServer 配置文件模式强制校验点使用的在线校验源(License Server 基址)。
|
||
// 未配置时,带 forced_check 的离线 license 只告警不强制(保持完全离线兼容)。
|
||
func WithValidationServer(baseURL string) Option {
|
||
return func(o *options) { o.validationServer = strings.TrimSuffix(baseURL, "/") }
|
||
}
|
||
|
||
// WithProxy 集群内代理模式(http://ef-proxy.ef-system.svc:8443)。
|
||
func WithProxy(addr string) Option { return func(o *options) { o.proxyAddr = addr } }
|
||
|
||
// WithSAToken 注入 ServiceAccount Token(attest 用;测试或外部刷新场景)。
|
||
func WithSAToken(tok string) Option { return func(o *options) { o.saToken = tok } }
|
||
|
||
// WithSATokenFile projected token 文件路径(K8s 内自动读取)。
|
||
func WithSATokenFile(path string) Option { return func(o *options) { o.saTokenFile = path } }
|
||
|
||
// snapshot 是不可变授权快照(读侧 atomic,写侧整包换装)。
|
||
type snapshot struct {
|
||
payload *license.Payload
|
||
rawToken string
|
||
state State
|
||
// GRACE 计时:进入 GRACE 时刻 + gracePeriod(wall 秒);0 表示无宽限约束
|
||
graceDeadline int64
|
||
}
|
||
|
||
// Client 是 SDK 入口。并发安全。
|
||
type Client struct {
|
||
opts options
|
||
snap atomic.Pointer[snapshot]
|
||
hc httpClient
|
||
stop chan struct{}
|
||
once sync.Once
|
||
|
||
mu sync.Mutex // 保护激活凭据与远程配置
|
||
actToken string
|
||
heartbeatEvery int64
|
||
gracePeriod int64
|
||
|
||
crlVersion atomic.Int64 // 最近应用/上报的 CRL 版本
|
||
lastCheckAt atomic.Int64 // 最近一次在线校验成功时刻(强制校验点计时)
|
||
clockSkew atomic.Int64 // 服务端时间 - 本地时间(trustedNow = 本地 + skew)
|
||
lastWall atomic.Int64 // 最近观测到的本地墙钟(回拨检测)
|
||
noCheckWarn sync.Once
|
||
fromCache bool
|
||
backoffBase time.Duration // 测试可缩短
|
||
backoffMax time.Duration
|
||
|
||
cacheSecretOnce sync.Once
|
||
cacheSecretVal []byte
|
||
cacheSecretErr error
|
||
}
|
||
|
||
// trustedNow 返回经 server_time 校正的可信时间。
|
||
func (c *Client) trustedNow() int64 {
|
||
return c.opts.clock.Now() + c.clockSkew.Load()
|
||
}
|
||
|
||
// observeWallClock 检测本地时钟回拨:发现倒退超过 60s 时补偿 skew,
|
||
// 保证 trustedNow 不随墙钟回拨而倒退(docs/design/12-security.md T7)。
|
||
func (c *Client) observeWallClock() {
|
||
now := c.opts.clock.Now()
|
||
prev := c.lastWall.Load()
|
||
if prev > 0 && now < prev-60 {
|
||
delta := prev - now
|
||
c.clockSkew.Add(delta)
|
||
c.opts.logger.Warn("检测到系统时钟回拨,已补偿可信时间",
|
||
"logger", "pkg.sdk.Client.observeWallClock", "rollback_seconds", delta)
|
||
// 水位线跟随回拨后的时钟:同一回拨事件只补偿一次,
|
||
// 否则恢复期内每个 tick 会重复累加 skew(SDK-01)。
|
||
c.lastWall.Store(now)
|
||
return
|
||
}
|
||
if now > prev {
|
||
c.lastWall.Store(now)
|
||
}
|
||
}
|
||
|
||
// applyServerTime 用服务端时间更新本地偏移估计。
|
||
func (c *Client) applyServerTime(serverTime int64) {
|
||
if serverTime <= 0 {
|
||
return
|
||
}
|
||
c.observeWallClock()
|
||
c.clockSkew.Store(serverTime - c.opts.clock.Now())
|
||
}
|
||
|
||
// New 创建 Client。
|
||
// 文件模式:立即加载并验证(失败返回错误)。
|
||
// 远程模式:验证推迟到 Start 的自动激活。
|
||
func New(opts ...Option) (*Client, error) {
|
||
o := options{clock: wallClock{}, pollInterval: 30 * time.Second, logger: slog.Default()}
|
||
for _, opt := range opts {
|
||
opt(&o)
|
||
}
|
||
if o.productKey == "" {
|
||
return nil, errors.New("sdk: 需要 WithProductKey")
|
||
}
|
||
if o.trust == nil {
|
||
return nil, errors.New("sdk: 需要 WithTrustChain(SDK 须锚定 root 公钥)")
|
||
}
|
||
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
|
||
}
|
||
// 未显式注入时读取 -ldflags -X 注入的 BuildTime(只解析一次)。
|
||
if !o.buildTimeSet {
|
||
if ts, ok := parseBuildTimeValue(BuildTime); ok {
|
||
o.buildTime, o.buildTimeSet = ts, true
|
||
}
|
||
}
|
||
|
||
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
|
||
}
|
||
|
||
// Start 启动后台循环:文件轮询 / 远程心跳。
|
||
func (c *Client) Start(ctx context.Context) error {
|
||
const logField = "pkg.sdk.Client.Start"
|
||
|
||
// 在线/代理模式优先;文件/字节 license 作为不可达时的兜底基线(模式叠加)。
|
||
if c.opts.remoteServer != "" || c.opts.proxyAddr != "" {
|
||
if c.opts.remoteServer != "" {
|
||
key := c.activationKey()
|
||
// 缓存恢复的 GRACE 无需立即激活;心跳 401/410 时会自动重激活
|
||
if key != "" && !c.fromCache {
|
||
if err := c.Activate(ctx, key); err != nil {
|
||
if !c.fallbackAvailable() {
|
||
return fmt.Errorf("sdk: 自动激活: %w", err)
|
||
}
|
||
c.opts.logger.Warn("远程激活失败,使用文件 license 兜底",
|
||
"logger", logField, "error", err)
|
||
}
|
||
} else if c.State() == StateUnverified {
|
||
return errors.New("sdk: 远程模式需要 WithLicenseKey/WithAutoActivate(或先手动 Activate)")
|
||
}
|
||
c.opts.logger.Info("SDK 远程模式已启动", "logger", logField, "server", c.opts.remoteServer)
|
||
} else {
|
||
if !c.fromCache {
|
||
if err := c.attestProxy(ctx); err != nil {
|
||
if !c.fallbackAvailable() {
|
||
return fmt.Errorf("sdk: 代理认证: %w", err)
|
||
}
|
||
c.opts.logger.Warn("代理认证失败,使用文件 license 兜底",
|
||
"logger", logField, "error", err)
|
||
}
|
||
}
|
||
c.opts.logger.Info("SDK 代理模式已启动", "logger", logField, "proxy", c.opts.proxyAddr)
|
||
}
|
||
go c.heartbeatLoop(ctx)
|
||
go c.tickLoop(ctx)
|
||
return nil
|
||
}
|
||
if c.opts.licenseFile != "" {
|
||
go c.fileLoop(ctx)
|
||
c.opts.logger.Info("SDK 文件模式已启动", "logger", logField, "file", c.opts.licenseFile)
|
||
return nil
|
||
}
|
||
if len(c.opts.licenseBytes) > 0 {
|
||
go c.tickLoop(ctx)
|
||
c.opts.logger.Info("SDK 内存 license 模式已启动", "logger", logField)
|
||
return nil
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// fallbackAvailable 报告是否存在可用的文件/字节 license 基线。
|
||
func (c *Client) fallbackAvailable() bool {
|
||
if c.opts.licenseFile == "" && len(c.opts.licenseBytes) == 0 {
|
||
return false
|
||
}
|
||
st := c.State()
|
||
return st == StateActive || st == StateGrace
|
||
}
|
||
|
||
// tickLoop 周期性推进过期/宽限/强制校验(在线模式也运行,文件热重载由 fileLoop 负责)。
|
||
func (c *Client) tickLoop(ctx context.Context) {
|
||
ticker := time.NewTicker(c.opts.pollInterval)
|
||
defer ticker.Stop()
|
||
for {
|
||
select {
|
||
case <-c.stop:
|
||
return
|
||
case <-ctx.Done():
|
||
return
|
||
case <-ticker.C:
|
||
c.tick()
|
||
}
|
||
}
|
||
}
|
||
|
||
// Close 停止后台循环(幂等)。
|
||
func (c *Client) Close() error {
|
||
c.once.Do(func() { close(c.stop) })
|
||
return nil
|
||
}
|
||
|
||
// State 返回当前授权状态。
|
||
func (c *Client) State() State {
|
||
s := c.snap.Load()
|
||
if s == nil {
|
||
return StateUnverified
|
||
}
|
||
return s.state
|
||
}
|
||
|
||
// ---- 状态迁移(唯一入口,回调在此触发) ----
|
||
|
||
func (c *Client) transition(s *snapshot, to State, graceDeadline int64) {
|
||
if s.state == to {
|
||
if s.graceDeadline == graceDeadline {
|
||
return
|
||
}
|
||
} else {
|
||
c.opts.logger.Info("状态迁移", "logger", "pkg.sdk.Client.transition",
|
||
"from", string(s.state), "to", string(to))
|
||
}
|
||
from := s.state
|
||
ns := *s
|
||
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)
|
||
}
|
||
}
|
||
|
||
// verifyToken 验证并装载一个 license/lease token(信任链 + 产品匹配 + 时间窗)。
|
||
func (c *Client) verifyToken(token string) (*license.Payload, error) {
|
||
p, err := crypto.VerifyToken(token, c.opts.trust, c.trustedNow())
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if p.Prod != c.opts.productKey {
|
||
return nil, fmt.Errorf("sdk: 产品不符(license=%s, 期望=%s)", p.Prod, c.opts.productKey)
|
||
}
|
||
// bind.fp 存在时必须校验:显式指纹 > 自定义采集器 > 默认机器采集;采集失败 fail-closed。
|
||
if p.Bind != nil && p.Bind.FP != "" {
|
||
fp, err := c.effectiveFingerprint()
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if fp != p.Bind.FP {
|
||
return nil, errors.New("sdk: 机器指纹绑定不符")
|
||
}
|
||
}
|
||
return p, nil
|
||
}
|
||
|
||
// buildCutoffDecision 依据签名 payload 的编译截止判定应用是否可运行。
|
||
// degrade=true 表示应以 OUTDATED 状态装载(查询零值);err != nil 表示拒绝。
|
||
func (c *Client) buildCutoffDecision(p *license.Payload) (degrade bool, err error) {
|
||
const logField = "pkg.sdk.Client.buildCutoffDecision"
|
||
if p.BC <= 0 {
|
||
return false, nil
|
||
}
|
||
action := p.EffectiveBuildCutoffAction()
|
||
if !c.opts.buildTimeSet {
|
||
c.opts.logger.Warn("license 含编译截止但应用未提供编译时间",
|
||
"logger", logField, "bc", p.BC, "action", action)
|
||
if action == license.BuildCutoffDegrade {
|
||
return true, nil
|
||
}
|
||
return false, fmt.Errorf("%w(bc=%d)", license.ErrBuildTimeUnknown, p.BC)
|
||
}
|
||
if !p.BuildCutoffExceeded(c.opts.buildTime) {
|
||
return false, nil
|
||
}
|
||
c.opts.logger.Warn("应用编译时间超出授权截止",
|
||
"logger", logField, "bc", p.BC, "build_time", c.opts.buildTime, "action", action)
|
||
if action == license.BuildCutoffDegrade {
|
||
return true, nil
|
||
}
|
||
return false, fmt.Errorf("%w(build_time=%d, bc=%d)", license.ErrBuildCutoff, c.opts.buildTime, p.BC)
|
||
}
|
||
|
||
// installVerified 以验证通过的 token 换装快照(ACTIVE;编译截止降级时为 OUTDATED)。
|
||
func (c *Client) installVerified(token string) error {
|
||
p, err := c.verifyToken(token)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
degrade, err := c.buildCutoffDecision(p)
|
||
if err != nil {
|
||
return err
|
||
}
|
||
state := StateActive
|
||
if degrade {
|
||
state = StateOutdated
|
||
}
|
||
old := c.snap.Load()
|
||
ns := &snapshot{payload: p, rawToken: token, state: state}
|
||
c.snap.Store(ns)
|
||
c.observeWallClock()
|
||
c.lastCheckAt.Store(c.trustedNow())
|
||
if old == nil || old.state != state {
|
||
c.opts.logger.Info("授权已装载", "logger", "pkg.sdk.Client.installVerified",
|
||
"jti", p.JTI, "state", string(state))
|
||
}
|
||
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"
|
||
s := c.snap.Load()
|
||
if s == nil || s.payload == nil {
|
||
return
|
||
}
|
||
c.observeWallClock()
|
||
now := c.trustedNow()
|
||
// 终态不迁移
|
||
if s.state == StateRevoked || s.state == StateInvalid {
|
||
return
|
||
}
|
||
// 时间窗检查(ACTIVE 下 license 自然过期)
|
||
if err := s.payload.TimeValid(now, crypto.DefaultClockSkewSeconds); err != nil {
|
||
c.transition(s, StateExpired, 0)
|
||
return
|
||
}
|
||
// 宽限耗尽
|
||
if s.state == StateGrace && s.graceDeadline != 0 && now > s.graceDeadline {
|
||
c.opts.logger.Warn("宽限期已耗尽", "logger", logField)
|
||
c.transition(s, StateExpired, 0)
|
||
return
|
||
}
|
||
// 离线强制校验点:到期必须成功在线校验一次,否则 EXPIRED(docs/design/07-sdk.md §6.4)
|
||
if c.forcedCheckDue(s, now) {
|
||
if err := c.validateOnline(context.Background()); err != nil {
|
||
c.opts.logger.Warn("强制在线校验失败,进入 EXPIRED", "logger", logField, "error", err)
|
||
c.transition(s, StateExpired, 0)
|
||
return
|
||
}
|
||
}
|
||
// 文件模式:热重载
|
||
if c.opts.licenseFile != "" {
|
||
c.reloadIfChanged()
|
||
}
|
||
}
|
||
|
||
// forcedCheckDue 判断是否到达强制校验点:
|
||
// 仅文件模式、payload 携带 pol.forced_check>0 且配置了校验源时生效。
|
||
func (c *Client) forcedCheckDue(s *snapshot, now int64) bool {
|
||
if c.opts.licenseFile == "" || s.payload == nil || s.payload.Pol == nil {
|
||
return false
|
||
}
|
||
forced := s.payload.Pol.ForcedCheck
|
||
if forced <= 0 {
|
||
return false
|
||
}
|
||
if c.opts.validationServer == "" {
|
||
c.noCheckWarn.Do(func() {
|
||
c.opts.logger.Warn("license 含 forced_check 但未配置 WithValidationServer,跳过强制在线校验",
|
||
"logger", "pkg.sdk.Client.forcedCheckDue", "forced_check", forced)
|
||
})
|
||
return false
|
||
}
|
||
last := c.lastCheckAt.Load()
|
||
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"
|
||
s := c.snap.Load()
|
||
if s == nil || s.rawToken == "" {
|
||
return errors.New("sdk: 无已装载 license,无法在线校验")
|
||
}
|
||
body := map[string]any{"license": s.rawToken, "crl_version": c.crlVersion.Load()}
|
||
var resp struct {
|
||
Valid bool `json:"valid"`
|
||
State string `json:"state"`
|
||
Verdict string `json:"verdict"`
|
||
CRL string `json:"crl"`
|
||
CRLVersion int64 `json:"crl_version"`
|
||
}
|
||
if err := c.postJSONTo(ctx, c.opts.validationServer, "/v1/validate", "", body, &resp); err != nil {
|
||
return fmt.Errorf("在线校验请求: %w", err)
|
||
}
|
||
if resp.CRL != "" {
|
||
if _, _, err := c.opts.trust.LoadCRL(resp.CRL); err != nil {
|
||
c.opts.logger.Warn("在线校验响应 CRL 验签失败,已忽略", "logger", logField, "error", err)
|
||
}
|
||
}
|
||
switch resp.State {
|
||
case validateStateActive:
|
||
if !resp.Valid {
|
||
return errors.New("服务端 state=ACTIVE 但 valid=false,按不可用处理")
|
||
}
|
||
case validateStateRevoked:
|
||
return errors.New("服务端判定 license 已吊销(state=REVOKED)")
|
||
case validateStateExpired:
|
||
return errors.New("服务端判定 license 已过期(state=EXPIRED)")
|
||
case validateStateUnknown, "":
|
||
return fmt.Errorf("服务端无法确认 license 状态(state=%q),按 fail-closed 处理", resp.State)
|
||
default:
|
||
return fmt.Errorf("服务端返回未识别状态 %q,按 fail-closed 处理", resp.State)
|
||
}
|
||
v, err := c.opts.trust.VerifyVerdict(resp.Verdict, c.opts.clock.Now())
|
||
if err != nil {
|
||
return fmt.Errorf("verdict 验签: %w", err)
|
||
}
|
||
if v.JTI != s.payload.JTI || v.State != validateStateActive {
|
||
return fmt.Errorf("verdict 与本地 license 不一致(jti=%s state=%s)", v.JTI, v.State)
|
||
}
|
||
c.lastCheckAt.Store(c.opts.clock.Now())
|
||
c.opts.logger.Debug("强制在线校验通过", "logger", logField, "jti", v.JTI)
|
||
return nil
|
||
}
|
||
|
||
// applyCRL 应用服务端下发的 CRL;命中当前快照时立即迁移 REVOKED。
|
||
func (c *Client) applyCRL(token string) {
|
||
const logField = "pkg.sdk.Client.applyCRL"
|
||
version, applied, err := c.opts.trust.LoadCRL(token)
|
||
if err != nil {
|
||
c.opts.logger.Warn("CRL 验签失败,已忽略", "logger", logField, "error", err)
|
||
return
|
||
}
|
||
if version > c.crlVersion.Load() {
|
||
c.crlVersion.Store(version)
|
||
}
|
||
if !applied {
|
||
return
|
||
}
|
||
c.opts.logger.Info("CRL 已更新", "logger", logField, "version", version)
|
||
s := c.snap.Load()
|
||
if s != nil && s.payload != nil && c.opts.trust.IsRevoked(s.payload.JTI) {
|
||
c.transition(s, StateRevoked, 0)
|
||
}
|
||
}
|
||
|
||
// ---- 文件模式 ----
|
||
|
||
func (c *Client) fileLoop(ctx context.Context) {
|
||
ticker := time.NewTicker(c.opts.pollInterval)
|
||
defer ticker.Stop()
|
||
for {
|
||
select {
|
||
case <-c.stop:
|
||
return
|
||
case <-ctx.Done():
|
||
return
|
||
case <-ticker.C:
|
||
c.tick()
|
||
}
|
||
}
|
||
}
|
||
|
||
func (c *Client) reloadFile() error {
|
||
data, err := os.ReadFile(c.opts.licenseFile)
|
||
if err != nil {
|
||
return fmt.Errorf("读取 license 文件: %w", err)
|
||
}
|
||
token := string(data)
|
||
return c.installVerified(token)
|
||
}
|
||
|
||
// reloadIfChanged 内容变化时热重载(mtime 秒级精度与等长替换不可靠,直接比对内容)。
|
||
func (c *Client) reloadIfChanged() {
|
||
data, err := os.ReadFile(c.opts.licenseFile)
|
||
if err != nil {
|
||
return
|
||
}
|
||
s := c.snap.Load()
|
||
if s != nil && s.rawToken == string(data) {
|
||
return // 内容未变
|
||
}
|
||
if err := c.installVerified(string(data)); err != nil {
|
||
// 热更新验证失败:保持旧快照并告警(不迁移 INVALID,旧授权仍有效)
|
||
c.opts.logger.Warn("license 文件热更新验证失败,保留旧快照", "logger", "pkg.sdk.Client.reloadIfChanged", "error", err)
|
||
}
|
||
}
|