feat(sdk): 支持编译截止授权模式与 OUTDATED 降级状态

- 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 aad752913a
9 files changed
+616 -15

No files matched your search

+18 -1
View File
@@ -43,7 +43,7 @@ client.TierAtLeast("pro") // 档位比较
client.Check("module.x") // (bool, Reason)——GRACE/EXPIRED/REVOKED 精确原因
```
状态机:`UNVERIFIED → ACTIVE → GRACE(断连宽限)→ EXPIRED / REVOKED(终态)`。
状态机:`UNVERIFIED → ACTIVE → GRACE(断连宽限)→ EXPIRED / REVOKED(终态)`;编译截止超期且 `bcm=degrade` 时 `ACTIVE → OUTDATED`(查询零值,装载到更宽截止的 license 后恢复)。
## 机器绑定
@@ -60,6 +60,23 @@ client, err := sdk.New(..., sdk.WithFingerprintFunc(func() (string, error) {
Linux 采集 machine-id + DMI product_uuid;macOS 采集 IOPlatformUUID;容器内默认拒绝自动采集(容器自身 ID 不稳定),需挂载宿主 `/etc/machine-id` 并注入自定义采集器,或显式指定指纹。
## 编译截止(Build Cutoff,v0.7.0)
License payload 可携带 `bc`(编译截止 Unix 秒)与 `bcm`(`deny`/`degrade`):只允许编译时间不晚于截止的应用版本运行。宿主应用需显式提供编译时间:
```go
// 方式一:运行期注入
client, err := sdk.New(..., sdk.WithBuildTime(builtAt)) // time.Time
client, err := sdk.New(..., sdk.WithBuildTimeUnix(builtAtUnix)) // int64
// 方式二:构建时注入(RFC3339 或 Unix 秒)
// go build -ldflags "-X 'git.wxccs.org/EntitleForge/EntitleForge-SDK-go/sdk.BuildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)'" .
```
- 编译时间缺失且 License 带截止时 fail-closed:`deny`(默认)返回 `license.ErrBuildTimeUnknown` / `license.ErrBuildCutoff`;`degrade` 装载为 `OUTDATED`。
- `OUTDATED` 下 `Enabled/Quantity/Tier/Allows/Check` 全部零值,`Entitlements/Info` 可读;不会因网络故障进入 `GRACE`。
- 引用该模式的 License 必须要求客户端 SDK ≥ v0.7.0(旧 SDK 会忽略 `bc`/`bcm`)。
## 缓存与降级
```go
+35
View File
@@ -42,11 +42,19 @@ const (
StateRenewed = "renewed"
)
// 编译截止超期处置(payload.bcm)。空值等价于 deny。
const (
BuildCutoffDeny = "deny"
BuildCutoffDegrade = "degrade"
)
var (
ErrExpired = errors.New("license: 已过期")
ErrNotYetValid = errors.New("license: 尚未生效")
ErrMalformed = errors.New("license: 格式损坏")
ErrUnsupported = errors.New("license: 不支持的版本或算法")
ErrBuildCutoff = errors.New("license: 编译版本超出授权截止")
ErrBuildTimeUnknown = errors.New("license: 未提供应用编译时间,无法校验编译截止")
)
// Bindings 是部署绑定约束(docs/design/03-license-format.md §2.2 bind 字段)。
@@ -88,6 +96,8 @@ type Payload struct {
Pol *PolicySnapshot `json:"pol,omitempty"`
Proxy *ProxyScope `json:"proxy,omitempty"` // Proxy Key 派发的 lease 必带
ACT string `json:"act,omitempty"` // lease 关联的 activation_id / 工作负载身份
BC int64 `json:"bc,omitempty"` // 编译截止(Unix 秒);0=不限制
BCM string `json:"bcm,omitempty"` // 超期处置:deny(缺省)| degrade
ST string `json:"st"`
}
@@ -124,9 +134,34 @@ func (p *Payload) Validate() error {
if p.Ent == nil {
return fmt.Errorf("%w: ent 不允许为 null", ErrMalformed)
}
if p.BC < 0 {
return fmt.Errorf("%w: bc 不能为负数", ErrMalformed)
}
switch p.BCM {
case "", BuildCutoffDeny, BuildCutoffDegrade:
default:
return fmt.Errorf("%w: 未知 bcm %q", ErrMalformed, p.BCM)
}
if p.BC == 0 && p.BCM != "" {
return fmt.Errorf("%w: bcm 必须与 bc 同时出现", ErrMalformed)
}
return nil
}
// EffectiveBuildCutoffAction 返回生效的超期处置动作(bcm 缺省时为 deny)。
func (p *Payload) EffectiveBuildCutoffAction() string {
if p.BCM == "" {
return BuildCutoffDeny
}
return p.BCM
}
// BuildCutoffExceeded 判断应用编译时间是否晚于编译截止。
// 截止时刻本身允许(编译时间 ≤ bc);bc=0 表示不限制。
func (p *Payload) BuildCutoffExceeded(buildTime int64) bool {
return p.BC > 0 && buildTime > p.BC
}
// TimeValid 校验时间窗(now/skew 为 Unix 秒)。exp=0 表示永久。
func (p *Payload) TimeValid(now, skew int64) error {
if p.NBF > now+skew {
+93
View File
@@ -101,6 +101,99 @@ func TestPayload_Validate_Enums(t *testing.T) {
}
}
func TestPayload_BuildCutoffEnums(t *testing.T) {
cases := []struct {
name string
bc int64
bcm string
wantErr bool
}{
{"无截止", 0, "", false},
{"截止+默认动作", 1762665600, "", false},
{"截止+deny", 1762665600, BuildCutoffDeny, false},
{"截止+degrade", 1762665600, BuildCutoffDegrade, false},
{"负截止", -1, "", true},
{"未知动作", 1762665600, "allow", true},
{"有动作无截止", 0, BuildCutoffDegrade, true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
p := testPayload()
p.BC, p.BCM = tc.bc, tc.bcm
err := p.Validate()
if tc.wantErr && err == nil {
t.Error("应报错, got nil")
}
if !tc.wantErr && err != nil {
t.Errorf("不应报错: %v", err)
}
})
}
}
func TestPayload_BuildCutoffExceeded(t *testing.T) {
const cutoff = int64(1762665600)
cases := []struct {
name string
bc int64
buildTime int64
want bool
}{
{"无截止不限制", 0, cutoff + 86400, false},
{"截止前编译", cutoff, cutoff - 1, false},
{"恰在截止时刻编译(含)", cutoff, cutoff, false},
{"截止后编译", cutoff, cutoff + 1, true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
p := testPayload()
p.BC = tc.bc
if got := p.BuildCutoffExceeded(tc.buildTime); got != tc.want {
t.Errorf("BuildCutoffExceeded(%d) = %v, want %v", tc.buildTime, got, tc.want)
}
})
}
}
func TestPayload_EffectiveBuildCutoffAction(t *testing.T) {
p := testPayload()
p.BC = 1762665600
if got := p.EffectiveBuildCutoffAction(); got != BuildCutoffDeny {
t.Errorf("缺省动作应为 deny: %q", got)
}
p.BCM = BuildCutoffDegrade
if got := p.EffectiveBuildCutoffAction(); got != BuildCutoffDegrade {
t.Errorf("动作应为 degrade: %q", got)
}
}
func TestPayload_BuildCutoffJSON(t *testing.T) {
p := testPayload()
p.BC, p.BCM = 1762665600, BuildCutoffDegrade
raw, err := json.Marshal(&p)
if err != nil {
t.Fatalf("marshal: %v", err)
}
var got Payload
if err := json.Unmarshal(raw, &got); err != nil {
t.Fatalf("roundtrip: %v", err)
}
if got.BC != p.BC || got.BCM != p.BCM {
t.Errorf("roundtrip 不一致: bc=%d bcm=%q", got.BC, got.BCM)
}
// 无截止时省略字段(向前兼容)
p.BC, p.BCM = 0, ""
raw, _ = json.Marshal(&p)
var m map[string]any
_ = json.Unmarshal(raw, &m)
if _, ok := m["bc"]; ok {
t.Error("bc=0 时应省略字段")
}
if _, ok := m["bcm"]; ok {
t.Error("bcm 为空时应省略字段")
}
}
func TestPayload_TimeValid(t *testing.T) {
const skew = 600
base := int64(1762665600)
+341
View File
@@ -0,0 +1,341 @@
package sdk
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/sign"
)
// writeCutoffLicense 签发并写入测试 license 文件,返回路径。
func writeCutoffLicense(t *testing.T, e *testEnv, mut func(*license.Payload)) string {
t.Helper()
return writeLicense(t, e.sign(mut))
}
func TestBuildCutoff_DenyByDefault(t *testing.T) {
e := newEnv(t)
path := writeCutoffLicense(t, e, func(p *license.Payload) {
p.BC = e.now - 100 // 早于应用编译时间
})
clock := &fakeClock{now: e.now}
_, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock), WithBuildTimeUnix(e.now))
if !errors.Is(err, license.ErrBuildCutoff) {
t.Fatalf("应因编译截止拒绝,got %v", err)
}
}
func TestBuildCutoff_ExplicitDeny(t *testing.T) {
e := newEnv(t)
path := writeCutoffLicense(t, e, func(p *license.Payload) {
p.BC, p.BCM = e.now-100, license.BuildCutoffDeny
})
clock := &fakeClock{now: e.now}
_, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock), WithBuildTime(time.Unix(e.now+1, 0)))
if !errors.Is(err, license.ErrBuildCutoff) {
t.Fatalf("应因编译截止拒绝,got %v", err)
}
}
func TestBuildCutoff_WithinCutoff(t *testing.T) {
e := newEnv(t)
cutoff := e.now - 100
path := writeCutoffLicense(t, e, func(p *license.Payload) { p.BC = cutoff })
clock := &fakeClock{now: e.now}
c, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock), WithBuildTimeUnix(cutoff))
if err != nil {
t.Fatalf("截止时刻及之前编译应允许: %v", err)
}
if c.State() != StateActive {
t.Fatalf("状态: %s", c.State())
}
if !c.Enabled("module.audit-log") || c.Quantity("seats") != 50 {
t.Error("截止内应正常授权")
}
}
func TestBuildCutoff_Degrade(t *testing.T) {
e := newEnv(t)
cutoff := e.now - 100
path := writeCutoffLicense(t, e, func(p *license.Payload) {
p.BC, p.BCM = cutoff, license.BuildCutoffDegrade
})
clock := &fakeClock{now: e.now}
c, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock), WithBuildTimeUnix(cutoff+1))
if err != nil {
t.Fatalf("degrade 模式应允许进程启动: %v", err)
}
defer c.Close() //nolint:errcheck // 测试清理
if c.State() != StateOutdated {
t.Fatalf("状态: %s,期望 OUTDATED", c.State())
}
if c.Enabled("module.audit-log") {
t.Error("OUTDATED 下布尔开关应关闭")
}
if c.Quantity("seats") != 0 {
t.Error("OUTDATED 下数量应为 0")
}
if c.Tier() != "" {
t.Error("OUTDATED 下档位应为空")
}
if c.Allows("allowed-regions", "cn-north") {
t.Error("OUTDATED 下约束应为空集")
}
if _, reason := c.Check("module.audit-log"); reason != ReasonStateOutdated {
t.Errorf("Check reason: %s", reason)
}
// 管理展示仍可读取真实授权集合
if len(c.Entitlements()) != 4 {
t.Errorf("Entitlements 应可读: %d", len(c.Entitlements()))
}
info := c.Info()
if info.BuildCutoff != cutoff || info.BuildCutoffAction != license.BuildCutoffDegrade {
t.Errorf("Info 截止信息: %+v", info)
}
}
func TestBuildCutoff_MissingBuildTime(t *testing.T) {
oldBuildTime := BuildTime
BuildTime = ""
defer func() { BuildTime = oldBuildTime }()
e := newEnv(t)
cases := []struct {
name string
action string
wantState State
wantErr error
}{
{"缺省动作 fail-closed", "", "", license.ErrBuildTimeUnknown},
{"显式 deny", license.BuildCutoffDeny, "", license.ErrBuildTimeUnknown},
{"degrade 降级", license.BuildCutoffDegrade, StateOutdated, nil},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
path := writeCutoffLicense(t, e, func(p *license.Payload) {
p.BC, p.BCM = e.now+86400, tc.action
})
clock := &fakeClock{now: e.now}
c, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock))
if tc.wantErr != nil {
if !errors.Is(err, tc.wantErr) {
t.Fatalf("应 fail-closed,got %v", err)
}
return
}
if err != nil {
t.Fatalf("degrade 不应阻止启动: %v", err)
}
if c.State() != tc.wantState {
t.Fatalf("状态: %s", c.State())
}
})
}
}
func TestBuildCutoff_LDFlagsBuildTime(t *testing.T) {
oldBuildTime := BuildTime
defer func() { BuildTime = oldBuildTime }()
e := newEnv(t)
cutoff := e.now - 100
cases := []struct {
name string
value string
}{
{"RFC3339", time.Unix(cutoff, 0).UTC().Format(time.RFC3339)},
{"Unix 秒", "1762665500"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
BuildTime = tc.value
path := writeCutoffLicense(t, e, func(p *license.Payload) { p.BC = cutoff })
clock := &fakeClock{now: e.now}
c, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock))
if err != nil {
t.Fatalf("注入的构建时间应被采信: %v", err)
}
if c.State() != StateActive {
t.Fatalf("状态: %s", c.State())
}
})
}
}
func TestBuildCutoff_NoCutoffIgnoresBuildTime(t *testing.T) {
oldBuildTime := BuildTime
defer func() { BuildTime = oldBuildTime }()
BuildTime = "not-a-time"
e := newEnv(t)
path := writeLicense(t, e.sign(nil))
clock := &fakeClock{now: e.now}
c, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock))
if err != nil {
t.Fatalf("无截止时构建时间无关: %v", err)
}
if c.State() != StateActive {
t.Fatalf("状态: %s", c.State())
}
}
func TestBuildCutoff_DegradeDoesNotEnterGrace(t *testing.T) {
e := newEnv(t)
cutoff := e.now - 100
path := writeCutoffLicense(t, e, func(p *license.Payload) {
p.BC, p.BCM = cutoff, license.BuildCutoffDegrade
})
clock := &fakeClock{now: e.now}
c, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock), WithBuildTimeUnix(cutoff+1))
if err != nil {
t.Fatal(err)
}
c.enterGrace(3600, errors.New("network down"))
if c.State() != StateOutdated {
t.Fatalf("OUTDATED 不应因网络故障进入 GRACE: %s", c.State())
}
if c.Enabled("module.audit-log") {
t.Error("OUTDATED 下不得恢复授权")
}
}
// leaseTokenWithCutoff 签发带编译截止的测试 lease。
func leaseTokenWithCutoff(t *testing.T, e *testEnv, cutoff int64, action string) string {
t.Helper()
p := e.payload(func(p *license.Payload) {
p.LT = license.TypeLease
p.ST = license.StateRenewed
p.ACT = "act-01JDFAKE00000000000000000"
p.EXP = e.now + 3600
p.BC, p.BCM = cutoff, action
})
raw, err := json.Marshal(p)
if err != nil {
t.Fatal(err)
}
token, err := sign.SignToken(e.priv, e.kid, license.TypLease, raw)
if err != nil {
t.Fatal(err)
}
return token
}
// TestHeartbeat_ChangedDegradeLeaseStaysOutdated 回归:GRACE 下收到超期 lease
// 不得被心跳的"GRACE→ACTIVE"恢复逻辑覆盖成 ACTIVE。
func TestHeartbeat_ChangedDegradeLeaseStaysOutdated(t *testing.T) {
e := newEnv(t)
clock := &fakeClock{now: e.now}
const cutoff = int64(1794201600)
c, err := New(WithLicenseBytes([]byte(e.sign(func(p *license.Payload) { p.EXP = e.now + 86400 }))),
WithProductKey("prod_test"), WithTrustChain(e.trust()), WithClock(clock),
WithBuildTimeUnix(cutoff+1))
if err != nil {
t.Fatalf("New: %v", err)
}
c.transition(c.snap.Load(), StateGrace, e.now+3600)
c.mu.Lock()
c.actToken = "tok-test"
c.mu.Unlock()
lease := leaseTokenWithCutoff(t, e, cutoff, license.BuildCutoffDegrade)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{
"changed": true, "lease": lease, "server_time": e.now, "crl_version": 0,
})
}))
defer srv.Close()
c.opts.remoteServer = srv.URL
if err := c.heartbeatOnce(context.Background()); err != nil {
t.Fatalf("心跳: %v", err)
}
if c.State() != StateOutdated {
t.Fatalf("超期 lease 应保持 OUTDATED,got %s", c.State())
}
if c.Enabled("module.audit-log") {
t.Error("OUTDATED 下不得恢复授权")
}
}
// TestProxyRenew_DegradeLeaseStaysOutdated 回归:Proxy 续租成功也不得把
// 超期 lease 导致的 OUTDATED 恢复为 ACTIVE。
func TestProxyRenew_DegradeLeaseStaysOutdated(t *testing.T) {
e := newEnv(t)
clock := &fakeClock{now: e.now}
cutoff := int64(1794201600)
c, err := New(WithLicenseBytes([]byte(e.sign(nil))), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock), WithProxy("http://placeholder"),
WithBuildTimeUnix(cutoff+1))
if err != nil {
t.Fatalf("New: %v", err)
}
c.transition(c.snap.Load(), StateGrace, e.now+3600)
c.mu.Lock()
c.actToken = "proxy-tok"
c.mu.Unlock()
lease := leaseTokenWithCutoff(t, e, cutoff, license.BuildCutoffDegrade)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{"lease": lease, "changed": true})
}))
defer srv.Close()
c.opts.proxyAddr = srv.URL
if err := c.renewProxy(context.Background()); err != nil {
t.Fatalf("renewProxy: %v", err)
}
if c.State() != StateOutdated {
t.Fatalf("超期 proxy lease 应保持 OUTDATED,got %s", c.State())
}
if c.Enabled("module.audit-log") {
t.Error("OUTDATED 下不得恢复授权")
}
}
// TestBuildCutoff_NotConfiguredIgnoresBuildTime 守护"不限制服务时间"模式:
// license 无 bc 时,无论是否提供/是否合法提供编译时间,均正常 ACTIVE。
func TestBuildCutoff_NotConfiguredIgnoresBuildTime(t *testing.T) {
e := newEnv(t)
path := writeLicense(t, e.sign(nil))
clock := &fakeClock{now: e.now}
cases := []struct {
name string
opts []Option
}{
{"未提供编译时间", nil},
{"提供合法编译时间", []Option{WithBuildTimeUnix(e.now - 86400)}},
{"提供未来时间", []Option{WithBuildTimeUnix(e.now + 10*365*86400)}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
opts := append([]Option{WithLicenseFile(path), WithProductKey("prod_test"),
WithTrustChain(e.trust()), WithClock(clock)}, tc.opts...)
c, err := New(opts...)
if err != nil {
t.Fatalf("无截止模式应正常装载: %v", err)
}
defer c.Close() //nolint:errcheck // 测试清理
if c.State() != StateActive {
t.Fatalf("状态: %s", c.State())
}
if !c.Enabled("module.audit-log") || c.Quantity("seats") != 50 {
t.Error("无截止模式授权应完整可用")
}
})
}
}
+11 -1
View File
@@ -148,12 +148,22 @@ func (c *Client) loadCache() bool {
c.clearCache()
return false
}
degrade, err := c.buildCutoffDecision(payload)
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})
state := StateGrace
if degrade {
state = StateOutdated
}
c.snap.Store(&snapshot{payload: payload, rawToken: entry.Lease, state: state, graceDeadline: deadline})
c.mu.Lock()
c.actToken = entry.ActToken
c.heartbeatEvery = c.effectiveHeartbeat(entry.Heartbeat)
+96 -4
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
@@ -142,6 +154,44 @@ func WithTrustChain(tc *crypto.TrustChain) Option { return func(o *options)
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) {
+4
View File
@@ -7,6 +7,10 @@
// 远程模式:WithRemoteServer + WithLicenseKey → Start 自动激活 + 心跳循环,
// 断连进入 GRACE(宽限期内查询正常),耗尽转 EXPIRED;terminate 转 REVOKED 终态。
//
// 编译截止:license payload 带 bc/bcm 时,通过 WithBuildTime(或构建时
// -ldflags -X 注入 sdk.BuildTime)提供宿主应用编译时间;超期按 bcm 拒绝
// (ErrBuildCutoff)或降级为 OUTDATED(查询零值)。
//
// 核心验证逻辑由 license 与 crypto 提供(服务端与 SDK 共享
// 同一份实现,禁止两套)。
package sdk
+10 -1
View File
@@ -15,6 +15,8 @@ type LicenseInfo struct {
LicenseType string `json:"license_type"`
ExpiresAt int64 `json:"expires_at"` // 0=永久
NotBefore int64 `json:"not_before"`
BuildCutoff int64 `json:"build_cutoff,omitempty"` // 0=不限制
BuildCutoffAction string `json:"build_cutoff_action,omitempty"` // deny|degrade
}
// usable 判断当前状态是否允许正常查询(ACTIVE/GRACE)。
@@ -110,6 +112,8 @@ func (c *Client) Check(fid string) (bool, Reason) {
return false, ReasonStateInvalid
case StateUnverified:
return false, ReasonStateUnverified
case StateOutdated:
return false, ReasonStateOutdated
case StateActive:
if _, ok := s.payload.Ent[fid]; !ok {
return false, ReasonNotEntitled
@@ -126,11 +130,16 @@ func (c *Client) Info() LicenseInfo {
return LicenseInfo{}
}
p := s.payload
return LicenseInfo{
info := LicenseInfo{
JTI: p.JTI, TenantID: p.TID, TenantName: p.TName,
ProductKey: p.Prod, LicenseType: p.LT,
ExpiresAt: p.EXP, NotBefore: p.NBF,
BuildCutoff: p.BC,
}
if p.BC > 0 {
info.BuildCutoffAction = p.EffectiveBuildCutoffAction()
}
return info
}
// tierRank 返回档位序号(未知档位返回 -1,视为低于一切已知档位)。
+8 -8
View File
@@ -157,8 +157,8 @@ func (c *Client) renewProxy(ctx context.Context) error {
c.opts.logger.Warn("续租 lease 验证失败,保留旧快照", "logger", "pkg.sdk.Client.renewProxy", "error", err)
}
}
if s.state == StateGrace {
c.transition(c.snap.Load(), StateActive, 0)
if cur := c.snap.Load(); cur != nil && cur.state == StateGrace {
c.transition(cur, StateActive, 0)
}
c.fromCache = false
c.saveCache()
@@ -237,10 +237,10 @@ func (c *Client) heartbeatOnce(ctx context.Context) error {
c.opts.logger.Info("授权变更已生效", "logger", logField)
}
}
// 心跳成功:GRACE → ACTIVE
if s.state == StateGrace {
ns := c.snap.Load()
c.transition(ns, StateActive, 0)
// 心跳成功:仅当当前快照仍处于 GRACE 时恢复 ACTIVE;
// 新 lease 因编译截止降级为 OUTDATED 时不得被此逻辑覆盖。
if cur := c.snap.Load(); cur != nil && cur.state == StateGrace {
c.transition(cur, StateActive, 0)
}
c.mu.Lock()
c.heartbeatEvery = c.effectiveHeartbeat(c.heartbeatEvery)
@@ -254,7 +254,7 @@ func (c *Client) heartbeatOnce(ctx context.Context) error {
// enterGrace 进入 GRACE(已在 GRACE 时续期 deadline 不变——从首次失败时刻起算)。
func (c *Client) enterGrace(gracePeriod int64, cause error) {
s := c.snap.Load()
if s == nil || s.state == StateRevoked || s.state == StateInvalid {
if s == nil || s.state == StateRevoked || s.state == StateInvalid || s.state == StateOutdated {
return
}
if s.state == StateGrace {
@@ -405,7 +405,7 @@ func (c *Client) postNoContent(ctx context.Context, path, bearer string, body an
return nil
}
const sdkVersion = "0.4.0"
const sdkVersion = "0.7.0"
// defaultFingerprint 是自动采集失败时的最后退路(仅 hostname),用于无绑定 license 的席位标识。
// 有 bind.fp 的 license 在文件模式会 fail-closed(见 MachineFingerprint / verifyToken)。