sdk-ci / test (push) Failing after 8s
- 自主仓 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 + 零依赖断言 + 三平台交叉编译冒烟)
324 lines
10 KiB
Go
324 lines
10 KiB
Go
// 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)
|
||
}
|
||
}
|