test(headers): 覆盖自定义请求头注入与测试连接链路
- applyCustomHeaders:覆盖内置头、跳过空值、无配置时保持原行为 - headersRoundTripper:经 Eino 传输链端到端验证头已下发 - %session_id%:有会话时替换、无会话时跳过该头 - TestOpenAI:测试连接会携带静态头,%session_id% 填充探测值, 未配置 headers 时仍使用 Bearer <api_key>
This commit is contained in:
parent
d6b0aed1de
commit
691dbd0107
|
|
@ -0,0 +1,89 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"cyberstrike-ai/internal/config"
|
||||
)
|
||||
|
||||
// TestTestOpenAIForwardsCustomHeaders 校验「测试连接」与真实对话一样会带上渠道自定义请求头:
|
||||
// 静态头原样发送,%session_id% 用探测值填充,Authorization 仍按 api_key 生成。
|
||||
func TestTestOpenAIForwardsCustomHeaders(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
var gotSession, gotFlag, gotAuth string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotSession = r.Header.Get("X-Opencode-Session")
|
||||
gotFlag = r.Header.Get("X-Custom-Flag")
|
||||
gotAuth = r.Header.Get("Authorization")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"id":"chatcmpl-test","model":"test-model","choices":[{"message":{"role":"assistant","content":"pong"}}]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
h := &ConfigHandler{config: &config.Config{}, logger: zap.NewNop()}
|
||||
|
||||
body := `{"provider":"openai","base_url":"` + srv.URL + `/v1","api_key":"test-key","model":"test-model",` +
|
||||
`"headers":{"X-Opencode-Session":"%session_id%","X-Custom-Flag":"hello"}}`
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/config/test-openai", strings.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
h.TestOpenAI(c)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp map[string]interface{}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if resp["success"] != true {
|
||||
t.Fatalf("probe failed: %s", w.Body.String())
|
||||
}
|
||||
if gotSession != "connect-test" {
|
||||
t.Fatalf("X-Opencode-Session = %q, want connect-test", gotSession)
|
||||
}
|
||||
if gotFlag != "hello" {
|
||||
t.Fatalf("X-Custom-Flag = %q, want hello", gotFlag)
|
||||
}
|
||||
if gotAuth != "Bearer test-key" {
|
||||
t.Fatalf("Authorization = %q", gotAuth)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTestOpenAIWithoutHeadersKeepsBuiltinAuth 确认未配置 headers 时行为不变。
|
||||
func TestTestOpenAIWithoutHeadersKeepsBuiltinAuth(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
var gotAuth string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotAuth = r.Header.Get("Authorization")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"id":"x","model":"m","choices":[{"message":{"role":"assistant","content":"pong"}}]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
h := &ConfigHandler{config: &config.Config{}, logger: zap.NewNop()}
|
||||
body := `{"provider":"openai","base_url":"` + srv.URL + `/v1","api_key":"plain-key","model":"m"}`
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(w)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/config/test-openai", strings.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
|
||||
h.TestOpenAI(c)
|
||||
|
||||
if gotAuth != "Bearer plain-key" {
|
||||
t.Fatalf("Authorization = %q, want Bearer plain-key", gotAuth)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,162 @@
|
|||
package openai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"cyberstrike-ai/internal/config"
|
||||
)
|
||||
|
||||
func TestApplyCustomHeadersOverridesBuiltinAndSkipsEmpty(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodPost, "http://example.com/v1/chat/completions", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("new request: %v", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer builtin")
|
||||
applyCustomHeaders(req, &config.OpenAIConfig{Headers: map[string]string{
|
||||
"Authorization": "Bearer custom",
|
||||
"X-Api-Key": "secret",
|
||||
"User-Agent": "cyberstrike-ai/1.0",
|
||||
"X-Empty": "",
|
||||
" ": "dropped",
|
||||
}})
|
||||
if got := req.Header.Get("Authorization"); got != "Bearer custom" {
|
||||
t.Fatalf("Authorization = %q, want custom override", got)
|
||||
}
|
||||
if got := req.Header.Get("X-Api-Key"); got != "secret" {
|
||||
t.Fatalf("X-Api-Key = %q", got)
|
||||
}
|
||||
if got := req.Header.Get("User-Agent"); got != "cyberstrike-ai/1.0" {
|
||||
t.Fatalf("User-Agent = %q", got)
|
||||
}
|
||||
if got := req.Header.Get("X-Empty"); got != "" {
|
||||
t.Fatalf("empty header value must be skipped, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyCustomHeadersNilConfigIsNoop(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodGet, "http://example.com/", nil)
|
||||
applyCustomHeaders(req, nil)
|
||||
if got := req.Header.Get("Authorization"); got != "" {
|
||||
t.Fatalf("unexpected Authorization %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeadersRoundTripperInjectsHeaders(t *testing.T) {
|
||||
var auth, provider string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
auth = r.Header.Get("Authorization")
|
||||
provider = r.Header.Get("X-Provider")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
cfg := &config.OpenAIConfig{Headers: map[string]string{
|
||||
"Authorization": "Bearer from-headers",
|
||||
"X-Provider": "opencode",
|
||||
}}
|
||||
client := NewEinoHTTPClient(cfg, srv.Client())
|
||||
req, _ := http.NewRequest(http.MethodPost, srv.URL+"/v1/chat/completions", nil)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("do: %v", err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if auth != "Bearer from-headers" {
|
||||
t.Fatalf("Authorization = %q", auth)
|
||||
}
|
||||
if provider != "opencode" {
|
||||
t.Fatalf("X-Provider = %q", provider)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpandHeaderMapEnv(t *testing.T) {
|
||||
t.Setenv("TEST_CS_HEADER_TOKEN", "tok-123")
|
||||
got := config.ExpandHeaderMap(map[string]string{
|
||||
"X-Api-Key": "${TEST_CS_HEADER_TOKEN}",
|
||||
"X-Default": "${TEST_CS_MISSING_VAR:-fallback}",
|
||||
})
|
||||
if got["X-Api-Key"] != "tok-123" {
|
||||
t.Fatalf("X-Api-Key = %q", got["X-Api-Key"])
|
||||
}
|
||||
if got["X-Default"] != "fallback" {
|
||||
t.Fatalf("X-Default = %q", got["X-Default"])
|
||||
}
|
||||
if config.ExpandHeaderMap(nil) != nil {
|
||||
t.Fatalf("nil headers should stay nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionHeaderPlaceholderRendering(t *testing.T) {
|
||||
cfg := &config.OpenAIConfig{Headers: map[string]string{
|
||||
"x-opencode-session": "%session_id%",
|
||||
"X-Prefixed": "pfx-%session_id%",
|
||||
"X-Fixed": "static",
|
||||
}}
|
||||
|
||||
ctx := WithSessionID(context.Background(), "conv-abc-123")
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://example.com/v1/chat/completions", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("new request: %v", err)
|
||||
}
|
||||
applyCustomHeaders(req, cfg)
|
||||
if got := req.Header.Get("x-opencode-session"); got != "conv-abc-123" {
|
||||
t.Fatalf("session header = %q, want conv-abc-123", got)
|
||||
}
|
||||
if got := req.Header.Get("X-Prefixed"); got != "pfx-conv-abc-123" {
|
||||
t.Fatalf("prefixed header = %q", got)
|
||||
}
|
||||
if got := req.Header.Get("X-Fixed"); got != "static" {
|
||||
t.Fatalf("fixed header = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionHeaderSkippedWithoutSession(t *testing.T) {
|
||||
cfg := &config.OpenAIConfig{Headers: map[string]string{
|
||||
"x-opencode-session": "%session_id%",
|
||||
"X-Fixed": "static",
|
||||
}}
|
||||
req, _ := http.NewRequest(http.MethodPost, "http://example.com/v1/chat/completions", nil)
|
||||
applyCustomHeaders(req, cfg)
|
||||
if got := req.Header.Get("x-opencode-session"); got != "" {
|
||||
t.Fatalf("placeholder must be skipped without session, got %q", got)
|
||||
}
|
||||
if got := req.Header.Get("X-Fixed"); got != "static" {
|
||||
t.Fatalf("fixed header must still be sent, got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionIDContextRoundTrip(t *testing.T) {
|
||||
if got := SessionIDFromContext(context.Background()); got != "" {
|
||||
t.Fatalf("empty context should yield empty id, got %q", got)
|
||||
}
|
||||
if got := SessionIDFromContext(WithSessionID(context.Background(), " ")); got != "" {
|
||||
t.Fatalf("blank id must be ignored, got %q", got)
|
||||
}
|
||||
ctx := WithSessionID(context.Background(), " conv-1 ")
|
||||
if got := SessionIDFromContext(ctx); got != "conv-1" {
|
||||
t.Fatalf("id = %q, want conv-1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderHeaderValueCases(t *testing.T) {
|
||||
cases := []struct {
|
||||
value string
|
||||
sid string
|
||||
want string
|
||||
ok bool
|
||||
}{
|
||||
{"static", "s1", "static", true},
|
||||
{"%session_id%", "s1", "s1", true},
|
||||
{"a-%session_id%-b", "s1", "a-s1-b", true},
|
||||
{"%session_id%", "", "", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
got, ok := renderHeaderValue(c.value, c.sid)
|
||||
if ok != c.ok || got != c.want {
|
||||
t.Fatalf("renderHeaderValue(%q,%q) = (%q,%v), want (%q,%v)", c.value, c.sid, got, ok, c.want, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue