Files
EntitleForge-SDK-go/sdk/client.go
T
iceking2nd 834882e044
sdk-ci / test (push) Successful in 1m54s
sdk-release / release (push) Failing after 39s
sdk-release / cleanup (push) Successful in 4s
fix(sdk): 离线 license 默认自动校验机器指纹
- 新增 sdk.MachineFingerprint:Linux machine-id+DMI、macOS IOPlatformUUID,容器内 fail-closed
- 文件模式在 bind.fp 存在时自动校验,无需显式 WithFingerprint;采集失败拒绝绑定 license
- 新增 WithFingerprintFunc 支持容器读取挂载宿主 machine-id;在线激活同步使用自动指纹
- license 包新增 NormalizeFingerprint(sha256:64hex 校验与小写归一化)
- 新增指纹绑定/采集失败/无绑定跳过等测试
2026-11-14 20:02:12 +08:00

340 lines
11 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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
fingerprintFn func() (string, error)
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 } }
// WithFingerprint 显式指定机器指纹;省略时 SDK 自动采集(见 MachineFingerprint)。
// 自定义采集(如容器内读取挂载的宿主 machine-id)使用 WithFingerprintFunc。
func WithFingerprint(fp string) Option { return func(o *options) { o.fingerprint = fp } }
// WithFingerprintFunc 自定义机器指纹采集器;仅在未显式 WithFingerprint 时生效。
func WithFingerprintFunc(fn func() (string, error)) Option {
return func(o *options) { o.fingerprintFn = fn }
}
func WithTrustChain(tc *crypto.TrustChain) Option { return func(o *options) { o.trust = tc } }
func WithTierOrder(order []string) Option { return func(o *options) { o.tierOrder = order } }
func WithClock(c Clock) Option { return func(o *options) { o.clock = c } }
func WithLogger(l *slog.Logger) Option { return func(o *options) { o.logger = l } }
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)
}
// bind.fp 存在时必须校验:显式指纹 > 自定义采集器 > 默认机器采集;采集失败 fail-closed。
if p.Bind != nil && p.Bind.FP != "" {
fp, err := c.effectiveFingerprint()
if err != nil {
return nil, err
}
if fp != p.Bind.FP {
return nil, errors.New("sdk: 机器指纹绑定不符")
}
}
return p, nil
}
// 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)
}
}