fix(identity): scope derived upstream sessions to the calling server key

Two callers whose conversations began identically were mapped onto the
same upstream session. Without a client session signal the session was
hashed from the first user turn alone, ignoring the server key and the
system prompt, so two users opening with "你好", or two Codex users in the
same working directory (whose first user turn is the boilerplate
<environment_context> block), shared one x-opencode-session, one sticky
upstream provider, one preferred key and one anonymous proxy exit. Every
caller without a client project also shared one constant project id.

- Mix the authenticated caller (server key fingerprint; Playground gets
  its own bucket) into every session and default project the gateway
  derives. Official OpenCode ses_ sessions sent by the client are kept
  verbatim because the client minted them uniquely.
- Read the session signals mainstream agents already send before falling
  back to a content seed: Codex's session_id / conversation_id headers
  and the session UUID inside Claude Code's metadata.user_id (underscore
  or JSON form). The per-user remainder of user_id is never used as a
  session.
- Seed from the system prompt (Anthropic system, Responses instructions,
  leading system/developer messages) plus the first user turn instead of
  the first user turn alone.
- Correct stale comments: x-opencode-request and the project header do
  reach upstream, rendered per lane.

Upgrading re-derives every gateway-made session once, so in-flight
conversations may move to another key or proxy and start with a cold
upstream cache. Conversations under one key that share both the system
prompt and the opening turn can still share affinity; the READMEs now
recommend separate server keys for users who must stay isolated.
This commit is contained in:
Jason Xu committed 2026-10-18 22:04:54 +08:00
1 parent cece86bb22
commit 9aa2133f84
6 files changed
+130 -41

No files matched your search

