- 自主仓 git.wxccs.org/EntitleForge/EntitleForge 拆分(协议实现单一归属: license/crypto/ulid 随 SDK 迁出,服务端反向依赖本仓) - sdk:Client 三模式(文件/远程/代理)、GRACE 状态机、查询 API(6.6ns/0 alloc) - license:三段式编解码与严格解析;crypto:Ed25519 信任链 + Proxy 受约束证书 - 零第三方依赖(CI 有依赖闭包断言红线);go.mod 零 require - CI:Gitea Actions(test + 零依赖断言 + 三平台交叉编译冒烟)
This commit is contained in:
32 files changed
+3940
No files matched your search
+323
@@ -0,0 +1,323 @@
|
||||
// Package sdk 是嵌入客户端的益铸(EntitleForge)Go SDK。
|
||||
// 设计依据:docs/design/07-sdk.md。目标:零重依赖(仅标准库 + internal 共享实现)、
|
||||
// 集成三行起步、验证失败走状态机而非 panic、查询永不阻塞(atomic 快照)。
|
||||
package sdk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"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"
|
||||
)
|
||||
|
||||
// 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"
|
||||
)
|
||||
|
||||
// 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"}
|
||||
|
||||
type options struct {
|
||||
licenseFile string
|
||||
remoteServer string
|
||||
licenseKey string
|
||||
productKey string
|
||||
fingerprint string
|
||||
trust *crypto.TrustChain
|
||||
tierOrder []string
|
||||
clock Clock
|
||||
logger *slog.Logger
|
||||
onState func(from, to State)
|
||||
pollInterval time.Duration
|
||||
|
||||
// Proxy 模式(docs/design/08-k8s-proxy.md §4)
|
||||
proxyAddr string
|
||||
saToken string
|
||||
saTokenFile string
|
||||
}
|
||||
|
||||
// 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 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 } }
|
||||
func WithFingerprint(fp string) Option { return func(o *options) { o.fingerprint = fp } }
|
||||
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 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 } }
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// 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 == "" && o.remoteServer == "" && o.proxyAddr == "" {
|
||||
return nil, errors.New("sdk: 需要 WithLicenseFile、WithRemoteServer 或 WithProxy")
|
||||
}
|
||||
if o.tierOrder == nil {
|
||||
o.tierOrder = defaultTierOrder
|
||||
}
|
||||
|
||||
c := &Client{opts: o, stop: make(chan struct{}), hc: defaultHTTPClient()}
|
||||
c.snap.Store(&snapshot{state: StateUnverified})
|
||||
|
||||
if o.licenseFile != "" {
|
||||
if err := c.reloadFile(); err != nil {
|
||||
return nil, fmt.Errorf("sdk: %w", err)
|
||||
}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Start 启动后台循环:文件轮询 / 远程心跳。
|
||||
func (c *Client) Start(ctx context.Context) error {
|
||||
const logField = "pkg.sdk.Client.Start"
|
||||
if c.opts.licenseFile != "" {
|
||||
go c.fileLoop(ctx)
|
||||
c.opts.logger.Info("SDK 文件模式已启动", "logger", logField, "file", c.opts.licenseFile)
|
||||
return nil
|
||||
}
|
||||
if c.opts.remoteServer != "" {
|
||||
if c.opts.licenseKey != "" {
|
||||
if err := c.Activate(ctx, c.opts.licenseKey); err != nil {
|
||||
return fmt.Errorf("sdk: 自动激活: %w", err)
|
||||
}
|
||||
} else if c.State() == StateUnverified {
|
||||
return errors.New("sdk: 远程模式需要 WithLicenseKey(或先手动 Activate)")
|
||||
}
|
||||
go c.heartbeatLoop(ctx)
|
||||
c.opts.logger.Info("SDK 远程模式已启动", "logger", logField, "server", c.opts.remoteServer)
|
||||
return nil
|
||||
}
|
||||
if c.opts.proxyAddr != "" {
|
||||
if err := c.attestProxy(ctx); err != nil {
|
||||
return fmt.Errorf("sdk: 代理认证: %w", err)
|
||||
}
|
||||
go c.heartbeatLoop(ctx)
|
||||
c.opts.logger.Info("SDK 代理模式已启动", "logger", logField, "proxy", c.opts.proxyAddr)
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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 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.opts.clock.Now())
|
||||
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)
|
||||
}
|
||||
if c.opts.fingerprint != "" && p.Bind != nil && p.Bind.FP != "" && p.Bind.FP != c.opts.fingerprint {
|
||||
return nil, errors.New("sdk: 机器指纹绑定不符")
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// installVerified 以验证通过的 token 换装快照(ACTIVE)。
|
||||
func (c *Client) installVerified(token string) error {
|
||||
p, err := c.verifyToken(token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
old := c.snap.Load()
|
||||
ns := &snapshot{payload: p, rawToken: token, state: StateActive}
|
||||
c.snap.Store(ns)
|
||||
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
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// tick 周期性重估:过期迁移、宽限耗尽、文件重载。测试直接调用以推进假时钟。
|
||||
func (c *Client) tick() {
|
||||
const logField = "pkg.sdk.Client.tick"
|
||||
s := c.snap.Load()
|
||||
if s == nil || s.payload == nil {
|
||||
return
|
||||
}
|
||||
now := c.opts.clock.Now()
|
||||
// 终态不迁移
|
||||
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
|
||||
}
|
||||
// 文件模式:热重载
|
||||
if c.opts.licenseFile != "" {
|
||||
c.reloadIfChanged()
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 文件模式 ----
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
package sdk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/crypto"
|
||||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
|
||||
)
|
||||
|
||||
// ---- 测试环境 ----
|
||||
|
||||
type testEnv struct {
|
||||
t *testing.T
|
||||
priv ed25519.PrivateKey
|
||||
kid string
|
||||
rootPub []byte
|
||||
chain *crypto.TrustChain
|
||||
now int64
|
||||
}
|
||||
|
||||
func newEnv(t *testing.T) *testEnv {
|
||||
root, _ := crypto.GenerateRootKey()
|
||||
sk, _ := crypto.GenerateSigningKey()
|
||||
chain := crypto.NewTrustChain(root.Pub)
|
||||
chain.AddSigningKey(sk.Kid, sk.Pub, crypto.KeyStatusActive, 0) //nolint:errcheck
|
||||
return &testEnv{t: t, priv: sk.Priv, kid: sk.Kid, rootPub: root.Pub, chain: chain, now: int64(1762665600)}
|
||||
}
|
||||
|
||||
// sign 签发测试 license token
|
||||
func (e *testEnv) sign(mut func(*license.Payload)) string {
|
||||
e.t.Helper()
|
||||
p := e.payload(mut)
|
||||
b, err := json.Marshal(p)
|
||||
if err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
token, err := crypto.SignToken(e.priv, e.kid, license.TypLicense, b)
|
||||
if err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
func (e *testEnv) payload(mut func(*license.Payload)) license.Payload {
|
||||
p := license.Payload{
|
||||
JTI: "01JDTEST000000000000000000", ISS: "EntitleForge",
|
||||
TID: "01JDTENANT0000000000000000", TName: "测试租户",
|
||||
Prod: "prod_test", IAT: e.now - 100, NBF: e.now - 100, EXP: e.now + 86400,
|
||||
LT: license.TypeSubscription, ST: license.StateIssued,
|
||||
Ent: map[string]license.Entitlement{
|
||||
"module.audit-log": license.Bool(true),
|
||||
"seats": license.Quantity(50),
|
||||
"tier": license.TierValue("enterprise"),
|
||||
"allowed-regions": license.Constraint([]string{"cn-north", "cn-east"}),
|
||||
},
|
||||
Pol: &license.PolicySnapshot{Heartbeat: 900, LeaseTTL: 3600, Grace: 259200, ForcedCheck: 86400},
|
||||
}
|
||||
if mut != nil {
|
||||
mut(&p)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func (e *testEnv) trust() *crypto.TrustChain { return e.chain }
|
||||
|
||||
// fakeClock 可注入时钟(GRACE 演进测试)
|
||||
type fakeClock struct {
|
||||
mu sync.Mutex
|
||||
now int64
|
||||
}
|
||||
|
||||
func (c *fakeClock) Now() int64 {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.now
|
||||
}
|
||||
func (c *fakeClock) Advance(d int64) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.now += d
|
||||
}
|
||||
|
||||
// ---- 文件模式 ----
|
||||
|
||||
func TestFileMode_BasicLifecycle(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "license.eflic")
|
||||
os.WriteFile(path, []byte(e.sign(nil)), 0o600) //nolint:errcheck
|
||||
|
||||
clock := &fakeClock{now: e.now}
|
||||
c, err := New(WithLicenseFile(path), WithProductKey("prod_test"), WithTrustChain(e.trust()), WithClock(clock))
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
if err := c.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start: %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
if c.State() != StateActive {
|
||||
t.Fatalf("初始状态: %s", c.State())
|
||||
}
|
||||
// 查询 API
|
||||
if !c.Enabled("module.audit-log") {
|
||||
t.Error("module.audit-log 应启用")
|
||||
}
|
||||
if c.Enabled("module.nonexistent") {
|
||||
t.Error("未授权 feature 应返回 false(缺省即无权)")
|
||||
}
|
||||
if got := c.Quantity("seats"); got != 50 {
|
||||
t.Errorf("seats: %d", got)
|
||||
}
|
||||
if got := c.Tier(); got != "enterprise" {
|
||||
t.Errorf("tier: %q", got)
|
||||
}
|
||||
if !c.TierAtLeast("pro") {
|
||||
t.Error("enterprise >= pro")
|
||||
}
|
||||
if c.TierAtLeast("ultimate") {
|
||||
t.Error("enterprise < ultimate")
|
||||
}
|
||||
if !c.Allows("allowed-regions", "cn-north") || c.Allows("allowed-regions", "us-west") {
|
||||
t.Error("Allows 语义错误")
|
||||
}
|
||||
if len(c.Entitlements()) != 4 {
|
||||
t.Errorf("Entitlements: %d", len(c.Entitlements()))
|
||||
}
|
||||
// Check Reason
|
||||
ok, reason := c.Check("module.audit-log")
|
||||
if !ok || reason != ReasonOK {
|
||||
t.Errorf("Check: %v %s", ok, reason)
|
||||
}
|
||||
ok, reason = c.Check("module.no")
|
||||
if ok || reason != ReasonNotEntitled {
|
||||
t.Errorf("Check 未授权: %v %s", ok, reason)
|
||||
}
|
||||
// Info
|
||||
info := c.Info()
|
||||
if info.JTI != "01JDTEST000000000000000000" || info.ProductKey != "prod_test" {
|
||||
t.Errorf("Info: %+v", info)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileMode_ExpiredTransition(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "license.eflic")
|
||||
os.WriteFile(path, []byte(e.sign(nil)), 0o600) //nolint:errcheck
|
||||
|
||||
clock := &fakeClock{now: e.now}
|
||||
var states []State
|
||||
c, _ := New(WithLicenseFile(path), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(clock), WithOnStateChange(func(from, to State) {
|
||||
states = append(states, to)
|
||||
}))
|
||||
c.Start(context.Background()) //nolint:errcheck
|
||||
defer c.Close()
|
||||
|
||||
// 推进至 exp + skew 容忍之外 → EXPIRED
|
||||
clock.Advance(86400 + 1200)
|
||||
c.tick()
|
||||
if c.State() != StateExpired {
|
||||
t.Fatalf("过期后状态: %s", c.State())
|
||||
}
|
||||
if c.Enabled("module.audit-log") {
|
||||
t.Error("EXPIRED 下查询应全部零值")
|
||||
}
|
||||
if c.Quantity("seats") != 0 || c.Tier() != "" {
|
||||
t.Error("EXPIRED 零值语义")
|
||||
}
|
||||
_, reason := c.Check("module.audit-log")
|
||||
if reason != ReasonStateExpired {
|
||||
t.Errorf("过期 Check reason: %s", reason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileMode_TamperedFile_Invalid(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "license.eflic")
|
||||
token := e.sign(nil)
|
||||
os.WriteFile(path, []byte(token[:len(token)-4]+"AAAA"), 0o600) //nolint:errcheck
|
||||
|
||||
c, err := New(WithLicenseFile(path), WithProductKey("prod_test"), WithTrustChain(e.trust()))
|
||||
if err == nil {
|
||||
c.Close()
|
||||
t.Fatal("验签失败应在 New 报错")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileMode_ProductMismatch(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "license.eflic")
|
||||
os.WriteFile(path, []byte(e.sign(nil)), 0o600) //nolint:errcheck
|
||||
|
||||
if _, err := New(WithLicenseFile(path), WithProductKey("prod_other"), WithTrustChain(e.trust())); err == nil {
|
||||
t.Fatal("产品不符应拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileMode_HotReload(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "license.eflic")
|
||||
os.WriteFile(path, []byte(e.sign(nil)), 0o600) //nolint:errcheck
|
||||
|
||||
clock := &fakeClock{now: e.now}
|
||||
c, _ := New(WithLicenseFile(path), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(clock))
|
||||
c.Start(context.Background()) //nolint:errcheck
|
||||
defer c.Close()
|
||||
if c.Quantity("seats") != 50 {
|
||||
t.Fatal("前置失败")
|
||||
}
|
||||
// 热更新:seats → 100(mtimer 触发由 tick 模拟)
|
||||
os.WriteFile(path, []byte(e.sign(func(p *license.Payload) {
|
||||
p.Ent["seats"] = license.Quantity(100)
|
||||
p.ST = license.StateRenewed
|
||||
})), 0o600) //nolint:errcheck
|
||||
c.tick()
|
||||
if c.Quantity("seats") != 100 {
|
||||
t.Errorf("热更新未生效: %d", c.Quantity("seats"))
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 远程模式(httptest 假数据面) ----
|
||||
|
||||
// fakeRemote 模拟数据面:激活 + 心跳(可控 terminate/变更)
|
||||
type fakeRemote struct {
|
||||
mu sync.Mutex
|
||||
server *httptest.Server
|
||||
lease string // 当前应答的 lease
|
||||
token string
|
||||
terminate bool
|
||||
crl string
|
||||
fail bool // 网络故障开关(503)
|
||||
heartbeats int
|
||||
}
|
||||
|
||||
func newFakeRemote(t *testing.T, e *testEnv) *fakeRemote {
|
||||
fr := &fakeRemote{}
|
||||
fr.lease = e.leaseToken()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /v1/activate", func(w http.ResponseWriter, r *http.Request) {
|
||||
fr.mu.Lock()
|
||||
defer fr.mu.Unlock()
|
||||
fr.token = "tok-" + time.Now().Format("150405.000")
|
||||
json.NewEncoder(w).Encode(map[string]any{ //nolint:errcheck
|
||||
"activation_id": "act-01JDFAKE00000000000000000",
|
||||
"activation_token": fr.token,
|
||||
"lease": fr.lease,
|
||||
"lease_ttl": int64(3600),
|
||||
"heartbeat_interval": 900,
|
||||
"grace_period": 259200,
|
||||
"server_time": e.now,
|
||||
"crl_version": 0,
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("POST /v1/heartbeat", func(w http.ResponseWriter, r *http.Request) {
|
||||
fr.mu.Lock()
|
||||
defer fr.mu.Unlock()
|
||||
fr.heartbeats++
|
||||
if fr.fail {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
resp := map[string]any{"changed": false, "server_time": e.now, "crl_version": 0}
|
||||
if fr.terminate {
|
||||
resp["terminate"] = true
|
||||
resp["crl"] = fr.crl
|
||||
}
|
||||
json.NewEncoder(w).Encode(resp) //nolint:errcheck
|
||||
})
|
||||
fr.server = httptest.NewServer(mux)
|
||||
t.Cleanup(fr.server.Close)
|
||||
return fr
|
||||
}
|
||||
|
||||
func (e *testEnv) leaseToken() string {
|
||||
p := e.payload(func(p *license.Payload) {
|
||||
p.LT = license.TypeLease
|
||||
p.ST = license.StateRenewed
|
||||
p.ACT = "act-01JDFAKE00000000000000000"
|
||||
p.EXP = e.now + 3600
|
||||
})
|
||||
b, _ := json.Marshal(p)
|
||||
token, _ := crypto.SignToken(e.priv, e.kid, license.TypLease, b)
|
||||
return token
|
||||
}
|
||||
|
||||
func TestRemoteMode_GraceCycle(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
fr := newFakeRemote(t, e)
|
||||
clock := &fakeClock{now: e.now}
|
||||
|
||||
c, err := New(WithRemoteServer(fr.server.URL), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(clock), WithLicenseKey("ef-TEST-TEST-TEST-TEST"))
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
if err := c.Start(context.Background()); err != nil {
|
||||
t.Fatalf("Start(自动激活): %v", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
if c.State() != StateActive {
|
||||
t.Fatalf("激活后状态: %s", c.State())
|
||||
}
|
||||
if c.Quantity("seats") != 50 {
|
||||
t.Errorf("seats: %d", c.Quantity("seats"))
|
||||
}
|
||||
|
||||
// 网络故障 → GRACE(查询仍可用)
|
||||
fr.mu.Lock()
|
||||
fr.fail = true
|
||||
fr.mu.Unlock()
|
||||
c.heartbeatOnce(context.Background())
|
||||
if c.State() != StateGrace {
|
||||
t.Fatalf("断连后应 GRACE: %s", c.State())
|
||||
}
|
||||
if c.Quantity("seats") != 50 {
|
||||
t.Error("GRACE 期间查询应正常")
|
||||
}
|
||||
_, reason := c.Check("seats")
|
||||
if reason != ReasonStateGrace {
|
||||
t.Errorf("GRACE reason: %s", reason)
|
||||
}
|
||||
|
||||
// 恢复 → ACTIVE
|
||||
fr.mu.Lock()
|
||||
fr.fail = false
|
||||
fr.mu.Unlock()
|
||||
c.heartbeatOnce(context.Background())
|
||||
if c.State() != StateActive {
|
||||
t.Fatalf("恢复后应 ACTIVE: %s", c.State())
|
||||
}
|
||||
|
||||
// 宽限期耗尽 → EXPIRED
|
||||
fr.mu.Lock()
|
||||
fr.fail = true
|
||||
fr.mu.Unlock()
|
||||
c.heartbeatOnce(context.Background())
|
||||
clock.Advance(259200 + 600) // grace 72h + skew
|
||||
c.tick()
|
||||
if c.State() != StateExpired {
|
||||
t.Fatalf("宽限耗尽应 EXPIRED: %s", c.State())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteMode_TerminateRevoked(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
fr := newFakeRemote(t, e)
|
||||
clock := &fakeClock{now: e.now}
|
||||
|
||||
c, _ := New(WithRemoteServer(fr.server.URL), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(clock), WithLicenseKey("ef-TEST-TEST-TEST-TEST"))
|
||||
c.Start(context.Background()) //nolint:errcheck
|
||||
defer c.Close()
|
||||
if c.State() != StateActive {
|
||||
t.Fatal("前置失败")
|
||||
}
|
||||
fr.mu.Lock()
|
||||
fr.terminate = true
|
||||
fr.mu.Unlock()
|
||||
c.heartbeatOnce(context.Background())
|
||||
if c.State() != StateRevoked {
|
||||
t.Fatalf("terminate 后应 REVOKED: %s", c.State())
|
||||
}
|
||||
if c.Enabled("module.audit-log") {
|
||||
t.Error("REVOKED 下应零值")
|
||||
}
|
||||
// REVOKED 是终态:不因后续成功心跳复活
|
||||
fr.mu.Lock()
|
||||
fr.terminate = false
|
||||
fr.mu.Unlock()
|
||||
c.heartbeatOnce(context.Background())
|
||||
if c.State() != StateRevoked {
|
||||
t.Fatalf("REVOKED 应为终态: %s", c.State())
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
// Package sdk 是嵌入客户端的益铸(EntitleForge)Go SDK(准公共 API)。
|
||||
//
|
||||
// 设计依据:docs/design/07-sdk.md。零第三方依赖(仅标准库 + internal 共享实现),
|
||||
// 集成三行起步、验证失败走状态机而非 panic、查询走 atomic 快照永不阻塞。
|
||||
//
|
||||
// 文件模式:WithLicenseFile + WithTrustChain → Start(mtime 轮询热更新)。
|
||||
// 远程模式:WithRemoteServer + WithLicenseKey → Start 自动激活 + 心跳循环,
|
||||
// 断连进入 GRACE(宽限期内查询正常),耗尽转 EXPIRED;terminate 转 REVOKED 终态。
|
||||
//
|
||||
// 核心验证逻辑由 internal/license 与 internal/crypto 提供(服务端与 SDK 共享
|
||||
// 同一份实现,禁止两套)。
|
||||
package sdk
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package sdk
|
||||
|
||||
import (
|
||||
"maps"
|
||||
|
||||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
|
||||
)
|
||||
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// usable 判断当前状态是否允许正常查询(ACTIVE/GRACE)。
|
||||
func (c *Client) usable() bool {
|
||||
switch c.State() {
|
||||
case StateActive, StateGrace:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Enabled 布尔开关查询;未授权或状态不可用一律 false(docs/design/05-entitlement-model.md §4 规则 1)。
|
||||
func (c *Client) Enabled(fid string) bool {
|
||||
ok, _ := c.Check(fid)
|
||||
return ok
|
||||
}
|
||||
|
||||
// Quantity 数量配额查询;未授权返回 0。
|
||||
func (c *Client) Quantity(fid string) int64 {
|
||||
s := c.snap.Load()
|
||||
if s == nil || !c.usable() || s.payload == nil {
|
||||
return 0
|
||||
}
|
||||
return s.payload.Ent[fid].AsInt()
|
||||
}
|
||||
|
||||
// Tier 返回档位;无档位授权返回空串。
|
||||
func (c *Client) Tier() string {
|
||||
s := c.snap.Load()
|
||||
if s == nil || !c.usable() || s.payload == nil {
|
||||
return ""
|
||||
}
|
||||
return s.payload.Ent["tier"].AsString()
|
||||
}
|
||||
|
||||
// TierAtLeast 档位序比较(档位序由 WithTierOrder 注入或用默认序)。
|
||||
func (c *Client) TierAtLeast(min string) bool {
|
||||
cur := c.Tier()
|
||||
if cur == "" {
|
||||
return false
|
||||
}
|
||||
return tierRank(cur, c.opts.tierOrder) >= tierRank(min, c.opts.tierOrder)
|
||||
}
|
||||
|
||||
// Allows 约束集合查询。
|
||||
func (c *Client) Allows(fid, value string) bool {
|
||||
s := c.snap.Load()
|
||||
if s == nil || !c.usable() || s.payload == nil {
|
||||
return false
|
||||
}
|
||||
return s.payload.Ent[fid].Allows(value)
|
||||
}
|
||||
|
||||
// Entitlements 返回授权集合拷贝(含全部状态下的真实值,供管理端点展示)。
|
||||
func (c *Client) Entitlements() map[string]license.Entitlement {
|
||||
s := c.snap.Load()
|
||||
if s == nil || s.payload == nil {
|
||||
return map[string]license.Entitlement{}
|
||||
}
|
||||
out := make(map[string]license.Entitlement, len(s.payload.Ent))
|
||||
maps.Copy(out, s.payload.Ent)
|
||||
return out
|
||||
}
|
||||
|
||||
// Check 一次性谓词:授权完整且状态可用时 OK,否则 false + 精确原因。
|
||||
func (c *Client) Check(fid string) (bool, Reason) {
|
||||
s := c.snap.Load()
|
||||
if s == nil || s.payload == nil {
|
||||
return false, ReasonStateUnverified
|
||||
}
|
||||
switch st := s.state; st {
|
||||
case StateGrace:
|
||||
if _, ok := s.payload.Ent[fid]; !ok {
|
||||
return false, ReasonNotEntitled
|
||||
}
|
||||
return true, ReasonStateGrace
|
||||
case StateExpired:
|
||||
return false, ReasonStateExpired
|
||||
case StateRevoked:
|
||||
return false, ReasonStateRevoked
|
||||
case StateInvalid:
|
||||
return false, ReasonStateInvalid
|
||||
case StateUnverified:
|
||||
return false, ReasonStateUnverified
|
||||
case StateActive:
|
||||
if _, ok := s.payload.Ent[fid]; !ok {
|
||||
return false, ReasonNotEntitled
|
||||
}
|
||||
return true, ReasonOK
|
||||
}
|
||||
return false, ReasonStateInvalid
|
||||
}
|
||||
|
||||
// Info 返回只读授权摘要(无授权时零值)。
|
||||
func (c *Client) Info() LicenseInfo {
|
||||
s := c.snap.Load()
|
||||
if s == nil || s.payload == nil {
|
||||
return LicenseInfo{}
|
||||
}
|
||||
p := s.payload
|
||||
return LicenseInfo{
|
||||
JTI: p.JTI, TenantID: p.TID, TenantName: p.TName,
|
||||
ProductKey: p.Prod, LicenseType: p.LT,
|
||||
ExpiresAt: p.EXP, NotBefore: p.NBF,
|
||||
}
|
||||
}
|
||||
|
||||
// tierRank 返回档位序号(未知档位返回 -1,视为低于一切已知档位)。
|
||||
func tierRank(tier string, order []string) int {
|
||||
for i, t := range order {
|
||||
if t == tier {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
package sdk
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
|
||||
)
|
||||
|
||||
// httpClient 抽象(测试注入)。
|
||||
type httpClient interface {
|
||||
Do(req *http.Request) (*http.Response, error)
|
||||
}
|
||||
|
||||
// defaultHTTPClient 生产默认客户端(超时约束)。
|
||||
func defaultHTTPClient() *http.Client {
|
||||
return &http.Client{Timeout: 10 * time.Second}
|
||||
}
|
||||
|
||||
// Activate 用 license key 换取租约并进入 ACTIVE(docs/design/09-api-spec.md §2.1)。
|
||||
func (c *Client) Activate(ctx context.Context, licenseKey string) error {
|
||||
const logField = "pkg.sdk.Client.Activate"
|
||||
fp := c.opts.fingerprint
|
||||
if fp == "" {
|
||||
fp = defaultFingerprint()
|
||||
}
|
||||
body := map[string]any{
|
||||
"license_key": licenseKey,
|
||||
"product_key": c.opts.productKey,
|
||||
"fingerprint": fp,
|
||||
"hostname": hostname(),
|
||||
"agent": "sdk-go/" + sdkVersion,
|
||||
}
|
||||
var resp activateResp
|
||||
if err := c.postJSON(ctx, "/v1/activate", "", body, &resp); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := c.installVerified(resp.Lease); err != nil {
|
||||
return fmt.Errorf("sdk: 服务端 lease 验证失败: %w", err)
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.actToken = resp.Token
|
||||
c.heartbeatEvery = resp.HeartbeatInterval
|
||||
c.gracePeriod = resp.GracePeriod
|
||||
c.mu.Unlock()
|
||||
c.opts.logger.Info("激活成功", "logger", logField, "activation", resp.ActivationID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Refresh 手动触发一次心跳(幂等,任意状态可调)。
|
||||
func (c *Client) Refresh(ctx context.Context) error { return c.heartbeatOnce(ctx) }
|
||||
|
||||
type activateResp struct {
|
||||
ActivationID string `json:"activation_id"`
|
||||
Token string `json:"activation_token"`
|
||||
Lease string `json:"lease"`
|
||||
LeaseTTL int64 `json:"lease_ttl"`
|
||||
HeartbeatInterval int64 `json:"heartbeat_interval"`
|
||||
GracePeriod int64 `json:"grace_period"`
|
||||
}
|
||||
|
||||
type heartbeatResp struct {
|
||||
Changed bool `json:"changed"`
|
||||
Lease string `json:"lease"`
|
||||
CRL string `json:"crl"`
|
||||
CRLVersion int64 `json:"crl_version"`
|
||||
ServerTime int64 `json:"server_time"`
|
||||
Terminate bool `json:"terminate"`
|
||||
}
|
||||
|
||||
// attestProxy 向集群内 Proxy 证明工作负载身份并换取受约束 lease(08 §4.1)。
|
||||
func (c *Client) attestProxy(ctx context.Context) error {
|
||||
const logField = "pkg.sdk.Client.attestProxy"
|
||||
token := c.opts.saToken
|
||||
if token == "" && c.opts.saTokenFile != "" {
|
||||
b, err := os.ReadFile(c.opts.saTokenFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sdk: 读取 SA token: %w", err)
|
||||
}
|
||||
token = strings.TrimSpace(string(b))
|
||||
}
|
||||
if token == "" {
|
||||
return errors.New("sdk: 需要 WithSAToken 或 WithSATokenFile(代理模式)")
|
||||
}
|
||||
var resp struct {
|
||||
ProxyToken string `json:"proxy_token"`
|
||||
Identity string `json:"identity"`
|
||||
Lease string `json:"lease"`
|
||||
RenewAfter int64 `json:"renew_after"`
|
||||
}
|
||||
orig := c.opts.remoteServer
|
||||
c.opts.remoteServer = c.opts.proxyAddr
|
||||
err := c.postJSON(ctx, "/v1/proxy/attest", "", map[string]any{"sa_token": token}, &resp)
|
||||
c.opts.remoteServer = orig
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := c.installVerified(resp.Lease); err != nil {
|
||||
return fmt.Errorf("sdk: 代理 lease 验证失败: %w", err)
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.actToken = resp.ProxyToken
|
||||
c.heartbeatEvery = resp.RenewAfter
|
||||
if c.gracePeriod == 0 {
|
||||
c.gracePeriod = 259200
|
||||
}
|
||||
c.mu.Unlock()
|
||||
c.opts.logger.Info("代理认证成功", "logger", logField, "identity", resp.Identity)
|
||||
return nil
|
||||
}
|
||||
|
||||
// renewProxy 执行一次代理续租(08 §4.2)。
|
||||
func (c *Client) renewProxy(ctx context.Context) error {
|
||||
c.mu.Lock()
|
||||
token := c.actToken
|
||||
grace := c.gracePeriod
|
||||
c.mu.Unlock()
|
||||
if token == "" {
|
||||
return errors.New("sdk: 未认证(无 proxy_token)")
|
||||
}
|
||||
var resp struct {
|
||||
Lease string `json:"lease"`
|
||||
Changed bool `json:"changed"`
|
||||
Terminate bool `json:"terminate"`
|
||||
}
|
||||
orig := c.opts.remoteServer
|
||||
c.opts.remoteServer = c.opts.proxyAddr
|
||||
err := c.postJSON(ctx, "/v1/proxy/renew", token, map[string]any{}, &resp)
|
||||
c.opts.remoteServer = orig
|
||||
if err != nil {
|
||||
c.enterGrace(grace, err)
|
||||
return err
|
||||
}
|
||||
s := c.snap.Load()
|
||||
if resp.Terminate {
|
||||
c.transition(s, StateRevoked, 0)
|
||||
return nil
|
||||
}
|
||||
if resp.Lease != "" {
|
||||
if err := c.installVerified(resp.Lease); err != nil {
|
||||
c.opts.logger.Warn("续租 lease 验证失败,保留旧快照", "logger", "pkg.sdk.Client.renewProxy", "error", err)
|
||||
}
|
||||
}
|
||||
if s.state == StateGrace {
|
||||
c.transition(c.snap.Load(), StateActive, 0)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// heartbeatOnce 执行一次心跳并按结果迁移状态。
|
||||
// 成功:terminate→REVOKED(终态);changed→换装新 lease;否则维持/恢复 ACTIVE。
|
||||
// 网络失败:进入 GRACE(宽限期从当前时刻起算)。
|
||||
func (c *Client) heartbeatOnce(ctx context.Context) error {
|
||||
const logField = "pkg.sdk.Client.heartbeatOnce"
|
||||
if c.opts.proxyAddr != "" {
|
||||
return c.renewProxy(ctx)
|
||||
}
|
||||
c.mu.Lock()
|
||||
token := c.actToken
|
||||
grace := c.gracePeriod
|
||||
c.mu.Unlock()
|
||||
if token == "" {
|
||||
return errors.New("sdk: 未激活(无 activation_token)")
|
||||
}
|
||||
|
||||
body := map[string]any{
|
||||
"entitlements_hash": c.currentHash(),
|
||||
"agent": "sdk-go/" + sdkVersion,
|
||||
"crl_version": int64(0),
|
||||
}
|
||||
var resp heartbeatResp
|
||||
err := c.postJSON(ctx, "/v1/heartbeat", token, body, &resp)
|
||||
if err != nil {
|
||||
c.enterGrace(grace, err)
|
||||
return err
|
||||
}
|
||||
|
||||
s := c.snap.Load()
|
||||
if resp.Terminate {
|
||||
// 吊销:终态(07 §5 状态机)
|
||||
c.transition(s, StateRevoked, 0)
|
||||
c.opts.logger.Warn("服务端下发终止指令,进入 REVOKED", "logger", logField)
|
||||
return nil
|
||||
}
|
||||
if resp.Changed && resp.Lease != "" {
|
||||
if err := c.installVerified(resp.Lease); err != nil {
|
||||
// 变更下发验证失败:保持现有快照(可能是服务端密钥轮换中),下次心跳重试
|
||||
c.opts.logger.Warn("变更 lease 验证失败,保留旧快照", "logger", logField, "error", err)
|
||||
} else {
|
||||
c.opts.logger.Info("授权变更已生效", "logger", logField)
|
||||
}
|
||||
}
|
||||
// 心跳成功:GRACE → ACTIVE
|
||||
if s.state == StateGrace {
|
||||
ns := c.snap.Load()
|
||||
c.transition(ns, StateActive, 0)
|
||||
}
|
||||
_ = grace
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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 {
|
||||
return
|
||||
}
|
||||
if s.state == StateGrace {
|
||||
return // deadline 保持首次失败时刻
|
||||
}
|
||||
if gracePeriod <= 0 {
|
||||
gracePeriod = 259200 // 72h 兜底
|
||||
}
|
||||
c.opts.logger.Warn("心跳失败,进入宽限期", "logger", "pkg.sdk.Client.enterGrace",
|
||||
"grace_seconds", gracePeriod, "cause", cause)
|
||||
c.transition(s, StateGrace, c.opts.clock.Now()+gracePeriod)
|
||||
}
|
||||
|
||||
func (c *Client) heartbeatLoop(ctx context.Context) {
|
||||
for {
|
||||
c.mu.Lock()
|
||||
every := c.heartbeatEvery
|
||||
c.mu.Unlock()
|
||||
if every <= 0 {
|
||||
every = 900
|
||||
}
|
||||
select {
|
||||
case <-c.stop:
|
||||
return
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(time.Duration(every) * time.Second):
|
||||
if err := c.heartbeatOnce(ctx); err != nil {
|
||||
// 指数退避已由 GRACE deadline 兜底;循环内静默重试
|
||||
_ = err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) currentHash() string {
|
||||
s := c.snap.Load()
|
||||
if s == nil || s.payload == nil {
|
||||
return ""
|
||||
}
|
||||
return license.EntitlementsHash(s.payload.Ent)
|
||||
}
|
||||
|
||||
// postJSON 发送 JSON POST 并解码响应;网络错误/非 2xx 均返回错误。
|
||||
func (c *Client) postJSON(ctx context.Context, path, bearer string, body any, out any) error {
|
||||
b, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.opts.remoteServer+path, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if bearer != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+bearer)
|
||||
}
|
||||
resp, err := c.hc.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sdk: 请求 %s: %w", path, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("sdk: %s 状态码 %d", path, resp.StatusCode)
|
||||
}
|
||||
return json.Unmarshal(raw, out)
|
||||
}
|
||||
|
||||
const sdkVersion = "0.1.0"
|
||||
|
||||
// defaultFingerprint 默认机器指纹采集(v1:hostname;生产版接 internal/crypto.Fingerprint 采集器)。
|
||||
func defaultFingerprint() string {
|
||||
return "sha256:host:" + hostname()
|
||||
}
|
||||
|
||||
func hostname() string {
|
||||
h, err := os.Hostname()
|
||||
if err != nil {
|
||||
return "unknown"
|
||||
}
|
||||
return h
|
||||
}
|
||||
Reference in new issue
Block a user