diff --git a/sdk/client.go b/sdk/client.go index cd7576b..29d1a02 100644 --- a/sdk/client.go +++ b/sdk/client.go @@ -248,36 +248,78 @@ func New(opts ...Option) (*Client, error) { // Start 启动后台循环:文件轮询 / 远程心跳。 func (c *Client) Start(ctx context.Context) error { const logField = "pkg.sdk.Client.Start" + + // 在线/代理模式优先;文件/字节 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)") + } + c.opts.logger.Info("SDK 远程模式已启动", "logger", logField, "server", c.opts.remoteServer) + } else { + if !c.fromCache { + if err := c.attestProxy(ctx); err != nil { + if !c.fallbackAvailable() { + return fmt.Errorf("sdk: 代理认证: %w", err) + } + 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 c.opts.remoteServer != "" { - key := c.activationKey() - // 缓存恢复的 GRACE 无需立即激活;心跳 401/410 时会自动重激活 - if key != "" && !c.fromCache { - if err := c.Activate(ctx, key); err != nil { - return fmt.Errorf("sdk: 自动激活: %w", 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 != "" { - 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) + 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) }) diff --git a/sdk/remote.go b/sdk/remote.go index 58189d3..fbfb792 100644 --- a/sdk/remote.go +++ b/sdk/remote.go @@ -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)") } diff --git a/sdk/v05_test.go b/sdk/v05_test.go new file mode 100644 index 0000000..6fa12d8 --- /dev/null +++ b/sdk/v05_test.go @@ -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 +}