feat(security): 完善信令认证与媒体加密
- 增加信令访问令牌、HTTPS 校验、限流及跨网段中继连接修复 - 同步三端媒体 v2 协议,实现 AES-GCM、防重放和乱序分片重组,升级 Rust ABI 6 - 修复文件鉴权、权限协商及剪贴板越权,完善上传校验和串流超时处理 - 增加跨端回归测试及部署文档,在 AGENTS.md 记录真机与真实跨网段待验收项目
This commit is contained in:
1 parent
4c9d006d11
commit
f6b7730684
58 files changed
+2167
-218
No files matched your search
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"ttstdconnect/signaling/internal/registry"
|
||||
@@ -15,15 +16,21 @@ import (
|
||||
type Handler struct {
|
||||
registry *registry.Registry
|
||||
relay *relay.Relay
|
||||
mu sync.Mutex
|
||||
routes map[string]relayRoute
|
||||
}
|
||||
|
||||
type relayRoute struct {
|
||||
peer string
|
||||
updated time.Time
|
||||
}
|
||||
|
||||
func NewHandler(reg *registry.Registry, relayStore *relay.Relay) http.Handler {
|
||||
return &Handler{registry: reg, relay: relayStore}
|
||||
return &Handler{registry: reg, relay: relayStore, routes: make(map[string]relayRoute)}
|
||||
}
|
||||
|
||||
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||
|
||||
if r.Method == http.MethodOptions {
|
||||
@@ -104,7 +111,43 @@ func (h *Handler) sendRelay(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
if _, ok := h.registry.Get(request.To); !ok {
|
||||
if request.From == "" || request.From == request.To {
|
||||
writeError(w, 400, fmt.Errorf("发送方或目标无效"))
|
||||
return
|
||||
}
|
||||
var envelope struct {
|
||||
From string `json:"from"`
|
||||
Kind string `json:"kind"`
|
||||
Protocol string `json:"ttstd"`
|
||||
}
|
||||
if err := json.Unmarshal(request.Payload, &envelope); err != nil || envelope.From != request.From || envelope.Protocol != "relay/1" {
|
||||
writeError(w, 400, fmt.Errorf("中继信封身份或版本不匹配"))
|
||||
return
|
||||
}
|
||||
_, targetOnline := h.registry.Get(request.To)
|
||||
now := time.Now()
|
||||
h.mu.Lock()
|
||||
for id, route := range h.routes {
|
||||
if now.Sub(route.updated) > 5*time.Minute {
|
||||
delete(h.routes, id)
|
||||
}
|
||||
}
|
||||
route, known := h.routes[request.To]
|
||||
canReply := known && route.peer == request.From
|
||||
if targetOnline && envelope.Kind == "hs" {
|
||||
if len(h.routes) >= 4096 {
|
||||
h.mu.Unlock()
|
||||
writeError(w, 503, fmt.Errorf("中继会话过多"))
|
||||
return
|
||||
}
|
||||
h.routes[request.From] = relayRoute{peer: request.To, updated: now}
|
||||
}
|
||||
if canReply {
|
||||
route.updated = now
|
||||
h.routes[request.To] = route
|
||||
}
|
||||
h.mu.Unlock()
|
||||
if !targetOnline && !canReply {
|
||||
writeError(w, http.StatusNotFound, fmt.Errorf("目标设备 %s 不在线", request.To))
|
||||
return
|
||||
}
|
||||
@@ -137,7 +180,7 @@ func (h *Handler) watch(w http.ResponseWriter, r *http.Request) {
|
||||
events, unsubscribe := h.registry.Subscribe()
|
||||
defer unsubscribe()
|
||||
|
||||
snapshot := map[string]any{"event": "snapshot", "devices": h.registry.List()}
|
||||
snapshot := map[string]any{"event": "snapshot"}
|
||||
if err := websocket.WriteText(conn, mustJSON(snapshot)); err != nil {
|
||||
return
|
||||
}
|
||||
@@ -157,7 +200,7 @@ func (h *Handler) watch(w http.ResponseWriter, r *http.Request) {
|
||||
for {
|
||||
select {
|
||||
case event := <-events:
|
||||
if err := websocket.WriteText(conn, mustJSON(event)); err != nil {
|
||||
if err := websocket.WriteText(conn, mustJSON(map[string]any{"event": event.Event, "deviceId": event.DeviceID})); err != nil {
|
||||
return
|
||||
}
|
||||
case <-ticker.C:
|
||||
|
||||
@@ -62,7 +62,7 @@ func TestRegisterListHeartbeatAndRelay(t *testing.T) {
|
||||
t.Fatalf("心跳失败: %+v", result)
|
||||
}
|
||||
|
||||
relayPayload := `{"from":"b","to":"a","payload":{"type":"offer"}}`
|
||||
relayPayload := `{"from":"b","to":"a","payload":{"ttstd":"relay/1","kind":"hs","from":"b"}}`
|
||||
if result = postJSON(t, server.URL+"/relay", relayPayload); result["ok"] != true {
|
||||
t.Fatalf("relay 失败: %+v", result)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type quota struct {
|
||||
tokens float64
|
||||
updated time.Time
|
||||
watches int
|
||||
}
|
||||
|
||||
// Secure protects discovery, registration and relay with the same private-network
|
||||
// credential. It is not a per-device identity or multi-tenant authorization system.
|
||||
func Secure(next http.Handler, token string) http.Handler {
|
||||
expected := sha256.Sum256([]byte(token))
|
||||
var mu sync.Mutex
|
||||
clients := make(map[string]*quota)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
host = r.RemoteAddr
|
||||
}
|
||||
now := time.Now()
|
||||
mu.Lock()
|
||||
q := clients[host]
|
||||
if q == nil {
|
||||
for key, old := range clients {
|
||||
if now.Sub(old.updated) > 5*time.Minute && old.watches == 0 {
|
||||
delete(clients, key)
|
||||
}
|
||||
}
|
||||
if len(clients) >= 4096 {
|
||||
mu.Unlock()
|
||||
http.Error(w, "server busy", 503)
|
||||
return
|
||||
}
|
||||
q = "a{tokens: 400, updated: now}
|
||||
clients[host] = q
|
||||
}
|
||||
q.tokens += now.Sub(q.updated).Seconds() * 200
|
||||
if q.tokens > 400 {
|
||||
q.tokens = 400
|
||||
}
|
||||
q.updated = now
|
||||
if q.tokens < 1 {
|
||||
mu.Unlock()
|
||||
w.Header().Set("Retry-After", "1")
|
||||
http.Error(w, "rate limited", 429)
|
||||
return
|
||||
}
|
||||
q.tokens--
|
||||
mu.Unlock()
|
||||
if r.URL.Path == "/healthz" && r.Method == http.MethodGet {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if token != "" {
|
||||
auth := r.Header.Get("Authorization")
|
||||
actual := sha256.Sum256([]byte(strings.TrimPrefix(auth, "Bearer ")))
|
||||
if !strings.HasPrefix(auth, "Bearer ") || subtle.ConstantTimeCompare(actual[:], expected[:]) != 1 {
|
||||
w.Header().Set("WWW-Authenticate", "Bearer")
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.URL.Path == "/watch" {
|
||||
mu.Lock()
|
||||
if q.watches >= 4 {
|
||||
mu.Unlock()
|
||||
http.Error(w, "too many watches", 429)
|
||||
return
|
||||
}
|
||||
q.watches++
|
||||
mu.Unlock()
|
||||
defer func() { mu.Lock(); q.watches--; mu.Unlock() }()
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
"ttstdconnect/signaling/internal/registry"
|
||||
"ttstdconnect/signaling/internal/relay"
|
||||
)
|
||||
|
||||
func TestAuthenticationProtectsEverySensitiveEndpoint(t *testing.T) {
|
||||
const token = "0123456789abcdef0123456789abcdef"
|
||||
handler := Secure(NewHandler(registry.New(time.Minute), relay.New()), token)
|
||||
for _, path := range []string{"/list", "/watch", "/register", "/heartbeat", "/unregister", "/relay", "/relay/poll?deviceId=a"} {
|
||||
for _, credential := range []string{"", "Bearer wrong"} {
|
||||
request := httptest.NewRequest("GET", path, nil)
|
||||
request.Header.Set("Authorization", credential)
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != 401 {
|
||||
t.Fatalf("%s: got %d", path, response.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
request := httptest.NewRequest("GET", "/list", nil)
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != 200 {
|
||||
t.Fatal(response.Code)
|
||||
}
|
||||
health := httptest.NewRecorder()
|
||||
handler.ServeHTTP(health, httptest.NewRequest("GET", "/healthz", nil))
|
||||
if health.Code != 200 {
|
||||
t.Fatal(health.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelayRepliesToUnregisteredControllerAndRejectsSpoofedEnvelope(t *testing.T) {
|
||||
handler := NewHandler(registry.New(time.Minute), relay.New())
|
||||
server := httptest.NewServer(handler)
|
||||
defer server.Close()
|
||||
postJSON(t, server.URL+"/register", samplePayload)
|
||||
post := func(body string) int {
|
||||
t.Helper()
|
||||
response, err := http.Post(server.URL+"/relay", "application/json", strings.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response.Body.Close()
|
||||
return response.StatusCode
|
||||
}
|
||||
if code := post(`{"from":"host-1","to":"a","payload":{"ttstd":"relay/1","kind":"hs","from":"other"}}`); code != 400 {
|
||||
t.Fatal(code)
|
||||
}
|
||||
if code := post(`{"from":"a","to":"host-1","payload":{"ttstd":"relay/1","kind":"hsAck","from":"a"}}`); code != 404 {
|
||||
t.Fatal(code)
|
||||
}
|
||||
if code := post(`{"from":"host-1","to":"a","payload":{"ttstd":"relay/1","kind":"hs","from":"host-1"}}`); code != 200 {
|
||||
t.Fatal(code)
|
||||
}
|
||||
if code := post(`{"from":"a","to":"host-1","payload":{"ttstd":"relay/1","kind":"hsAck","from":"a"}}`); code != 200 {
|
||||
t.Fatal(code)
|
||||
}
|
||||
if code := post(`{"from":"a","to":"host-1","payload":{"ttstd":"relay/1","kind":"frame","from":"a"}}`); code != 200 {
|
||||
t.Fatal(code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRateLimit(t *testing.T) {
|
||||
handler := Secure(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }), "")
|
||||
limited := false
|
||||
for i := 0; i < 1000; i++ {
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, httptest.NewRequest("GET", "/list", nil))
|
||||
if response.Code == 429 {
|
||||
limited = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !limited {
|
||||
t.Fatal("expected rate limit")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user