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:
9 files changed
+631
-30
No files matched your search
@@ -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
@@ -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)
|
||||
|
||||
+100
-8
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
+17
-8
@@ -8,13 +8,15 @@ import (
|
||||
|
||||
// LicenseInfo 是只读授权摘要。
|
||||
type LicenseInfo struct {
|
||||
JTI string `json:"jti"`
|
||||
TenantID string `json:"tenant_id"`
|
||||
TenantName string `json:"tenant_name,omitempty"`
|
||||
ProductKey string `json:"product_key"`
|
||||
LicenseType string `json:"license_type"`
|
||||
ExpiresAt int64 `json:"expires_at"` // 0=永久
|
||||
NotBefore int64 `json:"not_before"`
|
||||
JTI string `json:"jti"`
|
||||
TenantID string `json:"tenant_id"`
|
||||
TenantName string `json:"tenant_name,omitempty"`
|
||||
ProductKey string `json:"product_key"`
|
||||
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
@@ -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)。
|
||||
|
||||
Reference in new issue
Block a user