Files
ai-gateway-go/internal/gateway/resilience_test.go
T
superidou 9501751792 0.10.1: 安全与业务逻辑加固、新品牌与部署加固
三轮审查修复(60+ 项),相对远端 main(b536672)的关键变更:
- 安全: 数据面 SSRF 拨号防护(防 DNS rebinding)/上游凭据剥离/登录防枚举
  与锁定态统一/可信代理(X-Forwarded-For)限流加固/会话版本失效机制/
  撤销即时传播/弱密钥拒绝启动/脱敏字节级重写(保签名契约)
- 业务逻辑: 裸 body 上传 panic/bootstrap 审计管线卡死/定价通配符优先级/
  全局工具可见性/调度器停机补跑/TOTP 挑战令牌消费顺序/熔断探针语义/
  >4MB 响应 token 计量/管理员重置密码作废会话 等
- 前端: 新 logo(语枢 AI 网关主题)/Provider 凭据异常警示/删除入口/
  后端错误消息透传/localStorage 敏感数据收敛
- 部署: CREDENTIAL_MASTER_KEY 持久化与弱值拒绝/Provider DELETE 接口/
  nginx 安全头/worker 内存限制
- 新增迁移 000029(key_hash 索引)/000030(usage_daily 币种维度)
2026-08-13 10:50:51 +08:00

62 lines
2.1 KiB
Go

package gateway
import (
"errors"
"io"
"net/http"
"strings"
"testing"
"time"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) { return f(request) }
func TestResilientTransportRetriesReplayableRequest(t *testing.T) {
attempts := 0
transport := &resilientTransport{base: roundTripFunc(func(*http.Request) (*http.Response, error) {
attempts++
if attempts < 3 {
return &http.Response{StatusCode: http.StatusServiceUnavailable, Body: io.NopCloser(strings.NewReader("busy")), Header: make(http.Header)}, nil
}
return &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader("ok")), Header: make(http.Header)}, nil
}), circuit: newCircuitBreaker(), maxRetries: 2}
request, _ := http.NewRequest(http.MethodGet, "https://provider.example/v1/models", nil)
response, err := transport.RoundTrip(request)
if err != nil || response.StatusCode != http.StatusOK || attempts != 3 {
t.Fatalf("response=%v err=%v attempts=%d", response, err, attempts)
}
}
func TestResilientTransportDoesNotRetryUnsafePost(t *testing.T) {
attempts := 0
transport := &resilientTransport{base: roundTripFunc(func(*http.Request) (*http.Response, error) {
attempts++
return nil, errors.New("network failure")
}), circuit: newCircuitBreaker(), maxRetries: 2}
request, _ := http.NewRequest(http.MethodPost, "https://provider.example/v1/chat/completions", strings.NewReader("{}"))
_, _ = transport.RoundTrip(request)
if attempts != 1 {
t.Fatalf("unsafe POST attempted %d times", attempts)
}
}
func TestCircuitOpensAndAllowsSingleProbe(t *testing.T) {
circuit := newCircuitBreaker()
circuit.threshold = 2
circuit.openFor = time.Millisecond
now := time.Now()
circuit.failure(now)
circuit.failure(now)
if allowed, _ := circuit.allow(now); allowed {
t.Fatal("open circuit allowed request")
}
if allowed, probe := circuit.allow(now.Add(2 * time.Millisecond)); !allowed || !probe {
t.Fatal("circuit did not allow half-open probe")
}
if allowed, _ := circuit.allow(now.Add(2 * time.Millisecond)); allowed {
t.Fatal("circuit allowed concurrent half-open probe")
}
}