+2 -2
View File
@@ -241,9 +241,9 @@ Administration endpoints (login required; writes also require CSRF): `GET /api/m
Keys are initially spread across proxies. Real traffic can trigger proxy checks, key rebinding, and cooldowns. Unhealthy proxies are rechecked every 15 minutes against Cloudflare trace.
A stable session hash selects the preferred key or anonymous proxy. Send an explicit `x-session-id` to separate independent conversations. The gateway also accepts `x-opencode-session`, `x-session-affinity`, `conversation-id`, `conversation_id`, and `metadata.session_id`.
A stable session hash selects the preferred key or anonymous proxy. Send an explicit `x-session-id` to separate independent conversations. The gateway also accepts the `x-opencode-session`, `x-session-affinity`, `session_id`, `conversation-id`, and `conversation_id` headers, the `conversation_id` and `metadata.session_id` body fields, and the session ID inside Claude Code's `metadata.user_id`.
Without an explicit ID, the first user message is used as a seed. Conversations beginning with the same content can therefore share affinity. Changing pool membership can change the selected node.
Sessions and projects the gateway derives itself are scoped to the caller's server key, so different keys never share an upstream session, preferred key, or anonymous proxy. Official OpenCode sessions (`ses_…`) sent by the client are kept as-is. Without an explicit ID, the system prompt and the first user message are used as a seed. Conversations under the same key that begin with the same system prompt and content can therefore still share affinity; give users who must stay isolated their own server keys. Changing pool membership can change the selected node.
Cooldowns grow exponentially up to eight times `performance.failure_cooldown_seconds`, and a longer `Retry-After` is honored. If every authenticated key is cooling down, routing may try the key whose cooldown ends first. Anonymous nodes still in cooldown are skipped.
+2 -2
View File
@@ -245,9 +245,9 @@ Các endpoint quản trị (cần đăng nhập; ghi còn cần CSRF): `GET /api
Các key ban đầu được phân bố trên nhiều proxy. Lưu lượng thật có thể kích hoạt kiểm tra proxy, gán lại key và cooldown. Proxy không khoẻ được kiểm tra lại mỗi 15 phút bằng Cloudflare trace.
Một hash session ổn định chọn key hoặc proxy ẩn danh ưu tiên. Gửi `x-session-id` tường minh để tách các hội thoại độc lập. Gateway cũng chấp nhận `x-opencode-session`, `x-session-affinity`, `conversation-id`, `conversation_id` và `metadata.session_id`.
Một hash session ổn định chọn key hoặc proxy ẩn danh ưu tiên. Gửi `x-session-id` tường minh để tách các hội thoại độc lập. Gateway cũng chấp nhận các header `x-opencode-session`, `x-session-affinity`, `session_id`, `conversation-id`, `conversation_id`, các trường body `conversation_id`, `metadata.session_id`, và session ID nằm trong `metadata.user_id` của Claude Code.
Không có ID tường minh, tin nhắn người dùng đầu tiên được dùng làm seed. Vì vậy các hội thoại mở đầu bằng nội dung giống nhau có thể dùng chung affinity. Thay đổi thành phần nhóm có thể làm đổi nút được chọn.
Session và project do gateway tự tạo được tách theo server key của bên gọi, nên các key khác nhau không bao giờ dùng chung session upstream, key ưu tiên hay proxy ẩn danh. Session OpenCode chính thức (`ses_…`) do client gửi được giữ nguyên. Không có ID tường minh, system prompt cùng tin nhắn người dùng đầu tiên được dùng làm seed. Vì vậy các hội thoại trong cùng một key có system prompt và nội dung mở đầu giống nhau vẫn có thể dùng chung affinity; hãy cấp server key riêng cho những người dùng cần tách biệt. Thay đổi thành phần nhóm có thể làm đổi nút được chọn.
Cooldown tăng theo cấp số nhân tối đa tám lần `performance.failure_cooldown_seconds`, và giá trị `Retry-After` dài hơn sẽ được tôn trọng. Nếu mọi key có xác thực đều đang nghỉ, định tuyến có thể thử key mà cooldown kết thúc sớm nhất. Các nút ẩn danh còn trong cooldown sẽ bị bỏ qua.
+2 -2
View File
@@ -241,9 +241,9 @@ System One 使用原生 `noul` 类型询问“1+1 是否等于 2”,不注入
Key 初始化时均衡分配到代理。真实流量可以触发代理检查、Key 重新绑定和失败冷却。已经标记异常的代理,每 15 分钟通过 Cloudflare trace 复查一次。
服务使用稳定会话哈希选择首选 Key 或匿名代理。建议通过 `x-session-id` 区分独立会话,同时支持 `x-opencode-session`、`x-session-affinity`、`conversation-id`、`conversation_id` 与 `metadata.session_id`。
服务使用稳定会话哈希选择首选 Key 或匿名代理。建议通过 `x-session-id` 区分独立会话,同时支持 `x-opencode-session`、`x-session-affinity`、`session_id`、`conversation-id`、`conversation_id` 请求头,请求体中的 `conversation_id`、`metadata.session_id`,以及 Claude Code `metadata.user_id` 中的会话 ID。
没有显式会话 ID 时,使用第一条用户消息生成会话标识,因此开场内容相同的会话可能共享亲和性。调整 Key 或代理池成员后,原有会话选择的节点可能变化。
网关自行生成的会话与项目标识按调用方的服务端 Key 隔离,不同 Key 不会共享上游会话、首选 Key 或匿名代理;客户端自带的官方 OpenCode 会话(`ses_…`)原样保留。没有显式会话 ID 时,使用系统提示词和第一条用户消息生成会话标识,因此同一 Key 下系统提示词和开场内容都相同的会话仍可能共享亲和性。需要互相隔离的用户应各自使用独立的服务端 Key。调整 Key 或代理池成员后,原有会话选择的节点可能变化。
失败冷却按指数增长,最高为 `performance.failure_cooldown_seconds` 的八倍;如果上游的 `Retry-After` 更长,则使用更长时间。所有认证 Key 都处于冷却时,路由仍可能尝试最早结束冷却的 Key;仍在冷却的匿名节点会被跳过。
+20 -10
View File
@@ -133,18 +133,28 @@ func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc {
wire.WriteError(w, protocol, http.StatusUnauthorized, "invalid local API key", "authentication_error", "")
return
}
if meta := telemetry.MetaFromRequest(r); meta != nil {
// The Playground borrows the first enabled key to pass this check, so
// its traffic gets its own bucket instead of being billed to that key.
meta.ServerKeyID = config.Fingerprint(matched)
if isDiagnosticRequest(r.Context()) {
meta.ServerKeyID = telemetry.PlaygroundServerKey
}
// The Playground borrows the first enabled key to pass this check, so
// its traffic gets its own bucket instead of being billed to that key.
caller := config.Fingerprint(matched)
if isDiagnosticRequest(r.Context()) {
caller = telemetry.PlaygroundServerKey
}
next(w, r)
if meta := telemetry.MetaFromRequest(r); meta != nil {
meta.ServerKeyID = caller
}
next(w, r.WithContext(context.WithValue(r.Context(), callerContextKey{}, caller)))
}
}
type callerContextKey struct{}
// callerScope returns the authenticated caller that request identities are
// scoped to, so different server keys never share an upstream session.
func callerScope(ctx context.Context) string {
caller, _ := ctx.Value(callerContextKey{}).(string)
return caller
}
func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBody))
@@ -206,7 +216,7 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc {
wire.WriteError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "")
return
}
ids := identity.DeriveRequestIDs(r, payload)
ids := identity.DeriveRequestIDs(r, payload, callerScope(r.Context()))
if meta != nil {
meta.Request = ids.Request
meta.Session = ids.Session
@@ -390,7 +400,7 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body
for _, tier := range route.KeyTiers {
bodies[tier] = body
}
ids := identity.DeriveRequestIDs(r, payload)
ids := identity.DeriveRequestIDs(r, payload, callerScope(r.Context()))
if meta != nil {
meta.Request = ids.Request
meta.Session = ids.Session
+1 -1
View File
@@ -66,7 +66,7 @@ func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, externa
g.syncRotation()
ctx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second)
defer cancel()
ids := identity.DeriveRequestIDs(r, payload)
ids := identity.DeriveRequestIDs(r, payload, callerScope(r.Context()))
meta := telemetry.MetaFromRequest(r)
if meta != nil {
meta.Request = ids.Request
+103 -24
View File
@@ -22,9 +22,11 @@ import (
)
// RequestIDs carries the identity headers the upstream free tier inspects.
// Session is sent as both x-opencode-session and x-opencode-session-id; both
// headers are required since the 2026-10-14 gate. Request is retained for
// request-level tracing of this gateway only — it must NOT reach upstream.
// Session is sent as x-opencode-session on every lane and additionally as
// x-opencode-session-id on /inference, which requires both. Request travels as
// x-opencode-request on the legacy /zen/v1 lane only; /inference rejects it.
// Project is rendered per lane by the gateway (prj_* on /zen/v1, bare 40-hex
// on /inference).
type RequestIDs struct {
Session string
Request string
@@ -32,20 +34,30 @@ type RequestIDs struct {
ParentSession string
}
func DeriveRequestIDs(r *http.Request, body map[string]any) RequestIDs {
// DeriveRequestIDs derives the upstream identity of one request. scope names
// the authenticated caller (the server key fingerprint). Every session and
// project the gateway derives itself is mixed with it, so two callers whose
// conversations begin identically never share an upstream session, sticky
// provider, preferred key, or anonymous proxy. An official OpenCode session is
// kept verbatim because the client minted it uniquely.
func DeriveRequestIDs(r *http.Request, body map[string]any, scope string) RequestIDs {
signal := jsonutil.FirstString(
r.Header.Get("x-opencode-session"),
r.Header.Get("x-opencode-session-id"),
r.Header.Get("x-session-affinity"),
r.Header.Get("X-Session-Id"),
r.Header.Get("x-session-id"),
// Codex sends its conversation id in both underscore headers.
r.Header.Get("session_id"),
r.Header.Get("conversation-id"),
r.Header.Get("conversation_id"),
jsonutil.StringAt(body, "conversation_id"),
jsonutil.StringAt(body, "metadata", "session_id"),
claudeCodeSessionID(jsonutil.StringAt(body, "metadata", "user_id")),
)
if signal == "" {
// Using the first user turn keeps a multi-turn conversation stable as its
// history grows while separating conversations with different beginnings.
// The system prompt plus the first user turn keeps a multi-turn
// conversation stable as its history grows while separating
// conversations with different beginnings.
signal = conversationSeed(body)
}
if signal == "" {
@@ -54,14 +66,15 @@ func DeriveRequestIDs(r *http.Request, body map[string]any) RequestIDs {
if signal == "" || signal == `{}` {
signal = RandomID("fallback", 16)
}
session := CanonicalSessionID(signal)
// The upstream free tier 403s canonical prj_* project ids (2026-10-14
// probing) while accepting the literal "global" every official client
// sends. Anything non-canonical also passes, so the project header is only
// used as a local correlation hint and is no longer forwarded upstream.
session := scopedSessionID(scope, signal)
projectSignal := jsonutil.FirstString(r.Header.Get("x-opencode-project"), jsonutil.StringAt(body, "metadata", "project_id"))
if projectSignal == "" {
// Without a client project every caller would otherwise share one
// constant upstream project.
projectSignal = "opencode2api:default-project"
if scope != "" {
projectSignal += ":" + scope
}
}
parentSession := jsonutil.FirstString(
r.Header.Get("x-parent-session-id"),
@@ -75,23 +88,86 @@ func DeriveRequestIDs(r *http.Request, body map[string]any) RequestIDs {
}
}
// scopedSessionID keeps an official client-minted session verbatim and
// re-encodes every other signal within the caller's scope.
func scopedSessionID(scope, signal string) string {
if isOfficialSessionID(signal) {
return signal
}
if scope != "" {
signal = scope + "\x00" + signal
}
return CanonicalSessionID(signal)
}
// claudeCodeSessionPattern extracts the per-session UUID Claude Code embeds in
// metadata.user_id ("user_<hash>_account_<uuid>_session_<uuid>").
var claudeCodeSessionPattern = regexp.MustCompile(`_session_([0-9A-Fa-f-]{36})$`)
// claudeCodeSessionID returns the session part of a Claude Code user id, which
// is either the underscore form above or a JSON object carrying session_id.
// The rest of the user id is per user, not per conversation, so it is never
// used as a session on its own.
func claudeCodeSessionID(userID string) string {
if userID == "" {
return ""
}
if match := claudeCodeSessionPattern.FindStringSubmatch(userID); match != nil {
return match[1]
}
var value map[string]any
if json.Unmarshal([]byte(userID), &value) == nil {
return jsonutil.StringAt(value, "session_id")
}
return ""
}
// conversationSeed fingerprints how a conversation begins: its system prompt
// (Anthropic system, Responses instructions, or system/developer messages
// ahead of the first user turn) together with that first user turn. Agent
// clients often open with a boilerplate user turn such as an environment
// block, so the first user turn alone collides across unrelated users.
func conversationSeed(body map[string]any) string {
prelude := make([]any, 0, 2)
for _, field := range []string{"system", "instructions"} {
if value := body[field]; value != nil {
prelude = append(prelude, value)
}
}
first, ok := firstUserTurn(body, &prelude)
if !ok {
return ""
}
encoded, err := json.Marshal(append(prelude, first))
if err != nil {
return ""
}
return string(encoded)
}
// firstUserTurn returns the content of the first user turn and appends the
// content of every system or developer message ahead of it to prelude.
func firstUserTurn(body map[string]any, prelude *[]any) (any, bool) {
if input, ok := body["input"].(string); ok && input != "" {
return input
return input, true
}
for _, field := range []string{"messages", "input"} {
for _, raw := range jsonutil.SliceAt(body, field) {
item, ok := raw.(map[string]any)
if !ok || jsonutil.StringAt(item, "role") != "user" {
if !ok {
continue
}
encoded, _ := json.Marshal(item["content"])
if len(encoded) > 0 && string(encoded) != "null" {
return string(encoded)
switch jsonutil.StringAt(item, "role") {
case "system", "developer":
*prelude = append(*prelude, item["content"])
case "user":
if content := item["content"]; content != nil {
return content, true
}
}
}
}
return ""
return nil, false
}
func StableID(prefix, value string) string {
@@ -126,12 +202,8 @@ const base62Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrst
// session passes the free tier's encoding check where the raw hash shape was
// rejected with 403 FreeTierError.
func CanonicalSessionID(signal string) string {
if canonicalSessionPattern.MatchString(signal) {
if descendingTimePartPattern.MatchString(signal[4:16]) {
return signal
}
// Right shape but a foreign encoding (raw hash or ascending ID):
// fall through and re-encode deterministically.
if isOfficialSessionID(signal) {
return signal
}
sum := sha256.Sum256([]byte("ses\x00" + signal))
timePart := descendingTimePart(sum[:6])
@@ -139,6 +211,13 @@ func CanonicalSessionID(signal string) string {
return "ses_" + timePart + randomPart
}
// isOfficialSessionID reports whether signal is a session minted by the
// official client's Identifier.descending(). A value with the right ses_ shape
// but a foreign encoding (raw hash or ascending ID) is not official.
func isOfficialSessionID(signal string) bool {
return canonicalSessionPattern.MatchString(signal) && descendingTimePartPattern.MatchString(signal[4:16])
}
// descendingTimePart renders six hash bytes as the official client's
// Identifier.descending() layout: a 36-bit timestamp shifted into the top of
// a 48-bit word, ORed with counter 1, then bitwise-NOT-ed so the low 12 hex