Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2c1eeae070
|
||
|
|
834882e044
|
||
|
|
adcfb160ce
|
||
|
|
d5e3b4324a
|
||
|
|
7bfd44b588
|
||
|
|
f47fe893f1
|
||
|
|
e30101186c
|
||
|
|
c854215dc9
|
||
|
|
eebb4998d6
|
||
|
|
10c66cc30e
|
No files matched your search
+12
-7
@@ -4,26 +4,31 @@ name: sdk-ci
|
||||
on:
|
||||
push:
|
||||
branches: ["*"]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOPROXY: https://goproxy.cn,direct
|
||||
GOSUMDB: "off"
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.27"
|
||||
mirror: https://mirrors.aliyun.com/golang/
|
||||
- name: 全量测试(race + shuffle)
|
||||
run: go test -race -shuffle=on ./...
|
||||
- name: 依赖闭包断言(零第三方依赖红线)
|
||||
- name: 依赖闭包断言(零第三方依赖红线,go list -m 权威判据)
|
||||
run: |
|
||||
DEPS=$(go list -deps ./... | grep -vE "^(internal|vendor)/" | grep "\." | \
|
||||
grep -v "^git.wxccs.org/EntitleForge/EntitleForge-SDK-go" || true)
|
||||
if [ -n "$DEPS" ]; then
|
||||
echo "SDK 引入了第三方依赖(违反零依赖红线):"; echo "$DEPS"; exit 1
|
||||
MODS=$(go list -m all | grep -v "^git.wxccs.org/EntitleForge/EntitleForge-SDK-go" || true)
|
||||
if [ -n "$MODS" ]; then
|
||||
echo "SDK 引入了模块依赖(违反零依赖红线):"; echo "$MODS"; exit 1
|
||||
fi
|
||||
echo "依赖闭包:纯标准库 ✓"
|
||||
echo "依赖闭包:go.mod 零 require ✓(纯标准库)"
|
||||
- name: 交叉编译冒烟(CGO free)
|
||||
run: |
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build ./...
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
# 益铸 EntitleForge SDK 发布流水线(仅 v* tag 触发)。
|
||||
# go module 库的"发版"即 git tag(客户 go get 直接引用);此流水线补齐:
|
||||
# Gitea Release 记录 + 源码包附件,成功后清理失败的 action 记录。
|
||||
name: sdk-release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
|
||||
env:
|
||||
GOPROXY: https://goproxy.cn,direct
|
||||
GOSUMDB: "off"
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: "1.27"
|
||||
mirror: https://mirrors.aliyun.com/golang/
|
||||
- name: 发布前测试(tag 必须指向全绿代码)
|
||||
run: go test -race -shuffle=on ./...
|
||||
|
||||
- name: 创建 Release 并上传源码包
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.REGISTRY_PUSH_TOKEN }}
|
||||
run: |
|
||||
set -eu
|
||||
API="${GITHUB_SERVER_URL}/api/v1"
|
||||
REPO="${GITHUB_REPOSITORY}"
|
||||
VERSION="${GITHUB_REF_NAME}"
|
||||
tar -czf "entitleforge-sdk-${VERSION}.tar.gz" --exclude='.git' .
|
||||
PAYLOAD=$(printf '{"tag_name":"%s","name":"益铸 EntitleForge SDK %s","body":"go get %s@%s(零第三方依赖)","draft":false,"prerelease":false}' \
|
||||
"${VERSION}" "${VERSION}" "${REPO,,}" "${VERSION}")
|
||||
curl -sS -X POST -H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/json" -d "${PAYLOAD}" \
|
||||
"${API}/repos/${REPO}/releases" >/dev/null
|
||||
echo "Release ${VERSION} 创建完成(go get 引用即发版本体)"
|
||||
|
||||
# 清理失败的 action 记录——always():release 失败时更要清理(否则失败轮次永久堆积)
|
||||
cleanup:
|
||||
needs: release
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: 清理失败的 workflow runs
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.REGISTRY_PUSH_TOKEN }}
|
||||
run: |
|
||||
set -eu
|
||||
API="${GITHUB_SERVER_URL}/api/v1"
|
||||
REPO="${GITHUB_REPOSITORY}"
|
||||
PAGE=1
|
||||
while :; do
|
||||
RUNS=$(curl -sS -H "Authorization: token ${GITEA_TOKEN}" "${API}/repos/${REPO}/actions/tasks?limit=50&page=${PAGE}")
|
||||
TOTAL=$(echo "${RUNS}" | python3 -c "import json,sys; print(json.load(sys.stdin).get('total_count',0))")
|
||||
echo "${RUNS}" | python3 -c "import json,sys; [print(r['url']) for r in json.load(sys.stdin).get('workflow_runs',[]) if r.get('status') in ('failure','cancelled')]" | while read -r url; do
|
||||
RUN_API=$(echo "${url}" | sed "s|${GITHUB_SERVER_URL}/\\(.*\\)/actions/runs/|${API}/repos/\\1/actions/runs/|")
|
||||
echo "删除失败 run: ${url}"
|
||||
curl -sS -o /dev/null -X DELETE -H "Authorization: token ${GITEA_TOKEN}" "${RUN_API}"
|
||||
done
|
||||
[ "$((PAGE * 50))" -ge "${TOTAL}" ] && break
|
||||
PAGE=$((PAGE + 1))
|
||||
done
|
||||
echo "失败 action 清理完成"
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
益铸(EntitleForge)授权管理系统的客户端 SDK——**零第三方依赖**(纯 Go 标准库)。
|
||||
|
||||
服务端与控制台见 [EntitleForge 主仓](../EntitleForge)。
|
||||
服务端与控制台见 [EntitleForge 主仓](https://git.wxccs.org/EntitleForge/EntitleForge)。
|
||||
|
||||
## 引入
|
||||
|
||||
@@ -45,6 +45,34 @@ client.Check("module.x") // (bool, Reason)——GRACE/EXPIRED/REVO
|
||||
|
||||
状态机:`UNVERIFIED → ACTIVE → GRACE(断连宽限)→ EXPIRED / REVOKED(终态)`。
|
||||
|
||||
## 机器绑定
|
||||
|
||||
license payload 带 `bind.fp` 时,SDK 默认自动采集本机指纹并校验,不一致或采集失败即拒绝(fail-closed)。可用 `sdk.MachineFingerprint()` 查看本机值,或用 `WithFingerprint` / `WithFingerprintFunc` 显式注入:
|
||||
|
||||
```go
|
||||
fp, err := sdk.MachineFingerprint() // "sha256:…"
|
||||
client, err := sdk.New(sdk.WithLicenseFile("license.eflic"), ...) // 自动校验 bind.fp
|
||||
client, err := sdk.New(..., sdk.WithFingerprint(fp)) // 显式覆盖
|
||||
client, err := sdk.New(..., sdk.WithFingerprintFunc(func() (string, error) {
|
||||
return readHostMachineID() // 容器内读取挂载的宿主 ID
|
||||
}))
|
||||
```
|
||||
|
||||
Linux 采集 machine-id + DMI product_uuid;macOS 采集 IOPlatformUUID;容器内默认拒绝自动采集(容器自身 ID 不稳定),需挂载宿主 `/etc/machine-id` 并注入自定义采集器,或显式指定指纹。
|
||||
|
||||
## 吊销与强制校验
|
||||
|
||||
- 心跳响应携带的 CRL 会自动验签并应用(版本单调,防回滚);命中当前 license 立即转 `REVOKED`。
|
||||
- 文件模式可配置在线校验源,按 license 的 `pol.forced_check` 周期校验,失败转 `EXPIRED`:
|
||||
|
||||
```go
|
||||
client, err := sdk.New(sdk.WithLicenseFile("license.eflic"),
|
||||
sdk.WithProductKey("prod_x"), sdk.WithTrustChain(chain),
|
||||
sdk.WithValidationServer("https://license.vendor.com"))
|
||||
```
|
||||
|
||||
未配置 `WithValidationServer` 时保持完全离线兼容(仅告警跳过强制校验);完全离线的 license 应在 Policy 中设置 `forced_check: 0`。
|
||||
|
||||
## 包结构
|
||||
|
||||
| 包 | 职责 |
|
||||
@@ -57,7 +85,7 @@ client.Check("module.x") // (bool, Reason)——GRACE/EXPIRED/REVO
|
||||
## 与服务端的关系
|
||||
|
||||
本仓的 `license`/`crypto` 是协议实现的**单一归属**——服务端(EntitleForge 主仓)反向依赖本仓,
|
||||
杜绝两套实现漂移([设计文档 §2](../EntitleForge/docs/design/07-sdk.md))。
|
||||
杜绝两套实现漂移([设计文档 §2](https://git.wxccs.org/EntitleForge/EntitleForge/blob/main/docs/design/07-sdk.md))。
|
||||
|
||||
## 开发
|
||||
|
||||
|
||||
+108
-5
@@ -65,11 +65,12 @@ type proxyEntry struct {
|
||||
// TrustChain 是验证方的信任根集合:root 公钥 + signing 公钥(按 kid)+
|
||||
// 受约束 Proxy Key(按 kid)+ 本地 CRL。并发安全:读多写少,RWMutex 保护。
|
||||
type TrustChain struct {
|
||||
mu sync.RWMutex
|
||||
root ed25519.PublicKey
|
||||
keys map[string]signingEntry
|
||||
proxies map[string]proxyEntry
|
||||
revoked map[string]struct{}
|
||||
mu sync.RWMutex
|
||||
root ed25519.PublicKey
|
||||
keys map[string]signingEntry
|
||||
proxies map[string]proxyEntry
|
||||
revoked map[string]struct{}
|
||||
crlVersion int64
|
||||
}
|
||||
|
||||
// NewTrustChain 以 root 公钥为锚点创建空信任链。
|
||||
@@ -218,6 +219,108 @@ func (tc *TrustChain) RevokedList() []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// CRLPayload 是服务端物化 CRL 的载荷(docs/design/04-crypto.md §4)。
|
||||
type CRLPayload struct {
|
||||
V int `json:"v"`
|
||||
Version int64 `json:"version"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
Revoked []string `json:"revoked"`
|
||||
}
|
||||
|
||||
// LoadCRL 校验并应用服务端下发的 CRL(typ=crl,active signing key 签名)。
|
||||
// 版本单调:版本号不大于本地已应用版本时忽略(防回滚),返回 applied=false。
|
||||
// 已吊销条目只增不减——即使新 CRL 遗漏旧条目也不会“复活”。
|
||||
func (tc *TrustChain) LoadCRL(token string) (version int64, applied bool, err error) {
|
||||
h, payload, sig, err := license.Decode(token)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
if h.Typ != license.TypCRL {
|
||||
return 0, false, fmt.Errorf("%w: typ %q 非 crl", license.ErrUnsupported, h.Typ)
|
||||
}
|
||||
pub, ok := tc.KeyFor(h.Kid)
|
||||
if !ok {
|
||||
return 0, false, fmt.Errorf("%w: kid %q", ErrUnknownKey, h.Kid)
|
||||
}
|
||||
content, err := license.SignedContent(token)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
}
|
||||
if !ed25519.Verify(pub, []byte(content), sig) {
|
||||
return 0, false, ErrBadSignature
|
||||
}
|
||||
var p CRLPayload
|
||||
if err := json.Unmarshal(payload, &p); err != nil {
|
||||
return 0, false, fmt.Errorf("%w: crl payload: %v", license.ErrMalformed, err)
|
||||
}
|
||||
if p.V != 1 || p.Version <= 0 {
|
||||
return 0, false, fmt.Errorf("%w: crl 版本字段非法(v=%d version=%d)", license.ErrMalformed, p.V, p.Version)
|
||||
}
|
||||
|
||||
tc.mu.Lock()
|
||||
defer tc.mu.Unlock()
|
||||
if p.Version <= tc.crlVersion {
|
||||
return p.Version, false, nil
|
||||
}
|
||||
for _, jti := range p.Revoked {
|
||||
if jti != "" {
|
||||
tc.revoked[jti] = struct{}{}
|
||||
}
|
||||
}
|
||||
tc.crlVersion = p.Version
|
||||
return p.Version, true, nil
|
||||
}
|
||||
|
||||
// CRLVersion 返回本地已应用的最大 CRL 版本(0 = 尚未应用)。
|
||||
func (tc *TrustChain) CRLVersion() int64 {
|
||||
tc.mu.RLock()
|
||||
defer tc.mu.RUnlock()
|
||||
return tc.crlVersion
|
||||
}
|
||||
|
||||
// Verdict 是在线校验结论(typ=verdict)的载荷。
|
||||
type Verdict struct {
|
||||
JTI string `json:"jti"`
|
||||
State string `json:"state"`
|
||||
At int64 `json:"at"`
|
||||
}
|
||||
|
||||
// VerdictMaxAgeSeconds 是 verdict 的保鲜窗口:过期结论不得用于放行(防重放)。
|
||||
const VerdictMaxAgeSeconds int64 = 600
|
||||
|
||||
// VerifyVerdict 校验在线校验结论的签名与时效,返回可采信的结论。
|
||||
func (tc *TrustChain) VerifyVerdict(token string, now int64) (*Verdict, error) {
|
||||
h, payload, sig, err := license.Decode(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if h.Typ != license.TypVerdict {
|
||||
return nil, fmt.Errorf("%w: typ %q 非 verdict", license.ErrUnsupported, h.Typ)
|
||||
}
|
||||
pub, ok := tc.KeyFor(h.Kid)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: kid %q", ErrUnknownKey, h.Kid)
|
||||
}
|
||||
content, err := license.SignedContent(token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ed25519.Verify(pub, []byte(content), sig) {
|
||||
return nil, ErrBadSignature
|
||||
}
|
||||
var v Verdict
|
||||
if err := json.Unmarshal(payload, &v); err != nil {
|
||||
return nil, fmt.Errorf("%w: verdict payload: %v", license.ErrMalformed, err)
|
||||
}
|
||||
if v.JTI == "" || v.State == "" {
|
||||
return nil, fmt.Errorf("%w: verdict 缺少 jti/state", license.ErrMalformed)
|
||||
}
|
||||
if v.At != 0 && now-v.At > VerdictMaxAgeSeconds {
|
||||
return nil, fmt.Errorf("%w: verdict 已过期(age=%ds)", license.ErrMalformed, now-v.At)
|
||||
}
|
||||
return &v, nil
|
||||
}
|
||||
|
||||
// SignBundle 把当前 signing 集合与 CRL 打包为 root 签名的 trust bundle token。
|
||||
func (tc *TrustChain) SignBundle(rootPriv ed25519.PrivateKey) (string, error) {
|
||||
tc.mu.RLock()
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package license
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// fingerprintPattern 是 bind.fp 的协议形态:sha256:<64 位十六进制>。
|
||||
var fingerprintPattern = regexp.MustCompile(`(?i)^sha256:[0-9a-f]{64}$`)
|
||||
|
||||
// NormalizeFingerprint 校验并归一化机器指纹(统一为小写 sha256:<hex>)。
|
||||
// 空字符串表示不绑定,返回空值且无错误。
|
||||
func NormalizeFingerprint(fp string) (string, error) {
|
||||
fp = strings.TrimSpace(fp)
|
||||
if fp == "" {
|
||||
return "", nil
|
||||
}
|
||||
if !fingerprintPattern.MatchString(fp) {
|
||||
return "", errors.New("机器指纹必须形如 sha256:<64 位十六进制>")
|
||||
}
|
||||
return "sha256:" + strings.ToLower(fp[len("sha256:"):]), nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package license
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNormalizeFingerprint(t *testing.T) {
|
||||
valid := "sha256:" + strings.Repeat("a", 64)
|
||||
cases := []struct {
|
||||
input string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{"", "", false},
|
||||
{valid, valid, false},
|
||||
{" " + strings.ToUpper(valid) + " ", valid, false},
|
||||
{"not-a-fingerprint", "", true},
|
||||
{"sha256:xyz", "", true},
|
||||
{"sha256:" + strings.Repeat("g", 64), "", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got, err := NormalizeFingerprint(tc.input)
|
||||
if (err != nil) != tc.wantErr {
|
||||
t.Errorf("%q: err=%v wantErr=%v", tc.input, err, tc.wantErr)
|
||||
continue
|
||||
}
|
||||
if got != tc.want {
|
||||
t.Errorf("%q: got %q want %q", tc.input, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+135
-18
@@ -9,6 +9,7 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@@ -53,17 +54,19 @@ func (wallClock) Now() int64 { return time.Now().Unix() }
|
||||
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
|
||||
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
|
||||
validationServer string // 文件模式强制校验点(POST /v1/validate)
|
||||
|
||||
// Proxy 模式(docs/design/08-k8s-proxy.md §4)
|
||||
proxyAddr string
|
||||
@@ -74,11 +77,19 @@ type options struct {
|
||||
// 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 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 } }
|
||||
@@ -86,6 +97,12 @@ func WithLogger(l *slog.Logger) Option { return func(o *options)
|
||||
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 } }
|
||||
|
||||
// WithValidationServer 配置文件模式强制校验点使用的在线校验源(License Server 基址)。
|
||||
// 未配置时,带 forced_check 的离线 license 只告警不强制(保持完全离线兼容)。
|
||||
func WithValidationServer(baseURL string) Option {
|
||||
return func(o *options) { o.validationServer = strings.TrimSuffix(baseURL, "/") }
|
||||
}
|
||||
|
||||
// WithProxy 集群内代理模式(http://ef-proxy.ef-system.svc:8443)。
|
||||
func WithProxy(addr string) Option { return func(o *options) { o.proxyAddr = addr } }
|
||||
|
||||
@@ -116,6 +133,10 @@ type Client struct {
|
||||
actToken string
|
||||
heartbeatEvery int64
|
||||
gracePeriod int64
|
||||
|
||||
crlVersion atomic.Int64 // 最近应用/上报的 CRL 版本
|
||||
lastCheckAt atomic.Int64 // 最近一次在线校验成功时刻(强制校验点计时)
|
||||
noCheckWarn sync.Once
|
||||
}
|
||||
|
||||
// New 创建 Client。
|
||||
@@ -226,8 +247,15 @@ func (c *Client) verifyToken(token string) (*license.Payload, error) {
|
||||
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: 机器指纹绑定不符")
|
||||
// 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
|
||||
}
|
||||
@@ -241,6 +269,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.lastCheckAt.Store(c.opts.clock.Now())
|
||||
if old == nil || old.state != StateActive {
|
||||
c.opts.logger.Info("授权已装载", "logger", "pkg.sdk.Client.installVerified", "jti", p.JTI)
|
||||
}
|
||||
@@ -274,12 +303,100 @@ func (c *Client) tick() {
|
||||
c.transition(s, StateExpired, 0)
|
||||
return
|
||||
}
|
||||
// 离线强制校验点:到期必须成功在线校验一次,否则 EXPIRED(docs/design/07-sdk.md §6.4)
|
||||
if c.forcedCheckDue(s, now) {
|
||||
if err := c.validateOnline(context.Background()); err != nil {
|
||||
c.opts.logger.Warn("强制在线校验失败,进入 EXPIRED", "logger", logField, "error", err)
|
||||
c.transition(s, StateExpired, 0)
|
||||
return
|
||||
}
|
||||
}
|
||||
// 文件模式:热重载
|
||||
if c.opts.licenseFile != "" {
|
||||
c.reloadIfChanged()
|
||||
}
|
||||
}
|
||||
|
||||
// forcedCheckDue 判断是否到达强制校验点:
|
||||
// 仅文件模式、payload 携带 pol.forced_check>0 且配置了校验源时生效。
|
||||
func (c *Client) forcedCheckDue(s *snapshot, now int64) bool {
|
||||
if c.opts.licenseFile == "" || s.payload == nil || s.payload.Pol == nil {
|
||||
return false
|
||||
}
|
||||
forced := s.payload.Pol.ForcedCheck
|
||||
if forced <= 0 {
|
||||
return false
|
||||
}
|
||||
if c.opts.validationServer == "" {
|
||||
c.noCheckWarn.Do(func() {
|
||||
c.opts.logger.Warn("license 含 forced_check 但未配置 WithValidationServer,跳过强制在线校验",
|
||||
"logger", "pkg.sdk.Client.forcedCheckDue", "forced_check", forced)
|
||||
})
|
||||
return false
|
||||
}
|
||||
last := c.lastCheckAt.Load()
|
||||
return last > 0 && now-last >= forced
|
||||
}
|
||||
|
||||
// validateOnline 调用 /v1/validate 并验签 verdict;成功则刷新强制校验计时。
|
||||
func (c *Client) validateOnline(ctx context.Context) error {
|
||||
const logField = "pkg.sdk.Client.validateOnline"
|
||||
s := c.snap.Load()
|
||||
if s == nil || s.rawToken == "" {
|
||||
return errors.New("sdk: 无已装载 license,无法在线校验")
|
||||
}
|
||||
body := map[string]any{"license": s.rawToken, "crl_version": c.crlVersion.Load()}
|
||||
var resp struct {
|
||||
Valid bool `json:"valid"`
|
||||
State string `json:"state"`
|
||||
Verdict string `json:"verdict"`
|
||||
CRL string `json:"crl"`
|
||||
CRLVersion int64 `json:"crl_version"`
|
||||
}
|
||||
if err := c.postJSONTo(ctx, c.opts.validationServer, "/v1/validate", "", body, &resp); err != nil {
|
||||
return fmt.Errorf("在线校验请求: %w", err)
|
||||
}
|
||||
if resp.CRL != "" {
|
||||
if _, _, err := c.opts.trust.LoadCRL(resp.CRL); err != nil {
|
||||
c.opts.logger.Warn("在线校验响应 CRL 验签失败,已忽略", "logger", logField, "error", err)
|
||||
}
|
||||
}
|
||||
if !resp.Valid || resp.State != "ACTIVE" {
|
||||
return fmt.Errorf("服务端判定不可用(state=%s)", resp.State)
|
||||
}
|
||||
v, err := c.opts.trust.VerifyVerdict(resp.Verdict, c.opts.clock.Now())
|
||||
if err != nil {
|
||||
return fmt.Errorf("verdict 验签: %w", err)
|
||||
}
|
||||
if v.JTI != s.payload.JTI || v.State != "ACTIVE" {
|
||||
return fmt.Errorf("verdict 与本地 license 不一致(jti=%s state=%s)", v.JTI, v.State)
|
||||
}
|
||||
c.lastCheckAt.Store(c.opts.clock.Now())
|
||||
c.opts.logger.Debug("强制在线校验通过", "logger", logField, "jti", v.JTI)
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyCRL 应用服务端下发的 CRL;命中当前快照时立即迁移 REVOKED。
|
||||
func (c *Client) applyCRL(token string) {
|
||||
const logField = "pkg.sdk.Client.applyCRL"
|
||||
version, applied, err := c.opts.trust.LoadCRL(token)
|
||||
if err != nil {
|
||||
c.opts.logger.Warn("CRL 验签失败,已忽略", "logger", logField, "error", err)
|
||||
return
|
||||
}
|
||||
if version > c.crlVersion.Load() {
|
||||
c.crlVersion.Store(version)
|
||||
}
|
||||
if !applied {
|
||||
return
|
||||
}
|
||||
c.opts.logger.Info("CRL 已更新", "logger", logField, "version", version)
|
||||
s := c.snap.Load()
|
||||
if s != nil && s.payload != nil && c.opts.trust.IsRevoked(s.payload.JTI) {
|
||||
c.transition(s, StateRevoked, 0)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 文件模式 ----
|
||||
|
||||
func (c *Client) fileLoop(ctx context.Context) {
|
||||
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
package sdk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/crypto"
|
||||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
|
||||
)
|
||||
|
||||
// crlSign 用测试 signing key 签名 CRL token(服务端 buildCRLSigned 同构)。
|
||||
func (e *testEnv) crlToken(version int64, revoked []string) string {
|
||||
e.t.Helper()
|
||||
payload, err := json.Marshal(map[string]any{
|
||||
"v": 1, "version": version, "updated_at": e.now, "revoked": revoked,
|
||||
})
|
||||
if err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
token, err := crypto.SignToken(e.priv, e.kid, license.TypCRL, payload)
|
||||
if err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
type crlRemote struct {
|
||||
mu sync.Mutex
|
||||
server *httptest.Server
|
||||
lease string
|
||||
crl string
|
||||
crlVersion int64
|
||||
lastSentCRL int64 // 最近一次请求上报的 crl_version
|
||||
}
|
||||
|
||||
func newCRLRemote(t *testing.T, e *testEnv) *crlRemote {
|
||||
cr := &crlRemote{lease: e.leaseToken()}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /v1/activate", func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(map[string]any{ //nolint:errcheck
|
||||
"activation_id": "act-01JDFAKE00000000000000000", "activation_token": "tok",
|
||||
"lease": cr.lease, "lease_ttl": int64(3600), "heartbeat_interval": 900,
|
||||
"grace_period": 259200, "server_time": e.now, "crl_version": 0,
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("POST /v1/heartbeat", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
CRLVersion int64 `json:"crl_version"`
|
||||
}
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(raw, &body)
|
||||
cr.mu.Lock()
|
||||
cr.lastSentCRL = body.CRLVersion
|
||||
resp := map[string]any{
|
||||
"changed": false, "server_time": e.now, "crl_version": cr.crlVersion,
|
||||
}
|
||||
if cr.crl != "" && body.CRLVersion < cr.crlVersion {
|
||||
resp["crl"] = cr.crl
|
||||
}
|
||||
cr.mu.Unlock()
|
||||
json.NewEncoder(w).Encode(resp) //nolint:errcheck
|
||||
})
|
||||
cr.server = httptest.NewServer(mux)
|
||||
t.Cleanup(cr.server.Close)
|
||||
return cr
|
||||
}
|
||||
|
||||
// TestHeartbeat_AppliesCRLAndRevokes 心跳携带的 CRL 必须被应用:命中当前 jti → REVOKED。
|
||||
func TestHeartbeat_AppliesCRLAndRevokes(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
cr := newCRLRemote(t, e)
|
||||
clock := &fakeClock{now: e.now}
|
||||
|
||||
c, err := New(WithRemoteServer(cr.server.URL), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(clock), WithLicenseKey("ef-TEST-TEST-TEST-TEST"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := c.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
if c.State() != StateActive {
|
||||
t.Fatalf("激活后状态: %s", c.State())
|
||||
}
|
||||
|
||||
cr.mu.Lock()
|
||||
cr.crlVersion = 7
|
||||
cr.crl = e.crlToken(7, []string{"01JDTEST000000000000000000"})
|
||||
cr.mu.Unlock()
|
||||
|
||||
if err := c.heartbeatOnce(context.Background()); err != nil {
|
||||
t.Fatalf("心跳: %v", err)
|
||||
}
|
||||
if c.State() != StateRevoked {
|
||||
t.Fatalf("CRL 命中后应 REVOKED: %s", c.State())
|
||||
}
|
||||
cr.mu.Lock()
|
||||
sent := cr.lastSentCRL
|
||||
cr.mu.Unlock()
|
||||
if sent != 0 {
|
||||
t.Errorf("首次心跳应上报 crl_version=0: %d", sent)
|
||||
}
|
||||
|
||||
// 下一次心跳应上报已应用版本(服务端不再重复下发)
|
||||
if err := c.heartbeatOnce(context.Background()); err == nil {
|
||||
// REVOKED 终态下心跳可能仍成功;至少不应回退状态
|
||||
}
|
||||
if c.State() != StateRevoked {
|
||||
t.Fatalf("CRL 应用后状态不应回退: %s", c.State())
|
||||
}
|
||||
cr.mu.Lock()
|
||||
sent = cr.lastSentCRL
|
||||
cr.mu.Unlock()
|
||||
if sent != 7 {
|
||||
t.Errorf("应用后应上报 crl_version=7: %d", sent)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTrustChain_CRLRollbackIgnored 旧版本 CRL 不得回滚/撤销已应用条目。
|
||||
func TestTrustChain_CRLRollbackIgnored(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
tc := e.trust()
|
||||
|
||||
version, applied, err := tc.LoadCRL(e.crlToken(5, []string{"jti-a"}))
|
||||
if err != nil || !applied || version != 5 {
|
||||
t.Fatalf("首次应用: version=%d applied=%v err=%v", version, applied, err)
|
||||
}
|
||||
if !tc.IsRevoked("jti-a") {
|
||||
t.Fatal("jti-a 应被撤销")
|
||||
}
|
||||
|
||||
// 旧版本(无 jti-a)不得移除或替换已应用条目
|
||||
version, applied, err = tc.LoadCRL(e.crlToken(3, []string{"jti-b"}))
|
||||
if err != nil || applied || version != 3 {
|
||||
t.Fatalf("旧版本应忽略: version=%d applied=%v err=%v", version, applied, err)
|
||||
}
|
||||
if !tc.IsRevoked("jti-a") {
|
||||
t.Error("旧 CRL 不应撤销 jti-a 的吊销状态")
|
||||
}
|
||||
if tc.IsRevoked("jti-b") {
|
||||
t.Error("旧 CRL 不应生效")
|
||||
}
|
||||
if tc.CRLVersion() != 5 {
|
||||
t.Errorf("版本应保持 5: %d", tc.CRLVersion())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package sdk
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/crypto"
|
||||
)
|
||||
|
||||
// machineFingerprintProvider 是默认采集器,测试可替换。
|
||||
var machineFingerprintProvider = MachineFingerprint
|
||||
|
||||
// MachineFingerprint 采集本机稳定标识并返回 "sha256:" 前缀摘要。
|
||||
//
|
||||
// 采集原则见 docs/design/04-crypto.md §5:
|
||||
// - Linux:/etc/machine-id(或 /var/lib/dbus/machine-id)+ DMI product_uuid;
|
||||
// - macOS:IOPlatformUUID(ioreg);
|
||||
// - 容器:禁止使用容器自身 ID;需显式 WithFingerprint 或 WithFingerprintFunc
|
||||
// 读取挂载的宿主 machine-id(设置 EF_FINGERPRINT_ALLOW_CONTAINER=1 可放行,
|
||||
// 仅当你确认 /etc/machine-id 来自宿主)。
|
||||
//
|
||||
// 原始字段仅在本地参与哈希,返回值不包含任何原始硬件信息。
|
||||
func MachineFingerprint() (string, error) {
|
||||
fields, err := machineFields()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(fields) == 0 {
|
||||
return "", errors.New("sdk: 无法采集稳定的机器标识字段")
|
||||
}
|
||||
return crypto.Fingerprint(fields...), nil
|
||||
}
|
||||
|
||||
// effectiveFingerprint 解析本次校验应使用的指纹:
|
||||
// 显式 WithFingerprint 优先,其次自定义采集器,最后默认采集器。
|
||||
func (c *Client) effectiveFingerprint() (string, error) {
|
||||
if c.opts.fingerprint != "" {
|
||||
return c.opts.fingerprint, nil
|
||||
}
|
||||
if c.opts.fingerprintFn != nil {
|
||||
fp, err := c.opts.fingerprintFn()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("sdk: 机器指纹采集失败(自定义采集器): %w", err)
|
||||
}
|
||||
if strings.TrimSpace(fp) == "" {
|
||||
return "", errors.New("sdk: 自定义指纹采集器返回空值")
|
||||
}
|
||||
return fp, nil
|
||||
}
|
||||
fp, err := machineFingerprintProvider()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("sdk: 机器指纹采集失败: %w", err)
|
||||
}
|
||||
if strings.TrimSpace(fp) == "" {
|
||||
return "", errors.New("sdk: 机器指纹采集结果为空")
|
||||
}
|
||||
return fp, nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//go:build darwin
|
||||
|
||||
package sdk
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ioPlatformUUIDPattern = regexp.MustCompile(`"IOPlatformUUID"\s*=\s*"([^"]+)"`)
|
||||
|
||||
// machineFields macOS 采集:IOPlatformUUID(硬件平台 UUID),
|
||||
// ioreg 不可用时退回 hostname(稳定性较弱,但至少可用于普通拷贝防护)。
|
||||
func machineFields() ([]string, error) {
|
||||
if out, err := exec.Command("ioreg", "-rd1", "-c", "IOPlatformExpertDevice").Output(); err == nil {
|
||||
if m := ioPlatformUUIDPattern.FindStringSubmatch(string(out)); len(m) == 2 && strings.TrimSpace(m[1]) != "" {
|
||||
return []string{"io-platform-uuid:" + strings.ToLower(strings.TrimSpace(m[1]))}, nil
|
||||
}
|
||||
}
|
||||
if h := hostname(); h != "" && h != "unknown" {
|
||||
return []string{"hostname:" + h}, nil
|
||||
}
|
||||
return nil, errors.New("sdk: macOS 上未取得 IOPlatformUUID 或 hostname")
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//go:build linux
|
||||
|
||||
package sdk
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// machineFields Linux 采集:machine-id + DMI product_uuid;
|
||||
// 两者都不可用时退回首个物理网卡 MAC,最后退回 hostname。
|
||||
func machineFields() ([]string, error) {
|
||||
if inContainer() {
|
||||
return nil, errors.New("sdk: 检测到容器环境,容器自身 ID 不稳定;请显式 WithFingerprint,或用 WithFingerprintFunc 读取挂载的宿主 /etc/machine-id(若已挂载宿主 ID,可设置 EF_FINGERPRINT_ALLOW_CONTAINER=1 放行)")
|
||||
}
|
||||
|
||||
var fields []string
|
||||
if v := readTrimmed("/etc/machine-id"); v != "" {
|
||||
fields = append(fields, "machine-id:"+v)
|
||||
} else if v := readTrimmed("/var/lib/dbus/machine-id"); v != "" {
|
||||
fields = append(fields, "machine-id:"+v)
|
||||
}
|
||||
if v := readTrimmed("/sys/class/dmi/id/product_uuid"); v != "" && !junkUUID(v) {
|
||||
fields = append(fields, "product-uuid:"+strings.ToLower(v))
|
||||
}
|
||||
if len(fields) == 0 {
|
||||
if mac := firstPhysicalMAC(); mac != "" {
|
||||
fields = append(fields, "mac:"+mac)
|
||||
}
|
||||
}
|
||||
if len(fields) == 0 {
|
||||
if h := hostname(); h != "" && h != "unknown" {
|
||||
fields = append(fields, "hostname:"+h)
|
||||
}
|
||||
}
|
||||
if len(fields) == 0 {
|
||||
return nil, errors.New("sdk: Linux 上未找到 machine-id/DMI/MAC/hostname 任一稳定标识")
|
||||
}
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
// inContainer 判断常见容器运行时;显式放行环境变量供"宿主 machine-id 已挂载"场景使用。
|
||||
func inContainer() bool {
|
||||
if os.Getenv("EF_FINGERPRINT_ALLOW_CONTAINER") == "1" {
|
||||
return false
|
||||
}
|
||||
if _, err := os.Stat("/.dockerenv"); err == nil {
|
||||
return true
|
||||
}
|
||||
if _, err := os.Stat("/run/.containerenv"); err == nil {
|
||||
return true
|
||||
}
|
||||
if data, err := os.ReadFile("/proc/1/cgroup"); err == nil {
|
||||
text := string(data)
|
||||
for _, marker := range []string{"docker", "kubepods", "containerd", "libpod"} {
|
||||
if strings.Contains(text, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// junkUUID 过滤全零/全 F 一类无效 DMI UUID。
|
||||
func junkUUID(v string) bool {
|
||||
s := strings.ReplaceAll(strings.ToLower(v), "-", "")
|
||||
if len(s) < 16 {
|
||||
return true
|
||||
}
|
||||
return strings.Trim(s, "0") == "" || strings.Trim(s, "f") == ""
|
||||
}
|
||||
|
||||
// firstPhysicalMAC 返回首个非回环、非全零的 MAC(小写,带冒号)。
|
||||
func firstPhysicalMAC() string {
|
||||
ifaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
for _, iface := range ifaces {
|
||||
if iface.Flags&net.FlagLoopback != 0 {
|
||||
continue
|
||||
}
|
||||
mac := iface.HardwareAddr.String()
|
||||
if mac == "" {
|
||||
continue
|
||||
}
|
||||
compact := strings.ReplaceAll(mac, ":", "")
|
||||
if strings.Trim(compact, "0") == "" {
|
||||
continue
|
||||
}
|
||||
return strings.ToLower(mac)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func readTrimmed(path string) string {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build !linux && !darwin
|
||||
|
||||
package sdk
|
||||
|
||||
import "errors"
|
||||
|
||||
// machineFields 其他平台暂无稳定硬件标识采集实现:仅使用 hostname 兜底。
|
||||
// 生产接入应通过 WithFingerprint 或 WithFingerprintFunc 注入平台特定标识。
|
||||
func machineFields() ([]string, error) {
|
||||
if h := hostname(); h != "" && h != "unknown" {
|
||||
return []string{"hostname:" + h}, nil
|
||||
}
|
||||
return nil, errors.New("sdk: 当前平台无法采集机器标识")
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package sdk
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
|
||||
)
|
||||
|
||||
func writeLicense(t *testing.T, token string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "license.eflic")
|
||||
if err := os.WriteFile(path, []byte(token), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// TestFileMode_AutoFingerprintBinding 验证 bind.fp 在未显式传入指纹时也会自动校验。
|
||||
func TestFileMode_AutoFingerprintBinding(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
const bound = "sha256:bound-value"
|
||||
token := e.sign(func(p *license.Payload) {
|
||||
p.Bind = &license.Bindings{FP: bound}
|
||||
})
|
||||
path := writeLicense(t, token)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
opt Option
|
||||
wantErr string
|
||||
}{
|
||||
{"自动采集匹配", WithFingerprintFunc(func() (string, error) { return bound, nil }), ""},
|
||||
{"自动采集不符", WithFingerprintFunc(func() (string, error) { return "sha256:other", nil }), "指纹绑定不符"},
|
||||
{"自动采集失败", WithFingerprintFunc(func() (string, error) { return "", errors.New("无稳定硬件标识") }), "指纹采集失败"},
|
||||
{"显式指纹覆盖自动采集", WithFingerprint(bound), ""},
|
||||
{"显式指纹不符", WithFingerprint("sha256:explicit-other"), "指纹绑定不符"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
client, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(&fakeClock{now: e.now}), tc.opt)
|
||||
if tc.wantErr != "" {
|
||||
if err == nil {
|
||||
t.Fatalf("应拒绝,实际通过(状态 %s)", client.State())
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.wantErr) {
|
||||
t.Fatalf("错误应包含 %q: %v", tc.wantErr, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("应通过: %v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
if client.State() != StateActive {
|
||||
t.Fatalf("状态: %s", client.State())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestFileMode_DefaultProviderInvoked 验证默认路径确实调用了机器指纹采集器。
|
||||
func TestFileMode_DefaultProviderInvoked(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
token := e.sign(func(p *license.Payload) {
|
||||
p.Bind = &license.Bindings{FP: "sha256:auto-collected"}
|
||||
})
|
||||
path := writeLicense(t, token)
|
||||
|
||||
old := machineFingerprintProvider
|
||||
machineFingerprintProvider = func() (string, error) { return "sha256:auto-collected", nil }
|
||||
defer func() { machineFingerprintProvider = old }()
|
||||
|
||||
client, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(&fakeClock{now: e.now}))
|
||||
if err != nil {
|
||||
t.Fatalf("默认自动采集应通过: %v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
if client.State() != StateActive {
|
||||
t.Fatalf("状态: %s", client.State())
|
||||
}
|
||||
}
|
||||
|
||||
// TestFileMode_UnboundLicenseSkipsCollector 无绑定 license 不应因采集失败而不可用。
|
||||
func TestFileMode_UnboundLicenseSkipsCollector(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
path := writeLicense(t, e.sign(nil))
|
||||
|
||||
old := machineFingerprintProvider
|
||||
machineFingerprintProvider = func() (string, error) { return "", errors.New("采集失败") }
|
||||
defer func() { machineFingerprintProvider = old }()
|
||||
|
||||
client, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(&fakeClock{now: e.now}))
|
||||
if err != nil {
|
||||
t.Fatalf("无绑定 license 不应触发指纹采集: %v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
if client.State() != StateActive {
|
||||
t.Fatalf("状态: %s", client.State())
|
||||
}
|
||||
}
|
||||
|
||||
// TestMachineFingerprint_Shape 验证公开采集 API 的形态;容器内无法采集时跳过。
|
||||
func TestMachineFingerprint_Shape(t *testing.T) {
|
||||
fp, err := MachineFingerprint()
|
||||
if err != nil {
|
||||
t.Skipf("当前环境无法自动采集(预期于容器内): %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(fp, "sha256:") || len(fp) != len("sha256:")+64 {
|
||||
t.Fatalf("指纹形态非法: %q", fp)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package sdk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/crypto"
|
||||
"git.wxccs.org/EntitleForge/EntitleForge-SDK-go/license"
|
||||
)
|
||||
|
||||
type validationServer struct {
|
||||
mu sync.Mutex
|
||||
server *httptest.Server
|
||||
valid bool
|
||||
calls int
|
||||
lastCRLV int64
|
||||
clock *fakeClock
|
||||
}
|
||||
|
||||
func newValidationServer(t *testing.T, e *testEnv, clock *fakeClock) *validationServer {
|
||||
vs := &validationServer{valid: true, clock: clock}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /v1/validate", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
License string `json:"license"`
|
||||
CRLVersion int64 `json:"crl_version"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&body)
|
||||
vs.mu.Lock()
|
||||
vs.calls++
|
||||
vs.lastCRLV = body.CRLVersion
|
||||
state := "ACTIVE"
|
||||
if !vs.valid {
|
||||
state = "REVOKED"
|
||||
}
|
||||
vs.mu.Unlock()
|
||||
|
||||
verdictPayload, _ := json.Marshal(map[string]any{
|
||||
"jti": "01JDTEST000000000000000000", "state": state, "at": vs.clock.Now(),
|
||||
})
|
||||
verdict, err := crypto.SignToken(e.priv, e.kid, license.TypVerdict, verdictPayload)
|
||||
if err != nil {
|
||||
t.Errorf("签 verdict: %v", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{ //nolint:errcheck
|
||||
"valid": state == "ACTIVE", "state": state, "verdict": verdict,
|
||||
"crl_version": 0, "server_time": vs.clock.Now(),
|
||||
})
|
||||
})
|
||||
vs.server = httptest.NewServer(mux)
|
||||
t.Cleanup(vs.server.Close)
|
||||
return vs
|
||||
}
|
||||
|
||||
func writeFileLicense(t *testing.T, e *testEnv, forcedCheck int64) string {
|
||||
t.Helper()
|
||||
token := e.sign(func(p *license.Payload) {
|
||||
p.Pol = &license.PolicySnapshot{Heartbeat: 900, LeaseTTL: 3600, Grace: 259200, ForcedCheck: forcedCheck}
|
||||
})
|
||||
return writeLicense(t, token)
|
||||
}
|
||||
|
||||
// TestFileMode_ForcedCheckEnforced 到期必须在线校验;成功续期命中,失败转 EXPIRED。
|
||||
func TestFileMode_ForcedCheckEnforced(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
clock := &fakeClock{now: e.now}
|
||||
vs := newValidationServer(t, e, clock)
|
||||
path := writeFileLicense(t, e, 3600)
|
||||
|
||||
client, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(clock), WithValidationServer(vs.server.URL))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := client.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
clock.Advance(3601)
|
||||
client.tick()
|
||||
if vs.calls != 1 {
|
||||
t.Fatalf("到期应触发一次在线校验: %d", vs.calls)
|
||||
}
|
||||
if client.State() != StateActive {
|
||||
t.Fatalf("校验通过应保持 ACTIVE: %s", client.State())
|
||||
}
|
||||
|
||||
// 下一周期服务端拒绝 → EXPIRED
|
||||
vs.mu.Lock()
|
||||
vs.valid = false
|
||||
vs.mu.Unlock()
|
||||
clock.Advance(3601)
|
||||
client.tick()
|
||||
if vs.calls != 2 {
|
||||
t.Fatalf("应再次校验: %d", vs.calls)
|
||||
}
|
||||
if client.State() != StateExpired {
|
||||
t.Fatalf("在线校验失败应 EXPIRED: %s", client.State())
|
||||
}
|
||||
}
|
||||
|
||||
// TestFileMode_ForcedCheckWithoutServer 未配置校验源时保持向后兼容(仅告警)。
|
||||
func TestFileMode_ForcedCheckWithoutServer(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
clock := &fakeClock{now: e.now}
|
||||
path := writeFileLicense(t, e, 3600)
|
||||
|
||||
client, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(clock))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := client.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
clock.Advance(3601)
|
||||
client.tick()
|
||||
if client.State() != StateActive {
|
||||
t.Fatalf("无校验源时不应改变状态(兼容完全离线): %s", client.State())
|
||||
}
|
||||
}
|
||||
|
||||
// TestFileMode_ForcedCheckRejectsForgedVerdict 验签失败的 verdict 不得放行。
|
||||
func TestFileMode_ForcedCheckRejectsForgedVerdict(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
clock := &fakeClock{now: e.now}
|
||||
path := writeFileLicense(t, e, 3600)
|
||||
|
||||
// 自建恶意校验源:返回未签名/错误签名的 verdict
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /v1/validate", func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(map[string]any{ //nolint:errcheck
|
||||
"valid": true, "state": "ACTIVE", "verdict": "forged.token.value",
|
||||
"crl_version": 0, "server_time": clock.Now(),
|
||||
})
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
|
||||
client, err := New(WithLicenseFile(path), WithProductKey("prod_test"),
|
||||
WithTrustChain(e.trust()), WithClock(clock), WithValidationServer(srv.URL))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := client.Start(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
clock.Advance(3601)
|
||||
client.tick()
|
||||
if client.State() != StateExpired {
|
||||
t.Fatalf("伪造 verdict 应被拒绝并 EXPIRED: %s", client.State())
|
||||
}
|
||||
if client.Enabled("module.audit-log") {
|
||||
t.Error("EXPIRED 后不应放行授权查询")
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidationServer_TrimTrailingSlash 校验源 URL 末尾斜杠应被容忍。
|
||||
func TestValidationServer_TrimTrailingSlash(t *testing.T) {
|
||||
if got := strings.TrimSuffix("http://x/", "/"); got != "http://x" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
+24
-6
@@ -28,8 +28,12 @@ func defaultHTTPClient() *http.Client {
|
||||
// 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"
|
||||
fp := c.opts.fingerprint
|
||||
if fp == "" {
|
||||
// 指纹:显式注入 > 自定义采集器 > 自动采集;自动采集失败时退回 hostname 席位标识
|
||||
// (若 license 绑定了机器,服务端会以指纹不符拒绝,不会误放行)。
|
||||
fp, fpErr := c.effectiveFingerprint()
|
||||
if fpErr != nil {
|
||||
c.opts.logger.Warn("自动指纹采集失败,激活仅使用 hostname 席位标识",
|
||||
"logger", logField, "error", fpErr)
|
||||
fp = defaultFingerprint()
|
||||
}
|
||||
body := map[string]any{
|
||||
@@ -174,7 +178,7 @@ func (c *Client) heartbeatOnce(ctx context.Context) error {
|
||||
body := map[string]any{
|
||||
"entitlements_hash": c.currentHash(),
|
||||
"agent": "sdk-go/" + sdkVersion,
|
||||
"crl_version": int64(0),
|
||||
"crl_version": c.crlVersion.Load(),
|
||||
}
|
||||
var resp heartbeatResp
|
||||
err := c.postJSON(ctx, "/v1/heartbeat", token, body, &resp)
|
||||
@@ -183,6 +187,14 @@ func (c *Client) heartbeatOnce(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 先应用 CRL:命中当前 jti 直接转 REVOKED(docs/design/04-crypto.md §4)
|
||||
if resp.CRL != "" {
|
||||
c.applyCRL(resp.CRL)
|
||||
} else if resp.CRLVersion > c.crlVersion.Load() {
|
||||
// 服务端版本更新但未携带内容:记录版本,避免重复请求
|
||||
c.crlVersion.Store(resp.CRLVersion)
|
||||
}
|
||||
|
||||
s := c.snap.Load()
|
||||
if resp.Terminate {
|
||||
// 吊销:终态(07 §5 状态机)
|
||||
@@ -254,13 +266,18 @@ func (c *Client) currentHash() string {
|
||||
return license.EntitlementsHash(s.payload.Ent)
|
||||
}
|
||||
|
||||
// postJSON 发送 JSON POST 并解码响应;网络错误/非 2xx 均返回错误。
|
||||
// postJSON 发送 JSON POST 到远程/代理基址。
|
||||
func (c *Client) postJSON(ctx context.Context, path, bearer string, body any, out any) error {
|
||||
return c.postJSONTo(ctx, c.opts.remoteServer, path, bearer, body, out)
|
||||
}
|
||||
|
||||
// postJSONTo 发送 JSON POST 到指定基址(强制校验点复用)。
|
||||
func (c *Client) postJSONTo(ctx context.Context, base, 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))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+path, bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -282,7 +299,8 @@ func (c *Client) postJSON(ctx context.Context, path, bearer string, body any, ou
|
||||
|
||||
const sdkVersion = "0.1.0"
|
||||
|
||||
// defaultFingerprint 默认机器指纹采集(v1:hostname;生产版接 internal/crypto.Fingerprint 采集器)。
|
||||
// defaultFingerprint 是自动采集失败时的最后退路(仅 hostname),用于无绑定 license 的席位标识。
|
||||
// 有 bind.fp 的 license 在文件模式会 fail-closed(见 MachineFingerprint / verifyToken)。
|
||||
func defaultFingerprint() string {
|
||||
return "sha256:host:" + hostname()
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user