Files
ssw-tds-test/card/bridge.go
T
ssw-tds-test e4e5faa55e init: ssw-tds-test 可信数据空间部署测试工程
初始提交,沉淀 k8s-tenant-wuguirong 租户下完整可信数据空间
的部署、真机/真数据/真多方验证成果。

包含:
- CLAUDE.md / docs/:工程入口、armv7 glibc 兼容性整改规格、
  ssw-platform#1(armv7 stdout=文件即 exit 100)issue 正文
- build/:TDS 服务端 + tdc-connector 交叉构建脚本、cube 沙箱
  编排、三方拓扑/真机验收脚本、ELF 符号扫描工具
- card/:软卡(softcard)源码与预编译产物(local/amd64/armv7)
- evidence/:验收报告、三方真实结果、armv7 stdout 矩阵复现证据
- .workbuddy/memory/:工作日志

排除:ssw-tds/ 与 ssw-acz7015/ 为上游源码独立仓库(含 .git,
体积大);build/ 下 ctx-*/dist/pglite-* 等可重建中间产物;
build/.env.*、tdc-conn-key/、.tdc-identity-secret 等明文密钥。
2026-11-13 10:19:19 +08:00

243 lines
6.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
// TDS 心跳桥:让设备侧软卡自己按 TDS 协议上报心跳(不再依赖开发机上的保活进程)。
//
// 这是「1 设备 1 卡 1 连接器」的关键:认证/签名在卡内,连接器只跑业务。
// 心跳契约(照 ConnectorServiceImpl.heartbeat,不猜):
// signingText = connectorId + "\n" + timestamp(ms) + "\n" + nonce
// signature = Base64(DER(ECDSA-SHA256(signingText))) // Java SHA256withECDSA
// PUT /api/ssw/tds/Connector/{id}/Heartbeat (Bearer = TDS 登录 token)
// 时间窗 ±30s,nonce 一次性;TTL = interval × 3(默认 15s)
//
// 登录契约:POST /api/oauth/Login,x-www-form-urlencoded
// account / password(=encryptPassword 密文) / grant_type=password
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
type Bridge struct {
Card *Card
TDSURL string
Connector string
Account string
Password string
CipherKey string
Interval time.Duration
client *http.Client
mu sync.Mutex
token string
tokenAt time.Time
clockSkew time.Duration
lastStatus string
okCount int
failCount int
}
func (b *Bridge) now() int64 {
b.mu.Lock()
skew := b.clockSkew
b.mu.Unlock()
return time.Now().Add(skew).UnixMilli()
}
// syncClock 用 TDS 的 HTTP Date 头估计时钟偏移(ZYNQ 无 RTC,±30s 时间窗必需)。
func (b *Bridge) syncClock() {
resp, err := b.client.Get(strings.TrimRight(b.TDSURL, "/") + "/api/ssw/tds/Portal/TestMode")
if err != nil {
return
}
defer resp.Body.Close()
if d := resp.Header.Get("Date"); d != "" {
if t, err := http.ParseTime(d); err == nil {
b.mu.Lock()
b.clockSkew = time.Until(t)
b.mu.Unlock()
log.Printf("[bridge] 时钟偏移校准: %d ms", b.clockSkew.Milliseconds())
}
}
}
func (b *Bridge) login() error {
enc, err := encryptPassword(b.Password, b.CipherKey)
if err != nil {
return err
}
form := url.Values{"account": {b.Account}, "password": {enc}, "grant_type": {"password"}}
req, err := http.NewRequest(http.MethodPost,
strings.TrimRight(b.TDSURL, "/")+"/api/oauth/Login",
strings.NewReader(form.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := b.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
var obj struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Token string `json:"token"`
} `json:"data"`
Token string `json:"token"`
}
if err := json.Unmarshal(raw, &obj); err != nil {
return fmt.Errorf("登录响应解析失败: %w (%s)", err, string(raw[:min(len(raw), 120)]))
}
tok := obj.Token
if tok == "" {
tok = obj.Data.Token
}
if tok == "" {
return fmt.Errorf("登录未返回 token: %s", string(raw[:min(len(raw), 160)]))
}
b.mu.Lock()
b.token, b.tokenAt = tok, time.Now()
b.mu.Unlock()
return nil
}
func (b *Bridge) auth() (string, error) {
b.mu.Lock()
tok, age := b.token, time.Since(b.tokenAt)
b.mu.Unlock()
if tok != "" && age < 20*time.Minute {
return tok, nil
}
if err := b.login(); err != nil {
return "", err
}
b.mu.Lock()
defer b.mu.Unlock()
return b.token, nil
}
func nonce() string {
buf := make([]byte, 16)
_, _ = rand.Read(buf)
return hex.EncodeToString(buf)
}
func (b *Bridge) heartbeat() error {
tok, err := b.auth()
if err != nil {
return fmt.Errorf("login: %w", err)
}
ts := b.now()
text := fmt.Sprintf("%s\n%d\n%s", b.Connector, ts, nonce())
sig, err := b.Card.sign([]byte(text))
if err != nil {
return fmt.Errorf("card sign: %w", err)
}
parts := strings.Split(text, "\n")
body, _ := json.Marshal(map[string]any{
"connectorId": b.Connector, "timestamp": mustInt64(parts[1]),
"nonce": parts[2], "signature": sig,
})
req, err := http.NewRequest(http.MethodPut,
fmt.Sprintf("%s/api/ssw/tds/Connector/%s/Heartbeat", strings.TrimRight(b.TDSURL, "/"), b.Connector),
bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Authorization", tok)
req.Header.Set("Content-Type", "application/json")
resp, err := b.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if bytes.Contains(raw, []byte(`"code":200`)) {
b.record(true, "ONLINE")
return nil
}
msg := string(raw[:min(len(raw), 160)])
b.record(false, msg)
// token 失效则下次重登
if bytes.Contains(raw, []byte("Login expired")) || bytes.Contains(raw, []byte(`"code":600`)) {
b.mu.Lock()
b.token = ""
b.mu.Unlock()
}
return fmt.Errorf("heartbeat rejected: %s", msg)
}
func (b *Bridge) record(ok bool, status string) {
b.mu.Lock()
defer b.mu.Unlock()
if ok {
b.okCount++
} else {
b.failCount++
}
b.lastStatus = status
}
// Status 供 /v1/bridge 与巡检读取;Run 在独立 goroutine 写,读写都走锁。
func (b *Bridge) Status() map[string]any {
b.mu.Lock()
defer b.mu.Unlock()
return map[string]any{
"enabled": true, "connectorId": b.Connector,
"deviceId": b.Card.DeviceID, "cardId": b.Card.KeyID,
"status": b.lastStatus, "okCount": b.okCount, "failCount": b.failCount,
"intervalSeconds": b.Interval.Seconds(), "tds": b.TDSURL,
}
}
func (b *Bridge) Run() {
b.client = &http.Client{Timeout: 15 * time.Second}
b.syncClock()
if err := b.login(); err != nil {
log.Printf("[bridge] 首次登录失败(将重试): %v", err)
}
// 立即打一次心跳,不等第一个 tick(设备重启后尽快 ONLINE)
if err := b.heartbeat(); err != nil {
log.Printf("[bridge] FAIL %v", err)
}
ticker := time.NewTicker(b.Interval)
defer ticker.Stop()
var ticks int
for range ticker.C {
ticks++
if err := b.heartbeat(); err != nil {
log.Printf("[bridge] FAIL %v", err)
} else if st := b.Status(); st["okCount"].(int) == 1 || st["okCount"].(int)%12 == 0 {
log.Printf("[bridge] #%d ONLINE device=%s card=%s", st["okCount"], b.Card.DeviceID, b.Card.KeyID)
}
// 每小时校准一次时钟(嵌入式板无 RTC)
if ticks%720 == 0 {
b.syncClock()
}
}
}
func mustInt64(s string) int64 {
var v int64
_, _ = fmt.Sscanf(s, "%d", &v)
return v
}
func min(a, b int) int {
if a < b {
return a
}
return b
}