Merge pull request #9190 from pood1e/feat/openai-chat-session-id

feat(openai): let API-key accounts send an isolated session ID on Chat Completions
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-12-02 12:05:42 +08:00
commit cdbfa172e3
3 files changed
+181

No files matched your search

@@ -260,6 +260,7 @@ func (s *OpenAIGatewayService) sendCCUpstreamRequest(
// 官方 OpenCode / Command Code 上游收敛为规范客户端 UA:客户端透传的编程库
// UA 会命中其前置 Cloudflare bot 拦截(CF 1010/403),并被计入账号 403 strike。
applyOpenCodeUpstreamUserAgent(account, targetURL, upstreamReq.Header)
applyOpenAIChatSessionIDHeader(c, account, upstreamReq.Header, body)
// 账号级请求头覆写:放在所有内置默认头(含 Grok CLI 身份头)之后应用,
// 使配置值获得除共享传输层强制头之外的最高优先级。
@@ -0,0 +1,30 @@
package service
import (
"net/http"
"github.com/gin-gonic/gin"
)
// OpenAIChatSessionIDExtraKey 是账号 extra 中的可选开关,通过 admin 账号更新 API 的 extra
// 字段设置。为 true 时,OpenAI API Key 账号的 CC 出站请求携带按 API Key 隔离的会话标识,
// 供可信的自托管上游(如 vLLM router)做会话亲和。
const OpenAIChatSessionIDExtraKey = "openai_chat_session_id"
// openAIChatSessionIDHeader 是 vLLM router 读取会话标识的请求头。
const openAIChatSessionIDHeader = "X-Session-ID"
// applyOpenAIChatSessionIDHeader 为开启 OpenAIChatSessionIDExtraKey 的账号写入会话头。
// 会话来源与 x-opencode-session 相同:客户端会话头优先,其次是协议转换前记下的
// prompt_cache_key / metadata.user_id。出站值经 isolateOpenAIUpstreamSessionID 隔离,
// 不同 API Key 的同名会话互不冲突。
func applyOpenAIChatSessionIDHeader(c *gin.Context, account *Account, headers http.Header, body []byte) {
if account == nil || !account.IsOpenAIApiKey() || !account.getExtraBool(OpenAIChatSessionIDExtraKey) {
return
}
clientSessionID := resolveOpenCodeSessionID(c, nil, false, append(openCodeInboundBodies(c), body)...)
sessionID := isolateOpenAIUpstreamSessionID(getAPIKeyIDFromContext(c), codexAccountIdentitySource(c, account), clientSessionID)
if sessionID != "" {
headers.Set(openAIChatSessionIDHeader, sessionID)
}
}
@@ -0,0 +1,150 @@
//go:build unit
package service
import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func openAIChatSessionTestContext(path string, apiKeyID int64, header http.Header, body []byte) *gin.Context {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body))
for key, values := range header {
c.Request.Header[key] = values
}
c.Set("api_key", &APIKey{ID: apiKeyID})
return c
}
func openAIChatSessionTestUpstream() *httpUpstreamRecorder {
return &httpUpstreamRecorder{resp: &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(
`{"id":"chatcmpl_session","object":"chat.completion","model":"deepseek-v4.1-flash","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`,
)),
}}
}
// sendOpenAIChatSessionTestRequest sends a Chat Completions request through the
// shared CC outbound path and returns the headers the upstream received.
func sendOpenAIChatSessionTestRequest(t *testing.T, apiKeyID int64, account *Account, header http.Header, body string) http.Header {
t.Helper()
c := openAIChatSessionTestContext("/v1/chat/completions", apiKeyID, header, []byte(body))
upstream := openAIChatSessionTestUpstream()
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
resp, err := svc.sendCCUpstreamRequest(context.Background(), c, account, "http://vllm.internal:8000/v1/chat/completions", []byte(body), false, "sk-test", "", "")
require.NoError(t, err)
require.NoError(t, resp.Body.Close())
return upstream.lastReq.Header
}
func openAIChatSessionClientHeader(pairs ...string) http.Header {
header := http.Header{}
for i := 0; i+1 < len(pairs); i += 2 {
header.Set(pairs[i], pairs[i+1])
}
return header
}
func TestOpenAIChatSessionIDHeaderDisabledKeepsHeaders(t *testing.T) {
gin.SetMode(gin.TestMode)
oauth := selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: true})
oauth.Type = AccountTypeOAuth
disabled := map[string]*Account{
"not opted in": selfHostedRawChatCompletionsTestAccount(nil),
"explicitly false": selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: false}),
"string value": selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: "true"}),
"OAuth account": oauth,
}
client := openAIChatSessionClientHeader(
"session_id", "conv-1",
"X-Session-ID", "client-session",
"User-Agent", "opencode/1.19.6",
"Accept-Language", "zh-CN",
)
want := http.Header{
"Content-Type": []string{"application/json"},
"Authorization": []string{"Bearer sk-test"},
"Accept": []string{"application/json"},
"User-Agent": []string{"opencode/1.19.6"},
"Accept-Language": []string{"zh-CN"},
}
for name, account := range disabled {
t.Run(name, func(t *testing.T) {
got := sendOpenAIChatSessionTestRequest(t, 7, account, client, `{"model":"deepseek-v4.1-flash","prompt_cache_key":"pck-1"}`)
require.Equal(t, want, got)
})
}
}
func TestOpenAIChatSessionIDHeaderStablePerSession(t *testing.T) {
gin.SetMode(gin.TestMode)
account := selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: true})
client := openAIChatSessionClientHeader("session_id", "conv-1", "X-Session-ID", "client-session")
body := `{"model":"deepseek-v4.1-flash"}`
first := sendOpenAIChatSessionTestRequest(t, 7, account, client, body).Values(openAIChatSessionIDHeader)
require.Equal(t, []string{isolateOpenAIUpstreamSessionID(7, account, "conv-1")}, first, "the client session header wins and the raw X-Session-ID is never forwarded")
require.Regexp(t, `^[0-9a-f]{16}$`, first[0])
require.Equal(t, first, sendOpenAIChatSessionTestRequest(t, 7, account, client, body).Values(openAIChatSessionIDHeader))
fromPromptCacheKey := sendOpenAIChatSessionTestRequest(t, 7, account, nil, `{"model":"deepseek-v4.1-flash","prompt_cache_key":"pck-1"}`)
require.Equal(t, []string{isolateOpenAIUpstreamSessionID(7, account, "pck-1")}, fromPromptCacheKey.Values(openAIChatSessionIDHeader))
require.Empty(t, sendOpenAIChatSessionTestRequest(t, 7, account, nil, body).Values(openAIChatSessionIDHeader))
}
func TestOpenAIChatSessionIDHeaderIsolatesAPIKeys(t *testing.T) {
gin.SetMode(gin.TestMode)
account := selfHostedRawChatCompletionsTestAccount(map[string]any{OpenAIChatSessionIDExtraKey: true})
client := openAIChatSessionClientHeader("session_id", "conv-1")
body := `{"model":"deepseek-v4.1-flash"}`
first := sendOpenAIChatSessionTestRequest(t, 7, account, client, body).Get(openAIChatSessionIDHeader)
second := sendOpenAIChatSessionTestRequest(t, 8, account, client, body).Get(openAIChatSessionIDHeader)
require.NotEmpty(t, first)
require.NotEmpty(t, second)
require.NotEqual(t, first, second)
}
func TestForwardResponses_ChatFallbackSessionIDFromPromptCacheKey(t *testing.T) {
gin.SetMode(gin.TestMode)
account := forceChatResponsesFallbackAccount()
account.Extra[OpenAIChatSessionIDExtraKey] = true
body := []byte(`{"model":"deepseek-v4.1-flash","input":"hello","prompt_cache_key":"codex-thread-1","stream":false}`)
tests := []struct {
name string
header http.Header
want string
}{
{name: "without session header", want: "codex-thread-1"},
{name: "session header first", header: openAIChatSessionClientHeader("session_id", "conv-9"), want: "conv-9"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := openAIChatSessionTestContext("/v1/responses", 7, tt.header, body)
upstream := openAIChatSessionTestUpstream()
svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream}
_, err := svc.Forward(context.Background(), c, account, body)
require.NoError(t, err)
require.Equal(t, "http://upstream.example/v1/chat/completions", upstream.lastReq.URL.String())
require.Equal(t, []string{isolateOpenAIUpstreamSessionID(7, account, tt.want)}, upstream.lastReq.Header.Values(openAIChatSessionIDHeader))
})
}
}