diff --git a/.github/workflows/encrypted-history-409.yml b/.github/workflows/encrypted-history-409.yml index cbec6031b3a6..b97c0e399009 100644 --- a/.github/workflows/encrypted-history-409.yml +++ b/.github/workflows/encrypted-history-409.yml @@ -3,6 +3,10 @@ on: pull_request: paths: - 'backend/internal/service/openai_409_omit_history*' + - 'backend/internal/service/openai_agent_message_recovery.go' + - 'backend/internal/service/openai_gateway_forward.go' + - 'backend/internal/service/openai_gateway_request_body.go' + - 'backend/internal/service/openai_responses_item_id.go' - 'backend/internal/handler/openai_409_omit_history*' - 'frontend/src/components/settings/EncryptedHistory409Settings.vue' - '.github/scripts/encrypted-history-409-preview.mjs' @@ -34,11 +38,32 @@ jobs: run: | set -euo pipefail go test -race -tags=unit ./internal/service ./internal/handler ./internal/handler/admin -run '^Test(OmitOpenAIHistorical|OpenAI409|UpdateSettingsOpenAI409)' -count=1 -v -timeout=5m 2>&1 | tee "$RUNNER_TEMP/omit-history-protocol.log" + - name: Same HTTP regression against pinned pre-fix omission code must fail + shell: bash + run: | + set -euo pipefail + baseline=11f250894eab310cbd4508946c44c9e2a3a2eb48 + target=backend/internal/service/openai_409_omit_history.go + cp "$target" "$RUNNER_TEMP/omit-history-candidate.go" + trap 'cp "$RUNNER_TEMP/omit-history-candidate.go" "$target"' EXIT + git fetch --no-tags --depth=1 origin "$baseline" + git show "$baseline:$target" > "$target" + test "$(git hash-object "$target")" = "$(git rev-parse "$baseline:$target")" + set +e + (cd backend && go test -race -tags=unit ./internal/handler -run '^TestOpenAI409ReplayMetadataHTTP$' -count=1 -v -timeout=5m) > "$RUNNER_TEMP/omit-history-red.log" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/omit-history-red.log" + test "$result" -ne 0 + grep -q -- '--- FAIL: TestOpenAI409ReplayMetadataHTTP' "$RUNNER_TEMP/omit-history-red.log" + grep -q 'encrypted_agent_recovery_wire_changed' "$RUNNER_TEMP/omit-history-red.log" - uses: actions/upload-artifact@v7 if: always() with: name: encrypted-history-409-protocol-${{ github.event.pull_request.head.sha }} - path: ${{ runner.temp }}/omit-history-protocol.log + path: | + ${{ runner.temp }}/omit-history-protocol.log + ${{ runner.temp }}/omit-history-red.log screenshots: runs-on: ubuntu-latest timeout-minutes: 15 diff --git a/backend/internal/handler/openai_409_omit_history_test.go b/backend/internal/handler/openai_409_omit_history_test.go index 63c0c545ce53..a7dc05d135d6 100644 --- a/backend/internal/handler/openai_409_omit_history_test.go +++ b/backend/internal/handler/openai_409_omit_history_test.go @@ -18,6 +18,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/testutil" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) type omit409SettingsRepo struct { @@ -131,3 +132,111 @@ func TestOpenAI409OmitHistoryHTTP(t *testing.T) { } } } + +// This goes through actual handler selection, shared Redis ownership and a +// localhost HTTP provider. The provider validates the replay contract instead +// of accepting an arbitrary rewritten body as success. +func TestOpenAI409ReplayMetadataHTTP(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, scenario := range []string{"reasoning_id", "reasoning_status", "reasoning_summary", "message_id", "message_call_id", "upstream_rejects"} { + t.Run(fmt.Sprintf("%s/stream=%t", scenario, stream), func(t *testing.T) { + clients := issue805Redis(t) + var mu sync.Mutex + var bodies [][]byte + followup := issue715Body(true, stream) + var err error + followup, err = sjson.Set(followup, "store", false) + require.NoError(t, err) + // Exact integer and tool-result content are not replay metadata. + followup, err = sjson.SetRaw(followup, "input.1.sequence", "9007199254740993") + require.NoError(t, err) + reasoning := `{"type":"reasoning","encrypted_content":"fixture-reasoning-823","summary":[]}` + switch scenario { + case "reasoning_id", "upstream_rejects": + reasoning, err = sjson.Set(reasoning, "id", "rs_fixture_823") + case "reasoning_status": + reasoning, err = sjson.Set(reasoning, "status", "completed") + case "reasoning_summary": + reasoning, err = sjson.Delete(reasoning, "summary") + case "message_id": + followup, err = sjson.Set(followup, "input.1.id", "provider-item-823") + case "message_call_id": + followup, err = sjson.Set(followup, "input.1.call_id", "output-only-call-id") + } + require.NoError(t, err) + followup, err = sjson.SetRaw(followup, "input.-1", reasoning) + require.NoError(t, err) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, readErr := io.ReadAll(r.Body) + if readErr != nil { + t.Error(readErr) + return + } + mu.Lock() + bodies = append(bodies, body) + n := len(bodies) + mu.Unlock() + if n > 1 { + rule := gjson.GetBytes(body, "input.5") + valid := !rule.Get("id").Exists() && !rule.Get("status").Exists() && rule.Get("summary").IsArray() && + !gjson.GetBytes(body, "input.1.id").Exists() && !gjson.GetBytes(body, "input.1.call_id").Exists() && + gjson.GetBytes(body, "input.1.sequence").Raw == "9007199254740993" && + strings.Contains(string(body), "Historical encrypted content omitted") && + !strings.Contains(string(body), "fixture-task-reference-715") + if !valid || scenario == "upstream_rejects" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, `{"error":{"type":"invalid_request_error","message":"fixture replay metadata rejected"}}`) + return + } + } + output := "[" + issue715Agent + "]" + if n > 1 { + output = `[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"continued once"}]}]` + } + payload := fmt.Sprintf(`{"id":"resp_823_%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", payload) + } else { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, payload) + } + })) + defer srv.Close() + accounts := issue715AccountsOfType(service.AccountTypeAPIKey) + for i := range accounts { + accounts[i].Credentials["base_url"] = srv.URL + } + newNode := func(enabled bool) *OpenAIGatewayHandler { + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + settings := service.NewSettingService(&omit409SettingsRepo{enabled: enabled}, cfg) + h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, testutil.NewRealHTTPUpstream(cfg), repository.NewGatewayCache(clients()), settings, accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + return h + } + first := issue758Request(t, newNode(false), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1)) + require.Equal(t, http.StatusOK, first.Code, first.Body.String()) + owners := issue805Owners(t, clients()) + require.Len(t, owners, 1) + accounts[0].Schedulable = false + answer := issue758Request(t, newNode(true), followup) + mu.Lock() + defer mu.Unlock() + require.Len(t, bodies, 2, "one producer and exactly one sanitized continuation; response: %s", answer.Body.String()) + if scenario == "upstream_rejects" { + require.Equal(t, http.StatusBadRequest, answer.Code, answer.Body.String()) + require.Contains(t, answer.Body.String(), "fixture replay metadata rejected") + } else { + require.Equal(t, http.StatusOK, answer.Code, answer.Body.String()) + issue758CompletedResponse(t, answer.Body.String(), stream) + } + for _, path := range []string{"input.1.content", "input.1.sequence", "input.2", "input.3", "input.4", "input.5.encrypted_content"} { + require.JSONEq(t, gjson.Get(followup, path).Raw, gjson.GetBytes(bodies[1], path).Raw, path) + } + require.Equal(t, owners, issue805Owners(t, clients()), "old ownership remains intact") + }) + } + } +} diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go index e1872d2fc0d9..cb02792a6856 100644 --- a/backend/internal/service/openai_409_omit_history.go +++ b/backend/internal/service/openai_409_omit_history.go @@ -11,6 +11,7 @@ import ( "github.com/gin-gonic/gin" "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) const openAIHistoricalCiphertextOmitted = "[Historical encrypted content omitted by the gateway. Its contents are unavailable; do not infer missing instructions or results.]" @@ -44,6 +45,14 @@ func (s *OpenAIGatewayService) TryOmitOpenAI409History(ctx context.Context, c *g if !changed || ctx.Err() != nil { return ctx, body, false } + // Freeze the same narrowly normalized replay metadata that native Responses + // will send. Do this before recording the digest, never after arbitrary + // forwarder transformations. Readable content and call relationships stay + // covered by the original exact-input gate. + clean, err := normalizeOpenAI409ReplayMetadata(clean) + if err != nil { + return ctx, body, false + } next := s.WithOpenAIAgentMessageRecovery(ctx, c, clean, session, model) request := openAIAgentRecoveryFromContext(next) // Preserve the sanitized input at the actual send and reuse the existing @@ -161,3 +170,59 @@ func omitOpenAIHistoricalCiphertext(raw []byte) ([]byte, bool) { clean, err := json.Marshal(source) return clean, err == nil } + +// normalizeOpenAI409ReplayMetadata only removes output-only replay metadata. +// It must not use the general reasoning normalizers: those may delete entire +// reasoning items or visible content. Such changes still fail the send gate. +func normalizeOpenAI409ReplayMetadata(raw []byte) ([]byte, error) { + clean, _, err := sanitizeOpenAIResponsesInputItemIDs(raw) + if err != nil { + return nil, err + } + var source map[string]any + decoder := json.NewDecoder(bytes.NewReader(clean)) + decoder.UseNumber() + if err := decoder.Decode(&source); err != nil { + return nil, err + } + input, _ := source["input"].([]any) + storeFalse := gjson.GetBytes(clean, "store").Type == gjson.False + changed := false + for _, rawItem := range input { + item, ok := rawItem.(map[string]any) + if !ok || strings.TrimSpace(firstNonEmptyString(item["type"])) != "reasoning" { + continue + } + if _, exists := item["status"]; exists { + delete(item, "status") + changed = true + } + if !storeFalse { + continue + } + encrypted, _ := item["encrypted_content"].(string) + if strings.TrimSpace(encrypted) == "" { + // Preserve readable reasoning even if the general store=false replay + // path cannot transport it. Never bless its removal as normalization. + continue + } + if strings.HasPrefix(strings.TrimSpace(firstNonEmptyString(item["id"])), "rs_") { + delete(item, "id") + changed = true + } + if summary, exists := item["summary"]; !exists || summary == nil { + item["summary"] = []any{} + changed = true + } + } + if !changed { + return clean, nil + } + // Replace only input: top-level model mappings, flags and number spellings + // remain the handler's original values. UseNumber keeps nested integers exact. + encoded, err := json.Marshal(input) + if err != nil { + return nil, err + } + return sjson.SetRawBytes(clean, "input", encoded) +} diff --git a/backend/internal/service/openai_409_omit_history_test.go b/backend/internal/service/openai_409_omit_history_test.go index e2b10bdfaa4f..9f49842d944c 100644 --- a/backend/internal/service/openai_409_omit_history_test.go +++ b/backend/internal/service/openai_409_omit_history_test.go @@ -1,11 +1,16 @@ package service import ( + "bytes" "context" + "net/http" + "strings" "testing" + "github.com/Wei-Shaw/sub2api/internal/config" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) func TestOmitOpenAIHistoricalCiphertextPreservesReadableContext(t *testing.T) { @@ -89,3 +94,82 @@ func TestOmitOpenAIHistoricalAssistantAgentUsesUserTextParts(t *testing.T) { } require.Contains(t, string(clean), "readable") } + +func TestOpenAI409ReplayInputTamperingStillFails(t *testing.T) { + for _, mode := range []string{"unchanged", "user_text", "tool_arguments", "tool_result", "call_id", "large_integer", "reasoning_removed", "visible_reasoning_removed", "order", "replay_id_reintroduced"} { + t.Run(mode, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)} + a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + issue715LearnRoute(t, svc, a, issue715OpaqueBody) + raw := strings.TrimSuffix(issue715OpaqueBody, "]}") + `, + {"type":"reasoning","id":"rs_fixture_823","status":"completed","encrypted_content":"fixture-reasoning","content":[{"type":"reasoning_text","text":"visible reasoning must survive"}]}, + {"type":"function_call","name":"record","call_id":"call_823","arguments":"{\"value\":9007199254740993}"}, + {"type":"function_call_output","call_id":"call_823","output":"already recorded exactly once"}, + {"type":"message","role":"user","sequence":9007199254740993,"content":"continue with the result"}],"store":false}` + c, _ := newTurnStateTestContext(t, 715, "fixture-session") + c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)}) + ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, []byte(raw), "fixture-session", "gpt-6-astra") + next, clean, changed := svc.TryOmitOpenAI409History(ctx, c, []byte(raw), "fixture-session", "gpt-6-astra", openAIAgentRecoveryError("owner_unavailable")) + require.True(t, changed) + require.NotContains(t, string(clean), "fixture-opaque-reference") + require.Contains(t, string(clean), "visible reasoning must survive") + require.Equal(t, "9007199254740993", gjson.GetBytes(clean, "input.4.sequence").Raw) + require.False(t, gjson.GetBytes(clean, "input.1.id").Exists()) + require.False(t, gjson.GetBytes(clean, "input.1.status").Exists()) + require.True(t, gjson.GetBytes(clean, "input.1.summary").IsArray()) + originalDigest := openAIAgentRecoveryFromContext(next).inputDigest + var err error + switch mode { + case "user_text": + clean, err = sjson.SetBytes(clean, "input.4.content", "changed user task") + case "tool_arguments": + clean, err = sjson.SetBytes(clean, "input.2.arguments", `{}`) + case "tool_result": + clean, err = sjson.SetBytes(clean, "input.3.output", "lost result") + case "call_id": + clean, err = sjson.SetBytes(clean, "input.3.call_id", "different_call") + case "large_integer": + clean, err = sjson.SetRawBytes(clean, "input.4.sequence", []byte("9007199254740992")) + case "reasoning_removed": + clean, err = sjson.DeleteBytes(clean, "input.1") + case "visible_reasoning_removed": + clean, _, err = normalizeOpenAIResponsesReasoningContentReplay(clean) + case "order": + items := gjson.GetBytes(clean, "input").Array() + clean, err = sjson.SetRawBytes(clean, "input.2", []byte(items[3].Raw)) + require.NoError(t, err) + clean, err = sjson.SetRawBytes(clean, "input.3", []byte(items[2].Raw)) + case "replay_id_reintroduced": + clean, err = sjson.SetBytes(clean, "input.1.id", "rs_untrusted_replacement") + } + require.NoError(t, err) + req, err := http.NewRequest(http.MethodPost, "https://native.example/v1/responses", bytes.NewReader(clean)) + require.NoError(t, err) + finish, err := svc.prepareOpenAIAgentRecoveryAttempt(next, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, req) + defer finish(false) + if mode == "unchanged" { + require.NoError(t, err) + } else { + var refusal *OpenAIAgentRecoveryError + require.ErrorAs(t, err, &refusal) + require.Equal(t, "wire_changed", refusal.Reason) + } + require.Equal(t, originalDigest, openAIAgentRecoveryFromContext(next).inputDigest, "send validation must not rebase the trusted snapshot") + }) + } +} + +func TestOpenAI409ReplayPreservesOrdinaryAndStoredReasoning(t *testing.T) { + for _, store := range []string{"true", "false"} { + svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)} + issue715LearnRoute(t, svc, &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, issue715OpaqueBody) + body := strings.TrimSuffix(issue715OpaqueBody, "]}") + `,{"type":"reasoning","id":"rs_original","summary":[],"encrypted_content":"reasoning-cipher"},{"type":"reasoning","summary":[{"type":"summary_text","text":"readable reasoning"}]},{"role":"user","content":"continue"}],"store":` + store + `}` + c, _ := newTurnStateTestContext(t, 715, "fixture-session") + c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)}) + ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, []byte(body), "fixture-session", "gpt-6-astra") + _, clean, changed := svc.TryOmitOpenAI409History(ctx, c, []byte(body), "fixture-session", "gpt-6-astra", openAIAgentRecoveryError("owner_unavailable")) + require.True(t, changed) + require.Equal(t, store == "true", gjson.GetBytes(clean, "input.1.id").Exists(), "stored reasoning IDs are not disposable") + require.JSONEq(t, gjson.Get(body, "input.2").Raw, gjson.GetBytes(clean, "input.2").Raw, "readable reasoning without ciphertext must not be discarded") + } +} diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index c5c62ddad1e7..d01710763b71 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -364,6 +364,9 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con return noop, openAIAgentRecoveryError("wire_changed") } if request.preservesHistory() && openAIAgentRecoveryInputDigest(body) != request.inputDigest { + if request.omittedHistory { + logger.FromContext(ctx).Warn("openai.encrypted_history_409_refused", zap.String("stage", "input_integrity")) + } return noop, openAIAgentRecoveryError("wire_changed") } if request.previousResponseID != "" && gjson.GetBytes(body, "previous_response_id").String() != request.previousResponseID { diff --git a/docs/encrypted-history-409-beta.md b/docs/encrypted-history-409-beta.md index b89454943d9b..739ae7412cde 100644 --- a/docs/encrypted-history-409-beta.md +++ b/docs/encrypted-history-409-beta.md @@ -21,3 +21,13 @@ HTTP `/v1/responses` 在初次选号、尚未发送上游时,如果已登记 关闭后,后续请求恢复严格行为。无需数据库迁移或清 Redis;回退旧二进制会忽略此设置。切换不会取消在途请求,已省略的信息无法由关闭开关恢复。 回归用虚构历史、隔离 Redis 和 localhost 上游验证,不代表真实供应商兼容或生产验收。参考 #812 中的 BPS 历史省略机制,本功能在项目自己的原生 Responses 路径实现,没有加载第三方插件或复制未知二进制代码。 + +## 省略后发送校验与回放元数据(#823) + +省略后的完整 `input` 仍受到发送前摘要保护。固定摘要之前先执行受限的回放元数据规范化:复用原 ID 校验清理不合规的条目 ID/非配对 call_id,移除 reasoning 的 output-only status;仅当请求明确 `store:false` 且 reasoning 有非空 encrypted_content 时,移除 rs_ 回放 ID、补齐缺省或 null 的空 summary。`store:true` 的有效 reasoning ID 保留。 + +这一步只在 Beta 确实省略旧历史时执行。后续请求仍须与固定快照一致;不会在发送前重新计算并覆盖可信快照。工具参数/结果、调用关联、数组顺序、数字精度和可读 reasoning 内容的改写仍拒绝;普通请求、Beta 默认值和 owner/交付保护不变。 + +如果后续一般兼容逻辑会删除整个 reasoning 或可读 reasoning.content,仍会拒绝该输入,而不是静默丢弃。此时服务器记录 `openai.encrypted_history_409_refused`、`stage=input_integrity`,不含正文、凭据或密文摘要,客户端错误码保持 `encrypted_agent_recovery_wire_changed`。并非所有历史形态都保证可恢复,未知供应商接受度需另行验证。 + +CI 使用真实 handler、隔离 Redis 和 localhost HTTP 假上游,覆盖元数据规范化后的 JSON/SSE 续接、精确一次发送、真实上游拒绝透传及完整性负例;旧 2.21.1 的同一组新增场景必须命名失败。该证据不等于线上六条历史请求已经重放,也不表示修复已发布或部署。