diff --git a/.github/workflows/issue805-owner-policy.yml b/.github/workflows/issue805-owner-policy.yml new file mode 100644 index 000000000000..afac1a167b58 --- /dev/null +++ b/.github/workflows/issue805-owner-policy.yml @@ -0,0 +1,104 @@ +name: Issue805 owner policy + +on: + pull_request: + branches: [production] + paths: + - 'backend/**' + - '.github/workflows/issue805-owner-policy.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: issue805-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +env: + EXPECTED_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + +jobs: + evidence: + runs-on: ubuntu-latest + timeout-minutes: 35 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Install isolated Redis fixture + run: | + bash .github/scripts/ci-ubuntu-mirrors.sh + if ! command -v redis-server >/dev/null; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends redis-server + fi + redis-server --version + - name: Pinned production business RED in disposable worktree + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA" + test -z "$(git status --porcelain)" + mkdir -p "$RUNNER_TEMP/issue805-evidence" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/issue805-evidence/candidate.txt" + baseline=2cfdda4aeae1f482efd8a2ca6551b7f40f6e9d66 + git fetch --no-tags --depth=1 origin "$baseline" + git worktree add --detach "$RUNNER_TEMP/issue805-red" "$EXPECTED_HEAD_SHA" + cd "$RUNNER_TEMP/issue805-red" + # Retain candidate tests, restore every changed production Go blob. + while IFS= read -r target; do + case "$target" in *_test.go) continue ;; esac + if git cat-file -e "$baseline:$target" 2>/dev/null; then + mkdir -p "$(dirname "$target")" + git show "$baseline:$target" > "$target" + expected=$(git rev-parse "$baseline:$target") + actual=$(git hash-object "$target") + echo "$target baseline=present expected=$expected actual=$actual" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt" + test "$expected" = "$actual" + else + # Candidate-only production must not survive in the baseline. + # This directory is disposable; the candidate checkout stays clean. + candidate=$(git rev-parse "$EXPECTED_HEAD_SHA:$target") + rm -- "$target" + echo "$target baseline=absent candidate=$candidate actual=absent" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt" + test ! -e "$target" + fi + done < <(git diff --no-renames --name-only "$baseline" "$EXPECTED_HEAD_SHA" -- 'backend/**/*.go') + git diff --exit-code "$baseline" -- 'backend/**/*.go' ':!backend/**/*_test.go' + # Also prove the unchanged core blobs on the initial test-only head. + for target in backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_agent_message_delivery.go backend/internal/service/openai_ws_agent_recovery.go; do + expected=$(git rev-parse "$baseline:$target") + actual=$(git hash-object "$target") + echo "$target baseline=present expected=$expected actual=$actual" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt" + test "$expected" = "$actual" + done + git diff --stat > "$RUNNER_TEMP/issue805-evidence/red-diff.txt" + set +e + (cd backend && go test -tags=unit ./internal/handler -run '^TestIssue805HTTPCompletedHistorySelectsAlternative$' -count=1 -v -timeout=5m) > "$RUNNER_TEMP/issue805-evidence/red.log" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/issue805-evidence/red.log" + test "$result" -ne 0 + ! grep -Eiq 'build failed|no tests to run|undefined:|panic:|--- SKIP:' "$RUNNER_TEMP/issue805-evidence/red.log" + grep -q -- '--- FAIL: TestIssue805HTTPCompletedHistorySelectsAlternative/stream=false' "$RUNNER_TEMP/issue805-evidence/red.log" + grep -q -- '--- FAIL: TestIssue805HTTPCompletedHistorySelectsAlternative/stream=true' "$RUNNER_TEMP/issue805-evidence/red.log" + grep -q 'opt-out must dispatch complete A history to eligible B without clearing Redis' "$RUNNER_TEMP/issue805-evidence/red.log" + - name: Exact clean candidate GREEN and race + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA" + test -z "$(git status --porcelain)" + cd backend + go test -race -tags=unit ./internal/handler ./internal/service ./internal/config -run '^TestIssue805' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/issue805-evidence/green.log" + ! grep -Eiq 'no tests to run|--- SKIP:' "$RUNNER_TEMP/issue805-evidence/green.log" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: issue805-${{ env.EXPECTED_HEAD_SHA }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/issue805-evidence/ diff --git a/.gitignore b/.gitignore index fb0854352512..d3c130bf8293 100644 --- a/.gitignore +++ b/.gitignore @@ -139,6 +139,7 @@ docs/* !docs/reauth-identity-validation.md !docs/openai-context-limit-errors.md !docs/openai-agent-continuation.md +!docs/encrypted-agent-owner-policy.md !docs/stream-timing.md !docs/openai-sse-delivery.md !docs/user-traffic.md diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index 307c4623d3a9..751453148b99 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -1170,7 +1170,11 @@ func (c CodexWSAnchorConfig) Validate() error { } type GatewayConfig struct { - UpstreamRouting upstreamroute.Config `mapstructure:"upstream_routing"` + // DisableEncryptedAgentOwnerBinding permits completed opaque agent history + // on another normally eligible native Responses account. Delivery fences, + // response pointers, authorization and no-replay protections still apply. + DisableEncryptedAgentOwnerBinding bool `mapstructure:"disable_encrypted_agent_owner_binding"` + UpstreamRouting upstreamroute.Config `mapstructure:"upstream_routing"` // PrismBrowser is the server-managed browser-session adapter for prism.openai.com. // Account settings only select this route; cookies, sandbox state and the adapter // API key remain outside account credentials. @@ -2321,6 +2325,7 @@ func configureConfigSource(setConfigFile, addConfigPath func(string)) { } func setDefaults() { + viper.SetDefault("gateway.disable_encrypted_agent_owner_binding", false) viper.SetDefault("gateway.upstream_routing.enabled", false) viper.SetDefault("runtime.role", RuntimeRoleFull) viper.SetDefault("runtime.node_id", "") diff --git a/backend/internal/config/issue805_owner_policy_test.go b/backend/internal/config/issue805_owner_policy_test.go new file mode 100644 index 000000000000..422c2844bd55 --- /dev/null +++ b/backend/internal/config/issue805_owner_policy_test.go @@ -0,0 +1,33 @@ +package config + +import ( + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestIssue805OwnerPolicyConfiguration(t *testing.T) { + for _, tc := range []struct { + name, yaml, env string + want bool + }{ + {"default", "", "", false}, + {"yaml_false", "gateway:\n disable_encrypted_agent_owner_binding: false\n", "", false}, + {"yaml_true", "gateway:\n disable_encrypted_agent_owner_binding: true\n", "", true}, + {"env_true", "", "true", true}, + {"env_false_over_yaml", "gateway:\n disable_encrypted_agent_owner_binding: true\n", "false", false}, + } { + t.Run(tc.name, func(t *testing.T) { + resetViperWithJWTSecret(t) + path := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(path, []byte(tc.yaml), 0600)) + t.Setenv("CONFIG_FILE", path) + t.Setenv("GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING", tc.env) + cfg, err := Load() + require.NoError(t, err) + require.Equal(t, tc.want, cfg.Gateway.DisableEncryptedAgentOwnerBinding) + }) + } +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 4c7aa11ce200..4646634195d6 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1286,7 +1286,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { if failoverErr.ShouldReportAccountScheduleFailure() { h.gatewayService.ReportOpenAIAccountScheduleResult(account, openAIAccountScheduleModel(c, account, forwardModel, requireCompact, nil), false, nil, err) } - if service.OpenAIAgentToolResultContinuation(c.Request.Context()) { + if service.OpenAIAgentRecoveryNoReplay(c.Request.Context()) { h.handleFailoverExhausted(c, failoverErr, streamStarted) return } diff --git a/backend/internal/handler/openai_issue805_delivery_test.go b/backend/internal/handler/openai_issue805_delivery_test.go new file mode 100644 index 000000000000..605775b83ec0 --- /dev/null +++ b/backend/internal/handler/openai_issue805_delivery_test.go @@ -0,0 +1,306 @@ +//go:build unit + +package handler + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + "github.com/gin-gonic/gin" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func issue805HTTPNodes(t *testing.T, upstream string, clients func() *redis.Client, wrappers ...func(service.GatewayCache) service.GatewayCache) (func(bool) *OpenAIGatewayHandler, []service.Account) { + t.Helper() + accounts := issue715Accounts() + for i := range accounts { + accounts[i].Type = service.AccountTypeAPIKey + accounts[i].Credentials = map[string]any{"api_key": []string{"fixture-ws-one", "fixture-ws-two"}[i], "base_url": upstream, "pool_mode": true, "pool_mode_retry_count": 2, "pool_mode_retry_status_codes": []any{520}} + } + return func(disabled bool) *OpenAIGatewayHandler { + cfg := &config.Config{} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + cache := repository.NewGatewayCache(clients()) + for _, wrap := range wrappers { + cache = wrap(cache) + } + h := newOpenAIResponsesFailoverTestHandlerWithCache(t, testutil.NewRealHTTPUpstream(cfg), cache, accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + issue805Policy(t, h.cfg, disabled) + return h + }, accounts +} + +// Observe the actual cross-node Redis lookup, rather than infer that a +// consumer reached the delivery fence because a timer happened to elapse. +type issue805ReadObserver struct { + service.GatewayCache + issue715WSDeliveryCache + seen chan struct{} + once *sync.Once +} + +func (c *issue805ReadObserver) GetOpenAIAgentRecovery(ctx context.Context, key string) (string, error) { + raw, err := c.issue715WSDeliveryCache.GetOpenAIAgentRecovery(ctx, key) + if strings.HasPrefix(raw, "pending:") { + c.once.Do(func() { close(c.seen) }) + } + return raw, err +} + +func TestIssue805HTTPUpstreamRejectionIsSingleIntactSend(t *testing.T) { + for _, tc := range []struct { + name, code string + status int + }{ + {"invalid_encrypted", "invalid_encrypted_content", 400}, + {"unsupported", "unsupported_encrypted_agent_message", 400}, + {"pool_retryable", "server_error", 520}, + {"rejected_field", "unsupported_parameter", 400}, + {"stream_failure", "unsupported_encrypted_agent_message", 0}, + } { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/stream=%v", tc.name, stream), func(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + nodes, accounts := issue805HTTPNodes(t, srv.URL, clients) + first := issue758Request(t, nodes(false), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1)) + require.Equal(t, http.StatusOK, first.Code, first.Body.String()) + original := issue805Owners(t, clients()) + require.Len(t, original, 1) + reset := time.Now().Add(time.Hour) + accounts[0].RateLimitResetAt = &reset + u.mu.Lock() + u.rejection, u.rejectionStatus = tc.code, tc.status + if tc.name == "rejected_field" { + u.rejectionParam = "max_output_tokens" + } + u.mu.Unlock() + body := issue715Body(true, stream) + if tc.name == "rejected_field" { + body = strings.TrimSuffix(body, "}") + `,"max_output_tokens":256}` + } + answer := issue758Request(t, nodes(true), body) + require.NotContains(t, answer.Body.String(), "response.completed") + require.NotContains(t, answer.Body.String(), "existing ledger balance") + if tc.status == 400 { + require.Equal(t, http.StatusBadRequest, answer.Code) + require.Contains(t, answer.Body.String(), tc.code) + } else { + require.True(t, answer.Code >= 400 || strings.Contains(answer.Body.String(), "error") || strings.Contains(answer.Body.String(), "response.failed"), answer.Body.String()) + } + u.mu.Lock() + defer u.mu.Unlock() + require.Equal(t, []string{"Bearer fixture-ws-one", "Bearer fixture-ws-two"}, u.ids, "upstream rejection must not delete and retry or enter pool failover") + require.JSONEq(t, gjson.Get(body, "input").Raw, gjson.GetBytes(u.frames[1], "input").Raw) + if tc.name == "rejected_field" { + require.EqualValues(t, 256, gjson.GetBytes(u.frames[1], "max_output_tokens").Int(), "exercise a field that the ordinary same-account retry would remove") + } + require.Equal(t, original, issue805Owners(t, clients())) + }) + } + } +} + +type issue805DeliveryWriter struct { + gin.ResponseWriter + entered, release chan struct{} + once sync.Once + failure string + cancel context.CancelFunc +} + +func (w *issue805DeliveryWriter) Write(body []byte) (int, error) { + if strings.Contains(string(body), "fixture-task-produced-by-B") { + w.once.Do(func() { close(w.entered); <-w.release }) + switch w.failure { + case "error": + return 0, io.ErrClosedPipe + case "cancel": + w.cancel() + } + } + return w.ResponseWriter.Write(body) +} +func (w *issue805DeliveryWriter) WriteString(body string) (int, error) { return w.Write([]byte(body)) } + +func TestIssue805HTTPNewOutputDeliveryAcrossNodes(t *testing.T) { + for _, outcome := range []string{"commit", "error", "cancel"} { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/stream=%v", outcome, stream), func(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + observed := make(chan struct{}) + var observeOnce sync.Once + nodes, accounts := issue805HTTPNodes(t, srv.URL, clients, func(base service.GatewayCache) service.GatewayCache { + delivery, ok := base.(issue715WSDeliveryCache) + require.True(t, ok) + return &issue805ReadObserver{GatewayCache: base, issue715WSDeliveryCache: delivery, seen: observed, once: &observeOnce} + }) + first := issue758Request(t, nodes(false), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1)) + require.Equal(t, 200, first.Code, first.Body.String()) + probe := clients() + original := issue805Owners(t, probe) + require.Len(t, original, 1) + reset := time.Now().Add(time.Hour) + accounts[0].RateLimitResetAt = &reset + producer, consumer := nodes(true), nodes(true) + c, _ := newIssue715Context(t, issue715Body(true, stream)) + c.Request.Header.Set("session_id", "fixture-758-thread") + ctx, cancel := context.WithCancel(c.Request.Context()) + defer cancel() + c.Request = c.Request.WithContext(ctx) + w := &issue805DeliveryWriter{ResponseWriter: c.Writer, entered: make(chan struct{}), release: make(chan struct{}), failure: outcome, cancel: cancel} + c.Writer = w + var once sync.Once + release := func() { once.Do(func() { close(w.release) }) } + defer release() + done := make(chan struct{}) + go func() { defer close(done); producer.Responses(c) }() + issue715Await(t, w.entered) + pending := issue805Owners(t, probe) + require.Len(t, pending, 2) + for key, raw := range pending { + if old, ok := original[key]; ok { + require.Equal(t, old, raw) + } else { + require.True(t, strings.HasPrefix(raw, "pending:"), raw) + require.Contains(t, raw, `[1,2,`) + } + } + mixed := strings.Replace(issue715Body(true, stream), issue715Agent, issue715Agent+","+issue805AgentB, 1) + result := make(chan *httptest.ResponseRecorder, 1) + go func() { result <- issue758Request(t, consumer, mixed) }() + issue715Await(t, observed) + select { + case answer := <-result: + t.Fatalf("pending output was consumed before actual downstream write: %s", answer.Body.String()) + default: + } + u.mu.Lock() + require.Len(t, u.ids, 2, "pending must never reach another network send") + u.mu.Unlock() + release() + issue715Await(t, done) + var answer *httptest.ResponseRecorder + select { + case answer = <-result: + case <-time.After(5 * time.Second): + t.Fatal("cross-node consumer did not resolve delivery") + } + if outcome == "commit" { + require.Equal(t, 200, answer.Code, answer.Body.String()) + require.Contains(t, answer.Body.String(), "existing ledger balance 18") + } else { + require.Equal(t, http.StatusConflict, answer.Code, answer.Body.String()) + } + for key, raw := range issue805Owners(t, probe) { + if old, ok := original[key]; ok { + require.Equal(t, old, raw) + } else if outcome == "commit" { + require.EqualValues(t, 2, gjson.Get(raw, "1").Int()) + } else { + require.Equal(t, "failed", raw, "failed/canceled downstream write cannot commit B") + } + } + }) + } + } +} + +func TestIssue805HTTPKeyPermissionStillRejectsBeforeSend(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + nodes, accounts := issue805HTTPNodes(t, srv.URL, clients) + first := issue758Request(t, nodes(false), strings.Replace(issue715Body(false, false), issue715Agent+",", "", 1)) + require.Equal(t, http.StatusOK, first.Code, first.Body.String()) + reset := time.Now().Add(time.Hour) + accounts[0].RateLimitResetAt = &reset + c, rec := newIssue715Context(t, issue715Body(true, false)) + c.Request.Header.Set("session_id", "fixture-758-thread") + key, _ := c.Get(string(middleware.ContextKeyAPIKey)) + key.(*service.APIKey).AllowLongContext = false + nodes(true).Responses(c) + require.Equal(t, http.StatusBadRequest, rec.Code) + require.Equal(t, "context_unverifiable", gjson.Get(rec.Body.String(), "error.code").String()) + u.mu.Lock() + defer u.mu.Unlock() + require.Len(t, u.ids, 1, "policy cannot override Key permissions") +} + +func TestIssue805HTTPOldPointerCannotMoveToAlternative(t *testing.T) { + for _, fullHistory := range []bool{false, true} { + t.Run(fmt.Sprint("full=", fullHistory), func(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + nodes, accounts := issue805HTTPNodes(t, srv.URL, clients) + first := issue758Request(t, nodes(false), strings.Replace(issue715Body(false, false), issue715Agent+",", "", 1)) + require.Equal(t, http.StatusOK, first.Code, first.Body.String()) + responseID := gjson.Get(first.Body.String(), "id").String() + require.NotEmpty(t, responseID) + reset := time.Now().Add(time.Hour) + accounts[0].RateLimitResetAt = &reset + body := issue715Body(true, false) + if !fullHistory { + body = `{"model":"gpt-5.1","stream":false,"input":[{"type":"message","role":"user","content":"continue"}]}` + } + body = strings.TrimSuffix(body, "}") + fmt.Sprintf(`,"previous_response_id":%q}`, responseID) + answer := issue758Request(t, nodes(true), body) + require.GreaterOrEqual(t, answer.Code, http.StatusBadRequest, answer.Body.String()) + u.mu.Lock() + defer u.mu.Unlock() + require.Len(t, u.ids, 1, "server state pointer must not migrate with the agent-history policy") + }) + } +} + +func TestIssue805HTTPOldDeliveryFenceCannotBeBypassed(t *testing.T) { + for _, state := range []string{"pending", "failed", "conflict", "unknown_encoding"} { + t.Run(state, func(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + nodes, accounts := issue805HTTPNodes(t, srv.URL, clients) + first := issue758Request(t, nodes(false), strings.Replace(issue715Body(false, false), issue715Agent+",", "", 1)) + require.Equal(t, http.StatusOK, first.Code, first.Body.String()) + probe := clients() + owners := issue805Owners(t, probe) + require.Len(t, owners, 1) + for key, raw := range owners { + value := state + if state == "pending" { + value = "pending:fixture-uncertain:" + raw + } + require.NoError(t, probe.Set(context.Background(), key, value, time.Minute).Err()) + } + reset := time.Now().Add(time.Hour) + accounts[0].RateLimitResetAt = &reset + answer := issue758Request(t, nodes(true), issue715Body(true, false)) + require.Equal(t, http.StatusConflict, answer.Code, answer.Body.String()) + if state == "pending" { + require.Contains(t, answer.Body.String(), "encrypted_agent_recovery_delivery_pending") + } + u.mu.Lock() + defer u.mu.Unlock() + require.Len(t, u.ids, 1, "uncertain/failed/conflicting delivery must stop before network send") + }) + } +} diff --git a/backend/internal/handler/openai_issue805_owner_policy_test.go b/backend/internal/handler/openai_issue805_owner_policy_test.go new file mode 100644 index 000000000000..a1d76e71976d --- /dev/null +++ b/backend/internal/handler/openai_issue805_owner_policy_test.go @@ -0,0 +1,153 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// JSON deliberately ignores the future field on the pinned production RED. +// Both versions compile and execute the same network/business assertions. +func issue805Policy(t *testing.T, cfg *config.Config, disabled bool) { + t.Helper() + require.NoError(t, json.Unmarshal([]byte(fmt.Sprintf(`{"DisableEncryptedAgentOwnerBinding":%t}`, disabled)), &cfg.Gateway)) +} + +// Never use miniredis for ownership lifecycle evidence. Each fixture has its +// own real Redis process/socket, with persistence disabled and no TCP listener. +func issue805Redis(t *testing.T) func() *redis.Client { + t.Helper() + binary, err := exec.LookPath("redis-server") + if err != nil { + if os.Getenv("CI") != "" { + t.Fatal("Issue805 requires real redis-server in CI") + } + t.Skip("requires isolated real redis-server") + } + dir, err := os.MkdirTemp("", "s2-805-") + require.NoError(t, err) + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + socket := filepath.Join(dir, "r.sock") + //nolint:gosec // Fixed executable, isolated fixture arguments only. + process := exec.Command(binary, "--port", "0", "--unixsocket", socket, "--unixsocketperm", "700", "--save", "", "--appendonly", "no") + process.Stdout, process.Stderr = io.Discard, io.Discard + require.NoError(t, process.Start()) + t.Cleanup(func() { _ = process.Process.Kill(); _ = process.Wait() }) + newClient := func() *redis.Client { + client := redis.NewClient(&redis.Options{Network: "unix", Addr: socket, MaxRetries: -1}) + t.Cleanup(func() { _ = client.Close() }) + return client + } + probe := newClient() + require.Eventually(t, func() bool { return probe.Ping(context.Background()).Err() == nil }, 3*time.Second, 10*time.Millisecond) + info, err := probe.Info(context.Background(), "server").Result() + require.NoError(t, err) + require.Contains(t, info, "redis_version:") + t.Log("production ownership Lua, isolated real Redis, independent node clients") + return newClient +} + +func issue805Owners(t *testing.T, client *redis.Client) map[string]string { + t.Helper() + keys, err := client.Keys(context.Background(), "openai_agent_owner:*").Result() + require.NoError(t, err) + result := make(map[string]string) + for _, key := range keys { + result[key], err = client.Get(context.Background(), key).Result() + require.NoError(t, err) + } + return result +} + +func TestIssue805HTTPCompletedHistorySelectsAlternative(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprint("stream=", stream), func(t *testing.T) { + clients := issue805Redis(t) + var mu sync.Mutex + var ids []string + var bodies [][]byte + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + mu.Lock() + ids = append(ids, r.Header.Get("Authorization")) + bodies = append(bodies, body) + n := len(ids) + mu.Unlock() + output := "[" + issue715Agent + "]" + if n > 1 { + output = `[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"existing ledger balance 18"}]}]` + } + response := fmt.Sprintf(`{"id":"resp_805_%d","status":"completed","error":null,"model":"gpt-5.1","output":%s,"usage":{"input_tokens":5,"output_tokens":3}}`, n, output) + if gjson.GetBytes(body, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":%s}\n\ndata: [DONE]\n\n", response) + } else { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, response) + } + })) + defer srv.Close() + host, _, err := net.SplitHostPort(strings.TrimPrefix(srv.URL, "http://")) + require.NoError(t, err) + require.Equal(t, "127.0.0.1", host) + accounts := issue715Accounts() + for i := range accounts { + accounts[i].Type = service.AccountTypeAPIKey + accounts[i].Credentials = map[string]any{"api_key": fmt.Sprintf("fixture-805-%d", i+1), "base_url": srv.URL} + } + newNode := func(disabled bool) *OpenAIGatewayHandler { + cfg := &config.Config{} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + h := newOpenAIResponsesFailoverTestHandlerWithCache(t, testutil.NewRealHTTPUpstream(cfg), repository.NewGatewayCache(clients()), accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + issue805Policy(t, h.cfg, disabled) + return h + } + first := issue758Request(t, newNode(false), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1)) + require.Equal(t, http.StatusOK, first.Code, first.Body.String()) + require.JSONEq(t, issue715Agent, issue758CompletedResponse(t, first.Body.String(), stream).Get("output.0").Raw) + probe := clients() + original := issue805Owners(t, probe) + require.Len(t, original, 1, "A must complete downstream delivery before the policy changes") + reset := time.Now().Add(time.Hour) + accounts[0].RateLimitResetAt = &reset + strict := issue758Request(t, newNode(false), issue715Body(true, stream)) + require.Equal(t, http.StatusTooManyRequests, strict.Code, strict.Body.String()) + require.Contains(t, strict.Body.String(), "encrypted_agent_recovery_owner_rate_limited") + followup := issue715Body(true, stream) + answer := issue758Request(t, newNode(true), followup) + require.Equal(t, http.StatusOK, answer.Code, "opt-out must dispatch complete A history to eligible B without clearing Redis: %s", answer.Body.String()) + require.Contains(t, answer.Body.String(), "existing ledger balance 18") + mu.Lock() + defer mu.Unlock() + require.Equal(t, []string{"Bearer fixture-805-1", "Bearer fixture-805-2"}, ids) + require.JSONEq(t, gjson.Get(followup, "input").Raw, gjson.GetBytes(bodies[1], "input").Raw, "the real network send must preserve every original history/tool result item") + require.Equal(t, original, issue805Owners(t, probe), "consuming A on B must not overwrite or poison A ownership") + }) + } +} diff --git a/backend/internal/handler/openai_issue805_ws_test.go b/backend/internal/handler/openai_issue805_ws_test.go new file mode 100644 index 000000000000..142c6d0ca8e3 --- /dev/null +++ b/backend/internal/handler/openai_issue805_ws_test.go @@ -0,0 +1,465 @@ +//go:build unit + +package handler + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/service" + coderws "github.com/coder/websocket" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +var issue805AgentB = strings.ReplaceAll(issue715Agent, "fixture-task-reference-715", "fixture-task-produced-by-B") + +// A network oracle supports all three real WS adapters. Cross-account +// acceptance is synthetic; it makes no claim about provider cryptography. +type issue805Oracle struct { + mu sync.Mutex + ids []string + frames [][]byte + ws, http int + rejection string + rejectionParam string + rejectionStatus int + disconnect bool +} + +func (u *issue805Oracle) response(r *http.Request, body []byte) []byte { + u.mu.Lock() + defer u.mu.Unlock() + id := r.Header.Get("Authorization") + u.ids = append(u.ids, id) + u.frames = append(u.frames, append([]byte(nil), body...)) + if u.disconnect { + return nil + } + if u.rejection != "" { + return []byte(fmt.Sprintf(`{"type":"response.failed","response":{"id":"resp_805_rejected","status":"failed","error":{"code":%q,"param":%q,"message":"synthetic upstream rejected intact history"}}}`, u.rejection, u.rejectionParam)) + } + output := "[" + issue715Agent + "]" + if id == "Bearer fixture-ws-two" { + output = "[" + issue805AgentB + `,{"type":"message","role":"assistant","content":[{"type":"output_text","text":"existing ledger balance 18"}]}]` + } + return []byte(fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_805_%d","model":"gpt-5.1","status":"completed","error":null,"output":%s,"usage":{"input_tokens":5,"output_tokens":3}}}`, len(u.ids), output)) +} + +func (u *issue805Oracle) server(t *testing.T) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + u.mu.Lock() + u.http++ + u.mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + if response := u.response(r, body); response != nil { + u.mu.Lock() + status := u.rejectionStatus + u.mu.Unlock() + if status > 0 { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = fmt.Fprintf(w, `{"error":%s}`, gjson.GetBytes(response, "response.error").Raw) + } else { + _, _ = fmt.Fprintf(w, "data: %s\n\n", response) + } + } + return + } + conn, err := coderws.Accept(w, r, nil) + if err != nil { + t.Error(err) + return + } + defer conn.CloseNow() //nolint:errcheck // Fixture cleanup. + for { + _, body, err := conn.Read(r.Context()) + if err != nil { + return + } + u.mu.Lock() + u.ws++ + u.mu.Unlock() + response := u.response(r, body) + if response == nil || conn.Write(r.Context(), coderws.MessageText, response) != nil { + return + } + } + })) + t.Cleanup(srv.Close) + return srv +} + +func issue805WSNode(t *testing.T, mode, upstream string, cache service.GatewayCache, disabled, limited bool) *openAIWSPassthroughHandlerHarness { + t.Helper() + return newOpenAIWSPassthroughHandlerHarnessWithKey(t, upstream, + http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}}, + map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false"}, cache, + func(key *service.APIKey) { key.AllowLongContext = true }, + func(a *service.Account, cfg *config.Config, _ *service.HTTPUpstream, repo *service.AccountRepository) { + a.ID, a.Priority = 1, 0 + a.Credentials["api_key"] = "fixture-ws-one" + a.Extra["openai_apikey_responses_websockets_v2_mode"] = mode + a.Extra["codex_fingerprint_mode"] = "off" + cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = 15 + issue805Policy(t, cfg, disabled) + require.Equal(t, mode, a.ResolveOpenAIResponsesWebSocketV2Mode(cfg.Gateway.OpenAIWS.IngressModeDefault)) + other := *a + other.ID, other.Priority = 2, 1 + other.Credentials = map[string]any{"api_key": "fixture-ws-two", "base_url": upstream} + if limited { + reset := time.Now().Add(time.Hour) + a.RateLimitResetAt = &reset + } + *repo = &issue600SwitchRepo{&openAIWSFailoverHandlerAccountRepoStub{accounts: []service.Account{*a, other}}} + }) +} + +func TestIssue805WSCompletedHistoryAcrossNodesAndTurns(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} { + t.Run(mode, func(t *testing.T) { + clients := issue805Redis(t) + newCache := func() service.GatewayCache { return repository.NewGatewayCache(clients()) } + u := &issue805Oracle{} + srv := u.server(t) + producer := issue805WSNode(t, mode, srv.URL, newCache(), false, false) + issue715WSSend(t, producer.clientConn, issue715WSCreate("", false)) + first := issue715WSRead(t, producer.clientConn) + require.Contains(t, string(first), "fixture-task-reference-715") + probe := clients() + require.Eventually(t, func() bool { + owners := issue805Owners(t, probe) + if len(owners) != 1 { + return false + } + for _, raw := range owners { + if gjson.Get(raw, "1").Int() != 1 { + return false + } + } + return true + }, time.Second, 5*time.Millisecond) + original := issue805Owners(t, probe) + consumer := issue805WSNode(t, mode, srv.URL, newCache(), true, true) + body := issue715WSCreate("", true) + issue715WSSend(t, consumer.clientConn, body) + answer := issue715WSRead(t, consumer.clientConn) + require.Equal(t, "response.completed", gjson.GetBytes(answer, "type").String(), string(answer)) + require.Contains(t, string(answer), "existing ledger balance 18") + require.Eventually(t, func() bool { + owners := issue805Owners(t, probe) + if len(owners) != 2 { + return false + } + for key, raw := range owners { + if old, ok := original[key]; ok { + if raw != old { + return false + } + } else if gjson.Get(raw, "1").Int() != 2 { + return false + } + } + return true + }, time.Second, 5*time.Millisecond, "A must survive and the newly delivered output must commit real B") + previous := gjson.GetBytes(answer, "response.id").String() + mixed := strings.Replace(issue715WSCreate(previous, true), issue715Agent, issue715Agent+","+issue805AgentB, 1) + issue715WSSend(t, consumer.clientConn, mixed) + require.Equal(t, "response.completed", gjson.GetBytes(issue715WSRead(t, consumer.clientConn), "type").String()) + u.mu.Lock() + ids, frames, httpCount, wsCount := append([]string(nil), u.ids...), append([][]byte(nil), u.frames...), u.http, u.ws + u.mu.Unlock() + require.Equal(t, []string{"Bearer fixture-ws-one", "Bearer fixture-ws-two", "Bearer fixture-ws-two"}, ids) + for i, source := range []string{body, mixed} { + require.JSONEq(t, gjson.Get(source, "input").Raw, gjson.GetBytes(frames[i+1], "input").Raw, "actual adapter send must preserve complete current history and tool results") + } + if mode == service.OpenAIWSIngressModeHTTPBridge { + require.Equal(t, 3, httpCount) + require.Zero(t, wsCount) + } else { + require.Equal(t, 3, wsCount) + require.Zero(t, httpCount) + } + // Normal restart back to strict can reject mixed producers, but must + // neither erase evidence nor pretend that A's history was made by B. + strict := issue805WSNode(t, mode, srv.URL, newCache(), false, false) + issue715WSSend(t, strict.clientConn, strings.Replace(mixed, fmt.Sprintf(`,"previous_response_id":%q`, previous), "", 1)) + issue805WSRefusal(t, strict.clientConn, "encrypted_agent_recovery_owner_conflict") + u.mu.Lock() + require.Len(t, u.ids, 3) + u.mu.Unlock() + for _, node := range []*openAIWSPassthroughHandlerHarness{strict, consumer, producer} { + issue600Finish(t, node, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}}) + } + }) + } +} + +func issue805WSRefusal(t *testing.T, conn *coderws.Conn, expectedCode string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + explicitRefusal := false + for { + _, event, err := conn.Read(ctx) + if err != nil { + require.NotErrorIs(t, err, context.DeadlineExceeded, "refusal must close promptly") + require.True(t, explicitRefusal || coderws.CloseStatus(err) == coderws.StatusPolicyViolation, + "local policy refusal needs %s or a policy-violation close; arbitrary EOF is not evidence: %v", expectedCode, err) + return + } + require.Contains(t, []string{"error", "response.failed"}, gjson.GetBytes(event, "type").String(), string(event)) + explicitRefusal = explicitRefusal || gjson.GetBytes(event, "error.code").String() == expectedCode || + gjson.GetBytes(event, "response.error.code").String() == expectedCode + } +} + +// This oracle deliberately drops an in-flight upstream connection. EOF is an +// allowed transport outcome here, but proves no explicit local policy refusal. +// The caller separately asserts the exact sends and absence of warmup replay. +func issue805WSAmbiguousTermination(t *testing.T, conn *coderws.Conn) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + for { + _, event, err := conn.Read(ctx) + if err != nil { + require.NotErrorIs(t, err, context.DeadlineExceeded, "ambiguous turn must terminate promptly") + return + } + require.Contains(t, []string{"error", "response.failed"}, gjson.GetBytes(event, "type").String(), string(event)) + } +} + +func TestIssue805WSAmbiguousLaterTurnNeverReplaysWarmup(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} { + t.Run(mode, func(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + h := issue805WSNode(t, mode, srv.URL, repository.NewGatewayCache(clients()), true, false) + issue715WSSend(t, h.clientConn, issue715WSCreate("", false)) + require.Contains(t, string(issue715WSRead(t, h.clientConn)), "fixture-task-reference-715") + u.mu.Lock() + u.disconnect = true + u.mu.Unlock() + current := issue715WSCreate("", true) + issue715WSSend(t, h.clientConn, current) + issue805WSAmbiguousTermination(t, h.clientConn) + issue600Finish(t, h, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}}) + u.mu.Lock() + defer u.mu.Unlock() + require.Len(t, u.frames, 2, "one warmup and one ambiguous current turn; never replay either") + require.JSONEq(t, gjson.Get(current, "input").Raw, gjson.GetBytes(u.frames[1], "input").Raw) + }) + } +} + +func TestIssue805WSRejectsUnsafeHistoryBeforeNetworkSend(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} { + for _, state := range []string{"lost", "failed", "conflict", "foreign_pointer", "pointer_only"} { + t.Run(mode+"/"+state, func(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + cache := repository.NewGatewayCache(clients()) + h := issue805WSNode(t, mode, srv.URL, cache, true, false) + issue715WSSend(t, h.clientConn, issue715WSCreate("", false)) + first := issue715WSRead(t, h.clientConn) + require.Contains(t, string(first), "fixture-task-reference-715") + probe := clients() + require.Eventually(t, func() bool { + owners := issue805Owners(t, probe) + if len(owners) != 1 { + return false + } + for _, raw := range owners { + if gjson.Get(raw, "1").Int() != 1 { + return false + } + } + return true + }, time.Second, 5*time.Millisecond) + body := issue715WSCreate("", true) + switch state { + case "foreign_pointer", "pointer_only": + require.NoError(t, service.NewOpenAIWSStateStore(cache).BindResponseAccount(context.Background(), 4301, "resp_foreign805", 2, time.Minute)) + body = issue715WSCreate("resp_foreign805", state != "pointer_only") + default: + for key := range issue805Owners(t, probe) { + if state == "lost" { + require.NoError(t, probe.Del(context.Background(), key).Err()) + } else { + require.NoError(t, probe.Set(context.Background(), key, state, time.Minute).Err()) + } + } + } + issue715WSSend(t, h.clientConn, body) + code := "encrypted_agent_recovery_owner_unavailable" + if state == "conflict" { + code = "encrypted_agent_recovery_owner_conflict" + } + issue805WSRefusal(t, h.clientConn, code) + issue600Finish(t, h, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}}) + u.mu.Lock() + defer u.mu.Unlock() + require.Len(t, u.frames, 1, "unsafe current history cannot be sent or replaced with the first warmup") + }) + } + } +} + +func TestIssue805WSUpstreamRejectionNeverDeletesAndRetries(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} { + t.Run(mode, func(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + producer := issue805WSNode(t, mode, srv.URL, repository.NewGatewayCache(clients()), false, false) + issue715WSSend(t, producer.clientConn, issue715WSCreate("", false)) + require.Contains(t, string(issue715WSRead(t, producer.clientConn)), "fixture-task-reference-715") + u.mu.Lock() + u.rejection = "unsupported_encrypted_agent_message" + u.mu.Unlock() + consumer := issue805WSNode(t, mode, srv.URL, repository.NewGatewayCache(clients()), true, true) + body := issue715WSCreate("", true) + issue715WSSend(t, consumer.clientConn, body) + answer := issue715WSRead(t, consumer.clientConn) + require.Equal(t, "response.failed", gjson.GetBytes(answer, "type").String(), string(answer)) + require.Contains(t, string(answer), "unsupported_encrypted_agent_message") + for _, node := range []*openAIWSPassthroughHandlerHarness{consumer, producer} { + issue600Finish(t, node, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}}) + } + u.mu.Lock() + defer u.mu.Unlock() + require.Equal(t, []string{"Bearer fixture-ws-one", "Bearer fixture-ws-two"}, u.ids) + require.JSONEq(t, gjson.Get(body, "input").Raw, gjson.GetBytes(u.frames[1], "input").Raw) + }) + } +} + +func TestIssue805WSNewBOutputWaitsForCrossNodeCommit(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} { + t.Run(mode, func(t *testing.T) { + clients := issue805Redis(t) + newCache := func() service.GatewayCache { return repository.NewGatewayCache(clients()) } + u := &issue805Oracle{} + srv := u.server(t) + originalNode := issue805WSNode(t, mode, srv.URL, newCache(), false, false) + issue715WSSend(t, originalNode.clientConn, issue715WSCreate("", false)) + require.Contains(t, string(issue715WSRead(t, originalNode.clientConn)), "fixture-task-reference-715") + probe := clients() + require.Eventually(t, func() bool { + owners := issue805Owners(t, probe) + if len(owners) != 1 { + return false + } + for _, raw := range owners { + if gjson.Get(raw, "1").Int() != 1 { + return false + } + } + return true + }, time.Second, 5*time.Millisecond) + original := issue805Owners(t, probe) + base := newCache() + delivery, ok := base.(issue715WSDeliveryCache) + require.True(t, ok) + barrier := &issue715WSBarrierCache{GatewayCache: base, issue715WSDeliveryCache: delivery, entered: make(chan struct{}), release: make(chan struct{}), observed: make(chan struct{})} + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(barrier.release) }) } + defer release() + producer := issue805WSNode(t, mode, srv.URL, barrier, true, true) + issue715WSSend(t, producer.clientConn, issue715WSCreate("", true)) + answer := issue715WSRead(t, producer.clientConn) + require.Contains(t, string(answer), "fixture-task-produced-by-B") + issue715Await(t, barrier.entered) // Finish is reached only after the actual downstream write. + pending := issue805Owners(t, probe) + require.Len(t, pending, 2) + for key, raw := range pending { + if old, found := original[key]; found { + require.Equal(t, old, raw) + } else { + require.True(t, strings.HasPrefix(raw, "pending:"), raw) + require.Contains(t, raw, `[1,2,`) + } + } + readerBase := newCache() + readerDelivery, ok := readerBase.(issue715WSDeliveryCache) + require.True(t, ok) + observed := make(chan struct{}) + var observeOnce sync.Once + reader := &issue805ReadObserver{GatewayCache: readerBase, issue715WSDeliveryCache: readerDelivery, seen: observed, once: &observeOnce} + consumer := issue805WSNode(t, mode, srv.URL, reader, true, true) + mixed := strings.Replace(issue715WSCreate("", true), issue715Agent, issue715Agent+","+issue805AgentB, 1) + issue715WSSend(t, consumer.clientConn, mixed) + issue715Await(t, observed) + u.mu.Lock() + before := len(u.frames) + u.mu.Unlock() + require.Equal(t, 2, before, "client-visible B output cannot be consumed on another node before commit") + release() + require.Equal(t, "response.completed", gjson.GetBytes(issue715WSRead(t, consumer.clientConn), "type").String()) + for _, node := range []*openAIWSPassthroughHandlerHarness{consumer, producer, originalNode} { + issue600Finish(t, node, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}}) + } + u.mu.Lock() + defer u.mu.Unlock() + require.Equal(t, []string{"Bearer fixture-ws-one", "Bearer fixture-ws-two", "Bearer fixture-ws-two"}, u.ids) + require.JSONEq(t, gjson.Get(mixed, "input").Raw, gjson.GetBytes(u.frames[2], "input").Raw) + for key, raw := range issue805Owners(t, probe) { + if old, found := original[key]; found { + require.Equal(t, old, raw) + } else { + require.EqualValues(t, 2, gjson.Get(raw, "1").Int(), "new output must retain real B after commit") + } + } + }) + } +} + +func TestIssue805WSHTTPBridgeHTTPRejectionReportsOriginalCode(t *testing.T) { + for _, status := range []int{http.StatusBadRequest, 520} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + producer := issue805WSNode(t, service.OpenAIWSIngressModeHTTPBridge, srv.URL, repository.NewGatewayCache(clients()), false, false) + issue715WSSend(t, producer.clientConn, issue715WSCreate("", false)) + require.Contains(t, string(issue715WSRead(t, producer.clientConn)), "fixture-task-reference-715") + u.mu.Lock() + u.rejection, u.rejectionStatus = "unsupported_encrypted_agent_message", status + u.mu.Unlock() + consumer := issue805WSNode(t, service.OpenAIWSIngressModeHTTPBridge, srv.URL, repository.NewGatewayCache(clients()), true, true) + body := issue715WSCreate("", true) + issue715WSSend(t, consumer.clientConn, body) + answer := issue715WSRead(t, consumer.clientConn) + require.Equal(t, "error", gjson.GetBytes(answer, "type").String(), string(answer)) + require.Equal(t, "unsupported_encrypted_agent_message", gjson.GetBytes(answer, "error.code").String()) + require.EqualValues(t, status, gjson.GetBytes(answer, "status").Int()) + for _, node := range []*openAIWSPassthroughHandlerHarness{consumer, producer} { + issue600Finish(t, node, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}}) + } + u.mu.Lock() + defer u.mu.Unlock() + require.Equal(t, []string{"Bearer fixture-ws-one", "Bearer fixture-ws-two"}, u.ids) + require.JSONEq(t, gjson.Get(body, "input").Raw, gjson.GetBytes(u.frames[1], "input").Raw) + }) + } +} diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index 16bd26efd755..29e8433d157f 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -434,12 +434,29 @@ func (s *defaultOpenAIAccountScheduler) Select( derefGroupID(req.GroupID) != recovery.groupID || req.RequestedModel != recovery.model { return nil, decision, openAIAgentRecoveryError("owner_unavailable") } + } + if recovery.ownerBindingRequired() { req.StickyAccountID = recovery.owner.accountID req.StickyWeighted = false req.PreserveStickyBinding = true req.DisableStickyEscape = true req.PreviousResponseCanMove = false } + // Agent-history opt-out does not migrate provider-side response pointers. + // Keep this independent of the presence of an encrypted item owner. + pointerOwner := int64(0) + if recovery != nil && recovery.previousResponseID != "" { + var pointerErr error + pointerOwner, pointerErr = s.service.getOpenAIWSStateStore().GetResponseAccount(ctx, recovery.groupID, recovery.previousResponseID) + if pointerErr != nil || pointerOwner <= 0 || req.PreviousResponseID != recovery.previousResponseID { + return nil, decision, openAIAgentRecoveryError("owner_unavailable") + } + req.StickyAccountID = pointerOwner + req.StickyWeighted = false + req.PreserveStickyBinding = true + req.DisableStickyEscape = true + req.PreviousResponseCanMove = false + } if s != nil && s.service != nil && s.service.openAIGroupRequiresPrivacySet(ctx, req.GroupID) { req.RequirePrivacySet = true } @@ -604,13 +621,17 @@ func (s *defaultOpenAIAccountScheduler) Select( } } } - if recovery != nil && recovery.owner != nil { - if req.GuardianParentAccountID > 0 && req.GuardianParentAccountID != recovery.owner.accountID { + if recovery.ownerBindingRequired() || pointerOwner > 0 { + ownerID := pointerOwner + if recovery.ownerBindingRequired() { + ownerID = recovery.owner.accountID + } + if req.GuardianParentAccountID > 0 && req.GuardianParentAccountID != ownerID { return nil, decision, openAIAgentRecoveryError("owner_unavailable") } if previousResponseID != "" { - ownerID, readErr := s.service.getOpenAIWSStateStore().GetResponseAccount(ctx, derefGroupID(req.GroupID), previousResponseID) - if readErr != nil || ownerID != recovery.owner.accountID { + previousOwner, readErr := s.service.getOpenAIWSStateStore().GetResponseAccount(ctx, derefGroupID(req.GroupID), previousResponseID) + if readErr != nil || previousOwner != ownerID { return nil, decision, openAIAgentRecoveryError("owner_unavailable") } } diff --git a/backend/internal/service/openai_agent_message_delivery.go b/backend/internal/service/openai_agent_message_delivery.go index cad57e6b6b32..f86205b07828 100644 --- a/backend/internal/service/openai_agent_message_delivery.go +++ b/backend/internal/service/openai_agent_message_delivery.go @@ -90,6 +90,11 @@ func (d *openAIAgentRecoveryDelivery) reserve(items [][32]byte) error { defer cancel() for _, item := range items { key := d.request.itemKey(item) + if d.request.disableOwnerBinding && d.request.known[key] { + // An echoed completed input is still its original producer's item. + // Never reserve/publish it as the account consuming this history. + continue + } if d.keys[key] { continue } diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index 7b72f5a26087..4d4937ce96a5 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -45,22 +45,25 @@ type openAIAgentRecoveryState struct { } type openAIAgentRecoveryRequest struct { - keyID int64 - userID int64 - delivery *openAIAgentRecoveryDelivery - outputs [][32]byte - disallowLearning bool - nativeCompaction bool - lookupErr error - toolResult bool - known map[[32]byte]bool - keys [][32]byte - items [][32]byte - owner *openAIAgentRecoveryBinding - conflict bool - groupID int64 - model string - session string + disableOwnerBinding bool + previousResponseID string + inputDigest [32]byte + keyID int64 + userID int64 + delivery *openAIAgentRecoveryDelivery + outputs [][32]byte + disallowLearning bool + nativeCompaction bool + lookupErr error + toolResult bool + known map[[32]byte]bool + keys [][32]byte + items [][32]byte + owner *openAIAgentRecoveryBinding + conflict bool + groupID int64 + model string + session string } // WithOpenAIAgentMessageRecovery observes only opaque item identities. A route @@ -71,6 +74,10 @@ type openAIAgentRecoveryRequest struct { // Ordinary sticky writes, HTTP 200 and reasoning are not proof. func (s *OpenAIGatewayService) WithOpenAIAgentMessageRecovery(ctx context.Context, c *gin.Context, body []byte, sessionHash, model string) context.Context { request := &openAIAgentRecoveryRequest{groupID: getOpenAIGroupIDFromContext(c), model: model, session: sessionHash} + request.disableOwnerBinding = s != nil && s.cfg != nil && s.cfg.Gateway.DisableEncryptedAgentOwnerBinding + if request.disableOwnerBinding { + request.previousResponseID = strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) + } keyID := getAPIKeyIDFromContext(c) request.keyID = keyID request.userID = openAIAgentRecoveryHTTPUser(c, keyID) @@ -85,6 +92,9 @@ func (s *OpenAIGatewayService) WithOpenAIAgentMessageRecovery(ctx context.Contex return context.WithValue(ctx, openAIAgentRecoveryContextKey{}, request) } request.items = openAIAgentRecoveryItemDigests(body) + if request.preservesHistory() { + request.inputDigest = openAIAgentRecoveryInputDigest(body) + } gjson.GetBytes(body, "input").ForEach(func(_, item gjson.Result) bool { request.toolResult = request.toolResult || isCodexToolCallOutputItemType(item.Get("type").String()) return !request.toolResult @@ -105,7 +115,7 @@ func (s *OpenAIGatewayService) WithOpenAIAgentMessageRecovery(ctx context.Contex if !found { continue } - if binding.conflicted || (request.owner != nil && !sameOpenAIAgentRecoveryRoute(*request.owner, binding)) { + if binding.conflicted || (request.ownerBindingRequired() && !sameOpenAIAgentRecoveryRoute(*request.owner, binding)) { request.conflict = true break } @@ -126,7 +136,41 @@ func openAIAgentRecoveryFromContext(ctx context.Context) *openAIAgentRecoveryReq func openAIAgentRecoveryBound(ctx context.Context) bool { request := openAIAgentRecoveryFromContext(ctx) - return request != nil && (request.owner != nil || request.conflict || request.lookupErr != nil) + // Evidence still requires native integrity/delivery protection in opt-out + // mode. This must not be used to decide whether to pin the producer account. + return request != nil && (request.owner != nil || request.conflict || request.lookupErr != nil || request.preservesHistory() || request.previousResponseID != "") +} + +func (r *openAIAgentRecoveryRequest) ownerBindingRequired() bool { + return r != nil && r.owner != nil && !r.disableOwnerBinding +} + +func (r *openAIAgentRecoveryRequest) preservesHistory() bool { + return r != nil && r.disableOwnerBinding && len(r.items) > 0 +} + +func openAIAgentRecoveryPreservesHistory(ctx context.Context) bool { + return openAIAgentRecoveryFromContext(ctx).preservesHistory() +} + +// Keep the complete input, including ordinary history and executed tool +// results. Only JSON object-key ordering is ignored, never array order/numbers. +func openAIAgentRecoveryInputDigest(body []byte) [32]byte { + decoder := json.NewDecoder(strings.NewReader(gjson.GetBytes(body, "input").Raw)) + decoder.UseNumber() + var value any + if decoder.Decode(&value) != nil { + return [32]byte{} + } + canonical, err := json.Marshal(value) + if err != nil { + return [32]byte{} + } + return sha256.Sum256(canonical) +} + +func (s *OpenAIGatewayService) preserveOpenAIAgentHistory(body []byte) bool { + return s != nil && s.cfg != nil && s.cfg.Gateway.DisableEncryptedAgentOwnerBinding && len(openAIAgentRecoveryItemDigests(body)) > 0 } func openAIAgentRecoveryItemDigests(body []byte) [][32]byte { @@ -206,12 +250,23 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryAccount(ctx context.Conte if request.lookupErr != nil { return request.lookupErr } - if !request.conflict && request.owner == nil { - return nil - } if request.conflict { return openAIAgentRecoveryError("owner_conflict") } + // Provider-side response state is never made portable by the agent policy, + // even on a pointer-only request with no known opaque item owner. + if request.previousResponseID != "" { + owner, err := s.getOpenAIWSStateStore().GetResponseAccount(ctx, request.groupID, request.previousResponseID) + if err != nil || owner <= 0 || account == nil || owner != account.ID { + return openAIAgentRecoveryError("owner_unavailable") + } + if request.userID > 0 && !account.IsOpenAIApiKey() { + return openAIAgentRecoveryError("http_previous_response_unsupported") + } + } + if !request.ownerBindingRequired() { + return nil + } if account == nil || account.ID != request.owner.accountID { return openAIAgentRecoveryError("owner_unavailable") } @@ -259,7 +314,7 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con return noop, nil } if request.disallowLearning { - if request.nativeCompaction && request.owner != nil { + if request.nativeCompaction && (request.owner != nil || request.preservesHistory() || request.previousResponseID != "") { return noop, s.checkOpenAIAgentRecoveryCompaction(ctx, account, req) } return noop, nil @@ -281,14 +336,14 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con return noop, nil } if req.GetBody == nil { - if len(request.items) == 0 && request.owner == nil { + if len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { return noop, nil } return noop, openAIAgentRecoveryError("wire_changed") } reader, err := req.GetBody() if err != nil { - if len(request.items) == 0 && request.owner == nil { + if len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { return noop, nil } return noop, openAIAgentRecoveryError("wire_changed") @@ -296,17 +351,23 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con body, err := io.ReadAll(reader) _ = reader.Close() if err != nil { - if len(request.items) == 0 && request.owner == nil { + if len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { return noop, nil } return noop, openAIAgentRecoveryError("wire_changed") } if !utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body) { - if len(request.items) == 0 && request.owner == nil { + if len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { return noop, nil } return noop, openAIAgentRecoveryError("wire_changed") } + if request.preservesHistory() && openAIAgentRecoveryInputDigest(body) != request.inputDigest { + return noop, openAIAgentRecoveryError("wire_changed") + } + if request.previousResponseID != "" && gjson.GetBytes(body, "previous_response_id").String() != request.previousResponseID { + return noop, openAIAgentRecoveryError("owner_unavailable") + } items := openAIAgentRecoveryItemDigests(body) if len(items) != len(request.items) { if request.owner != nil { @@ -324,9 +385,28 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con } wire := openAIAgentRecoveryWireDigest(req.URL.String(), req.Header, gjson.GetBytes(body, "model").String()) binding := openAIAgentRecoveryBinding{accountID: account.ID, config: openAIAgentRecoveryConfig(account, request.model), wire: wire, expiresAt: time.Now().Add(s.openAIWSSessionStickyTTL())} - if request.owner != nil && !sameOpenAIAgentRecoveryRoute(*request.owner, binding) { + if request.ownerBindingRequired() && !sameOpenAIAgentRecoveryRoute(*request.owner, binding) { return noop, openAIAgentRecoveryError("wire_changed") } + if err := s.checkOpenAIAgentRecoveryRecords(ctx, request, binding); err != nil { + return noop, err + } + delivery := newOpenAIAgentRecoveryDelivery(s, ctx, request, binding) + request.delivery = delivery + return func(completed bool) { + delivery.finish(completed && ctx.Err() == nil) + if !completed || ctx.Err() != nil || request.disableOwnerBinding { + // Consumption is not production. In opt-out mode inputs retain their + // original records (including concurrent fences); only actual new + // outputs receive the admitted producer's transactional grant above. + return + } + binding.expiresAt = time.Now().Add(s.openAIWSSessionStickyTTL()) + s.publishOpenAIAgentRecoveryInputs(ctx, request, binding) + }, nil +} + +func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryRecords(ctx context.Context, request *openAIAgentRecoveryRequest, binding openAIAgentRecoveryBinding) error { shared, _ := s.cache.(OpenAIAgentRecoveryCache) if shared != nil { storeCtx, cancel := context.WithTimeout(ctx, 3*time.Second) @@ -334,17 +414,17 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con for _, key := range request.keys { raw, err := shared.GetOpenAIAgentRecovery(storeCtx, hex.EncodeToString(key[:])) if err != nil { - return noop, openAIAgentRecoveryError("store_unavailable") + return openAIAgentRecoveryError("store_unavailable") } old, found, err := decodeOpenAIAgentRecoveryBinding(raw) if err != nil { - return noop, openAIAgentRecoveryError("store_unavailable") + return openAIAgentRecoveryError("store_unavailable") } - if found && (old.conflicted || old.failed || old.pending != "" || !sameOpenAIAgentRecoveryRoute(old, binding)) { - return noop, openAIAgentRecoveryError("owner_conflict") + if found && (old.conflicted || old.failed || old.pending != "" || (!request.disableOwnerBinding && !sameOpenAIAgentRecoveryRoute(old, binding))) { + return openAIAgentRecoveryError("owner_conflict") } if !found && request.known[key] { - return noop, openAIAgentRecoveryError("owner_unavailable") + return openAIAgentRecoveryError("owner_unavailable") } } } else { @@ -352,66 +432,65 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con state.mu.Lock() defer state.mu.Unlock() for _, key := range request.keys { - if old, exists := state.bindings[key]; exists && time.Now().Before(old.expiresAt) && - (old.conflicted || old.failed || old.pending != "" || !sameOpenAIAgentRecoveryRoute(old, binding)) { - return noop, openAIAgentRecoveryError("owner_conflict") + old, exists := state.bindings[key] + found := exists && time.Now().Before(old.expiresAt) + if found && (old.conflicted || old.failed || old.pending != "" || (!request.disableOwnerBinding && !sameOpenAIAgentRecoveryRoute(old, binding))) { + return openAIAgentRecoveryError("owner_conflict") + } + if request.disableOwnerBinding && !found && request.known[key] { + return openAIAgentRecoveryError("owner_unavailable") } } } - delivery := newOpenAIAgentRecoveryDelivery(s, ctx, request, binding) - request.delivery = delivery - return func(completed bool) { - delivery.finish(completed && ctx.Err() == nil) - if !completed || ctx.Err() != nil { - return + return nil +} + +func (s *OpenAIGatewayService) publishOpenAIAgentRecoveryInputs(ctx context.Context, request *openAIAgentRecoveryRequest, binding openAIAgentRecoveryBinding) { + keys := append([][32]byte(nil), request.keys...) + shared, _ := s.cache.(OpenAIAgentRecoveryCache) + if shared != nil { + storeCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + for _, key := range keys { + // After delivery a failed publication cannot be undone. It loses + // future availability; it never authorizes an unproven owner. + if err := shared.PublishOpenAIAgentRecovery(storeCtx, hex.EncodeToString(key[:]), encodeOpenAIAgentRecoveryBinding(binding), time.Until(binding.expiresAt)); err != nil { + logger.L().Warn("openai.agent_recovery_publish_failed", zap.Int64("account_id", binding.accountID), zap.Error(err)) + break + } } - binding.expiresAt = time.Now().Add(s.openAIWSSessionStickyTTL()) - keys := append([][32]byte(nil), request.keys...) - shared, _ := s.cache.(OpenAIAgentRecoveryCache) - if shared != nil { - storeCtx, cancel := context.WithTimeout(ctx, 3*time.Second) - defer cancel() - for _, key := range keys { - // After delivery a failed publication cannot be undone. It loses - // future availability; it never authorizes an unproven owner. - if err := shared.PublishOpenAIAgentRecovery(storeCtx, hex.EncodeToString(key[:]), encodeOpenAIAgentRecoveryBinding(binding), time.Until(binding.expiresAt)); err != nil { - logger.L().Warn("openai.agent_recovery_publish_failed", zap.Int64("account_id", binding.accountID), zap.Error(err)) - break - } + return + } + state := &s.agentMessageRecovery + state.mu.Lock() + defer state.mu.Unlock() + if state.bindings == nil { + state.bindings = make(map[[32]byte]openAIAgentRecoveryBinding) + } + if len(state.bindings) >= openAIAgentRecoveryMaxEntries { + for key, value := range state.bindings { + if !time.Now().Before(value.expiresAt) { + delete(state.bindings, key) } - return } - state := &s.agentMessageRecovery - state.mu.Lock() - defer state.mu.Unlock() - if state.bindings == nil { - state.bindings = make(map[[32]byte]openAIAgentRecoveryBinding) + } + for _, key := range keys { + old, exists := state.bindings[key] + if exists && time.Now().Before(old.expiresAt) && (old.conflicted || old.failed || old.pending != "" || !sameOpenAIAgentRecoveryRoute(old, binding)) { + old.conflicted = true + state.bindings[key] = old + continue } - if len(state.bindings) >= openAIAgentRecoveryMaxEntries { - for key, value := range state.bindings { - if !time.Now().Before(value.expiresAt) { - delete(state.bindings, key) - } - } + if !exists && len(state.bindings) >= openAIAgentRecoveryMaxEntries { + // Saturation loses recovery availability, never task contents. + continue } - for _, key := range keys { - old, exists := state.bindings[key] - if exists && time.Now().Before(old.expiresAt) && (old.conflicted || old.failed || old.pending != "" || !sameOpenAIAgentRecoveryRoute(old, binding)) { - old.conflicted = true - state.bindings[key] = old - continue - } - if !exists && len(state.bindings) >= openAIAgentRecoveryMaxEntries { - // Saturation loses recovery availability, never task contents. - continue - } - retained := binding - if exists && old.expiresAt.After(retained.expiresAt) { - retained.expiresAt = old.expiresAt - } - state.bindings[key] = retained + retained := binding + if exists && old.expiresAt.After(retained.expiresAt) { + retained.expiresAt = old.expiresAt } - }, nil + state.bindings[key] = retained + } } func (r *openAIAgentRecoveryRequest) itemKey(item [32]byte) [32]byte { @@ -454,7 +533,13 @@ func observeOpenAIAgentRecoveryOutput(c *gin.Context, body []byte, nested bool) // proven native task route, including pool-mode same-account retry. func OpenAIAgentToolResultContinuation(ctx context.Context) bool { r := openAIAgentRecoveryFromContext(ctx) - return r != nil && r.owner != nil && r.toolResult + return r != nil && (r.owner != nil || r.preservesHistory()) && r.toolResult +} + +// Opt-out permits one intact attempt, not automatic cross-account retries or +// input-rewriting retries. Strict mode retains its existing tool-result rule. +func OpenAIAgentRecoveryNoReplay(ctx context.Context) bool { + return OpenAIAgentToolResultContinuation(ctx) || openAIAgentRecoveryPreservesHistory(ctx) } // Native remote compaction v2 consumes an already proven task but proves no new @@ -465,7 +550,7 @@ func OpenAIAgentToolResultContinuation(ctx context.Context) bool { // routes do not advertise it on ordinary turns). func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryCompaction(ctx context.Context, account *Account, req *http.Request) error { request := openAIAgentRecoveryFromContext(ctx) - if request == nil || request.owner == nil { + if request == nil || (request.owner == nil && !request.preservesHistory() && request.previousResponseID == "") { return nil } if err := s.checkOpenAIAgentRecoveryAccount(ctx, account); err != nil { @@ -485,6 +570,12 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryCompaction(ctx context.Co if err != nil || !utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body) { return openAIAgentRecoveryError("wire_changed") } + if request.preservesHistory() && openAIAgentRecoveryInputDigest(body) != request.inputDigest { + return openAIAgentRecoveryError("wire_changed") + } + if request.previousResponseID != "" && gjson.GetBytes(body, "previous_response_id").String() != request.previousResponseID { + return openAIAgentRecoveryError("owner_unavailable") + } items := openAIAgentRecoveryItemDigests(body) if len(items) != len(request.items) { return openAIAgentRecoveryError("wire_changed") @@ -494,6 +585,9 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryCompaction(ctx context.Co return openAIAgentRecoveryError("wire_changed") } } + if request.disableOwnerBinding { + return s.checkOpenAIAgentRecoveryRecords(ctx, request, openAIAgentRecoveryBinding{}) + } model := gjson.GetBytes(body, "model").String() url := req.URL.String() if openAIAgentRecoveryWireDigest(url, req.Header, model) == request.owner.wire || diff --git a/backend/internal/service/openai_agent_message_recovery_wait.go b/backend/internal/service/openai_agent_message_recovery_wait.go index 0f4e6a781dff..3b993d0ee50d 100644 --- a/backend/internal/service/openai_agent_message_recovery_wait.go +++ b/backend/internal/service/openai_agent_message_recovery_wait.go @@ -9,7 +9,7 @@ import ( // A cooldown is not evidence of incompatible ciphertext. Preserve the existing // evidence while waiting, without admitting a request or guessing another owner. func (s *defaultOpenAIAccountScheduler) checkOpenAIAgentRecoveryCooldown(ctx context.Context, req OpenAIAccountScheduleRequest, recovery *openAIAgentRecoveryRequest) error { - if recovery == nil || recovery.owner == nil || s.service.accountRepo == nil { + if !recovery.ownerBindingRequired() || s.service.accountRepo == nil { return nil } // The scheduler snapshot may filter out quota-blocked accounts entirely. diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index dbde057fad2d..d85d02cfcd92 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -951,7 +951,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco lineageGroupID := getOpenAIGroupIDFromContext(c) lineageEntryBody := body lineageSessionHash := "" - if stateStore := s.getOpenAIWSStateStore(); stateStore != nil && stateStore.HasAnySessionInvalidEncryptedContent() { + if stateStore := s.getOpenAIWSStateStore(); !openAIAgentRecoveryPreservesHistory(ctx) && stateStore != nil && stateStore.HasAnySessionInvalidEncryptedContent() { lineageSessionHash = openAIEncryptedLineageKey(c, account.ID, s.openAIWSLineageSessionHashFromContext(c, body)) if invalidDigests := stateStore.GetSessionInvalidEncryptedContentDigests(lineageGroupID, lineageSessionHash); len(invalidDigests) > 0 { strippedBody, strippedCount := s.stripSessionInvalidEncryptedContentLogged( @@ -967,7 +967,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco // 上游通过 WS/SSE 拒绝密文时,安全的一次恢复及无法恢复的出口都记录 // 可明确归属的进场密文摘要,供后续 turn 使用同一 lineage 会话键。 markInvalidEncryptedContentLineage := func(transport string, rejectedBody, rejection []byte) { - if isControlledExperiment(ctx) { + if isControlledExperiment(ctx) || openAIAgentRecoveryPreservesHistory(ctx) { return } invalidDigests := openAIRejectedEncryptedDigests(rejectedBody, rejection) @@ -1330,7 +1330,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco rejectedFieldRetryState := openAIResponsesRejectedFieldRetryStateForRequest(c, body) // HTTP 400 and pre-output SSE rejection share one same-account retry. recoverInvalidEncryptedContentHTTP := func(resp *http.Response, rejection []byte) (bool, error) { - if isControlledExperiment(ctx) || httpInvalidEncryptedContentRetryTried || ctx.Err() != nil || + if isControlledExperiment(ctx) || openAIAgentRecoveryPreservesHistory(ctx) || httpInvalidEncryptedContentRetryTried || ctx.Err() != nil || (c != nil && c.Request != nil && c.Request.Context().Err() != nil) || openAIStreamClientOutputStarted(c, false) { return false, nil } @@ -1482,6 +1482,11 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } respBody = s.redactAgentIdentitySensitiveBody(ctx, account, respBody) resp.Body = io.NopCloser(bytes.NewReader(respBody)) + if openAIAgentRecoveryPreservesHistory(ctx) { + // The administrator allowed one intact cross-account attempt. An + // actual rejection is not permission to rewrite or resubmit it. + return s.handleErrorResponse(ctx, resp, c, account, body, resolveOpenAIErrorSchedulingModel(billingModel, upstreamModel)) + } if resp.StatusCode == http.StatusBadRequest && isOpenAIInvalidEncryptedContentError(upstreamCode, extractUpstreamErrorMessage(respBody)) { markInvalidEncryptedContentLineage("http", body, respBody) if retry, retryErr := recoverInvalidEncryptedContentHTTP(resp, respBody); retryErr != nil { @@ -1627,7 +1632,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if signal, ok := asOpenAICompactFallbackSignal(err); ok { if retryBody, fallbackModel, retry := s.prepareOpenAICompactFallbackRetry( c, account, requestedModel, body, http.StatusBadRequest, signal.message, signal.payload, compactModelFallbackRetried, - ); retry { + ); retry && !openAIAgentRecoveryPreservesHistory(ctx) { s.appendOpenAICompactFallbackRetryOps(c, account, resp, signal.payload, signal.message, false) body = retryBody requestView = newOpenAIRequestView(body) @@ -1684,7 +1689,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if signal, ok := asOpenAICompactFallbackSignal(err); ok { if retryBody, fallbackModel, retry := s.prepareOpenAICompactFallbackRetry( c, account, requestedModel, body, http.StatusBadRequest, signal.message, signal.payload, compactModelFallbackRetried, - ); retry { + ); retry && !openAIAgentRecoveryPreservesHistory(ctx) { s.appendOpenAICompactFallbackRetryOps(c, account, resp, signal.payload, signal.message, false) body = retryBody requestView = newOpenAIRequestView(body) diff --git a/backend/internal/service/openai_issue805_owner_policy_test.go b/backend/internal/service/openai_issue805_owner_policy_test.go new file mode 100644 index 000000000000..038f963f11a6 --- /dev/null +++ b/backend/internal/service/openai_issue805_owner_policy_test.go @@ -0,0 +1,245 @@ +package service + +import ( + "bytes" + "context" + "errors" + "net/http" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestIssue805PolicySeparatesRoutingFromReplaySafety(t *testing.T) { + for _, known := range []bool{false, true} { + for _, disabled := range []bool{false, true} { + t.Run(strings.Join([]string{map[bool]string{false: "unknown", true: "known"}[known], map[bool]string{false: "strict", true: "relaxed"}[disabled]}, "/"), func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}} + a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + if known { + issue715LearnRoute(t, svc, a, issue715OpaqueBody) + } + svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = disabled + c, _ := newTurnStateTestContext(t, 715, "fixture-session") + c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)}) + body := strings.TrimSuffix(issue715OpaqueBody, "]}") + `,{"type":"function_call_output","call_id":"fixture","output":"already applied"}]}` + ctx := svc.WithOpenAIWSAgentRecovery(context.Background(), c, []byte(body), "fixture-session", "gpt-6-astra") + if known || disabled { + require.True(t, OpenAIAgentToolResultContinuation(ctx), "removing binding cannot authorize tool-result replay") + require.False(t, OpenAIWSAgentRecoveryCanRetry(ctx), "unknown opaque input is not evidence for replay") + } + b := &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + req, err := http.NewRequest(http.MethodPost, "https://other.example/responses", bytes.NewBufferString(body)) + require.NoError(t, err) + finish, err := svc.prepareOpenAIAgentRecoveryAttempt(ctx, b, req) + if known && !disabled { + require.Error(t, err) + return + } + require.NoError(t, err) + finish(true) + if known && disabled { + for _, binding := range svc.agentMessageRecovery.bindings { + require.EqualValues(t, 1, binding.accountID) + } + } + }) + } + } +} + +func TestIssue805AlternativeStillNeedsNormalAdmission(t *testing.T) { + for _, restriction := range []string{"none", "group", "model", "group_model", "quota", "disabled", "excluded", "concurrency"} { + t.Run(restriction, func(t *testing.T) { + accounts := []Account{ + {ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, GroupIDs: []int64{715}}, + {ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, GroupIDs: []int64{715}, Credentials: map[string]any{}, Concurrency: 1}, + } + // The real repository's group query only returns group members. + // Preserve that contract instead of using the intentionally broad + // generic scheduler stub for the group-revocation case. + svc := &OpenAIGatewayService{cfg: &config.Config{}, accountRepo: schedulerGroupAwareOpenAIAccountRepo{schedulerTestOpenAIAccountRepo{accounts: accounts}}} + issue715LearnRoute(t, svc, &accounts[0], issue715OpaqueBody) + svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true + reset := time.Now().Add(time.Hour) + accounts[0].RateLimitResetAt = &reset + excluded := map[int64]struct{}{} + switch restriction { + case "group": + accounts[1].GroupIDs = []int64{716} + case "model": + accounts[1].Credentials["model_mapping"] = map[string]any{"other-model": "other-model"} + case "group_model": + accounts[1].AccountGroups = []AccountGroup{{GroupID: 715, AllowedModels: []string{"other-model"}}} + case "quota": + accounts[1].Extra = map[string]any{"quota_limit": float64(10), "quota_used": float64(10)} + case "disabled": + accounts[1].Schedulable = false + case "excluded": + excluded[2] = struct{}{} + case "concurrency": + svc.concurrencyService = NewConcurrencyService(schedulerTestConcurrencyCache{acquireResults: map[int64]bool{2: false}}) + } + c, _ := newTurnStateTestContext(t, 715, "fixture-session") + c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)}) + ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, []byte(issue715OpaqueBody), "fixture-session", "gpt-6-astra") + selected, _, err := svc.SelectAccountWithScheduler(ctx, int64Ptr(715), "", "fixture-session", "gpt-6-astra", excluded, OpenAIUpstreamTransportAny, false) + if selected != nil && selected.ReleaseFunc != nil { + defer selected.ReleaseFunc() + } + if restriction == "none" { + require.NoError(t, err) + require.NotNil(t, selected) + require.EqualValues(t, 2, selected.Account.ID) + return + } + if restriction == "concurrency" && selected != nil { + require.False(t, selected.Acquired, "opt-out cannot grant an occupied slot") + require.NotNil(t, selected.WaitPlan) + return + } + require.Error(t, err) + require.Nil(t, selected) + }) + } +} + +func TestIssue805FinalAdmissionStillRechecksGroup(t *testing.T) { + accounts := []Account{{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true, GroupIDs: []int64{715}}} + repo := &turnAdmissionRepo{account: &accounts[0]} + svc := &OpenAIGatewayService{cfg: &config.Config{}, accountRepo: repo, requireLatestTurnAdmission: true} + svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true + selected := accounts[0] + _, err := svc.admitOpenAITurnForGroup(context.Background(), 715, true, &selected, "gpt-6-astra") + require.NoError(t, err, "the originally selected account must qualify before revocation") + accounts[0].GroupIDs = []int64{716} + _, err = svc.admitOpenAITurnForGroup(context.Background(), 715, true, &selected, "gpt-6-astra") + var denied *OpenAITurnAdmissionError + require.ErrorAs(t, err, &denied) + require.Equal(t, "group_membership_changed", denied.Reason, "opt-out cannot bypass final fresh admission") + require.Equal(t, 2, repo.reads, "both sends must use the production authoritative admission contract") +} + +func TestIssue805FinalSendPreservesHistoryAndDeliveryFences(t *testing.T) { + for _, mutation := range []string{"intact", "tool_result", "user_history", "agent", "pending", "failed", "conflict", "lost", "canceled"} { + t.Run(mutation, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}} + a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + issue715LearnRoute(t, svc, a, issue715OpaqueBody) + svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true + c, _ := newTurnStateTestContext(t, 715, "fixture-session") + c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)}) + body := strings.TrimSuffix(issue715OpaqueBody, "]}") + `,{"type":"message","role":"user","content":"original user history"},{"type":"function_call_output","call_id":"fixture","output":"already applied"}]}` + parent, cancel := context.WithCancel(context.Background()) + defer cancel() + ctx := svc.WithOpenAIAgentMessageRecovery(parent, c, []byte(body), "fixture-session", "gpt-6-astra") + switch mutation { + case "tool_result": + body = strings.Replace(body, "already applied", "changed", 1) + case "user_history": + body = strings.Replace(body, "original user history", "changed", 1) + case "agent": + body = strings.Replace(body, "fixture-opaque-reference", "changed", 1) + case "canceled": + cancel() + default: + for key, binding := range svc.agentMessageRecovery.bindings { + switch mutation { + case "pending": + binding.pending = "pending:fixture" + case "failed": + binding.failed = true + case "conflict": + binding.conflicted = true + case "lost": + delete(svc.agentMessageRecovery.bindings, key) + continue + } + svc.agentMessageRecovery.bindings[key] = binding + } + } + req, err := http.NewRequest(http.MethodPost, "https://other.example/responses", bytes.NewBufferString(body)) + require.NoError(t, err) + finish, err := svc.prepareOpenAIAgentRecoveryAttempt(ctx, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, req) + if mutation == "intact" { + require.NoError(t, err) + finish(true) + } else { + require.Error(t, err, "policy must not disable the final safety check") + } + }) + } +} + +func TestIssue805WSPointerAndRecordLossStayConservative(t *testing.T) { + for _, mutation := range []string{"foreign_pointer", "unknown_pointer", "pointer_only", "record_loss", "write_error", "cancel"} { + t.Run(mutation, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}} + svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true + parent, cancel := context.WithCancel(context.Background()) + defer cancel() + manager, _, account := issue715WSManager(t, svc, parent) + defer manager.abort() + require.NoError(t, issue715WSBegin(t, manager, account, `{"model":"gpt-6-astra","input":[]}`, "ctx_pool")) + item := `{"type":"agent_message","encrypted_content":"fixture-805"}` + terminal := `{"type":"response.completed","response":{"id":"resp_805_owner","status":"completed","output":[` + item + `]}}` + err := manager.write([]byte(terminal), func() error { + if mutation == "cancel" { + cancel() + } + if mutation == "write_error" { + return errors.New("fixture downstream failure") + } + return nil + }) + if mutation == "write_error" { + require.Error(t, err) + } else { + require.NoError(t, err) + } + body := `{"model":"gpt-6-astra","input":[` + item + `]}` + account.ID = 2 + switch mutation { + case "foreign_pointer", "pointer_only": + body = strings.Replace(body, `"input":`, `"previous_response_id":"resp_805_owner","input":`, 1) + if mutation == "pointer_only" { + body = strings.Replace(body, item, "", 1) + } + case "unknown_pointer": + body = strings.Replace(body, `"input":`, `"previous_response_id":"resp_unknown","input":`, 1) + case "record_loss": + clear(svc.agentMessageRecovery.bindings) + } + require.Error(t, issue715WSBegin(t, manager, account, body, "ctx_pool"), "neither a server pointer nor uncertain delivery becomes portable") + require.False(t, OpenAIWSAgentRecoveryCanRetry(manager.ctx)) + }) + } +} + +func TestIssue805WSFirstSeenHistoryDoesNotInventOwner(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}} + svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true + manager, _, account := issue715WSManager(t, svc, context.Background()) + defer manager.abort() + require.NoError(t, issue715WSBegin(t, manager, account, issue715OpaqueBody, "ctx_pool")) + require.NoError(t, manager.write([]byte(`{"type":"response.completed","response":{"id":"resp_805_first_seen","status":"completed","output":[]}}`), func() error { return nil })) + require.Empty(t, svc.agentMessageRecovery.bindings, "consumption of unknown history is not a producer observation") + require.Empty(t, manager.known, "later explicit turns must not confuse an unpublished input with lost records") + require.False(t, OpenAIWSAgentRecoveryCanRetry(manager.ctx), "lack of an owner is never permission to automatically replay opaque work") + account.ID = 2 + require.NoError(t, issue715WSBegin(t, manager, account, issue715OpaqueBody, "ctx_pool"), "fresh first-seen history follows ordinary admission without inferring a forgotten owner") +} + +func TestIssue805WSRefusedCurrentPointerCannotReplayWarmup(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}} + svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true + manager, _, account := issue715WSManager(t, svc, context.Background()) + defer manager.abort() + require.True(t, OpenAIWSAgentRecoveryCanRetry(manager.ctx), "empty warmup has no prior opaque side effect") + err := issue715WSBegin(t, manager, account, `{"model":"gpt-6-astra","previous_response_id":"resp_unknown","input":[]}`, "ctx_pool") + require.Error(t, err) + require.False(t, OpenAIWSAgentRecoveryCanRetry(manager.ctx), "a refused current pointer cannot be replaced by replaying the initial warmup") +} diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index f854f869602f..12333b6f26a0 100644 --- a/backend/internal/service/openai_ws_agent_recovery.go +++ b/backend/internal/service/openai_ws_agent_recovery.go @@ -151,6 +151,11 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, } ctx := r.service.WithOpenAIAgentMessageRecovery(r.ctx, r.c, source, r.session, model) r.request = openAIAgentRecoveryFromContext(ctx) + if r.request.disableOwnerBinding && (openAIAgentRecoveryBound(ctx) || len(r.request.items) > 0) { + // Record current-turn replay safety even when a later delivery/pointer + // check refuses the send. The initial warmup context cannot replace it. + r.preventReplay() + } for _, key := range r.request.keys { if r.known[key] && !r.request.known[key] { return openAIAgentRecoveryError("owner_unavailable") @@ -162,14 +167,14 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, // established transport. Final fresh admission and the captured wire remain // authoritative; managed/other credentials are excluded by prepare below. r.request.disallowLearning = r.request.disallowLearning || account.IsExcelBPSEnabledForModel(model) || account.IsPrismBrowserEnabledForModel(model) - if r.request.owner != nil && r.request.disallowLearning { + if (r.request.owner != nil || r.request.preservesHistory()) && r.request.disallowLearning { return openAIAgentRecoveryError("route_changed") } if err := r.service.checkOpenAIAgentRecoveryAccount(ctx, account); err != nil { return err } previous := gjson.GetBytes(source, "previous_response_id").String() - if r.request.owner != nil && previous != "" { + if (r.request.owner != nil || r.request.disableOwnerBinding) && previous != "" { owner, err := r.service.getOpenAIWSStateStore().GetResponseAccount(ctx, r.request.groupID, previous) if err != nil || owner != account.ID || gjson.GetBytes(payload, "previous_response_id").String() != previous { return openAIAgentRecoveryError("owner_unavailable") @@ -256,7 +261,12 @@ func (r *openAIWSAgentRecovery) write(payload []byte, write func() error) error r.finish(completed) if completed { for _, key := range request.keys { - r.known[key] = true + // Opt-out consumption does not publish new input ownership. Only + // remember inputs that already had completed records; otherwise a + // later turn would mistake an ordinary miss for record loss. + if !request.disableOwnerBinding || request.known[key] { + r.known[key] = true + } } for _, item := range request.outputs { r.known[request.itemKey(item)] = true diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 6990ec355347..fcff9837e12c 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -1369,7 +1369,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } // 剥离本会话已知失效的加密项,阻断同一失效密文随历史反复触发上游拒绝。 // 历史序列须同步剥离,否则与已剥离的当前 input 项错位,prefix 复用失配。 - if invalidDigests := s.sessionInvalidEncryptedContentDigests(groupID, openAIEncryptedLineageKey(c, account.ID, sessionHash)); len(invalidDigests) > 0 { + if invalidDigests := s.sessionInvalidEncryptedContentDigests(groupID, openAIEncryptedLineageKey(c, account.ID, sessionHash)); len(invalidDigests) > 0 && !s.preserveOpenAIAgentHistory(currentBridgePayload.clientPayloadRaw) { strippedPayload, strippedCount := s.stripSessionInvalidEncryptedContentLogged( currentBridgePayload.payloadRaw, invalidDigests, "ingress_ws_http_bridge_invalid_encrypted_lineage_strip", account.ID, turn, ) @@ -2495,7 +2495,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( skipBeforeTurn = false // 剥离本会话已知失效的加密项,阻断同一失效密文随历史反复触发上游拒绝。 // 历史序列须同步剥离,否则与已剥离的当前 input 项错位,prefix 复用失配。 - if invalidDigests := s.sessionInvalidEncryptedContentDigests(groupID, openAIEncryptedLineageKey(c, account.ID, sessionHash)); len(invalidDigests) > 0 { + if invalidDigests := s.sessionInvalidEncryptedContentDigests(groupID, openAIEncryptedLineageKey(c, account.ID, sessionHash)); len(invalidDigests) > 0 && !s.preserveOpenAIAgentHistory(currentPayload) { strippedPayload, strippedCount := s.stripSessionInvalidEncryptedContentLogged( currentPayload, invalidDigests, "ingress_ws_invalid_encrypted_lineage_strip", account.ID, turn, ) diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 9e8207a9df5a..ed1708f3c2ee 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -354,7 +354,7 @@ func (c *openAIWSToolCallReplayCollector) addItem(item gjson.Result) { c.items = append(c.items, json.RawMessage(raw)) } -func buildOpenAIWSHTTPBridgeErrorEvent(statusCode int, message string) []byte { +func buildOpenAIWSHTTPBridgeErrorEvent(statusCode int, message string, source ...[]byte) []byte { message = strings.TrimSpace(message) if message == "" { message = http.StatusText(statusCode) @@ -362,14 +362,22 @@ func buildOpenAIWSHTTPBridgeErrorEvent(statusCode int, message string) []byte { if message == "" { message = "upstream request failed" } + errorBody := map[string]any{"type": "upstream_error", "message": message} + if len(source) > 0 { + // Preserve only the standard error identity fields, not an arbitrary + // upstream envelope. The caller already sanitized the message. + for _, field := range []string{"code", "type", "param"} { + value := gjson.GetBytes(source[0], "error."+field) + if value.Type == gjson.String && value.String() != "" { + errorBody[field] = value.String() + } + } + } event := map[string]any{ "type": "error", "sequence_number": 0, "status": statusCode, - "error": map[string]any{ - "type": "upstream_error", - "message": message, - }, + "error": errorBody, } body, err := json.Marshal(event) if err != nil { @@ -456,6 +464,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( strictSession := smartProtocolStrict(ctx) statefulSession := smartProtocolStateful(ctx) + preserveAgentHistory := s.preserveOpenAIAgentHistory(payload) if statefulSession && gjson.GetBytes(payload, "store").Type != gjson.True { return nil, denyOpenAITurn("http_session_requires_storage") } @@ -680,13 +689,16 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( if shouldFailover && (turn == 1 || resp.StatusCode == http.StatusTooManyRequests) { return nil, newOpenAIUpstreamFailoverError(resp.StatusCode, resp.Header, respBody, upstreamMsg, false).WithGrokForbiddenPolicy(account) } - } else if !strictSession && shouldFailover && (turn == 1 || resp.StatusCode == http.StatusTooManyRequests) { + } else if !strictSession && !preserveAgentHistory && shouldFailover && (turn == 1 || resp.StatusCode == http.StatusTooManyRequests) { return nil, s.handleFailoverErrorResponsePassthrough(ctx, resp, c, account, body, respBody) } if account.Platform != PlatformGrok && (shouldFailover || shouldCooldownOpenAITransientUpstreamError(resp.StatusCode, respBody)) { s.handleOpenAIAccountUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, actualModel) } clientError := buildOpenAIWSHTTPBridgeErrorEvent(resp.StatusCode, upstreamMsg) + if preserveAgentHistory { + clientError = buildOpenAIWSHTTPBridgeErrorEvent(resp.StatusCode, upstreamMsg, respBody) + } if writeErr := writeClientMessage(clientError); writeErr == nil { markOpenAIWSClientVisibleFailure(c, "error", clientError) } @@ -957,7 +969,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( } // A disconnected client needs this attempt drained for usage, not replayed, // even when only non-semantic heartbeats were delivered. - if !strictSession && !clientDisconnected && !wroteDownstream && shouldFailover && (turn == 1 || statusCode == http.StatusTooManyRequests) { + if !strictSession && !preserveAgentHistory && !clientDisconnected && !wroteDownstream && shouldFailover && (turn == 1 || statusCode == http.StatusTooManyRequests) { if account.Platform == PlatformGrok { return nil, newOpenAIUpstreamFailoverError(statusCode, resp.Header, upstreamMessage, errMessage, false).WithGrokForbiddenPolicy(account) } diff --git a/deploy/.env.example b/deploy/.env.example index 67490ea23a7e..b7b11d9f4641 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -302,6 +302,9 @@ RATE_LIMIT_OVERLOAD_COOLDOWN_MINUTES=10 # # 默认:false GATEWAY_FORCE_CODEX_CLI=false +# 完整且已交付的加密 agent 历史可尝试其他合格账号;默认保持严格归属。 +# 所有共享 Redis 节点统一配置并排空 WS 后重启,详见 docs/encrypted-agent-owner-policy.md。 +GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING=false # OpenAI /responses/compact 上游模型(默认 gpt-5.5)。 # 当 compact 端点暂未支持更新模型时,可通过这里降级规避失败。 GATEWAY_OPENAI_COMPACT_MODEL=gpt-5.5 diff --git a/deploy/config.example.yaml b/deploy/config.example.yaml index 244a04bd3479..6ef7088d98e3 100644 --- a/deploy/config.example.yaml +++ b/deploy/config.example.yaml @@ -296,6 +296,10 @@ gateway: # 已提交请求超时后终止,不表示上游停止执行或费用为零;已收到响应头的正文流不受此计时器影响。 # 0 disables this timer without inheriting the generic 600s timeout. openai_response_header_timeout: 0 + # Optional cross-account attempt for complete, delivered encrypted agent history. + # 默认严格;true 不保证密文兼容,不解除权限/额度/并发和交付安全检查。 + # 所有节点统一配置、排空旧 WS 后重启;详见 docs/encrypted-agent-owner-policy.md。 + disable_encrypted_agent_owner_binding: false # Grok text Responses first-byte timeout (seconds, 0=disabled; default 120) # Grok 文本 Responses 首字节超时时间(秒,0=禁用;默认 120) grok_response_header_timeout: 120 diff --git a/deploy/docker-compose.dev.yml b/deploy/docker-compose.dev.yml index d32e9a6232d4..b849a9949fe5 100644 --- a/deploy/docker-compose.dev.yml +++ b/deploy/docker-compose.dev.yml @@ -62,6 +62,7 @@ services: # Fallbacks mirror Sub2API backend defaults so omitted values preserve behavior. - GATEWAY_FORCE_CODEX_CLI=${GATEWAY_FORCE_CODEX_CLI:-false} - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5} + - GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING=${GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING:-false} - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna} - SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS=${SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS:-} - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0} diff --git a/deploy/docker-compose.local.yml b/deploy/docker-compose.local.yml index c551605e53a7..bf9a4b4bd432 100644 --- a/deploy/docker-compose.local.yml +++ b/deploy/docker-compose.local.yml @@ -170,6 +170,7 @@ services: # Fallbacks mirror Sub2API backend defaults so omitted values preserve behavior. - GATEWAY_FORCE_CODEX_CLI=${GATEWAY_FORCE_CODEX_CLI:-false} - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5} + - GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING=${GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING:-false} - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna} - SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS=${SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS:-} - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0} diff --git a/deploy/docker-compose.standalone.yml b/deploy/docker-compose.standalone.yml index 5ec75c3d1eb4..afc1b47fc012 100644 --- a/deploy/docker-compose.standalone.yml +++ b/deploy/docker-compose.standalone.yml @@ -117,6 +117,7 @@ services: # Fallbacks mirror Sub2API backend defaults so omitted values preserve behavior. - GATEWAY_FORCE_CODEX_CLI=${GATEWAY_FORCE_CODEX_CLI:-false} - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5} + - GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING=${GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING:-false} - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna} - SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS=${SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS:-} - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0} diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index f7859c00715a..90ff6d599f33 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -167,6 +167,7 @@ services: # Fallbacks mirror Sub2API backend defaults so omitted values preserve behavior. - GATEWAY_FORCE_CODEX_CLI=${GATEWAY_FORCE_CODEX_CLI:-false} - GATEWAY_OPENAI_COMPACT_MODEL=${GATEWAY_OPENAI_COMPACT_MODEL:-gpt-5.5} + - GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING=${GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING:-false} - SUB2API_IMAGES_MAIN_MODEL=${SUB2API_IMAGES_MAIN_MODEL:-gpt-5.6-luna} - SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS=${SUB2API_IMAGE_EDIT_FORM_ACCOUNT_IDS:-} - GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT=${GATEWAY_OPENAI_RESPONSE_HEADER_TIMEOUT:-0} diff --git a/docs/encrypted-agent-owner-policy.md b/docs/encrypted-agent-owner-policy.md new file mode 100644 index 000000000000..2f0804a5070b --- /dev/null +++ b/docs/encrypted-agent-owner-policy.md @@ -0,0 +1,30 @@ +# 加密 agent 历史账号策略 + +默认仍按已登记的账号和原生 Responses 路线恢复加密 `agent_message`。原账号限流或过载时,保留原等待提示和恢复时间。管理员可显式允许完整历史尝试普通账号池中的其他合格账号: + +```yaml +gateway: + disable_encrypted_agent_owner_binding: false +``` + +环境变量 `GATEWAY_DISABLE_ENCRYPTED_AGENT_OWNER_BINDING=true` 优先于 YAML;未配置或 `false` 为严格模式。Compose 模板透传此变量。它是进程启动配置,没有后台 UI 或逐请求覆盖接口。 + +开启后,已完成交付的 agent 历史不会仅因原账号/路线绑定阻止选择 B。网关保留原始历史、密文和工具结果,通过普通身份、用户及 Key 权限、分组、模型、余额、额度、账号状态和并发准入后才尝试发送。没有合格账号仍返回错误。原账号的服务端 `previous_response_id` 不是可移植历史:指针归属未知或属于其他账号时,仍明确拒绝。当前请求或现有 WS 连接已经观察过的 owner 记录丢失,也必须拒绝,不能用预热帧补造当前历史。请从客户端提供完整原历史,不要删除密文或工具结果来续接。 + +跨账号的密文兼容由上游决定。本开关不保证上游接受、无损续接或费用不变。上游拒绝时保留原错误处理;不能通过删除消息、重放连接首帧或把已执行工具结果再次自动提交来伪造成功。网络中断、客户端取消和未确定交付的请求也不能据此自动重放。 + +## Redis 与切换流程 + +无需迁移数据库或清空 Redis。已完成的 A 输入记录保留原 producer,不会因为被 B 消费就改成 B 或制造 A/B conflict。B 新生成的密文输出仍先建立 pending 屏障,仅在成功的最终下游写之后提交 B;失败、未确定交付、存储错误和现有 conflict 继续保守拒绝。原有 TTL 仍生效。新请求首次遇到的历史若已过期或没有 owner 记录,无法推断被遗忘的原账号;沿用普通准入并不构成已交付或密文兼容的证明,也不授权自动重放。它与当前请求/连接已知记录随后丢失的明确拒绝不同。 + +1. 先保存客户端当前完整历史,停止接入新请求,等待在途请求结束并排空旧 WS 连接。 +2. 在所有共享该 Redis 的网关节点配置相同值,按正常配置流程重建/重启进程。 +3. 恢复流量,客户端重连 WS,再提交完整当前历史。不能把连接初始预热帧当作后续轮历史。 + +不要混跑 true/false 节点或将旧 WS 无条件保留到新策略中。进程持有启动配置,旧节点仍会严格拒绝;旧版本的消费发布行为还可能产生冲突,因此不承诺无条件滚动切换。 + +回到 `false` 同样需要所有节点统一配置、排空连接和正常重启。只有 A 记录的历史恢复严格绑定 A;同时含 A 和 B 已完成输出的历史会明确拒绝为混合归属,不能伪造成单一 owner。回退二进制也有这个限制,清 Redis 不是安全恢复手段。 + +## 验证边界 + +Issue805 回归夹具使用隔离的真实 Redis、虚构密文和真实 localhost HTTP/WS 网络连接,包含 HTTP JSON/SSE、WS `ctx_pool`、`passthrough` 和 `http_bridge` 场景。实际执行结果以对应提交的 GitHub CI 日志为准。即使合成上游接受 B,也只证明策略与发送行为,不证明真实供应商的跨账号加密兼容;不需要调用付费上游或读取生产凭据。 diff --git a/docs/openai-agent-continuation.md b/docs/openai-agent-continuation.md index cdc9dead716c..0b5c8da15a0a 100644 --- a/docs/openai-agent-continuation.md +++ b/docs/openai-agent-continuation.md @@ -2,6 +2,8 @@ 本页说明 #727 已合入源码的归属保护,关联 [Issue #715](https://github.com/ranxi2001/sub2api/issues/715)。源码合并、Release 和实例部署分别核实;不能只凭版本号认为当前实例已启用这些路径,也不能把离线回归当作真实供应商的格式兼容证明。 +下文描述默认严格策略。管理员可通过默认 `false` 的 `gateway.disable_encrypted_agent_owner_binding` 显式允许完整已交付历史尝试其他合格账号;配置方法、交付安全、统一节点切换与回 strict 的混合 owner 限制见[加密 agent 历史账号策略](encrypted-agent-owner-policy.md)。开关不保证上游密文兼容,也不允许重放不确定交付的任务。 + ## 保留任务后再判断故障 `unsupported_encrypted_agent_message` 表示某一层不能消费代理任务的加密格式。它不等同于 reasoning 的 `invalid_encrypted_content`,也不证明故障来自 BPS;先确定同一故障请求的端点、实际通道和部署 SHA。