feat(sdk): 支持编译截止授权模式与 OUTDATED 降级状态
sdk-ci / test (push) Successful in 2m19s
sdk-release / release (push) Failing after 49s
sdk-release / cleanup (push) Successful in 6s

- payload 新增 bc(编译截止 Unix 秒)/bcm(deny|degrade),结构校验拒绝负值与非法动作
- SDK 支持 WithBuildTime/WithBuildTimeUnix 与 ldflags BuildTime 注入;未提供构建时间时 fail-closed
- degrade 模式进入 OUTDATED 状态,授权查询零值但进程继续运行;修复心跳/Proxy 续租覆盖该状态的隐患
- 缓存恢复路径同样执行截止判定;无截止的存量 license 行为不变
- 补充 license/sdk 单元测试与状态迁移回归用例
This commit is contained in:
iceking2nd committed 2026-11-17 13:19:23 +08:00
1 parent fc4ef4e644
commit 431cf3feae
9 files changed
+631 -30

No files matched your search

+100 -8
View File
@@ -10,6 +10,7 @@ import (
"log/slog"
"net/http"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
@@ -29,6 +30,8 @@ const (
StateExpired State = "EXPIRED"
StateRevoked State = "REVOKED"
StateInvalid State = "INVALID"
// StateOutdated 表示应用编译时间晚于 license 的编译截止(bcm=degrade)。
StateOutdated State = "OUTDATED"
)
// Reason 是 Check 的机器可读原因。
@@ -42,6 +45,7 @@ const (
ReasonStateRevoked Reason = "STATE_REVOKED"
ReasonStateInvalid Reason = "STATE_INVALID"
ReasonStateUnverified Reason = "STATE_UNVERIFIED"
ReasonStateOutdated Reason = "STATE_OUTDATED"
)
// Clock 提供可信时间(测试注入用假时钟)。
@@ -54,6 +58,12 @@ 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
@@ -66,6 +76,8 @@ type options struct {
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
@@ -138,10 +150,48 @@ func WithFingerprint(fp string) Option { return func(o *options) { o.fingerprint
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 } }
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 } }
@@ -244,6 +294,12 @@ func New(opts ...Option) (*Client, error) {
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 {
@@ -403,19 +459,55 @@ func (c *Client) verifyToken(token string) (*license.Payload, error) {
return p, nil
}
// installVerified 以验证通过的 token 换装快照(ACTIVE)。
// 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: StateActive}
ns := &snapshot{payload: p, rawToken: token, state: state}
c.snap.Store(ns)
c.observeWallClock()
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.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) {