fix(identity): salt derived session ids per process (#160)

CanonicalSessionID re-encodes a conversation signal from the server key and
the seed alone, so the upstream `x-opencode-session` was identical in every
process on the same UTC day. The free tier keeps charging that session, so
after a 429 a gateway restart no longer changed anything upstream: the same
`ses_…` walked into the new exit's bucket and 429'd again.

Mix a 16-byte nonce, minted once per process, into the hash. A running
gateway still derives one stable session per conversation, while a restart
re-mints the ids and starts a fresh upstream identity. Official client
sessions are still forwarded verbatim.

Refs #159, #158
This commit is contained in:
CheerC authored and GitHub committed 2026-10-29 21:38:45 +08:00
1 parent b13bf6989c
commit 9946e66fa6
4 files changed
+64 -6

No files matched your search

+1 -1
View File
@@ -286,7 +286,7 @@ Keys are initially spread across proxies. Real traffic can trigger proxy checks,
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`.
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.
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. Derived session ids are salted per process, so restarting the gateway re-mints them instead of resuming the upstream session of the previous run. 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. A configured `models.anonymous_backoff` breaker is a separate lane-level guard: it pauses the whole anonymous lane for hours, while these cooldowns stay per exit and short. If every authenticated key is cooling down, routing may try the key whose cooldown ends first. Anonymous nodes still in cooldown are skipped.
+1 -1
View File
@@ -286,7 +286,7 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K
服务使用稳定会话哈希选择首选 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。
网关自行生成的会话与项目标识按调用方的服务端 Key 隔离,不同 Key 不会共享上游会话、首选 Key 或匿名代理;客户端自带的官方 OpenCode 会话(`ses_…`)原样保留。没有显式会话 ID 时,使用系统提示词和第一条用户消息生成会话标识,因此同一 Key 下系统提示词和开场内容都相同的会话仍可能共享亲和性。需要互相隔离的用户应各自使用独立的服务端 Key。调整 Key 或代理池成员后,原有会话选择的节点可能变化。
网关自行生成的会话与项目标识按调用方的服务端 Key 隔离,不同 Key 不会共享上游会话、首选 Key 或匿名代理;客户端自带的官方 OpenCode 会话(`ses_…`)原样保留;网关自行派生的会话标识按进程加盐,重启网关后会用新的标识,而不会沿用上一轮进程的上游会话。没有显式会话 ID 时,使用系统提示词和第一条用户消息生成会话标识,因此同一 Key 下系统提示词和开场内容都相同的会话仍可能共享亲和性。需要互相隔离的用户应各自使用独立的服务端 Key。调整 Key 或代理池成员后,原有会话选择的节点可能变化。
失败冷却按指数增长,最高为 `performance.failure_cooldown_seconds` 的八倍;如果上游的 `Retry-After` 更长,则使用更长时间。所有认证 Key 都处于冷却时,路由仍可能尝试最早结束冷却的 Key;仍在冷却的匿名节点会被跳过。
+29 -4
View File
@@ -201,13 +201,33 @@ var descendingTimePartPattern = regexp.MustCompile(`^[0-9a-f]{9}f[c-f][0-9a-f]$`
const base62Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
// bootNonce separates the sessions one gateway process derives from those its
// earlier runs derived. It is minted once per process and mixed into every
// synthesized session, so restarting the daemon re-mints the upstream session
// ids for the same conversations, while a single run keeps one stable id per
// conversation. Official client sessions bypass it and stay verbatim.
var bootNonce = mintBootNonce()
// mintBootNonce returns the per-process session salt. It panics when the
// system random source fails.
func mintBootNonce() []byte {
buf := make([]byte, 16)
if _, err := rand.Read(buf); err != nil {
panic("crypto/rand failed: " + err.Error())
}
return buf
}
// CanonicalSessionID returns signal unchanged when it already carries an
// official OpenCode session minted by the client's Identifier.descending()
// (preserving upstream prompt-cache affinity). Any other downstream identity
// (UUIDs, foreign client sessions, legacy gateway sessions, conversation
// seeds) is deterministically re-encoded into that exact layout — inverted
// 48-bit millisecond timestamp with counter 1, so the low 12 hex digits are
// ffe — while keeping the same stable session per conversation. A re-encoded
// seeds) is re-encoded into that exact layout — inverted 48-bit millisecond
// timestamp with counter 1, so the low 12 hex digits are ffe — keeping one
// stable session per conversation for the life of the process. The upstream
// free tier also ties a session id to its risk/quota bookkeeping, so the
// re-encoding is salted with bootNonce: a restart yields fresh ids instead of
// resuming whatever the previous run's exits were charged for. A re-encoded
// session passes the free tier's encoding check where the raw hash shape was
// rejected with 403 FreeTierError.
//
@@ -225,7 +245,12 @@ func CanonicalSessionID(signal string) string {
if isOfficialSessionID(signal) {
return signal
}
sum := sha256.Sum256([]byte("ses\x00" + signal))
hasher := sha256.New()
hasher.Write([]byte("ses\x00"))
hasher.Write(bootNonce)
hasher.Write([]byte{0})
hasher.Write([]byte(signal))
sum := hasher.Sum(nil)
timePart := descendingTimePart(time.Now(), sum[:6])
randomPart := base62Fixed(new(big.Int).SetBytes(sum[6:16]), 14)
return "ses_" + timePart + randomPart
+33
View File
@@ -0,0 +1,33 @@
package identity
import "testing"
// TestCanonicalSessionIDRestartSalt verifies that a synthesized session is
// stable within one process but changes when the process salt changes, which is
// what a daemon restart does.
func TestCanonicalSessionIDRestartSalt(t *testing.T) {
original := bootNonce
t.Cleanup(func() { bootNonce = original })
first := CanonicalSessionID("conversation seed")
if again := CanonicalSessionID("conversation seed"); again != first {
t.Fatalf("session id changed within one process: %q then %q", first, again)
}
if !isOfficialSessionID(first) {
t.Fatalf("session id %q is not accepted by the free tier pattern", first)
}
bootNonce = []byte("different boot")
if restarted := CanonicalSessionID("conversation seed"); restarted == first {
t.Fatalf("session id survived a restart: %q", restarted)
}
}
// TestCanonicalSessionIDKeepsOfficialID verifies that a client-minted official
// session is never re-salted, since its affinity belongs to the client.
func TestCanonicalSessionIDKeepsOfficialID(t *testing.T) {
official := "ses_012345678fc0ABCDEFGHIJKLMN"
if got := CanonicalSessionID(official); got != official {
t.Fatalf("official session rewritten: %q, want %q", got, official)
}
}