- 新增 sdk.MachineFingerprint:Linux machine-id+DMI、macOS IOPlatformUUID,容器内 fail-closed - 文件模式在 bind.fp 存在时自动校验,无需显式 WithFingerprint;采集失败拒绝绑定 license - 新增 WithFingerprintFunc 支持容器读取挂载宿主 machine-id;在线激活同步使用自动指纹 - license 包新增 NormalizeFingerprint(sha256:64hex 校验与小写归一化) - 新增指纹绑定/采集失败/无绑定跳过等测试
302 lines
8.7 KiB
Go
302 lines
8.7 KiB
Go
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"
|
||
// 指纹:显式注入 > 自定义采集器 > 自动采集;自动采集失败时退回 hostname 席位标识
|
||
// (若 license 绑定了机器,服务端会以指纹不符拒绝,不会误放行)。
|
||
fp, fpErr := c.effectiveFingerprint()
|
||
if fpErr != nil {
|
||
c.opts.logger.Warn("自动指纹采集失败,激活仅使用 hostname 席位标识",
|
||
"logger", logField, "error", fpErr)
|
||
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 是自动采集失败时的最后退路(仅 hostname),用于无绑定 license 的席位标识。
|
||
// 有 bind.fp 的 license 在文件模式会 fail-closed(见 MachineFingerprint / verifyToken)。
|
||
func defaultFingerprint() string {
|
||
return "sha256:host:" + hostname()
|
||
}
|
||
|
||
func hostname() string {
|
||
h, err := os.Hostname()
|
||
if err != nil {
|
||
return "unknown"
|
||
}
|
||
return h
|
||
}
|