Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5cc2d73cdd
|
||
|
|
c320f7c91f
|
No files matched your search
+74
-10
@@ -185,6 +185,7 @@ type Client struct {
|
||||
crlVersion atomic.Int64 // 最近应用/上报的 CRL 版本
|
||||
lastCheckAt atomic.Int64 // 最近一次在线校验成功时刻(强制校验点计时)
|
||||
clockSkew atomic.Int64 // 服务端时间 - 本地时间(trustedNow = 本地 + skew)
|
||||
lastWall atomic.Int64 // 最近观测到的本地墙钟(回拨检测)
|
||||
noCheckWarn sync.Once
|
||||
fromCache bool
|
||||
}
|
||||
@@ -194,11 +195,30 @@ func (c *Client) trustedNow() int64 {
|
||||
return c.opts.clock.Now() + c.clockSkew.Load()
|
||||
}
|
||||
|
||||
// observeWallClock 检测本地时钟回拨:发现倒退超过 60s 时补偿 skew,
|
||||
// 保证 trustedNow 不随墙钟回拨而倒退(docs/design/12-security.md T7)。
|
||||
func (c *Client) observeWallClock() {
|
||||
now := c.opts.clock.Now()
|
||||
prev := c.lastWall.Load()
|
||||
if prev > 0 && now < prev-60 {
|
||||
delta := prev - now
|
||||
c.clockSkew.Add(delta)
|
||||
c.opts.logger.Warn("检测到系统时钟回拨,已补偿可信时间",
|
||||
"logger", "pkg.sdk.Client.observeWallClock", "rollback_seconds", delta)
|
||||
c.lastWall.Store(prev)
|
||||
return
|
||||
}
|
||||
if now > prev {
|
||||
c.lastWall.Store(now)
|
||||
}
|
||||
}
|
||||
|
||||
// applyServerTime 用服务端时间更新本地偏移估计。
|
||||
func (c *Client) applyServerTime(serverTime int64) {
|
||||
if serverTime <= 0 {
|
||||
return
|
||||
}
|
||||
c.observeWallClock()
|
||||
c.clockSkew.Store(serverTime - c.opts.clock.Now())
|
||||
}
|
||||
|
||||
@@ -248,36 +268,78 @@ func New(opts ...Option) (*Client, error) {
|
||||
// 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
|
||||
}
|
||||
|
||||
// 在线/代理模式优先;文件/字节 license 作为不可达时的兜底基线(模式叠加)。
|
||||
if c.opts.remoteServer != "" || c.opts.proxyAddr != "" {
|
||||
if c.opts.remoteServer != "" {
|
||||
key := c.activationKey()
|
||||
// 缓存恢复的 GRACE 无需立即激活;心跳 401/410 时会自动重激活
|
||||
if key != "" && !c.fromCache {
|
||||
if err := c.Activate(ctx, key); err != nil {
|
||||
if !c.fallbackAvailable() {
|
||||
return fmt.Errorf("sdk: 自动激活: %w", err)
|
||||
}
|
||||
c.opts.logger.Warn("远程激活失败,使用文件 license 兜底",
|
||||
"logger", logField, "error", err)
|
||||
}
|
||||
} else if c.State() == StateUnverified {
|
||||
return errors.New("sdk: 远程模式需要 WithLicenseKey/WithAutoActivate(或先手动 Activate)")
|
||||
}
|
||||
go c.heartbeatLoop(ctx)
|
||||
c.opts.logger.Info("SDK 远程模式已启动", "logger", logField, "server", c.opts.remoteServer)
|
||||
return nil
|
||||
}
|
||||
if c.opts.proxyAddr != "" {
|
||||
} else {
|
||||
if !c.fromCache {
|
||||
if err := c.attestProxy(ctx); err != nil {
|
||||
if !c.fallbackAvailable() {
|
||||
return fmt.Errorf("sdk: 代理认证: %w", err)
|
||||
}
|
||||
go c.heartbeatLoop(ctx)
|
||||
c.opts.logger.Warn("代理认证失败,使用文件 license 兜底",
|
||||
"logger", logField, "error", err)
|
||||
}
|
||||
}
|
||||
c.opts.logger.Info("SDK 代理模式已启动", "logger", logField, "proxy", c.opts.proxyAddr)
|
||||
}
|
||||
go c.heartbeatLoop(ctx)
|
||||
go c.tickLoop(ctx)
|
||||
return nil
|
||||
}
|
||||
if c.opts.licenseFile != "" {
|
||||
go c.fileLoop(ctx)
|
||||
c.opts.logger.Info("SDK 文件模式已启动", "logger", logField, "file", c.opts.licenseFile)
|
||||
return nil
|
||||
}
|
||||
if len(c.opts.licenseBytes) > 0 {
|
||||
go c.tickLoop(ctx)
|
||||
c.opts.logger.Info("SDK 内存 license 模式已启动", "logger", logField)
|
||||
return nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// fallbackAvailable 报告是否存在可用的文件/字节 license 基线。
|
||||
func (c *Client) fallbackAvailable() bool {
|
||||
if c.opts.licenseFile == "" && len(c.opts.licenseBytes) == 0 {
|
||||
return false
|
||||
}
|
||||
st := c.State()
|
||||
return st == StateActive || st == StateGrace
|
||||
}
|
||||
|
||||
// tickLoop 周期性推进过期/宽限/强制校验(在线模式也运行,文件热重载由 fileLoop 负责)。
|
||||
func (c *Client) tickLoop(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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Close 停止后台循环(幂等)。
|
||||
func (c *Client) Close() error {
|
||||
c.once.Do(func() { close(c.stop) })
|
||||
@@ -348,6 +410,7 @@ func (c *Client) installVerified(token string) error {
|
||||
old := c.snap.Load()
|
||||
ns := &snapshot{payload: p, rawToken: token, state: StateActive}
|
||||
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)
|
||||
@@ -411,6 +474,7 @@ func (c *Client) tick() {
|
||||
if s == nil || s.payload == nil {
|
||||
return
|
||||
}
|
||||
c.observeWallClock()
|
||||
now := c.trustedNow()
|
||||
// 终态不迁移
|
||||
if s.state == StateRevoked || s.state == StateInvalid {
|
||||
|
||||
@@ -171,6 +171,14 @@ func (c *Client) renewProxy(ctx context.Context) error {
|
||||
func (c *Client) heartbeatOnce(ctx context.Context) error {
|
||||
const logField = "pkg.sdk.Client.heartbeatOnce"
|
||||
if c.opts.proxyAddr != "" {
|
||||
c.mu.Lock()
|
||||
token := c.actToken
|
||||
c.mu.Unlock()
|
||||
if token == "" {
|
||||
if err := c.attestProxy(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return c.renewProxy(ctx)
|
||||
}
|
||||
c.mu.Lock()
|
||||
@@ -178,6 +186,9 @@ func (c *Client) heartbeatOnce(ctx context.Context) error {
|
||||
grace := c.gracePeriod
|
||||
c.mu.Unlock()
|
||||
if token == "" {
|
||||
if key := c.activationKey(); key != "" {
|
||||
return c.Activate(ctx, key)
|
||||
}
|
||||
return errors.New("sdk: 未激活(无 activation_token)")
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package sdk
|
||||
|
||||
import "testing"
|
||||
|
||||
// TestClockRollback_Compensated 本地时钟回拨不得让可信时间倒退。
|
||||
func TestClockRollback_Compensated(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
clock := &fakeClock{now: e.now}
|
||||
path := writeFileLicense(t, e, 0)
|
||||
c, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(clock))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
before := c.trustedNow()
|
||||
clock.Advance(-3600) // 墙钟回拨 1h
|
||||
c.tick()
|
||||
if got := c.trustedNow(); got < before {
|
||||
t.Fatalf("可信时间倒退: before=%d after=%d", before, got)
|
||||
}
|
||||
if c.State() != StateActive {
|
||||
t.Fatalf("回拨不应改变有效状态: %s", c.State())
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package sdk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
|
||||
)
|
||||
|
||||
// TestModeStack_RemoteFailsFallsBackToFile 在线激活失败时保留文件 license。
|
||||
func TestModeStack_RemoteFailsFallsBackToFile(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
path := writeFileLicense(t, e, 0)
|
||||
fail := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer fail.Close()
|
||||
|
||||
c, err := New(WithLicenseFile(path), WithRemoteServer(fail.URL),
|
||||
WithProductKey("prod_test"), WithTrustChain(e.trust()),
|
||||
WithClock(&fakeClock{now: e.now}), WithLicenseKey("ef-KEY"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
if err := c.Start(context.Background()); err != nil {
|
||||
t.Fatalf("应回退到文件 license: %v", err)
|
||||
}
|
||||
if c.State() != StateActive {
|
||||
t.Fatalf("回退后状态: %s", c.State())
|
||||
}
|
||||
if !c.Enabled("module.audit-log") {
|
||||
t.Error("文件 license 授权应可用")
|
||||
}
|
||||
}
|
||||
|
||||
// TestModeStack_ProxyFailsFallsBackToFile 代理不可达时保留文件 license。
|
||||
func TestModeStack_ProxyFailsFallsBackToFile(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
path := writeFileLicense(t, e, 0)
|
||||
fail := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer fail.Close()
|
||||
|
||||
c, err := New(WithLicenseFile(path), WithProxy(fail.URL), WithSAToken("sa"),
|
||||
WithProductKey("prod_test"), WithTrustChain(e.trust()),
|
||||
WithClock(&fakeClock{now: e.now}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
if err := c.Start(context.Background()); err != nil {
|
||||
t.Fatalf("应回退: %v", err)
|
||||
}
|
||||
if c.State() != StateActive {
|
||||
t.Fatalf("状态: %s", c.State())
|
||||
}
|
||||
}
|
||||
|
||||
// TestProxy_HeartbeatAttestsWhenNoToken 无 proxy_token 时心跳先认证再续租。
|
||||
func TestProxy_HeartbeatAttestsWhenNoToken(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
var attest, renew int
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /v1/proxy/attest", func(w http.ResponseWriter, r *http.Request) {
|
||||
attest++
|
||||
json.NewEncoder(w).Encode(map[string]any{ //nolint:errcheck
|
||||
"proxy_token": "ptok", "identity": "system:serviceaccount:ns:sa",
|
||||
"lease": e.leaseToken(), "renew_after": 60,
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("POST /v1/proxy/renew", func(w http.ResponseWriter, r *http.Request) {
|
||||
renew++
|
||||
json.NewEncoder(w).Encode(map[string]any{"lease": e.leaseToken(), "changed": true}) //nolint:errcheck
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
c, err := New(WithProxy(srv.URL), WithSAToken("sa"), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(&fakeClock{now: e.now}))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
if err := c.heartbeatOnce(context.Background()); err != nil {
|
||||
t.Fatalf("首次心跳应自动认证: %v", err)
|
||||
}
|
||||
if attest != 1 || renew != 1 {
|
||||
t.Errorf("attest=%d renew=%d", attest, renew)
|
||||
}
|
||||
if c.State() != StateActive {
|
||||
t.Errorf("状态: %s", c.State())
|
||||
}
|
||||
}
|
||||
|
||||
// TestFileMode_BytesTick 内存 license 在过期时应迁移 EXPIRED。
|
||||
func TestFileMode_BytesTick(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
clock := &fakeClock{now: e.now}
|
||||
c, err := New(WithLicenseBytes([]byte(e.sign(nil))), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(clock))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
clock.Advance(86400 + 1200)
|
||||
c.tick()
|
||||
if c.State() != StateExpired {
|
||||
t.Fatalf("内存 license 过期应 EXPIRED: %s", c.State())
|
||||
}
|
||||
_ = license.TypeSubscription
|
||||
}
|
||||
Reference in new issue
Block a user